1 /***************************************************************************
2 * Copyright (C) 2007 PCSX-df Team *
3 * Copyright (C) 2009 Wei Mingzhi *
4 * Copyright (C) 2012 notaz *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
20 ***************************************************************************/
22 #include "psxcommon.h"
35 #define WIN32_LEAN_AND_MEAN
38 #define strcasecmp _stricmp
45 #ifdef USE_LIBRETRO_VFS
46 #include <streams/file_stream_transforms.h>
53 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
55 unsigned int cdrIsoMultidiskCount;
56 unsigned int cdrIsoMultidiskSelect;
58 static FILE *cdHandle = NULL;
59 static FILE *cddaHandle = NULL;
60 static FILE *subHandle = NULL;
62 static boolean subChanMixed = FALSE;
63 static boolean subChanRaw = FALSE;
65 static boolean multifile = FALSE;
67 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
68 static unsigned char subbuffer[SUB_FRAMESIZE];
70 static boolean playing = FALSE;
71 static boolean cddaBigEndian = FALSE;
72 /* Frame offset into CD image where pregap data would be found if it was there.
73 * If a game seeks there we must *not* return subchannel data since it's
74 * not in the CD image, so that cdrom code can fake subchannel data instead.
75 * XXX: there could be multiple pregaps but PSX dumps only have one? */
76 static unsigned int pregapOffset;
78 static unsigned int cddaCurPos;
80 // compressed image stuff
82 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
83 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
85 unsigned int index_len;
86 unsigned int block_shift;
87 unsigned int current_block;
88 unsigned int sector_in_blk;
93 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
95 const chd_header* header;
96 unsigned int sectors_per_hunk;
97 unsigned int current_hunk;
98 unsigned int sector_in_hunk;
102 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
103 static int (*cdimg_read_sub_func)(FILE *f, int sector);
105 char* CALLBACK CDR__getDriveLetter(void);
106 long CALLBACK CDR__configure(void);
107 long CALLBACK CDR__test(void);
108 void CALLBACK CDR__about(void);
109 long CALLBACK CDR__setfilename(char *filename);
110 long CALLBACK CDR__getStatus(struct CdrStat *stat);
112 static void DecodeRawSubData(void);
115 enum {DATA=1, CDDA} type;
116 char start[3]; // MSF-format
117 char length[3]; // MSF-format
118 FILE *handle; // for multi-track images CDDA
119 unsigned int start_offset; // byte offset from start of above file
122 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
124 static int numtracks = 0;
125 static struct trackinfo ti[MAXTRACKS];
127 // get a sector from a msf-array
128 static unsigned int msf2sec(char *msf) {
129 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
132 static void sec2msf(unsigned int s, char *msf) {
133 msf[0] = s / 75 / 60;
134 s = s - msf[0] * 75 * 60;
140 // divide a string of xx:yy:zz into m, s, f
141 static void tok2msf(char *time, char *msf) {
144 token = strtok(time, ":");
146 msf[0] = atoi(token);
152 token = strtok(NULL, ":");
154 msf[1] = atoi(token);
160 token = strtok(NULL, ":");
162 msf[2] = atoi(token);
169 // this function tries to get the .toc file of the given .bin
170 // the necessary data is put into the ti (trackinformation)-array
171 static int parsetoc(const char *isofile) {
172 char tocname[MAXPATHLEN];
174 char linebuf[256], tmp[256], name[256];
176 char time[20], time2[20];
177 unsigned int t, sector_offs, sector_size;
178 unsigned int current_zero_gap = 0;
182 // copy name of the iso and change extension from .bin to .toc
183 strncpy(tocname, isofile, sizeof(tocname));
184 tocname[MAXPATHLEN - 1] = '\0';
185 if (strlen(tocname) >= 4) {
186 strcpy(tocname + strlen(tocname) - 4, ".toc");
192 if ((fi = fopen(tocname, "r")) == NULL) {
193 // try changing extension to .cue (to satisfy some stupid tutorials)
194 strcpy(tocname + strlen(tocname) - 4, ".cue");
195 if ((fi = fopen(tocname, "r")) == NULL) {
196 // if filename is image.toc.bin, try removing .bin (for Brasero)
197 strcpy(tocname, isofile);
199 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
200 tocname[t - 4] = '\0';
201 if ((fi = fopen(tocname, "r")) == NULL) {
209 // check if it's really a TOC named as a .cue
210 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
211 token = strtok(linebuf, " ");
212 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
217 fseek(fi, 0, SEEK_SET);
220 memset(&ti, 0, sizeof(ti));
221 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
223 sector_size = CD_FRAMESIZE_RAW;
224 sector_offs = 2 * 75;
226 // parse the .toc file
227 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
229 strncpy(tmp, linebuf, sizeof(linebuf));
230 token = strtok(tmp, " ");
232 if (token == NULL) continue;
234 if (!strcmp(token, "TRACK")) {
235 sector_offs += current_zero_gap;
236 current_zero_gap = 0;
239 token = strtok(NULL, " ");
242 if (!strncmp(token, "MODE2_RAW", 9)) {
243 ti[numtracks].type = DATA;
244 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
246 // check if this image contains mixed subchannel data
247 token = strtok(NULL, " ");
248 if (token != NULL && !strncmp(token, "RW", 2)) {
249 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
251 if (!strncmp(token, "RW_RAW", 6))
255 else if (!strncmp(token, "AUDIO", 5)) {
256 ti[numtracks].type = CDDA;
259 else if (!strcmp(token, "DATAFILE")) {
260 if (ti[numtracks].type == CDDA) {
261 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
262 ti[numtracks].start_offset = t;
263 t = t / sector_size + sector_offs;
264 sec2msf(t, (char *)&ti[numtracks].start);
265 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
268 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
269 tok2msf((char *)&time, (char *)&ti[numtracks].length);
272 else if (!strcmp(token, "FILE")) {
273 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
274 tok2msf((char *)&time, (char *)&ti[numtracks].start);
275 t += msf2sec(ti[numtracks].start) * sector_size;
276 ti[numtracks].start_offset = t;
277 t = t / sector_size + sector_offs;
278 sec2msf(t, (char *)&ti[numtracks].start);
279 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
281 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
282 // skip unneeded optional fields
283 while (token != NULL) {
284 token = strtok(NULL, " ");
285 if (strchr(token, ':') != NULL)
290 current_zero_gap = msf2sec(tmp);
293 t = ti[numtracks - 1].start_offset;
295 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
298 else if (!strcmp(token, "START")) {
299 token = strtok(NULL, " ");
300 if (token != NULL && strchr(token, ':')) {
303 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
304 t = msf2sec(ti[numtracks].start) + t;
305 sec2msf(t, (char *)&ti[numtracks].start);
315 // this function tries to get the .cue file of the given .bin
316 // the necessary data is put into the ti (trackinformation)-array
317 static int parsecue(const char *isofile) {
318 char cuename[MAXPATHLEN];
319 char filepath[MAXPATHLEN];
325 char linebuf[256], tmpb[256], dummy[256];
326 unsigned int incue_max_len;
327 unsigned int t, file_len, mode, sector_offs;
328 unsigned int sector_size = 2352;
332 // copy name of the iso and change extension from .bin to .cue
333 strncpy(cuename, isofile, sizeof(cuename));
334 cuename[MAXPATHLEN - 1] = '\0';
335 if (strlen(cuename) >= 4) {
336 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
337 // and don't try to search the additional .cue file
338 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
339 strcpy(cuename + strlen(cuename) - 4, ".cue");
345 if ((fi = fopen(cuename, "r")) == NULL) {
349 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
350 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
352 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
353 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
354 // Don't proceed further, as this is actually a .toc file rather
357 return parsetoc(isofile);
359 fseek(fi, 0, SEEK_SET);
362 // build a path for files referenced in .cue
363 strncpy(filepath, cuename, sizeof(filepath));
364 tmp = strrchr(filepath, '/');
366 tmp = strrchr(filepath, '\\');
372 filepath[sizeof(filepath) - 1] = 0;
374 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
376 memset(&ti, 0, sizeof(ti));
379 sector_offs = 2 * 75;
381 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
382 strncpy(dummy, linebuf, sizeof(linebuf));
383 token = strtok(dummy, " ");
389 if (!strcmp(token, "TRACK")) {
393 if (strstr(linebuf, "AUDIO") != NULL) {
394 ti[numtracks].type = CDDA;
397 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
398 ti[numtracks].type = DATA;
400 SysPrintf(".cue: failed to parse TRACK\n");
401 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
403 if (sector_size == 0)
406 else if (!strcmp(token, "INDEX")) {
407 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
408 SysPrintf(".cue: failed to parse INDEX\n");
409 tok2msf(time, (char *)&ti[numtracks].start);
411 t = msf2sec(ti[numtracks].start);
412 ti[numtracks].start_offset = t * sector_size;
414 sec2msf(t, ti[numtracks].start);
416 // default track length to file length
417 t = file_len - ti[numtracks].start_offset / sector_size;
418 sec2msf(t, ti[numtracks].length);
420 if (numtracks > 1 && ti[numtracks].handle == NULL) {
421 // this track uses the same file as the last,
422 // start of this track is last track's end
423 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
424 sec2msf(t, ti[numtracks - 1].length);
426 if (numtracks > 1 && pregapOffset == -1)
427 pregapOffset = ti[numtracks].start_offset / sector_size;
429 else if (!strcmp(token, "PREGAP")) {
430 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
431 tok2msf(time, dummy);
432 sector_offs += msf2sec(dummy);
434 pregapOffset = -1; // mark to fill track start_offset
436 else if (!strcmp(token, "FILE")) {
437 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
439 sscanf(linebuf, " FILE %255s", tmpb);
441 tmp = strrchr(tmpb, '\\');
443 tmp = strrchr(tmpb, '/');
448 strncpy(incue_fname, tmp, incue_max_len);
449 ti[numtracks + 1].handle = fopen(filepath, "rb");
451 // update global offset if this is not first file in this .cue
452 if (numtracks + 1 > 1) {
454 sector_offs += file_len;
458 if (ti[numtracks + 1].handle == NULL) {
459 SysPrintf(_("\ncould not open: %s\n"), filepath);
462 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
463 file_len = ftell(ti[numtracks + 1].handle) / 2352;
465 if (numtracks == 0 && strlen(isofile) >= 4 &&
466 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
467 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
468 // user selected .cue/.cdX as image file, use it's data track instead
470 cdHandle = fopen(filepath, "rb");
477 // if there are no tracks detected, then it's not a cue file
484 // this function tries to get the .ccd file of the given .img
485 // the necessary data is put into the ti (trackinformation)-array
486 static int parseccd(const char *isofile) {
487 char ccdname[MAXPATHLEN];
494 // copy name of the iso and change extension from .img to .ccd
495 strncpy(ccdname, isofile, sizeof(ccdname));
496 ccdname[MAXPATHLEN - 1] = '\0';
497 if (strlen(ccdname) >= 4) {
498 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
504 if ((fi = fopen(ccdname, "r")) == NULL) {
508 memset(&ti, 0, sizeof(ti));
510 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
511 if (!strncmp(linebuf, "[TRACK", 6)){
514 else if (!strncmp(linebuf, "MODE=", 5)) {
515 sscanf(linebuf, "MODE=%d", &t);
516 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
518 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
519 sscanf(linebuf, "INDEX 1=%d", &t);
520 sec2msf(t + 2 * 75, ti[numtracks].start);
521 ti[numtracks].start_offset = t * 2352;
523 // If we've already seen another track, this is its end
525 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
526 sec2msf(t, ti[numtracks - 1].length);
533 // Fill out the last track's end based on size
534 if (numtracks >= 1) {
535 fseek(cdHandle, 0, SEEK_END);
536 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
537 sec2msf(t, ti[numtracks].length);
543 // this function tries to get the .mds file of the given .mdf
544 // the necessary data is put into the ti (trackinformation)-array
545 static int parsemds(const char *isofile) {
546 char mdsname[MAXPATHLEN];
548 unsigned int offset, extra_offset, l, i;
553 // copy name of the iso and change extension from .mdf to .mds
554 strncpy(mdsname, isofile, sizeof(mdsname));
555 mdsname[MAXPATHLEN - 1] = '\0';
556 if (strlen(mdsname) >= 4) {
557 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
563 if ((fi = fopen(mdsname, "rb")) == NULL) {
567 memset(&ti, 0, sizeof(ti));
569 // check if it's a valid mds file
570 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
573 if (i != 0x4944454D) {
574 // not an valid mds file
579 // get offset to session block
580 fseek(fi, 0x50, SEEK_SET);
581 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
583 offset = SWAP32(offset);
585 // get total number of tracks
587 fseek(fi, offset, SEEK_SET);
588 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
593 // get offset to track blocks
594 fseek(fi, 4, SEEK_CUR);
595 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
597 offset = SWAP32(offset);
601 fseek(fi, offset + 4, SEEK_SET);
602 if (fgetc(fi) < 0xA0) {
608 // check if the image contains mixed subchannel data
609 fseek(fi, offset + 1, SEEK_SET);
610 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
613 for (i = 1; i <= numtracks; i++) {
614 fseek(fi, offset, SEEK_SET);
616 // get the track type
617 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
618 fseek(fi, 8, SEEK_CUR);
620 // get the track starting point
621 ti[i].start[0] = fgetc(fi);
622 ti[i].start[1] = fgetc(fi);
623 ti[i].start[2] = fgetc(fi);
625 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
627 extra_offset = SWAP32(extra_offset);
629 // get track start offset (in .mdf)
630 fseek(fi, offset + 0x28, SEEK_SET);
631 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
634 ti[i].start_offset = l;
637 fseek(fi, extra_offset, SEEK_SET);
638 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
642 pregapOffset = msf2sec(ti[i].start);
644 // get the track length
645 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
648 sec2msf(l, ti[i].length);
656 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
662 static int handlepbp(const char *isofile) {
665 unsigned int dontcare[8];
666 unsigned int psar_offs;
679 unsigned int dontcare[6];
682 off_t psisoimg_offs, cdimg_base;
683 unsigned int t, cd_length;
684 unsigned int offsettab[8];
685 unsigned int psar_offs, index_entry_size, index_entry_offset;
686 const char *ext = NULL;
689 if (strlen(isofile) >= 4)
690 ext = isofile + strlen(isofile) - 4;
691 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
694 fseeko(cdHandle, 0, SEEK_SET);
698 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
699 if (ret != sizeof(pbp_hdr)) {
700 SysPrintf("failed to read pbp\n");
704 psar_offs = SWAP32(pbp_hdr.psar_offs);
706 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
708 SysPrintf("failed to seek to %x\n", psar_offs);
712 psisoimg_offs = psar_offs;
713 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
716 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
718 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
720 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
724 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
725 SysPrintf("failed to read offsettab\n");
729 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
730 if (offsettab[i] == 0)
733 cdrIsoMultidiskCount = i;
734 if (cdrIsoMultidiskCount == 0) {
735 SysPrintf("multidisk eboot has 0 images?\n");
739 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
740 cdrIsoMultidiskSelect = 0;
742 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
744 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
746 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
750 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
755 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
756 SysPrintf("bad psar_sig: %s\n", psar_sig);
761 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
763 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
767 // first 3 entries are special
768 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
769 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
771 numtracks = btoi(toc_entry.index1[0]);
773 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
775 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
776 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
778 for (i = 1; i <= numtracks; i++) {
779 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
782 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
784 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
785 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
786 ti[i].start_offset *= 2352;
787 ti[i].start[0] = btoi(toc_entry.index1[0]);
788 ti[i].start[1] = btoi(toc_entry.index1[1]);
789 ti[i].start[2] = btoi(toc_entry.index1[2]);
792 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
793 sec2msf(t, ti[i - 1].length);
796 t = cd_length - ti[numtracks].start_offset / 2352;
797 sec2msf(t, ti[numtracks].length);
800 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
802 SysPrintf("failed to seek to ISO index\n");
806 compr_img = calloc(1, sizeof(*compr_img));
807 if (compr_img == NULL)
810 compr_img->block_shift = 4;
811 compr_img->current_block = (unsigned int)-1;
813 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
814 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
815 if (compr_img->index_table == NULL)
818 cdimg_base = psisoimg_offs + 0x100000;
819 for (i = 0; i < compr_img->index_len; i++) {
820 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
821 if (ret != sizeof(index_entry)) {
822 SysPrintf("failed to read index_entry #%d\n", i);
826 index_entry_size = SWAP32(index_entry.size);
827 index_entry_offset = SWAP32(index_entry.offset);
829 if (index_entry_size == 0)
832 compr_img->index_table[i] = cdimg_base + index_entry_offset;
834 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
839 free(compr_img->index_table);
840 compr_img->index_table = NULL;
845 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
849 if (compr_img != NULL) {
856 static int handlecbin(const char *isofile) {
860 unsigned int header_size;
861 unsigned long long total_bytes;
862 unsigned int block_size;
863 unsigned char ver; // 1
865 unsigned char rsv_06[2];
867 const char *ext = NULL;
868 unsigned int *index_table = NULL;
869 unsigned int index = 0, plain;
872 if (strlen(isofile) >= 5)
873 ext = isofile + strlen(isofile) - 5;
874 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
877 fseek(cdHandle, 0, SEEK_SET);
879 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
880 if (ret != sizeof(ciso_hdr)) {
881 SysPrintf("failed to read ciso header\n");
885 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
886 SysPrintf("bad ciso header\n");
889 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
890 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
892 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
897 compr_img = calloc(1, sizeof(*compr_img));
898 if (compr_img == NULL)
901 compr_img->block_shift = 0;
902 compr_img->current_block = (unsigned int)-1;
904 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
905 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
906 if (index_table == NULL)
909 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
910 if (ret != compr_img->index_len) {
911 SysPrintf("failed to read index table\n");
915 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
916 if (compr_img->index_table == NULL)
919 for (i = 0; i < compr_img->index_len + 1; i++) {
920 index = index_table[i];
921 plain = index & 0x80000000;
923 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
925 compr_img->index_table[i] |= OFF_T_MSB;
933 if (compr_img != NULL) {
941 static int handlechd(const char *isofile) {
942 int frame_offset = 150;
945 chd_img = calloc(1, sizeof(*chd_img));
949 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
952 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
955 chd_img->header = chd_get_header(chd_img->chd);
957 chd_img->buffer = malloc(chd_img->header->hunkbytes);
958 if (chd_img->buffer == NULL)
961 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
962 chd_img->current_hunk = (unsigned int)-1;
964 cddaBigEndian = TRUE;
967 memset(ti, 0, sizeof(ti));
982 uint32_t meta_size = 0;
984 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
985 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
986 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
987 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
991 SysPrintf("chd: %s\n", meta);
994 if (!strncmp(md.subtype, "RW", 2)) {
996 if (!strcmp(md.subtype, "RW_RAW"))
1001 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1003 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1004 sec2msf(md.frames, ti[md.track].length);
1006 ti[md.track].start_offset = file_offset + md.pregap;
1008 // XXX: what about postgap?
1009 frame_offset += md.frames;
1010 file_offset += md.frames;
1018 if (chd_img != NULL) {
1019 free(chd_img->buffer);
1027 // this function tries to get the .sub file of the given .img
1028 static int opensubfile(const char *isoname) {
1029 char subname[MAXPATHLEN];
1031 // copy name of the iso and change extension from .img to .sub
1032 strncpy(subname, isoname, sizeof(subname));
1033 subname[MAXPATHLEN - 1] = '\0';
1034 if (strlen(subname) >= 4) {
1035 strcpy(subname + strlen(subname) - 4, ".sub");
1041 subHandle = fopen(subname, "rb");
1042 if (subHandle == NULL) {
1049 static int opensbifile(const char *isoname) {
1050 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1053 strncpy(sbiname, isoname, sizeof(sbiname));
1054 sbiname[MAXPATHLEN - 1] = '\0';
1055 if (strlen(sbiname) >= 4) {
1056 if (cdrIsoMultidiskCount > 1) {
1057 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1058 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1061 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1067 fseek(cdHandle, 0, SEEK_END);
1068 s = ftell(cdHandle) / 2352;
1070 return LoadSBI(sbiname, s);
1074 static void readThreadStop() {}
1075 static void readThreadStart() {}
1077 static pthread_t read_thread_id;
1079 static pthread_cond_t read_thread_msg_avail;
1080 static pthread_cond_t read_thread_msg_done;
1081 static pthread_mutex_t read_thread_msg_lock;
1083 static pthread_cond_t sectorbuffer_cond;
1084 static pthread_mutex_t sectorbuffer_lock;
1086 static boolean read_thread_running = FALSE;
1087 static int read_thread_sector_start = -1;
1088 static int read_thread_sector_end = -1;
1093 unsigned char data[CD_FRAMESIZE_RAW];
1094 } SectorBufferEntry;
1096 #define SECTOR_BUFFER_SIZE 4096
1098 static SectorBufferEntry *sectorbuffer;
1099 static size_t sectorbuffer_index;
1101 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1102 unsigned char *(*sync_CDR_getBuffer)(void);
1104 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1105 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1107 static void *readThreadMain(void *param) {
1108 int max_sector = -1;
1109 int requested_sector_start = -1;
1110 int requested_sector_end = -1;
1111 int last_read_sector = -1;
1117 int speedmult_ra = 4;
1120 int how_far_ahead = 0;
1122 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1125 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1128 pthread_mutex_lock(&read_thread_msg_lock);
1130 // If we don't have readahead and we don't have a sector request, wait for one.
1131 // If we still have readahead to go, don't block, just keep going.
1132 // And if we ever have a sector request pending, acknowledge and reset it.
1135 if (read_thread_sector_start == -1 && read_thread_running) {
1136 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1140 if (read_thread_sector_start != -1) {
1141 requested_sector_start = read_thread_sector_start;
1142 requested_sector_end = read_thread_sector_end;
1143 read_thread_sector_start = -1;
1144 read_thread_sector_end = -1;
1145 pthread_cond_signal(&read_thread_msg_done);
1148 pthread_mutex_unlock(&read_thread_msg_lock);
1150 if (!read_thread_running)
1153 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1154 if (requested_sector_start != -1) {
1155 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1156 how_far_ahead = ra_sector - requested_sector_end;
1158 if(how_far_ahead <= max_ra)
1159 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1162 } else if (requested_sector_end != last_read_sector) {
1163 ra_sector = requested_sector_end;
1164 ra_count = initial_ra;
1167 last_read_sector = requested_sector_end;
1170 index = ra_sector % SECTOR_BUFFER_SIZE;
1172 // check for end of CD
1173 if (ra_count && ra_sector >= max_sector) {
1175 pthread_mutex_lock(§orbuffer_lock);
1176 sectorbuffer[index].ret = -1;
1177 sectorbuffer[index].sector = ra_sector;
1178 pthread_cond_signal(§orbuffer_cond);
1179 pthread_mutex_unlock(§orbuffer_lock);
1183 pthread_mutex_lock(§orbuffer_lock);
1184 if (sectorbuffer[index].sector != ra_sector) {
1185 pthread_mutex_unlock(§orbuffer_lock);
1187 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1189 pthread_mutex_lock(§orbuffer_lock);
1190 sectorbuffer[index].ret = ret;
1191 sectorbuffer[index].sector = ra_sector;
1192 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1194 pthread_cond_signal(§orbuffer_cond);
1195 pthread_mutex_unlock(§orbuffer_lock);
1205 static void readThreadStop() {
1206 if (read_thread_running == TRUE) {
1207 read_thread_running = FALSE;
1208 pthread_cond_signal(&read_thread_msg_avail);
1209 pthread_join(read_thread_id, NULL);
1212 pthread_cond_destroy(&read_thread_msg_done);
1213 pthread_cond_destroy(&read_thread_msg_avail);
1214 pthread_mutex_destroy(&read_thread_msg_lock);
1216 pthread_cond_destroy(§orbuffer_cond);
1217 pthread_mutex_destroy(§orbuffer_lock);
1219 CDR_getBuffer = sync_CDR_getBuffer;
1220 cdimg_read_func = sync_cdimg_read_func;
1223 sectorbuffer = NULL;
1226 static void readThreadStart() {
1227 SysPrintf("Starting async CD thread\n");
1229 if (read_thread_running == TRUE)
1232 read_thread_running = TRUE;
1233 read_thread_sector_start = -1;
1234 read_thread_sector_end = -1;
1235 sectorbuffer_index = 0;
1237 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1241 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1243 sync_CDR_getBuffer = CDR_getBuffer;
1244 CDR_getBuffer = ISOgetBuffer_async;
1245 sync_cdimg_read_func = cdimg_read_func;
1246 cdimg_read_func = cdread_async;
1248 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1249 pthread_cond_init(&read_thread_msg_done, NULL) ||
1250 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1251 pthread_cond_init(§orbuffer_cond, NULL) ||
1252 pthread_mutex_init(§orbuffer_lock, NULL) ||
1253 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1259 SysPrintf("Error starting async CD thread\n");
1260 SysPrintf("Falling back to sync\n");
1266 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1269 if (fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1271 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1277 // often happens in cdda gaps of a split cue/bin, so not logged
1278 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1282 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1286 if (fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1288 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1294 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1298 static int cdread_sub_sub_mixed(FILE *f, int sector)
1300 if (fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1302 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1305 return SUB_FRAMESIZE;
1308 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1312 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1317 if (z.zalloc == NULL) {
1318 // XXX: one-time leak here..
1324 ret = inflateInit2(&z, -15);
1327 ret = inflateReset(&z);
1332 z.avail_in = in_size;
1334 z.avail_out = *out_size;
1336 ret = inflate(&z, Z_NO_FLUSH);
1339 *out_size -= z.avail_out;
1340 return ret == 1 ? 0 : ret;
1343 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1345 unsigned long cdbuffer_size, cdbuffer_size_expect;
1352 sector += base / 2352;
1354 block = sector >> compr_img->block_shift;
1355 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1357 if (block == compr_img->current_block) {
1358 //printf("hit sect %d\n", sector);
1362 if (sector >= compr_img->index_len * 16) {
1363 SysPrintf("sector %d is past img end\n", sector);
1367 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1368 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1369 SysPrintf("seek error for block %d at %llx: ",
1370 block, (long long)start_byte);
1375 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1376 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1377 if (size > sizeof(compr_img->buff_compressed)) {
1378 SysPrintf("block %d is too large: %u\n", block, size);
1382 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1383 1, size, cdHandle) != size) {
1384 SysPrintf("read error for block %d at %x: ", block, start_byte);
1389 if (is_compressed) {
1390 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1391 cdbuffer_size = cdbuffer_size_expect;
1392 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1394 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1395 ret, block, sector);
1398 if (cdbuffer_size != cdbuffer_size_expect)
1399 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1400 cdbuffer_size_expect, sector);
1404 compr_img->current_block = block;
1407 if (dest != cdbuffer) // copy avoid HACK
1408 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1410 return CD_FRAMESIZE_RAW;
1414 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1420 hunk = sector / chd_img->sectors_per_hunk;
1421 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1423 if (hunk != chd_img->current_hunk)
1425 chd_read(chd_img->chd, hunk, chd_img->buffer);
1426 chd_img->current_hunk = hunk;
1429 if (dest != cdbuffer) // copy avoid HACK
1430 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1432 return CD_FRAMESIZE_RAW;
1435 static int cdread_sub_chd(FILE *f, int sector)
1442 hunk = sector / chd_img->sectors_per_hunk;
1443 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1445 if (hunk != chd_img->current_hunk)
1447 chd_read(chd_img->chd, hunk, chd_img->buffer);
1448 chd_img->current_hunk = hunk;
1451 memcpy(subbuffer, chd_img->buffer[chd_img->sector_in_hunk] + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1452 return SUB_FRAMESIZE;
1456 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1460 fseek(f, base + sector * 2048, SEEK_SET);
1461 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1463 // not really necessary, fake mode 2 header
1464 memset(cdbuffer, 0, 12 * 2);
1465 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1466 cdbuffer[12 + 3] = 1;
1473 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1474 boolean found = FALSE;
1475 int i = sector % SECTOR_BUFFER_SIZE;
1478 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1479 // Async reads are only supported for cdbuffer, so call the sync
1480 // function directly.
1481 return sync_cdimg_read_func(f, base, dest, sector);
1484 pthread_mutex_lock(&read_thread_msg_lock);
1486 // Only wait if we're not trying to read the next sector and
1487 // sector_start is set (meaning the last request hasn't been
1489 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1490 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1493 if (read_thread_sector_start == -1)
1494 read_thread_sector_start = sector;
1496 read_thread_sector_end = sector;
1497 pthread_cond_signal(&read_thread_msg_avail);
1498 pthread_mutex_unlock(&read_thread_msg_lock);
1501 pthread_mutex_lock(§orbuffer_lock);
1502 if (sectorbuffer[i].sector == sector) {
1503 sectorbuffer_index = i;
1504 ret = sectorbuffer[i].ret;
1509 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1511 pthread_mutex_unlock(§orbuffer_lock);
1519 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1520 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1524 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1525 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1530 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1531 unsigned char *buffer;
1532 pthread_mutex_lock(§orbuffer_lock);
1533 buffer = sectorbuffer[sectorbuffer_index].data;
1534 pthread_mutex_unlock(§orbuffer_lock);
1540 static unsigned char * CALLBACK ISOgetBuffer(void) {
1541 return cdbuffer + 12;
1544 static void PrintTracks(void) {
1547 for (i = 1; i <= numtracks; i++) {
1548 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1549 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1550 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1551 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1555 // This function is invoked by the front-end when opening an ISO
1556 // file for playback
1557 static long CALLBACK ISOopen(void) {
1558 boolean isMode1ISO = FALSE;
1559 char alt_bin_filename[MAXPATHLEN];
1560 const char *bin_filename;
1561 char image_str[1024];
1564 if (cdHandle != NULL) {
1565 return 0; // it's already open
1568 cdHandle = fopen(GetIsoFile(), "rb");
1569 if (cdHandle == NULL) {
1570 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1571 GetIsoFile(), strerror(errno));
1575 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1576 "Loaded CD Image: %s", GetIsoFile());
1578 cddaBigEndian = FALSE;
1579 subChanMixed = FALSE;
1582 cdrIsoMultidiskCount = 1;
1585 CDR_getBuffer = ISOgetBuffer;
1586 cdimg_read_func = cdread_normal;
1587 cdimg_read_sub_func = NULL;
1589 if (parsetoc(GetIsoFile()) == 0) {
1590 strcat(image_str, "[+toc]");
1592 else if (parseccd(GetIsoFile()) == 0) {
1593 strcat(image_str, "[+ccd]");
1595 else if (parsemds(GetIsoFile()) == 0) {
1596 strcat(image_str, "[+mds]");
1598 else if (parsecue(GetIsoFile()) == 0) {
1599 strcat(image_str, "[+cue]");
1601 if (handlepbp(GetIsoFile()) == 0) {
1602 strcat(image_str, "[+pbp]");
1603 CDR_getBuffer = ISOgetBuffer_compr;
1604 cdimg_read_func = cdread_compressed;
1606 else if (handlecbin(GetIsoFile()) == 0) {
1607 strcat(image_str, "[+cbin]");
1608 CDR_getBuffer = ISOgetBuffer_compr;
1609 cdimg_read_func = cdread_compressed;
1612 else if (handlechd(GetIsoFile()) == 0) {
1613 strcat(image_str, "[+chd]");
1614 CDR_getBuffer = ISOgetBuffer_chd;
1615 cdimg_read_func = cdread_chd;
1616 cdimg_read_sub_func = cdread_sub_chd;
1621 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1622 strcat(image_str, "[+sub]");
1624 if (opensbifile(GetIsoFile()) == 0) {
1625 strcat(image_str, "[+sbi]");
1628 fseeko(cdHandle, 0, SEEK_END);
1630 // maybe user selected metadata file instead of main .bin ..
1631 bin_filename = GetIsoFile();
1632 if (ftello(cdHandle) < 2352 * 0x10) {
1633 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1638 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1639 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1640 if (strlen(alt_bin_filename) >= 4) {
1641 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1642 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1644 tmpf = fopen(alt_bin_filename, "rb");
1650 bin_filename = alt_bin_filename;
1653 fseeko(cdHandle, 0, SEEK_END);
1657 // guess whether it is mode1/2048
1658 if (ftello(cdHandle) % 2048 == 0) {
1659 unsigned int modeTest = 0;
1660 fseek(cdHandle, 0, SEEK_SET);
1661 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1663 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1667 if (SWAP32(modeTest) != 0xffffff00) {
1668 strcat(image_str, "[2048]");
1672 fseek(cdHandle, 0, SEEK_SET);
1674 SysPrintf("%s.\n", image_str);
1678 if (subChanMixed && !is_chd) {
1679 cdimg_read_func = cdread_sub_mixed;
1680 cdimg_read_sub_func = cdread_sub_sub_mixed;
1682 else if (isMode1ISO) {
1683 cdimg_read_func = cdread_2048;
1684 cdimg_read_sub_func = NULL;
1687 // make sure we have another handle open for cdda
1688 if (numtracks > 1 && ti[1].handle == NULL) {
1689 ti[1].handle = fopen(bin_filename, "rb");
1692 if (Config.AsyncCD) {
1698 static long CALLBACK ISOclose(void) {
1701 if (cdHandle != NULL) {
1705 if (subHandle != NULL) {
1712 if (compr_img != NULL) {
1713 free(compr_img->index_table);
1719 if (chd_img != NULL) {
1720 chd_close(chd_img->chd);
1721 free(chd_img->buffer);
1727 for (i = 1; i <= numtracks; i++) {
1728 if (ti[i].handle != NULL) {
1729 fclose(ti[i].handle);
1730 ti[i].handle = NULL;
1737 memset(cdbuffer, 0, sizeof(cdbuffer));
1738 CDR_getBuffer = ISOgetBuffer;
1740 if (Config.AsyncCD) {
1747 static long CALLBACK ISOinit(void) {
1748 assert(cdHandle == NULL);
1749 assert(subHandle == NULL);
1751 return 0; // do nothing
1754 static long CALLBACK ISOshutdown(void) {
1759 // return Starting and Ending Track
1761 // byte 0 - start track
1762 // byte 1 - end track
1763 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1766 if (numtracks > 0) {
1767 buffer[1] = numtracks;
1776 // return Track Time
1781 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1784 unsigned char time[3];
1785 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1786 sec2msf(sect, (char *)time);
1787 buffer[2] = time[0];
1788 buffer[1] = time[1];
1789 buffer[0] = time[2];
1791 else if (numtracks > 0 && track <= numtracks) {
1792 buffer[2] = ti[track].start[0];
1793 buffer[1] = ti[track].start[1];
1794 buffer[0] = ti[track].start[2];
1805 // decode 'raw' subchannel data ripped by cdrdao
1806 static void DecodeRawSubData(void) {
1807 unsigned char subQData[12];
1810 memset(subQData, 0, sizeof(subQData));
1812 for (i = 0; i < 8 * 12; i++) {
1813 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1814 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1818 memcpy(&subbuffer[12], subQData, 12);
1822 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1824 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1825 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1828 if (cdHandle == NULL) {
1832 if (pregapOffset && sector >= pregapOffset)
1835 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1836 if (ret < 12*2 + 2048)
1843 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1844 // does NOT uses bcd format
1845 static long CALLBACK ISOplay(unsigned char *time) {
1851 static long CALLBACK ISOstop(void) {
1856 // gets subchannel data
1857 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1858 if (pregapOffset && sector >= pregapOffset) {
1860 if (sector < pregapOffset) // ?
1864 if (cdimg_read_sub_func != NULL) {
1865 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1868 else if (subHandle != NULL) {
1869 if (fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1871 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1878 if (subChanRaw) DecodeRawSubData();
1882 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1885 CDR__getStatus(stat);
1889 stat->Status |= 0x80;
1892 // BIOS - boot ID (CD type)
1893 stat->Type = ti[1].type;
1896 // relative -> absolute time
1898 sec2msf(sect, (char *)stat->Time);
1903 // read CDDA sector into buffer
1904 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1905 unsigned char msf[3] = {m, s, f};
1906 unsigned int file, track, track_start = 0;
1909 cddaCurPos = msf2sec((char *)msf);
1911 // find current track index
1912 for (track = numtracks; ; track--) {
1913 track_start = msf2sec(ti[track].start);
1914 if (track_start <= cddaCurPos)
1920 // data tracks play silent
1921 if (ti[track].type != CDDA) {
1922 memset(buffer, 0, CD_FRAMESIZE_RAW);
1928 // find the file that contains this track
1929 for (file = track; file > 1; file--)
1930 if (ti[file].handle != NULL)
1934 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1935 buffer, cddaCurPos - track_start);
1936 if (ret != CD_FRAMESIZE_RAW) {
1937 memset(buffer, 0, CD_FRAMESIZE_RAW);
1941 if (cddaBigEndian) {
1945 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1946 tmp = buffer[i * 2];
1947 buffer[i * 2] = buffer[i * 2 + 1];
1948 buffer[i * 2 + 1] = tmp;
1955 void cdrIsoInit(void) {
1957 CDR_shutdown = ISOshutdown;
1959 CDR_close = ISOclose;
1960 CDR_getTN = ISOgetTN;
1961 CDR_getTD = ISOgetTD;
1962 CDR_readTrack = ISOreadTrack;
1963 CDR_getBuffer = ISOgetBuffer;
1966 CDR_getBufferSub = ISOgetBufferSub;
1967 CDR_getStatus = ISOgetStatus;
1968 CDR_readCDDA = ISOreadCDDA;
1970 CDR_getDriveLetter = CDR__getDriveLetter;
1971 CDR_configure = CDR__configure;
1972 CDR_test = CDR__test;
1973 CDR_about = CDR__about;
1974 CDR_setfilename = CDR__setfilename;
1979 int cdrIsoActive(void) {
1980 return (cdHandle != NULL);