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"
31 #include <libchdr/chd.h>
35 #define strcasecmp _stricmp
37 #include <sys/types.h>
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 0 //P_HAVE_PTHREAD
51 #ifdef USE_LIBRETRO_VFS
52 #include <streams/file_stream_transforms.h>
58 #define rewind(f_) rfseek(f_, 0, SEEK_SET)
61 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
63 unsigned int cdrIsoMultidiskCount;
64 unsigned int cdrIsoMultidiskSelect;
66 static FILE *cdHandle = NULL;
67 static FILE *cddaHandle = NULL;
68 static FILE *subHandle = NULL;
70 static boolean subChanMixed = FALSE;
71 static boolean subChanRaw = FALSE;
73 static boolean multifile = FALSE;
75 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
76 static unsigned char subbuffer[SUB_FRAMESIZE];
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 // compressed image stuff
87 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
88 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
90 unsigned int index_len;
91 unsigned int block_shift;
92 unsigned int current_block;
93 unsigned int sector_in_blk;
98 unsigned char *buffer;
100 const chd_header* header;
101 unsigned int sectors_per_hunk;
102 unsigned int current_hunk[2];
103 unsigned int current_buffer;
104 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__prefetch(u8 m, u8 s, u8 f);
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 static off_t get_size(FILE *f)
180 #if !defined(USE_LIBRETRO_VFS)
182 if (fstat(fileno(f), &st) == 0)
186 fseeko(f, 0, SEEK_END);
188 fseeko(f, old, SEEK_SET);
192 // this function tries to get the .toc file of the given .bin
193 // the necessary data is put into the ti (trackinformation)-array
194 static int parsetoc(const char *isofile) {
195 char tocname[MAXPATHLEN];
197 char linebuf[256], tmp[256], name[256];
199 char time[20], time2[20];
200 unsigned int t, sector_offs, sector_size;
201 unsigned int current_zero_gap = 0;
205 // copy name of the iso and change extension from .bin to .toc
206 strncpy(tocname, isofile, sizeof(tocname));
207 tocname[MAXPATHLEN - 1] = '\0';
208 if (strlen(tocname) >= 4) {
209 strcpy(tocname + strlen(tocname) - 4, ".toc");
215 if ((fi = fopen(tocname, "r")) == NULL) {
216 // try changing extension to .cue (to satisfy some stupid tutorials)
217 strcpy(tocname + strlen(tocname) - 4, ".cue");
218 if ((fi = fopen(tocname, "r")) == NULL) {
219 // if filename is image.toc.bin, try removing .bin (for Brasero)
220 strcpy(tocname, isofile);
222 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
223 tocname[t - 4] = '\0';
224 if ((fi = fopen(tocname, "r")) == NULL) {
232 // check if it's really a TOC named as a .cue
233 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
234 token = strtok(linebuf, " ");
235 if (token && strncmp(token, "CD", 2) != 0) {
236 // && strcmp(token, "CATALOG") != 0) - valid for a real .cue
241 fseek(fi, 0, SEEK_SET);
244 memset(&ti, 0, sizeof(ti));
245 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
247 sector_size = CD_FRAMESIZE_RAW;
248 sector_offs = 2 * 75;
250 // parse the .toc file
251 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
253 strncpy(tmp, linebuf, sizeof(linebuf));
254 token = strtok(tmp, " ");
256 if (token == NULL) continue;
258 if (!strcmp(token, "TRACK")) {
259 sector_offs += current_zero_gap;
260 current_zero_gap = 0;
263 token = strtok(NULL, " ");
266 if (!strncmp(token, "MODE2_RAW", 9)) {
267 ti[numtracks].type = DATA;
268 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
270 // check if this image contains mixed subchannel data
271 token = strtok(NULL, " ");
272 if (token != NULL && !strncmp(token, "RW", 2)) {
273 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
275 if (!strncmp(token, "RW_RAW", 6))
279 else if (!strncmp(token, "AUDIO", 5)) {
280 ti[numtracks].type = CDDA;
283 else if (!strcmp(token, "DATAFILE")) {
284 if (ti[numtracks].type == CDDA) {
285 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
286 ti[numtracks].start_offset = t;
287 t = t / sector_size + sector_offs;
288 sec2msf(t, (char *)&ti[numtracks].start);
289 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
292 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
293 tok2msf((char *)&time, (char *)&ti[numtracks].length);
296 else if (!strcmp(token, "FILE")) {
297 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
298 tok2msf((char *)&time, (char *)&ti[numtracks].start);
299 t += msf2sec(ti[numtracks].start) * sector_size;
300 ti[numtracks].start_offset = t;
301 t = t / sector_size + sector_offs;
302 sec2msf(t, (char *)&ti[numtracks].start);
303 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
305 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
306 // skip unneeded optional fields
307 while (token != NULL) {
308 token = strtok(NULL, " ");
309 if (strchr(token, ':') != NULL)
314 current_zero_gap = msf2sec(tmp);
317 t = ti[numtracks - 1].start_offset;
319 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
322 else if (!strcmp(token, "START")) {
323 token = strtok(NULL, " ");
324 if (token != NULL && strchr(token, ':')) {
327 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
328 t = msf2sec(ti[numtracks].start) + t;
329 sec2msf(t, (char *)&ti[numtracks].start);
339 // this function tries to get the .cue file of the given .bin
340 // the necessary data is put into the ti (trackinformation)-array
341 static int parsecue(const char *isofile) {
342 char cuename[MAXPATHLEN];
343 char filepath[MAXPATHLEN];
350 char linebuf[256], tmpb[256], dummy[256];
351 unsigned int incue_max_len;
352 unsigned int t, file_len, mode, sector_offs;
353 unsigned int sector_size = 2352;
357 // copy name of the iso and change extension from .bin to .cue
358 strncpy(cuename, isofile, sizeof(cuename));
359 cuename[MAXPATHLEN - 1] = '\0';
360 if (strlen(cuename) < 4)
362 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
363 // it's already open as cdHandle
367 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
368 // and don't try to search the additional .cue file
369 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
370 strcpy(cuename + strlen(cuename) - 4, ".cue");
372 if ((ftmp = fopen(cuename, "r")) == NULL)
377 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
378 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
380 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
381 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
382 // Don't proceed further, as this is actually a .toc file rather
386 return parsetoc(isofile);
391 // build a path for files referenced in .cue
392 strncpy(filepath, cuename, sizeof(filepath));
393 tmp = strrchr(filepath, '/');
395 tmp = strrchr(filepath, '\\');
401 filepath[sizeof(filepath) - 1] = 0;
403 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
405 memset(&ti, 0, sizeof(ti));
408 sector_offs = 2 * 75;
410 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
411 strncpy(dummy, linebuf, sizeof(linebuf));
412 token = strtok(dummy, " ");
418 if (!strcmp(token, "TRACK")) {
422 if (strstr(linebuf, "AUDIO") != NULL) {
423 ti[numtracks].type = CDDA;
426 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
427 ti[numtracks].type = DATA;
429 SysPrintf(".cue: failed to parse TRACK\n");
430 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
432 if (sector_size == 0)
435 else if (!strcmp(token, "INDEX")) {
436 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
437 SysPrintf(".cue: failed to parse INDEX\n");
438 tok2msf(time, (char *)&ti[numtracks].start);
440 t = msf2sec(ti[numtracks].start);
441 ti[numtracks].start_offset = t * sector_size;
443 sec2msf(t, ti[numtracks].start);
445 // default track length to file length
446 t = file_len - ti[numtracks].start_offset / sector_size;
447 sec2msf(t, ti[numtracks].length);
449 if (numtracks > 1 && ti[numtracks].handle == NULL) {
450 // this track uses the same file as the last,
451 // start of this track is last track's end
452 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
453 sec2msf(t, ti[numtracks - 1].length);
455 if (numtracks > 1 && pregapOffset == -1)
456 pregapOffset = ti[numtracks].start_offset / sector_size;
458 else if (!strcmp(token, "PREGAP")) {
459 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
460 tok2msf(time, dummy);
461 sector_offs += msf2sec(dummy);
463 pregapOffset = -1; // mark to fill track start_offset
465 else if (!strcmp(token, "FILE")) {
466 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
468 sscanf(linebuf, " FILE %255s", tmpb);
470 tmp = strrchr(tmpb, '\\');
472 tmp = strrchr(tmpb, '/');
477 strncpy(incue_fname, tmp, incue_max_len);
478 ti[numtracks + 1].handle = fopen(filepath, "rb");
480 // update global offset if this is not first file in this .cue
481 if (numtracks + 1 > 1) {
483 sector_offs += file_len;
487 if (ti[numtracks + 1].handle == NULL) {
488 SysPrintf(_("\ncould not open: %s\n"), filepath);
491 file_len = get_size(ti[numtracks + 1].handle) / 2352;
498 // if there are no tracks detected, then it's not a cue file
502 // the data track handle is always in cdHandle
505 cdHandle = ti[1].handle;
511 // this function tries to get the .ccd file of the given .img
512 // the necessary data is put into the ti (trackinformation)-array
513 static int parseccd(const char *isofile) {
514 char ccdname[MAXPATHLEN];
521 // copy name of the iso and change extension from .img to .ccd
522 strncpy(ccdname, isofile, sizeof(ccdname));
523 ccdname[MAXPATHLEN - 1] = '\0';
524 if (strlen(ccdname) >= 4) {
525 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
531 if ((fi = fopen(ccdname, "r")) == NULL) {
535 memset(&ti, 0, sizeof(ti));
537 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
538 if (!strncmp(linebuf, "[TRACK", 6)){
541 else if (!strncmp(linebuf, "MODE=", 5)) {
542 sscanf(linebuf, "MODE=%d", &t);
543 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
545 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
546 sscanf(linebuf, "INDEX 1=%d", &t);
547 sec2msf(t + 2 * 75, ti[numtracks].start);
548 ti[numtracks].start_offset = t * 2352;
550 // If we've already seen another track, this is its end
552 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
553 sec2msf(t, ti[numtracks - 1].length);
560 // Fill out the last track's end based on size
561 if (numtracks >= 1) {
562 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
563 sec2msf(t, ti[numtracks].length);
569 // this function tries to get the .mds file of the given .mdf
570 // the necessary data is put into the ti (trackinformation)-array
571 static int parsemds(const char *isofile) {
572 char mdsname[MAXPATHLEN];
574 unsigned int offset, extra_offset, l, i;
579 // copy name of the iso and change extension from .mdf to .mds
580 strncpy(mdsname, isofile, sizeof(mdsname));
581 mdsname[MAXPATHLEN - 1] = '\0';
582 if (strlen(mdsname) >= 4) {
583 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
589 if ((fi = fopen(mdsname, "rb")) == NULL) {
593 memset(&ti, 0, sizeof(ti));
595 // check if it's a valid mds file
596 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
599 if (i != 0x4944454D) {
600 // not an valid mds file
605 // get offset to session block
606 fseek(fi, 0x50, SEEK_SET);
607 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
609 offset = SWAP32(offset);
611 // get total number of tracks
613 fseek(fi, offset, SEEK_SET);
614 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
619 // get offset to track blocks
620 fseek(fi, 4, SEEK_CUR);
621 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
623 offset = SWAP32(offset);
627 fseek(fi, offset + 4, SEEK_SET);
628 if (fgetc(fi) < 0xA0) {
634 // check if the image contains mixed subchannel data
635 fseek(fi, offset + 1, SEEK_SET);
636 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
639 for (i = 1; i <= numtracks; i++) {
640 fseek(fi, offset, SEEK_SET);
642 // get the track type
643 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
644 fseek(fi, 8, SEEK_CUR);
646 // get the track starting point
647 ti[i].start[0] = fgetc(fi);
648 ti[i].start[1] = fgetc(fi);
649 ti[i].start[2] = fgetc(fi);
651 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
653 extra_offset = SWAP32(extra_offset);
655 // get track start offset (in .mdf)
656 fseek(fi, offset + 0x28, SEEK_SET);
657 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
660 ti[i].start_offset = l;
663 fseek(fi, extra_offset, SEEK_SET);
664 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
668 pregapOffset = msf2sec(ti[i].start);
670 // get the track length
671 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
674 sec2msf(l, ti[i].length);
682 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
688 static int handlepbp(const char *isofile) {
691 unsigned int dontcare[8];
692 unsigned int psar_offs;
705 unsigned int dontcare[6];
708 off_t psisoimg_offs, cdimg_base;
709 unsigned int t, cd_length;
710 unsigned int offsettab[8];
711 unsigned int psar_offs, index_entry_size, index_entry_offset;
712 const char *ext = NULL;
715 if (strlen(isofile) >= 4)
716 ext = isofile + strlen(isofile) - 4;
717 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
722 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
723 if (ret != sizeof(pbp_hdr)) {
724 SysPrintf("failed to read pbp\n");
728 psar_offs = SWAP32(pbp_hdr.psar_offs);
730 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
732 SysPrintf("failed to seek to %x\n", psar_offs);
736 psisoimg_offs = psar_offs;
737 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
740 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
742 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
744 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
748 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
749 SysPrintf("failed to read offsettab\n");
753 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
754 if (offsettab[i] == 0)
757 cdrIsoMultidiskCount = i;
758 if (cdrIsoMultidiskCount == 0) {
759 SysPrintf("multidisk eboot has 0 images?\n");
763 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
764 cdrIsoMultidiskSelect = 0;
766 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
768 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
770 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
774 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
779 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
780 SysPrintf("bad psar_sig: %s\n", psar_sig);
785 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
787 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
791 // first 3 entries are special
792 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
793 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
795 numtracks = btoi(toc_entry.index1[0]);
797 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
799 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
800 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
802 for (i = 1; i <= numtracks; i++) {
803 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
806 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
808 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
809 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
810 ti[i].start_offset *= 2352;
811 ti[i].start[0] = btoi(toc_entry.index1[0]);
812 ti[i].start[1] = btoi(toc_entry.index1[1]);
813 ti[i].start[2] = btoi(toc_entry.index1[2]);
816 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
817 sec2msf(t, ti[i - 1].length);
820 t = cd_length - ti[numtracks].start_offset / 2352;
821 sec2msf(t, ti[numtracks].length);
824 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
826 SysPrintf("failed to seek to ISO index\n");
830 compr_img = calloc(1, sizeof(*compr_img));
831 if (compr_img == NULL)
834 compr_img->block_shift = 4;
835 compr_img->current_block = (unsigned int)-1;
837 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
838 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
839 if (compr_img->index_table == NULL)
842 cdimg_base = psisoimg_offs + 0x100000;
843 for (i = 0; i < compr_img->index_len; i++) {
844 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
845 if (ret != sizeof(index_entry)) {
846 SysPrintf("failed to read index_entry #%d\n", i);
850 index_entry_size = SWAP32(index_entry.size);
851 index_entry_offset = SWAP32(index_entry.offset);
853 if (index_entry_size == 0)
856 compr_img->index_table[i] = cdimg_base + index_entry_offset;
858 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
863 free(compr_img->index_table);
864 compr_img->index_table = NULL;
868 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
872 if (compr_img != NULL) {
879 static int handlecbin(const char *isofile) {
883 unsigned int header_size;
884 unsigned long long total_bytes;
885 unsigned int block_size;
886 unsigned char ver; // 1
888 unsigned char rsv_06[2];
890 const char *ext = NULL;
891 unsigned int *index_table = NULL;
892 unsigned int index = 0, plain;
895 if (strlen(isofile) >= 5)
896 ext = isofile + strlen(isofile) - 5;
897 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
900 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
901 if (ret != sizeof(ciso_hdr)) {
902 SysPrintf("failed to read ciso header\n");
906 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
907 SysPrintf("bad ciso header\n");
910 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
911 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
913 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
918 compr_img = calloc(1, sizeof(*compr_img));
919 if (compr_img == NULL)
922 compr_img->block_shift = 0;
923 compr_img->current_block = (unsigned int)-1;
925 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
926 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
927 if (index_table == NULL)
930 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
931 if (ret != compr_img->index_len) {
932 SysPrintf("failed to read index table\n");
936 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
937 if (compr_img->index_table == NULL)
940 for (i = 0; i < compr_img->index_len + 1; i++) {
941 index = index_table[i];
942 plain = index & 0x80000000;
944 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
946 compr_img->index_table[i] |= OFF_T_MSB;
954 if (compr_img != NULL) {
963 static int handlechd(const char *isofile) {
964 int frame_offset = 150;
967 chd_img = calloc(1, sizeof(*chd_img));
971 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
974 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
977 chd_img->header = chd_get_header(chd_img->chd);
979 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
980 if (chd_img->buffer == NULL)
983 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
984 chd_img->current_hunk[0] = (unsigned int)-1;
985 chd_img->current_hunk[1] = (unsigned int)-1;
987 cddaBigEndian = TRUE;
990 memset(ti, 0, sizeof(ti));
1005 uint32_t meta_size = 0;
1007 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1008 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1009 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1010 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1014 SysPrintf("chd: %s\n", meta);
1016 if (md.track == 1) {
1017 if (!strncmp(md.subtype, "RW", 2)) {
1018 subChanMixed = TRUE;
1019 if (!strcmp(md.subtype, "RW_RAW"))
1024 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1026 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1027 sec2msf(md.frames, ti[md.track].length);
1029 ti[md.track].start_offset = file_offset + md.pregap;
1031 // XXX: what about postgap?
1032 frame_offset += md.frames;
1033 file_offset += md.frames;
1041 if (chd_img != NULL) {
1042 free(chd_img->buffer);
1050 // this function tries to get the .sub file of the given .img
1051 static int opensubfile(const char *isoname) {
1052 char subname[MAXPATHLEN];
1054 // copy name of the iso and change extension from .img to .sub
1055 strncpy(subname, isoname, sizeof(subname));
1056 subname[MAXPATHLEN - 1] = '\0';
1057 if (strlen(subname) >= 4) {
1058 strcpy(subname + strlen(subname) - 4, ".sub");
1064 subHandle = fopen(subname, "rb");
1065 if (subHandle == NULL) {
1072 static int opensbifile(const char *isoname) {
1073 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1076 strncpy(sbiname, isoname, sizeof(sbiname));
1077 sbiname[MAXPATHLEN - 1] = '\0';
1078 if (strlen(sbiname) >= 4) {
1079 if (cdrIsoMultidiskCount > 1) {
1080 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1081 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1084 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1090 s = msf2sec(ti[1].length);
1092 return LoadSBI(sbiname, s);
1095 #if !USE_READ_THREAD
1096 static void readThreadStop() {}
1097 static void readThreadStart() {}
1099 static pthread_t read_thread_id;
1101 static pthread_cond_t read_thread_msg_avail;
1102 static pthread_cond_t read_thread_msg_done;
1103 static pthread_mutex_t read_thread_msg_lock;
1105 static pthread_cond_t sectorbuffer_cond;
1106 static pthread_mutex_t sectorbuffer_lock;
1108 static boolean read_thread_running = FALSE;
1109 static int read_thread_sector_start = -1;
1110 static int read_thread_sector_end = -1;
1115 unsigned char data[CD_FRAMESIZE_RAW];
1116 } SectorBufferEntry;
1118 #define SECTOR_BUFFER_SIZE 4096
1120 static SectorBufferEntry *sectorbuffer;
1121 static size_t sectorbuffer_index;
1123 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1124 unsigned char *(*sync_CDR_getBuffer)(void);
1126 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1127 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1129 static void *readThreadMain(void *param) {
1130 int max_sector = -1;
1131 int requested_sector_start = -1;
1132 int requested_sector_end = -1;
1133 int last_read_sector = -1;
1139 int speedmult_ra = 4;
1142 int how_far_ahead = 0;
1144 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1147 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1150 pthread_mutex_lock(&read_thread_msg_lock);
1152 // If we don't have readahead and we don't have a sector request, wait for one.
1153 // If we still have readahead to go, don't block, just keep going.
1154 // And if we ever have a sector request pending, acknowledge and reset it.
1157 if (read_thread_sector_start == -1 && read_thread_running) {
1158 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1162 if (read_thread_sector_start != -1) {
1163 requested_sector_start = read_thread_sector_start;
1164 requested_sector_end = read_thread_sector_end;
1165 read_thread_sector_start = -1;
1166 read_thread_sector_end = -1;
1167 pthread_cond_signal(&read_thread_msg_done);
1170 pthread_mutex_unlock(&read_thread_msg_lock);
1172 if (!read_thread_running)
1175 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1176 if (requested_sector_start != -1) {
1177 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1178 how_far_ahead = ra_sector - requested_sector_end;
1180 if(how_far_ahead <= max_ra)
1181 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1184 } else if (requested_sector_end != last_read_sector) {
1185 ra_sector = requested_sector_end;
1186 ra_count = initial_ra;
1189 last_read_sector = requested_sector_end;
1192 index = ra_sector % SECTOR_BUFFER_SIZE;
1194 // check for end of CD
1195 if (ra_count && ra_sector >= max_sector) {
1197 pthread_mutex_lock(§orbuffer_lock);
1198 sectorbuffer[index].ret = -1;
1199 sectorbuffer[index].sector = ra_sector;
1200 pthread_cond_signal(§orbuffer_cond);
1201 pthread_mutex_unlock(§orbuffer_lock);
1205 pthread_mutex_lock(§orbuffer_lock);
1206 if (sectorbuffer[index].sector != ra_sector) {
1207 pthread_mutex_unlock(§orbuffer_lock);
1209 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1211 pthread_mutex_lock(§orbuffer_lock);
1212 sectorbuffer[index].ret = ret;
1213 sectorbuffer[index].sector = ra_sector;
1214 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1216 pthread_cond_signal(§orbuffer_cond);
1217 pthread_mutex_unlock(§orbuffer_lock);
1227 static void readThreadStop() {
1228 if (read_thread_running == TRUE) {
1229 read_thread_running = FALSE;
1230 pthread_cond_signal(&read_thread_msg_avail);
1231 pthread_join(read_thread_id, NULL);
1234 pthread_cond_destroy(&read_thread_msg_done);
1235 pthread_cond_destroy(&read_thread_msg_avail);
1236 pthread_mutex_destroy(&read_thread_msg_lock);
1238 pthread_cond_destroy(§orbuffer_cond);
1239 pthread_mutex_destroy(§orbuffer_lock);
1241 CDR_getBuffer = sync_CDR_getBuffer;
1242 cdimg_read_func = sync_cdimg_read_func;
1245 sectorbuffer = NULL;
1248 static void readThreadStart() {
1249 SysPrintf("Starting async CD thread\n");
1251 if (read_thread_running == TRUE)
1254 read_thread_running = TRUE;
1255 read_thread_sector_start = -1;
1256 read_thread_sector_end = -1;
1257 sectorbuffer_index = 0;
1259 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1263 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1265 sync_CDR_getBuffer = CDR_getBuffer;
1266 CDR_getBuffer = ISOgetBuffer_async;
1267 sync_cdimg_read_func = cdimg_read_func;
1268 cdimg_read_func = cdread_async;
1270 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1271 pthread_cond_init(&read_thread_msg_done, NULL) ||
1272 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1273 pthread_cond_init(§orbuffer_cond, NULL) ||
1274 pthread_mutex_init(§orbuffer_lock, NULL) ||
1275 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1281 SysPrintf("Error starting async CD thread\n");
1282 SysPrintf("Falling back to sync\n");
1288 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1293 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1295 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1301 // often happens in cdda gaps of a split cue/bin, so not logged
1302 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1306 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1312 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1314 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1320 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1324 static int cdread_sub_sub_mixed(FILE *f, int sector)
1328 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1330 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1333 return SUB_FRAMESIZE;
1336 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1340 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1345 if (z.zalloc == NULL) {
1346 // XXX: one-time leak here..
1352 ret = inflateInit2(&z, -15);
1355 ret = inflateReset(&z);
1360 z.avail_in = in_size;
1362 z.avail_out = *out_size;
1364 ret = inflate(&z, Z_NO_FLUSH);
1367 *out_size -= z.avail_out;
1368 return ret == 1 ? 0 : ret;
1371 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1373 unsigned long cdbuffer_size, cdbuffer_size_expect;
1382 sector += base / 2352;
1384 block = sector >> compr_img->block_shift;
1385 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1387 if (block == compr_img->current_block) {
1388 //printf("hit sect %d\n", sector);
1392 if (sector >= compr_img->index_len * 16) {
1393 SysPrintf("sector %d is past img end\n", sector);
1397 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1398 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1399 SysPrintf("seek error for block %d at %llx: ",
1400 block, (long long)start_byte);
1405 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1406 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1407 if (size > sizeof(compr_img->buff_compressed)) {
1408 SysPrintf("block %d is too large: %u\n", block, size);
1412 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1413 1, size, cdHandle) != size) {
1414 SysPrintf("read error for block %d at %x: ", block, start_byte);
1419 if (is_compressed) {
1420 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1421 cdbuffer_size = cdbuffer_size_expect;
1422 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1424 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1425 ret, block, sector);
1428 if (cdbuffer_size != cdbuffer_size_expect)
1429 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1430 cdbuffer_size_expect, sector);
1434 compr_img->current_block = block;
1437 if (dest != cdbuffer) // copy avoid HACK
1438 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1440 return CD_FRAMESIZE_RAW;
1444 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1446 return chd_img->buffer
1447 + current_buffer * chd_img->header->hunkbytes
1448 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1451 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1457 hunk = sector / chd_img->sectors_per_hunk;
1458 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1460 if (hunk == chd_img->current_hunk[0])
1461 chd_img->current_buffer = 0;
1462 else if (hunk == chd_img->current_hunk[1])
1463 chd_img->current_buffer = 1;
1466 chd_read(chd_img->chd, hunk, chd_img->buffer +
1467 chd_img->current_buffer * chd_img->header->hunkbytes);
1468 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1471 if (dest != cdbuffer) // copy avoid HACK
1472 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1474 return CD_FRAMESIZE_RAW;
1477 static int cdread_sub_chd(FILE *f, int sector)
1479 unsigned int sector_in_hunk;
1480 unsigned int buffer;
1486 hunk = sector / chd_img->sectors_per_hunk;
1487 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1489 if (hunk == chd_img->current_hunk[0])
1491 else if (hunk == chd_img->current_hunk[1])
1495 buffer = chd_img->current_buffer ^ 1;
1496 chd_read(chd_img->chd, hunk, chd_img->buffer +
1497 buffer * chd_img->header->hunkbytes);
1498 chd_img->current_hunk[buffer] = hunk;
1501 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1502 return SUB_FRAMESIZE;
1506 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1512 fseeko(f, base + sector * 2048, SEEK_SET);
1513 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1515 // not really necessary, fake mode 2 header
1516 memset(cdbuffer, 0, 12 * 2);
1517 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1518 cdbuffer[12 + 3] = 1;
1525 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1526 boolean found = FALSE;
1527 int i = sector % SECTOR_BUFFER_SIZE;
1530 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1531 // Async reads are only supported for cdbuffer, so call the sync
1532 // function directly.
1533 return sync_cdimg_read_func(f, base, dest, sector);
1536 pthread_mutex_lock(&read_thread_msg_lock);
1538 // Only wait if we're not trying to read the next sector and
1539 // sector_start is set (meaning the last request hasn't been
1541 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1542 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1545 if (read_thread_sector_start == -1)
1546 read_thread_sector_start = sector;
1548 read_thread_sector_end = sector;
1549 pthread_cond_signal(&read_thread_msg_avail);
1550 pthread_mutex_unlock(&read_thread_msg_lock);
1553 pthread_mutex_lock(§orbuffer_lock);
1554 if (sectorbuffer[i].sector == sector) {
1555 sectorbuffer_index = i;
1556 ret = sectorbuffer[i].ret;
1561 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1563 pthread_mutex_unlock(§orbuffer_lock);
1571 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1572 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1576 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1577 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1582 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1583 unsigned char *buffer;
1584 pthread_mutex_lock(§orbuffer_lock);
1585 buffer = sectorbuffer[sectorbuffer_index].data;
1586 pthread_mutex_unlock(§orbuffer_lock);
1591 unsigned char * CALLBACK ISOgetBuffer(void) {
1592 return cdbuffer + 12;
1595 static void PrintTracks(void) {
1598 for (i = 1; i <= numtracks; i++) {
1599 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1600 i, (ti[i].type == DATA ? "DATA" :
1601 (ti[i].type == CDDA ? "AUDIO" : "UNKNOWN")),
1602 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1603 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1607 // This function is invoked by the front-end when opening an ISO
1608 // file for playback
1609 static long CALLBACK ISOopen(void) {
1610 boolean isMode1ISO = FALSE;
1611 char alt_bin_filename[MAXPATHLEN];
1612 const char *bin_filename;
1613 char image_str[1024];
1616 if (cdHandle || chd_img) {
1617 return 0; // it's already open
1620 cdHandle = fopen(GetIsoFile(), "rb");
1621 if (cdHandle == NULL) {
1622 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1623 GetIsoFile(), strerror(errno));
1626 size_main = get_size(cdHandle);
1628 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1629 "Loaded CD Image: %s", GetIsoFile());
1631 cddaBigEndian = FALSE;
1632 subChanMixed = FALSE;
1635 cdrIsoMultidiskCount = 1;
1638 CDR_getBuffer = ISOgetBuffer;
1639 cdimg_read_func = cdread_normal;
1640 cdimg_read_sub_func = NULL;
1642 if (parsetoc(GetIsoFile()) == 0) {
1643 strcat(image_str, "[+toc]");
1645 else if (parseccd(GetIsoFile()) == 0) {
1646 strcat(image_str, "[+ccd]");
1648 else if (parsemds(GetIsoFile()) == 0) {
1649 strcat(image_str, "[+mds]");
1651 else if (parsecue(GetIsoFile()) == 0) {
1652 strcat(image_str, "[+cue]");
1654 if (handlepbp(GetIsoFile()) == 0) {
1655 strcat(image_str, "[+pbp]");
1656 CDR_getBuffer = ISOgetBuffer_compr;
1657 cdimg_read_func = cdread_compressed;
1659 else if (handlecbin(GetIsoFile()) == 0) {
1660 strcat(image_str, "[+cbin]");
1661 CDR_getBuffer = ISOgetBuffer_compr;
1662 cdimg_read_func = cdread_compressed;
1665 else if (handlechd(GetIsoFile()) == 0) {
1666 strcat(image_str, "[+chd]");
1667 CDR_getBuffer = ISOgetBuffer_chd;
1668 cdimg_read_func = cdread_chd;
1669 cdimg_read_sub_func = cdread_sub_chd;
1675 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1676 strcat(image_str, "[+sub]");
1678 if (opensbifile(GetIsoFile()) == 0) {
1679 strcat(image_str, "[+sbi]");
1682 // maybe user selected metadata file instead of main .bin ..
1683 bin_filename = GetIsoFile();
1684 if (cdHandle && size_main < 2352 * 0x10) {
1685 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1690 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1691 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1692 if (strlen(alt_bin_filename) >= 4) {
1693 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1694 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1696 tmpf = fopen(alt_bin_filename, "rb");
1702 bin_filename = alt_bin_filename;
1705 size_main = get_size(cdHandle);
1709 // guess whether it is mode1/2048
1710 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1711 unsigned int modeTest = 0;
1712 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1713 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1715 if (SWAP32(modeTest) != 0xffffff00) {
1716 strcat(image_str, "[2048]");
1721 SysPrintf("%s.\n", image_str);
1725 if (subChanMixed && cdimg_read_func == cdread_normal) {
1726 cdimg_read_func = cdread_sub_mixed;
1727 cdimg_read_sub_func = cdread_sub_sub_mixed;
1729 else if (isMode1ISO) {
1730 cdimg_read_func = cdread_2048;
1731 cdimg_read_sub_func = NULL;
1734 if (Config.AsyncCD) {
1740 static long CALLBACK ISOclose(void) {
1743 if (cdHandle != NULL) {
1747 if (subHandle != NULL) {
1753 if (compr_img != NULL) {
1754 free(compr_img->index_table);
1760 if (chd_img != NULL) {
1761 chd_close(chd_img->chd);
1762 free(chd_img->buffer);
1768 for (i = 1; i <= numtracks; i++) {
1769 if (ti[i].handle != NULL) {
1770 fclose(ti[i].handle);
1771 ti[i].handle = NULL;
1778 memset(cdbuffer, 0, sizeof(cdbuffer));
1779 CDR_getBuffer = ISOgetBuffer;
1781 if (Config.AsyncCD) {
1788 static long CALLBACK ISOinit(void) {
1789 assert(cdHandle == NULL);
1790 assert(subHandle == NULL);
1792 return 0; // do nothing
1795 static long CALLBACK ISOshutdown(void) {
1800 // return Starting and Ending Track
1802 // byte 0 - start track
1803 // byte 1 - end track
1804 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1807 if (numtracks > 0) {
1808 buffer[1] = numtracks;
1817 // return Track Time
1822 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1825 unsigned char time[3];
1826 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1827 sec2msf(sect, (char *)time);
1828 buffer[2] = time[0];
1829 buffer[1] = time[1];
1830 buffer[0] = time[2];
1832 else if (numtracks > 0 && track <= numtracks) {
1833 buffer[2] = ti[track].start[0];
1834 buffer[1] = ti[track].start[1];
1835 buffer[0] = ti[track].start[2];
1846 // decode 'raw' subchannel data ripped by cdrdao
1847 static void DecodeRawSubData(void) {
1848 unsigned char subQData[12];
1851 memset(subQData, 0, sizeof(subQData));
1853 for (i = 0; i < 8 * 12; i++) {
1854 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1855 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1859 memcpy(&subbuffer[12], subQData, 12);
1863 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1865 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1866 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1869 if (!cdHandle && !chd_img)
1872 if (pregapOffset && sector >= pregapOffset)
1875 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1876 if (ret < 12*2 + 2048)
1883 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1884 // does NOT uses bcd format
1885 static long CALLBACK ISOplay(unsigned char *time) {
1890 static long CALLBACK ISOstop(void) {
1894 // gets subchannel data
1895 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1896 if (pregapOffset && sector >= pregapOffset) {
1898 if (sector < pregapOffset) // ?
1902 if (cdimg_read_sub_func != NULL) {
1903 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1906 else if (subHandle != NULL) {
1907 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1909 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1916 if (subChanRaw) DecodeRawSubData();
1920 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1921 CDR__getStatus(stat);
1923 // BIOS - boot ID (CD type)
1924 stat->Type = ti[1].type;
1929 // read CDDA sector into buffer
1930 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1931 unsigned char msf[3] = {m, s, f};
1932 unsigned int track, track_start = 0;
1933 FILE *handle = cdHandle;
1934 unsigned int cddaCurPos;
1937 cddaCurPos = msf2sec((char *)msf);
1939 // find current track index
1940 for (track = numtracks; ; track--) {
1941 track_start = msf2sec(ti[track].start);
1942 if (track_start <= cddaCurPos)
1948 // data tracks play silent
1949 if (ti[track].type != CDDA) {
1950 memset(buffer, 0, CD_FRAMESIZE_RAW);
1955 // find the file that contains this track
1957 for (file = track; file > 1; file--) {
1958 if (ti[file].handle != NULL) {
1959 handle = ti[file].handle;
1964 if (!handle && !chd_img) {
1965 memset(buffer, 0, CD_FRAMESIZE_RAW);
1969 ret = cdimg_read_func(handle, ti[track].start_offset,
1970 buffer, cddaCurPos - track_start);
1971 if (ret != CD_FRAMESIZE_RAW) {
1972 memset(buffer, 0, CD_FRAMESIZE_RAW);
1976 if (cddaBigEndian) {
1980 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1981 tmp = buffer[i * 2];
1982 buffer[i * 2] = buffer[i * 2 + 1];
1983 buffer[i * 2 + 1] = tmp;
1990 void cdrIsoInit(void) {
1992 CDR_shutdown = ISOshutdown;
1994 CDR_close = ISOclose;
1995 CDR_getTN = ISOgetTN;
1996 CDR_getTD = ISOgetTD;
1997 CDR_readTrack = ISOreadTrack;
1998 CDR_getBuffer = ISOgetBuffer;
2001 CDR_getBufferSub = ISOgetBufferSub;
2002 CDR_getStatus = ISOgetStatus;
2003 CDR_readCDDA = ISOreadCDDA;
2005 CDR_getDriveLetter = CDR__getDriveLetter;
2006 CDR_configure = CDR__configure;
2007 CDR_test = CDR__test;
2008 CDR_about = CDR__about;
2009 CDR_setfilename = CDR__setfilename;
2010 CDR_prefetch = CDR__prefetch;
2015 int cdrIsoActive(void) {
2016 return (cdHandle || chd_img);