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
46 // to enable the USE_READ_THREAD code, fix:
47 // - https://github.com/notaz/pcsx_rearmed/issues/257
48 // - ISOgetBufferSub to not race with async code
49 //#define USE_READ_THREAD
52 #ifdef USE_LIBRETRO_VFS
53 #include <streams/file_stream_transforms.h>
60 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
62 unsigned int cdrIsoMultidiskCount;
63 unsigned int cdrIsoMultidiskSelect;
65 static FILE *cdHandle = NULL;
66 static FILE *cddaHandle = NULL;
67 static FILE *subHandle = NULL;
69 static boolean subChanMixed = FALSE;
70 static boolean subChanRaw = FALSE;
72 static boolean multifile = FALSE;
74 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
75 static unsigned char subbuffer[SUB_FRAMESIZE];
77 static boolean playing = FALSE;
78 static boolean cddaBigEndian = FALSE;
79 /* Frame offset into CD image where pregap data would be found if it was there.
80 * If a game seeks there we must *not* return subchannel data since it's
81 * not in the CD image, so that cdrom code can fake subchannel data instead.
82 * XXX: there could be multiple pregaps but PSX dumps only have one? */
83 static unsigned int pregapOffset;
85 static unsigned int cddaCurPos;
87 // compressed image stuff
89 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
90 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
92 unsigned int index_len;
93 unsigned int block_shift;
94 unsigned int current_block;
95 unsigned int sector_in_blk;
100 unsigned char *buffer;
102 const chd_header* header;
103 unsigned int sectors_per_hunk;
104 unsigned int current_hunk[2];
105 unsigned int current_buffer;
106 unsigned int sector_in_hunk;
110 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
111 static int (*cdimg_read_sub_func)(FILE *f, int sector);
113 char* CALLBACK CDR__getDriveLetter(void);
114 long CALLBACK CDR__configure(void);
115 long CALLBACK CDR__test(void);
116 void CALLBACK CDR__about(void);
117 long CALLBACK CDR__setfilename(char *filename);
118 long CALLBACK CDR__getStatus(struct CdrStat *stat);
120 static void DecodeRawSubData(void);
123 enum {DATA=1, CDDA} type;
124 char start[3]; // MSF-format
125 char length[3]; // MSF-format
126 FILE *handle; // for multi-track images CDDA
127 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
130 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
132 static int numtracks = 0;
133 static struct trackinfo ti[MAXTRACKS];
135 // get a sector from a msf-array
136 static unsigned int msf2sec(char *msf) {
137 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
140 static void sec2msf(unsigned int s, char *msf) {
141 msf[0] = s / 75 / 60;
142 s = s - msf[0] * 75 * 60;
148 // divide a string of xx:yy:zz into m, s, f
149 static void tok2msf(char *time, char *msf) {
152 token = strtok(time, ":");
154 msf[0] = atoi(token);
160 token = strtok(NULL, ":");
162 msf[1] = atoi(token);
168 token = strtok(NULL, ":");
170 msf[2] = atoi(token);
177 // this function tries to get the .toc file of the given .bin
178 // the necessary data is put into the ti (trackinformation)-array
179 static int parsetoc(const char *isofile) {
180 char tocname[MAXPATHLEN];
182 char linebuf[256], tmp[256], name[256];
184 char time[20], time2[20];
185 unsigned int t, sector_offs, sector_size;
186 unsigned int current_zero_gap = 0;
190 // copy name of the iso and change extension from .bin to .toc
191 strncpy(tocname, isofile, sizeof(tocname));
192 tocname[MAXPATHLEN - 1] = '\0';
193 if (strlen(tocname) >= 4) {
194 strcpy(tocname + strlen(tocname) - 4, ".toc");
200 if ((fi = fopen(tocname, "r")) == NULL) {
201 // try changing extension to .cue (to satisfy some stupid tutorials)
202 strcpy(tocname + strlen(tocname) - 4, ".cue");
203 if ((fi = fopen(tocname, "r")) == NULL) {
204 // if filename is image.toc.bin, try removing .bin (for Brasero)
205 strcpy(tocname, isofile);
207 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
208 tocname[t - 4] = '\0';
209 if ((fi = fopen(tocname, "r")) == NULL) {
217 // check if it's really a TOC named as a .cue
218 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
219 token = strtok(linebuf, " ");
220 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
225 fseek(fi, 0, SEEK_SET);
228 memset(&ti, 0, sizeof(ti));
229 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
231 sector_size = CD_FRAMESIZE_RAW;
232 sector_offs = 2 * 75;
234 // parse the .toc file
235 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
237 strncpy(tmp, linebuf, sizeof(linebuf));
238 token = strtok(tmp, " ");
240 if (token == NULL) continue;
242 if (!strcmp(token, "TRACK")) {
243 sector_offs += current_zero_gap;
244 current_zero_gap = 0;
247 token = strtok(NULL, " ");
250 if (!strncmp(token, "MODE2_RAW", 9)) {
251 ti[numtracks].type = DATA;
252 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
254 // check if this image contains mixed subchannel data
255 token = strtok(NULL, " ");
256 if (token != NULL && !strncmp(token, "RW", 2)) {
257 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
259 if (!strncmp(token, "RW_RAW", 6))
263 else if (!strncmp(token, "AUDIO", 5)) {
264 ti[numtracks].type = CDDA;
267 else if (!strcmp(token, "DATAFILE")) {
268 if (ti[numtracks].type == CDDA) {
269 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
270 ti[numtracks].start_offset = t;
271 t = t / sector_size + sector_offs;
272 sec2msf(t, (char *)&ti[numtracks].start);
273 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
276 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
277 tok2msf((char *)&time, (char *)&ti[numtracks].length);
280 else if (!strcmp(token, "FILE")) {
281 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
282 tok2msf((char *)&time, (char *)&ti[numtracks].start);
283 t += msf2sec(ti[numtracks].start) * sector_size;
284 ti[numtracks].start_offset = t;
285 t = t / sector_size + sector_offs;
286 sec2msf(t, (char *)&ti[numtracks].start);
287 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
289 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
290 // skip unneeded optional fields
291 while (token != NULL) {
292 token = strtok(NULL, " ");
293 if (strchr(token, ':') != NULL)
298 current_zero_gap = msf2sec(tmp);
301 t = ti[numtracks - 1].start_offset;
303 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
306 else if (!strcmp(token, "START")) {
307 token = strtok(NULL, " ");
308 if (token != NULL && strchr(token, ':')) {
311 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
312 t = msf2sec(ti[numtracks].start) + t;
313 sec2msf(t, (char *)&ti[numtracks].start);
323 // this function tries to get the .cue file of the given .bin
324 // the necessary data is put into the ti (trackinformation)-array
325 static int parsecue(const char *isofile) {
326 char cuename[MAXPATHLEN];
327 char filepath[MAXPATHLEN];
333 char linebuf[256], tmpb[256], dummy[256];
334 unsigned int incue_max_len;
335 unsigned int t, file_len, mode, sector_offs;
336 unsigned int sector_size = 2352;
340 // copy name of the iso and change extension from .bin to .cue
341 strncpy(cuename, isofile, sizeof(cuename));
342 cuename[MAXPATHLEN - 1] = '\0';
343 if (strlen(cuename) >= 4) {
344 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
345 // and don't try to search the additional .cue file
346 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
347 strcpy(cuename + strlen(cuename) - 4, ".cue");
353 if ((fi = fopen(cuename, "r")) == NULL) {
357 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
358 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
360 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
361 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
362 // Don't proceed further, as this is actually a .toc file rather
365 return parsetoc(isofile);
367 fseek(fi, 0, SEEK_SET);
370 // build a path for files referenced in .cue
371 strncpy(filepath, cuename, sizeof(filepath));
372 tmp = strrchr(filepath, '/');
374 tmp = strrchr(filepath, '\\');
380 filepath[sizeof(filepath) - 1] = 0;
382 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
384 memset(&ti, 0, sizeof(ti));
387 sector_offs = 2 * 75;
389 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
390 strncpy(dummy, linebuf, sizeof(linebuf));
391 token = strtok(dummy, " ");
397 if (!strcmp(token, "TRACK")) {
401 if (strstr(linebuf, "AUDIO") != NULL) {
402 ti[numtracks].type = CDDA;
405 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
406 ti[numtracks].type = DATA;
408 SysPrintf(".cue: failed to parse TRACK\n");
409 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
411 if (sector_size == 0)
414 else if (!strcmp(token, "INDEX")) {
415 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
416 SysPrintf(".cue: failed to parse INDEX\n");
417 tok2msf(time, (char *)&ti[numtracks].start);
419 t = msf2sec(ti[numtracks].start);
420 ti[numtracks].start_offset = t * sector_size;
422 sec2msf(t, ti[numtracks].start);
424 // default track length to file length
425 t = file_len - ti[numtracks].start_offset / sector_size;
426 sec2msf(t, ti[numtracks].length);
428 if (numtracks > 1 && ti[numtracks].handle == NULL) {
429 // this track uses the same file as the last,
430 // start of this track is last track's end
431 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
432 sec2msf(t, ti[numtracks - 1].length);
434 if (numtracks > 1 && pregapOffset == -1)
435 pregapOffset = ti[numtracks].start_offset / sector_size;
437 else if (!strcmp(token, "PREGAP")) {
438 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
439 tok2msf(time, dummy);
440 sector_offs += msf2sec(dummy);
442 pregapOffset = -1; // mark to fill track start_offset
444 else if (!strcmp(token, "FILE")) {
445 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
447 sscanf(linebuf, " FILE %255s", tmpb);
449 tmp = strrchr(tmpb, '\\');
451 tmp = strrchr(tmpb, '/');
456 strncpy(incue_fname, tmp, incue_max_len);
457 ti[numtracks + 1].handle = fopen(filepath, "rb");
459 // update global offset if this is not first file in this .cue
460 if (numtracks + 1 > 1) {
462 sector_offs += file_len;
466 if (ti[numtracks + 1].handle == NULL) {
467 SysPrintf(_("\ncould not open: %s\n"), filepath);
470 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
471 file_len = ftell(ti[numtracks + 1].handle) / 2352;
473 if (numtracks == 0 && strlen(isofile) >= 4 &&
474 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
475 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
476 // user selected .cue/.cdX as image file, use it's data track instead
478 cdHandle = fopen(filepath, "rb");
485 // if there are no tracks detected, then it's not a cue file
492 // this function tries to get the .ccd file of the given .img
493 // the necessary data is put into the ti (trackinformation)-array
494 static int parseccd(const char *isofile) {
495 char ccdname[MAXPATHLEN];
502 // copy name of the iso and change extension from .img to .ccd
503 strncpy(ccdname, isofile, sizeof(ccdname));
504 ccdname[MAXPATHLEN - 1] = '\0';
505 if (strlen(ccdname) >= 4) {
506 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
512 if ((fi = fopen(ccdname, "r")) == NULL) {
516 memset(&ti, 0, sizeof(ti));
518 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
519 if (!strncmp(linebuf, "[TRACK", 6)){
522 else if (!strncmp(linebuf, "MODE=", 5)) {
523 sscanf(linebuf, "MODE=%d", &t);
524 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
526 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
527 sscanf(linebuf, "INDEX 1=%d", &t);
528 sec2msf(t + 2 * 75, ti[numtracks].start);
529 ti[numtracks].start_offset = t * 2352;
531 // If we've already seen another track, this is its end
533 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
534 sec2msf(t, ti[numtracks - 1].length);
541 // Fill out the last track's end based on size
542 if (numtracks >= 1) {
543 fseek(cdHandle, 0, SEEK_END);
544 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
545 sec2msf(t, ti[numtracks].length);
551 // this function tries to get the .mds file of the given .mdf
552 // the necessary data is put into the ti (trackinformation)-array
553 static int parsemds(const char *isofile) {
554 char mdsname[MAXPATHLEN];
556 unsigned int offset, extra_offset, l, i;
561 // copy name of the iso and change extension from .mdf to .mds
562 strncpy(mdsname, isofile, sizeof(mdsname));
563 mdsname[MAXPATHLEN - 1] = '\0';
564 if (strlen(mdsname) >= 4) {
565 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
571 if ((fi = fopen(mdsname, "rb")) == NULL) {
575 memset(&ti, 0, sizeof(ti));
577 // check if it's a valid mds file
578 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
581 if (i != 0x4944454D) {
582 // not an valid mds file
587 // get offset to session block
588 fseek(fi, 0x50, SEEK_SET);
589 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
591 offset = SWAP32(offset);
593 // get total number of tracks
595 fseek(fi, offset, SEEK_SET);
596 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
601 // get offset to track blocks
602 fseek(fi, 4, SEEK_CUR);
603 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
605 offset = SWAP32(offset);
609 fseek(fi, offset + 4, SEEK_SET);
610 if (fgetc(fi) < 0xA0) {
616 // check if the image contains mixed subchannel data
617 fseek(fi, offset + 1, SEEK_SET);
618 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
621 for (i = 1; i <= numtracks; i++) {
622 fseek(fi, offset, SEEK_SET);
624 // get the track type
625 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
626 fseek(fi, 8, SEEK_CUR);
628 // get the track starting point
629 ti[i].start[0] = fgetc(fi);
630 ti[i].start[1] = fgetc(fi);
631 ti[i].start[2] = fgetc(fi);
633 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
635 extra_offset = SWAP32(extra_offset);
637 // get track start offset (in .mdf)
638 fseek(fi, offset + 0x28, SEEK_SET);
639 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
642 ti[i].start_offset = l;
645 fseek(fi, extra_offset, SEEK_SET);
646 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
650 pregapOffset = msf2sec(ti[i].start);
652 // get the track length
653 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
656 sec2msf(l, ti[i].length);
664 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
670 static int handlepbp(const char *isofile) {
673 unsigned int dontcare[8];
674 unsigned int psar_offs;
687 unsigned int dontcare[6];
690 off_t psisoimg_offs, cdimg_base;
691 unsigned int t, cd_length;
692 unsigned int offsettab[8];
693 unsigned int psar_offs, index_entry_size, index_entry_offset;
694 const char *ext = NULL;
697 if (strlen(isofile) >= 4)
698 ext = isofile + strlen(isofile) - 4;
699 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
702 fseeko(cdHandle, 0, SEEK_SET);
706 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
707 if (ret != sizeof(pbp_hdr)) {
708 SysPrintf("failed to read pbp\n");
712 psar_offs = SWAP32(pbp_hdr.psar_offs);
714 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
716 SysPrintf("failed to seek to %x\n", psar_offs);
720 psisoimg_offs = psar_offs;
721 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
724 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
726 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
728 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
732 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
733 SysPrintf("failed to read offsettab\n");
737 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
738 if (offsettab[i] == 0)
741 cdrIsoMultidiskCount = i;
742 if (cdrIsoMultidiskCount == 0) {
743 SysPrintf("multidisk eboot has 0 images?\n");
747 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
748 cdrIsoMultidiskSelect = 0;
750 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
752 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
754 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
758 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
763 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
764 SysPrintf("bad psar_sig: %s\n", psar_sig);
769 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
771 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
775 // first 3 entries are special
776 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
777 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
779 numtracks = btoi(toc_entry.index1[0]);
781 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
783 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
784 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
786 for (i = 1; i <= numtracks; i++) {
787 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
790 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
792 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
793 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
794 ti[i].start_offset *= 2352;
795 ti[i].start[0] = btoi(toc_entry.index1[0]);
796 ti[i].start[1] = btoi(toc_entry.index1[1]);
797 ti[i].start[2] = btoi(toc_entry.index1[2]);
800 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
801 sec2msf(t, ti[i - 1].length);
804 t = cd_length - ti[numtracks].start_offset / 2352;
805 sec2msf(t, ti[numtracks].length);
808 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
810 SysPrintf("failed to seek to ISO index\n");
814 compr_img = calloc(1, sizeof(*compr_img));
815 if (compr_img == NULL)
818 compr_img->block_shift = 4;
819 compr_img->current_block = (unsigned int)-1;
821 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
822 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
823 if (compr_img->index_table == NULL)
826 cdimg_base = psisoimg_offs + 0x100000;
827 for (i = 0; i < compr_img->index_len; i++) {
828 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
829 if (ret != sizeof(index_entry)) {
830 SysPrintf("failed to read index_entry #%d\n", i);
834 index_entry_size = SWAP32(index_entry.size);
835 index_entry_offset = SWAP32(index_entry.offset);
837 if (index_entry_size == 0)
840 compr_img->index_table[i] = cdimg_base + index_entry_offset;
842 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
847 free(compr_img->index_table);
848 compr_img->index_table = NULL;
853 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
857 if (compr_img != NULL) {
864 static int handlecbin(const char *isofile) {
868 unsigned int header_size;
869 unsigned long long total_bytes;
870 unsigned int block_size;
871 unsigned char ver; // 1
873 unsigned char rsv_06[2];
875 const char *ext = NULL;
876 unsigned int *index_table = NULL;
877 unsigned int index = 0, plain;
880 if (strlen(isofile) >= 5)
881 ext = isofile + strlen(isofile) - 5;
882 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
885 fseek(cdHandle, 0, SEEK_SET);
887 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
888 if (ret != sizeof(ciso_hdr)) {
889 SysPrintf("failed to read ciso header\n");
893 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
894 SysPrintf("bad ciso header\n");
897 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
898 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
900 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
905 compr_img = calloc(1, sizeof(*compr_img));
906 if (compr_img == NULL)
909 compr_img->block_shift = 0;
910 compr_img->current_block = (unsigned int)-1;
912 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
913 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
914 if (index_table == NULL)
917 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
918 if (ret != compr_img->index_len) {
919 SysPrintf("failed to read index table\n");
923 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
924 if (compr_img->index_table == NULL)
927 for (i = 0; i < compr_img->index_len + 1; i++) {
928 index = index_table[i];
929 plain = index & 0x80000000;
931 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
933 compr_img->index_table[i] |= OFF_T_MSB;
941 if (compr_img != NULL) {
949 static int handlechd(const char *isofile) {
950 int frame_offset = 150;
953 chd_img = calloc(1, sizeof(*chd_img));
957 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
960 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
963 chd_img->header = chd_get_header(chd_img->chd);
965 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
966 if (chd_img->buffer == NULL)
969 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
970 chd_img->current_hunk[0] = (unsigned int)-1;
971 chd_img->current_hunk[1] = (unsigned int)-1;
973 cddaBigEndian = TRUE;
976 memset(ti, 0, sizeof(ti));
991 uint32_t meta_size = 0;
993 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
994 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
995 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
996 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1000 SysPrintf("chd: %s\n", meta);
1002 if (md.track == 1) {
1003 if (!strncmp(md.subtype, "RW", 2)) {
1004 subChanMixed = TRUE;
1005 if (!strcmp(md.subtype, "RW_RAW"))
1010 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1012 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1013 sec2msf(md.frames, ti[md.track].length);
1015 ti[md.track].start_offset = file_offset + md.pregap;
1017 // XXX: what about postgap?
1018 frame_offset += md.frames;
1019 file_offset += md.frames;
1027 if (chd_img != NULL) {
1028 free(chd_img->buffer);
1036 // this function tries to get the .sub file of the given .img
1037 static int opensubfile(const char *isoname) {
1038 char subname[MAXPATHLEN];
1040 // copy name of the iso and change extension from .img to .sub
1041 strncpy(subname, isoname, sizeof(subname));
1042 subname[MAXPATHLEN - 1] = '\0';
1043 if (strlen(subname) >= 4) {
1044 strcpy(subname + strlen(subname) - 4, ".sub");
1050 subHandle = fopen(subname, "rb");
1051 if (subHandle == NULL) {
1058 static int opensbifile(const char *isoname) {
1059 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1062 strncpy(sbiname, isoname, sizeof(sbiname));
1063 sbiname[MAXPATHLEN - 1] = '\0';
1064 if (strlen(sbiname) >= 4) {
1065 if (cdrIsoMultidiskCount > 1) {
1066 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1067 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1070 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1076 fseek(cdHandle, 0, SEEK_END);
1077 s = ftell(cdHandle) / 2352;
1079 return LoadSBI(sbiname, s);
1082 #ifndef USE_READ_THREAD
1083 static void readThreadStop() {}
1084 static void readThreadStart() {}
1086 static pthread_t read_thread_id;
1088 static pthread_cond_t read_thread_msg_avail;
1089 static pthread_cond_t read_thread_msg_done;
1090 static pthread_mutex_t read_thread_msg_lock;
1092 static pthread_cond_t sectorbuffer_cond;
1093 static pthread_mutex_t sectorbuffer_lock;
1095 static boolean read_thread_running = FALSE;
1096 static int read_thread_sector_start = -1;
1097 static int read_thread_sector_end = -1;
1102 unsigned char data[CD_FRAMESIZE_RAW];
1103 } SectorBufferEntry;
1105 #define SECTOR_BUFFER_SIZE 4096
1107 static SectorBufferEntry *sectorbuffer;
1108 static size_t sectorbuffer_index;
1110 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1111 unsigned char *(*sync_CDR_getBuffer)(void);
1113 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1114 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1116 static void *readThreadMain(void *param) {
1117 int max_sector = -1;
1118 int requested_sector_start = -1;
1119 int requested_sector_end = -1;
1120 int last_read_sector = -1;
1126 int speedmult_ra = 4;
1129 int how_far_ahead = 0;
1131 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1134 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1137 pthread_mutex_lock(&read_thread_msg_lock);
1139 // If we don't have readahead and we don't have a sector request, wait for one.
1140 // If we still have readahead to go, don't block, just keep going.
1141 // And if we ever have a sector request pending, acknowledge and reset it.
1144 if (read_thread_sector_start == -1 && read_thread_running) {
1145 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1149 if (read_thread_sector_start != -1) {
1150 requested_sector_start = read_thread_sector_start;
1151 requested_sector_end = read_thread_sector_end;
1152 read_thread_sector_start = -1;
1153 read_thread_sector_end = -1;
1154 pthread_cond_signal(&read_thread_msg_done);
1157 pthread_mutex_unlock(&read_thread_msg_lock);
1159 if (!read_thread_running)
1162 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1163 if (requested_sector_start != -1) {
1164 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1165 how_far_ahead = ra_sector - requested_sector_end;
1167 if(how_far_ahead <= max_ra)
1168 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1171 } else if (requested_sector_end != last_read_sector) {
1172 ra_sector = requested_sector_end;
1173 ra_count = initial_ra;
1176 last_read_sector = requested_sector_end;
1179 index = ra_sector % SECTOR_BUFFER_SIZE;
1181 // check for end of CD
1182 if (ra_count && ra_sector >= max_sector) {
1184 pthread_mutex_lock(§orbuffer_lock);
1185 sectorbuffer[index].ret = -1;
1186 sectorbuffer[index].sector = ra_sector;
1187 pthread_cond_signal(§orbuffer_cond);
1188 pthread_mutex_unlock(§orbuffer_lock);
1192 pthread_mutex_lock(§orbuffer_lock);
1193 if (sectorbuffer[index].sector != ra_sector) {
1194 pthread_mutex_unlock(§orbuffer_lock);
1196 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1198 pthread_mutex_lock(§orbuffer_lock);
1199 sectorbuffer[index].ret = ret;
1200 sectorbuffer[index].sector = ra_sector;
1201 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1203 pthread_cond_signal(§orbuffer_cond);
1204 pthread_mutex_unlock(§orbuffer_lock);
1214 static void readThreadStop() {
1215 if (read_thread_running == TRUE) {
1216 read_thread_running = FALSE;
1217 pthread_cond_signal(&read_thread_msg_avail);
1218 pthread_join(read_thread_id, NULL);
1221 pthread_cond_destroy(&read_thread_msg_done);
1222 pthread_cond_destroy(&read_thread_msg_avail);
1223 pthread_mutex_destroy(&read_thread_msg_lock);
1225 pthread_cond_destroy(§orbuffer_cond);
1226 pthread_mutex_destroy(§orbuffer_lock);
1228 CDR_getBuffer = sync_CDR_getBuffer;
1229 cdimg_read_func = sync_cdimg_read_func;
1232 sectorbuffer = NULL;
1235 static void readThreadStart() {
1236 SysPrintf("Starting async CD thread\n");
1238 if (read_thread_running == TRUE)
1241 read_thread_running = TRUE;
1242 read_thread_sector_start = -1;
1243 read_thread_sector_end = -1;
1244 sectorbuffer_index = 0;
1246 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1250 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1252 sync_CDR_getBuffer = CDR_getBuffer;
1253 CDR_getBuffer = ISOgetBuffer_async;
1254 sync_cdimg_read_func = cdimg_read_func;
1255 cdimg_read_func = cdread_async;
1257 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1258 pthread_cond_init(&read_thread_msg_done, NULL) ||
1259 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1260 pthread_cond_init(§orbuffer_cond, NULL) ||
1261 pthread_mutex_init(§orbuffer_lock, NULL) ||
1262 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1268 SysPrintf("Error starting async CD thread\n");
1269 SysPrintf("Falling back to sync\n");
1275 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1278 if (fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1280 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1286 // often happens in cdda gaps of a split cue/bin, so not logged
1287 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1291 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1295 if (fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1297 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1303 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1307 static int cdread_sub_sub_mixed(FILE *f, int sector)
1309 if (fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1311 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1314 return SUB_FRAMESIZE;
1317 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1321 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1326 if (z.zalloc == NULL) {
1327 // XXX: one-time leak here..
1333 ret = inflateInit2(&z, -15);
1336 ret = inflateReset(&z);
1341 z.avail_in = in_size;
1343 z.avail_out = *out_size;
1345 ret = inflate(&z, Z_NO_FLUSH);
1348 *out_size -= z.avail_out;
1349 return ret == 1 ? 0 : ret;
1352 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1354 unsigned long cdbuffer_size, cdbuffer_size_expect;
1361 sector += base / 2352;
1363 block = sector >> compr_img->block_shift;
1364 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1366 if (block == compr_img->current_block) {
1367 //printf("hit sect %d\n", sector);
1371 if (sector >= compr_img->index_len * 16) {
1372 SysPrintf("sector %d is past img end\n", sector);
1376 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1377 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1378 SysPrintf("seek error for block %d at %llx: ",
1379 block, (long long)start_byte);
1384 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1385 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1386 if (size > sizeof(compr_img->buff_compressed)) {
1387 SysPrintf("block %d is too large: %u\n", block, size);
1391 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1392 1, size, cdHandle) != size) {
1393 SysPrintf("read error for block %d at %x: ", block, start_byte);
1398 if (is_compressed) {
1399 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1400 cdbuffer_size = cdbuffer_size_expect;
1401 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1403 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1404 ret, block, sector);
1407 if (cdbuffer_size != cdbuffer_size_expect)
1408 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1409 cdbuffer_size_expect, sector);
1413 compr_img->current_block = block;
1416 if (dest != cdbuffer) // copy avoid HACK
1417 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1419 return CD_FRAMESIZE_RAW;
1423 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1425 return chd_img->buffer
1426 + current_buffer * chd_img->header->hunkbytes
1427 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1430 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1436 hunk = sector / chd_img->sectors_per_hunk;
1437 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1439 if (hunk == chd_img->current_hunk[0])
1440 chd_img->current_buffer = 0;
1441 else if (hunk == chd_img->current_hunk[1])
1442 chd_img->current_buffer = 1;
1445 chd_read(chd_img->chd, hunk, chd_img->buffer +
1446 chd_img->current_buffer * chd_img->header->hunkbytes);
1447 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1450 if (dest != cdbuffer) // copy avoid HACK
1451 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1453 return CD_FRAMESIZE_RAW;
1456 static int cdread_sub_chd(FILE *f, int sector)
1458 unsigned int sector_in_hunk;
1459 unsigned int buffer;
1465 hunk = sector / chd_img->sectors_per_hunk;
1466 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1468 if (hunk == chd_img->current_hunk[0])
1470 else if (hunk == chd_img->current_hunk[1])
1474 buffer = chd_img->current_buffer ^ 1;
1475 chd_read(chd_img->chd, hunk, chd_img->buffer +
1476 buffer * chd_img->header->hunkbytes);
1477 chd_img->current_hunk[buffer] = hunk;
1480 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1481 return SUB_FRAMESIZE;
1485 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1489 fseek(f, base + sector * 2048, SEEK_SET);
1490 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1492 // not really necessary, fake mode 2 header
1493 memset(cdbuffer, 0, 12 * 2);
1494 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1495 cdbuffer[12 + 3] = 1;
1500 #ifdef USE_READ_THREAD
1502 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1503 boolean found = FALSE;
1504 int i = sector % SECTOR_BUFFER_SIZE;
1507 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1508 // Async reads are only supported for cdbuffer, so call the sync
1509 // function directly.
1510 return sync_cdimg_read_func(f, base, dest, sector);
1513 pthread_mutex_lock(&read_thread_msg_lock);
1515 // Only wait if we're not trying to read the next sector and
1516 // sector_start is set (meaning the last request hasn't been
1518 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1519 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1522 if (read_thread_sector_start == -1)
1523 read_thread_sector_start = sector;
1525 read_thread_sector_end = sector;
1526 pthread_cond_signal(&read_thread_msg_avail);
1527 pthread_mutex_unlock(&read_thread_msg_lock);
1530 pthread_mutex_lock(§orbuffer_lock);
1531 if (sectorbuffer[i].sector == sector) {
1532 sectorbuffer_index = i;
1533 ret = sectorbuffer[i].ret;
1538 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1540 pthread_mutex_unlock(§orbuffer_lock);
1548 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1549 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1553 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1554 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1558 #ifdef USE_READ_THREAD
1559 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1560 unsigned char *buffer;
1561 pthread_mutex_lock(§orbuffer_lock);
1562 buffer = sectorbuffer[sectorbuffer_index].data;
1563 pthread_mutex_unlock(§orbuffer_lock);
1569 static unsigned char * CALLBACK ISOgetBuffer(void) {
1570 return cdbuffer + 12;
1573 static void PrintTracks(void) {
1576 for (i = 1; i <= numtracks; i++) {
1577 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1578 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1579 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1580 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1584 // This function is invoked by the front-end when opening an ISO
1585 // file for playback
1586 static long CALLBACK ISOopen(void) {
1587 boolean isMode1ISO = FALSE;
1588 char alt_bin_filename[MAXPATHLEN];
1589 const char *bin_filename;
1590 char image_str[1024];
1593 if (cdHandle != NULL) {
1594 return 0; // it's already open
1597 cdHandle = fopen(GetIsoFile(), "rb");
1598 if (cdHandle == NULL) {
1599 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1600 GetIsoFile(), strerror(errno));
1604 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1605 "Loaded CD Image: %s", GetIsoFile());
1607 cddaBigEndian = FALSE;
1608 subChanMixed = FALSE;
1611 cdrIsoMultidiskCount = 1;
1614 CDR_getBuffer = ISOgetBuffer;
1615 cdimg_read_func = cdread_normal;
1616 cdimg_read_sub_func = NULL;
1618 if (parsetoc(GetIsoFile()) == 0) {
1619 strcat(image_str, "[+toc]");
1621 else if (parseccd(GetIsoFile()) == 0) {
1622 strcat(image_str, "[+ccd]");
1624 else if (parsemds(GetIsoFile()) == 0) {
1625 strcat(image_str, "[+mds]");
1627 else if (parsecue(GetIsoFile()) == 0) {
1628 strcat(image_str, "[+cue]");
1630 if (handlepbp(GetIsoFile()) == 0) {
1631 strcat(image_str, "[+pbp]");
1632 CDR_getBuffer = ISOgetBuffer_compr;
1633 cdimg_read_func = cdread_compressed;
1635 else if (handlecbin(GetIsoFile()) == 0) {
1636 strcat(image_str, "[+cbin]");
1637 CDR_getBuffer = ISOgetBuffer_compr;
1638 cdimg_read_func = cdread_compressed;
1641 else if (handlechd(GetIsoFile()) == 0) {
1642 strcat(image_str, "[+chd]");
1643 CDR_getBuffer = ISOgetBuffer_chd;
1644 cdimg_read_func = cdread_chd;
1645 cdimg_read_sub_func = cdread_sub_chd;
1650 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1651 strcat(image_str, "[+sub]");
1653 if (opensbifile(GetIsoFile()) == 0) {
1654 strcat(image_str, "[+sbi]");
1657 fseeko(cdHandle, 0, SEEK_END);
1659 // maybe user selected metadata file instead of main .bin ..
1660 bin_filename = GetIsoFile();
1661 if (ftello(cdHandle) < 2352 * 0x10) {
1662 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1667 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1668 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1669 if (strlen(alt_bin_filename) >= 4) {
1670 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1671 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1673 tmpf = fopen(alt_bin_filename, "rb");
1679 bin_filename = alt_bin_filename;
1682 fseeko(cdHandle, 0, SEEK_END);
1686 // guess whether it is mode1/2048
1687 if (ftello(cdHandle) % 2048 == 0) {
1688 unsigned int modeTest = 0;
1689 fseek(cdHandle, 0, SEEK_SET);
1690 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1692 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1696 if (SWAP32(modeTest) != 0xffffff00) {
1697 strcat(image_str, "[2048]");
1701 fseek(cdHandle, 0, SEEK_SET);
1703 SysPrintf("%s.\n", image_str);
1707 if (subChanMixed && !is_chd) {
1708 cdimg_read_func = cdread_sub_mixed;
1709 cdimg_read_sub_func = cdread_sub_sub_mixed;
1711 else if (isMode1ISO) {
1712 cdimg_read_func = cdread_2048;
1713 cdimg_read_sub_func = NULL;
1716 // make sure we have another handle open for cdda
1717 if (numtracks > 1 && ti[1].handle == NULL) {
1718 ti[1].handle = fopen(bin_filename, "rb");
1721 if (Config.AsyncCD) {
1727 static long CALLBACK ISOclose(void) {
1730 if (cdHandle != NULL) {
1734 if (subHandle != NULL) {
1741 if (compr_img != NULL) {
1742 free(compr_img->index_table);
1748 if (chd_img != NULL) {
1749 chd_close(chd_img->chd);
1750 free(chd_img->buffer);
1756 for (i = 1; i <= numtracks; i++) {
1757 if (ti[i].handle != NULL) {
1758 fclose(ti[i].handle);
1759 ti[i].handle = NULL;
1766 memset(cdbuffer, 0, sizeof(cdbuffer));
1767 CDR_getBuffer = ISOgetBuffer;
1769 if (Config.AsyncCD) {
1776 static long CALLBACK ISOinit(void) {
1777 assert(cdHandle == NULL);
1778 assert(subHandle == NULL);
1780 return 0; // do nothing
1783 static long CALLBACK ISOshutdown(void) {
1788 // return Starting and Ending Track
1790 // byte 0 - start track
1791 // byte 1 - end track
1792 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1795 if (numtracks > 0) {
1796 buffer[1] = numtracks;
1805 // return Track Time
1810 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1813 unsigned char time[3];
1814 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1815 sec2msf(sect, (char *)time);
1816 buffer[2] = time[0];
1817 buffer[1] = time[1];
1818 buffer[0] = time[2];
1820 else if (numtracks > 0 && track <= numtracks) {
1821 buffer[2] = ti[track].start[0];
1822 buffer[1] = ti[track].start[1];
1823 buffer[0] = ti[track].start[2];
1834 // decode 'raw' subchannel data ripped by cdrdao
1835 static void DecodeRawSubData(void) {
1836 unsigned char subQData[12];
1839 memset(subQData, 0, sizeof(subQData));
1841 for (i = 0; i < 8 * 12; i++) {
1842 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1843 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1847 memcpy(&subbuffer[12], subQData, 12);
1851 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1853 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1854 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1857 if (cdHandle == NULL) {
1861 if (pregapOffset && sector >= pregapOffset)
1864 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1865 if (ret < 12*2 + 2048)
1872 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1873 // does NOT uses bcd format
1874 static long CALLBACK ISOplay(unsigned char *time) {
1880 static long CALLBACK ISOstop(void) {
1885 // gets subchannel data
1886 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1887 if (pregapOffset && sector >= pregapOffset) {
1889 if (sector < pregapOffset) // ?
1893 if (cdimg_read_sub_func != NULL) {
1894 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1897 else if (subHandle != NULL) {
1898 if (fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1900 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1907 if (subChanRaw) DecodeRawSubData();
1911 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1914 CDR__getStatus(stat);
1918 stat->Status |= 0x80;
1921 // BIOS - boot ID (CD type)
1922 stat->Type = ti[1].type;
1925 // relative -> absolute time
1927 sec2msf(sect, (char *)stat->Time);
1932 // read CDDA sector into buffer
1933 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1934 unsigned char msf[3] = {m, s, f};
1935 unsigned int file, track, track_start = 0;
1938 cddaCurPos = msf2sec((char *)msf);
1940 // find current track index
1941 for (track = numtracks; ; track--) {
1942 track_start = msf2sec(ti[track].start);
1943 if (track_start <= cddaCurPos)
1949 // data tracks play silent
1950 if (ti[track].type != CDDA) {
1951 memset(buffer, 0, CD_FRAMESIZE_RAW);
1957 // find the file that contains this track
1958 for (file = track; file > 1; file--)
1959 if (ti[file].handle != NULL)
1963 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1964 buffer, cddaCurPos - track_start);
1965 if (ret != CD_FRAMESIZE_RAW) {
1966 memset(buffer, 0, CD_FRAMESIZE_RAW);
1970 if (cddaBigEndian) {
1974 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1975 tmp = buffer[i * 2];
1976 buffer[i * 2] = buffer[i * 2 + 1];
1977 buffer[i * 2 + 1] = tmp;
1984 void cdrIsoInit(void) {
1986 CDR_shutdown = ISOshutdown;
1988 CDR_close = ISOclose;
1989 CDR_getTN = ISOgetTN;
1990 CDR_getTD = ISOgetTD;
1991 CDR_readTrack = ISOreadTrack;
1992 CDR_getBuffer = ISOgetBuffer;
1995 CDR_getBufferSub = ISOgetBufferSub;
1996 CDR_getStatus = ISOgetStatus;
1997 CDR_readCDDA = ISOreadCDDA;
1999 CDR_getDriveLetter = CDR__getDriveLetter;
2000 CDR_configure = CDR__configure;
2001 CDR_test = CDR__test;
2002 CDR_about = CDR__about;
2003 CDR_setfilename = CDR__setfilename;
2008 int cdrIsoActive(void) {
2009 return (cdHandle != NULL);