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 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 playing = FALSE;
79 static boolean cddaBigEndian = FALSE;
80 /* Frame offset into CD image where pregap data would be found if it was there.
81 * If a game seeks there we must *not* return subchannel data since it's
82 * not in the CD image, so that cdrom code can fake subchannel data instead.
83 * XXX: there could be multiple pregaps but PSX dumps only have one? */
84 static unsigned int pregapOffset;
86 static unsigned int cddaCurPos;
88 // compressed image stuff
90 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
91 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
93 unsigned int index_len;
94 unsigned int block_shift;
95 unsigned int current_block;
96 unsigned int sector_in_blk;
101 unsigned char *buffer;
103 const chd_header* header;
104 unsigned int sectors_per_hunk;
105 unsigned int current_hunk[2];
106 unsigned int current_buffer;
107 unsigned int sector_in_hunk;
113 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
114 static int (*cdimg_read_sub_func)(FILE *f, int sector);
116 char* CALLBACK CDR__getDriveLetter(void);
117 long CALLBACK CDR__configure(void);
118 long CALLBACK CDR__test(void);
119 void CALLBACK CDR__about(void);
120 long CALLBACK CDR__setfilename(char *filename);
122 static void DecodeRawSubData(void);
125 enum {DATA=1, CDDA} type;
126 char start[3]; // MSF-format
127 char length[3]; // MSF-format
128 FILE *handle; // for multi-track images CDDA
129 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
132 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
134 static int numtracks = 0;
135 static struct trackinfo ti[MAXTRACKS];
137 // get a sector from a msf-array
138 static unsigned int msf2sec(char *msf) {
139 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
142 static void sec2msf(unsigned int s, char *msf) {
143 msf[0] = s / 75 / 60;
144 s = s - msf[0] * 75 * 60;
150 // divide a string of xx:yy:zz into m, s, f
151 static void tok2msf(char *time, char *msf) {
154 token = strtok(time, ":");
156 msf[0] = atoi(token);
162 token = strtok(NULL, ":");
164 msf[1] = atoi(token);
170 token = strtok(NULL, ":");
172 msf[2] = atoi(token);
179 static off_t get_size(FILE *f)
182 #if !defined(USE_LIBRETRO_VFS)
184 if (fstat(fileno(f), &st) == 0)
188 fseeko(f, 0, SEEK_END);
190 fseeko(f, old, SEEK_SET);
194 // this function tries to get the .toc file of the given .bin
195 // the necessary data is put into the ti (trackinformation)-array
196 static int parsetoc(const char *isofile) {
197 char tocname[MAXPATHLEN];
199 char linebuf[256], tmp[256], name[256];
201 char time[20], time2[20];
202 unsigned int t, sector_offs, sector_size;
203 unsigned int current_zero_gap = 0;
207 // copy name of the iso and change extension from .bin to .toc
208 strncpy(tocname, isofile, sizeof(tocname));
209 tocname[MAXPATHLEN - 1] = '\0';
210 if (strlen(tocname) >= 4) {
211 strcpy(tocname + strlen(tocname) - 4, ".toc");
217 if ((fi = fopen(tocname, "r")) == NULL) {
218 // try changing extension to .cue (to satisfy some stupid tutorials)
219 strcpy(tocname + strlen(tocname) - 4, ".cue");
220 if ((fi = fopen(tocname, "r")) == NULL) {
221 // if filename is image.toc.bin, try removing .bin (for Brasero)
222 strcpy(tocname, isofile);
224 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
225 tocname[t - 4] = '\0';
226 if ((fi = fopen(tocname, "r")) == NULL) {
234 // check if it's really a TOC named as a .cue
235 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
236 token = strtok(linebuf, " ");
237 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
242 fseek(fi, 0, SEEK_SET);
245 memset(&ti, 0, sizeof(ti));
246 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
248 sector_size = CD_FRAMESIZE_RAW;
249 sector_offs = 2 * 75;
251 // parse the .toc file
252 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
254 strncpy(tmp, linebuf, sizeof(linebuf));
255 token = strtok(tmp, " ");
257 if (token == NULL) continue;
259 if (!strcmp(token, "TRACK")) {
260 sector_offs += current_zero_gap;
261 current_zero_gap = 0;
264 token = strtok(NULL, " ");
267 if (!strncmp(token, "MODE2_RAW", 9)) {
268 ti[numtracks].type = DATA;
269 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
271 // check if this image contains mixed subchannel data
272 token = strtok(NULL, " ");
273 if (token != NULL && !strncmp(token, "RW", 2)) {
274 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
276 if (!strncmp(token, "RW_RAW", 6))
280 else if (!strncmp(token, "AUDIO", 5)) {
281 ti[numtracks].type = CDDA;
284 else if (!strcmp(token, "DATAFILE")) {
285 if (ti[numtracks].type == CDDA) {
286 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
287 ti[numtracks].start_offset = t;
288 t = t / sector_size + sector_offs;
289 sec2msf(t, (char *)&ti[numtracks].start);
290 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
293 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
294 tok2msf((char *)&time, (char *)&ti[numtracks].length);
297 else if (!strcmp(token, "FILE")) {
298 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
299 tok2msf((char *)&time, (char *)&ti[numtracks].start);
300 t += msf2sec(ti[numtracks].start) * sector_size;
301 ti[numtracks].start_offset = t;
302 t = t / sector_size + sector_offs;
303 sec2msf(t, (char *)&ti[numtracks].start);
304 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
306 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
307 // skip unneeded optional fields
308 while (token != NULL) {
309 token = strtok(NULL, " ");
310 if (strchr(token, ':') != NULL)
315 current_zero_gap = msf2sec(tmp);
318 t = ti[numtracks - 1].start_offset;
320 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
323 else if (!strcmp(token, "START")) {
324 token = strtok(NULL, " ");
325 if (token != NULL && strchr(token, ':')) {
328 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
329 t = msf2sec(ti[numtracks].start) + t;
330 sec2msf(t, (char *)&ti[numtracks].start);
340 // this function tries to get the .cue file of the given .bin
341 // the necessary data is put into the ti (trackinformation)-array
342 static int parsecue(const char *isofile) {
343 char cuename[MAXPATHLEN];
344 char filepath[MAXPATHLEN];
351 char linebuf[256], tmpb[256], dummy[256];
352 unsigned int incue_max_len;
353 unsigned int t, file_len, mode, sector_offs;
354 unsigned int sector_size = 2352;
358 // copy name of the iso and change extension from .bin to .cue
359 strncpy(cuename, isofile, sizeof(cuename));
360 cuename[MAXPATHLEN - 1] = '\0';
361 if (strlen(cuename) < 4)
363 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
364 // it's already open as cdHandle
368 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
369 // and don't try to search the additional .cue file
370 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
371 strcpy(cuename + strlen(cuename) - 4, ".cue");
373 if ((ftmp = fopen(cuename, "r")) == NULL)
378 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
379 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
381 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
382 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
383 // Don't proceed further, as this is actually a .toc file rather
387 return parsetoc(isofile);
392 // build a path for files referenced in .cue
393 strncpy(filepath, cuename, sizeof(filepath));
394 tmp = strrchr(filepath, '/');
396 tmp = strrchr(filepath, '\\');
402 filepath[sizeof(filepath) - 1] = 0;
404 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
406 memset(&ti, 0, sizeof(ti));
409 sector_offs = 2 * 75;
411 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
412 strncpy(dummy, linebuf, sizeof(linebuf));
413 token = strtok(dummy, " ");
419 if (!strcmp(token, "TRACK")) {
423 if (strstr(linebuf, "AUDIO") != NULL) {
424 ti[numtracks].type = CDDA;
427 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
428 ti[numtracks].type = DATA;
430 SysPrintf(".cue: failed to parse TRACK\n");
431 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
433 if (sector_size == 0)
436 else if (!strcmp(token, "INDEX")) {
437 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
438 SysPrintf(".cue: failed to parse INDEX\n");
439 tok2msf(time, (char *)&ti[numtracks].start);
441 t = msf2sec(ti[numtracks].start);
442 ti[numtracks].start_offset = t * sector_size;
444 sec2msf(t, ti[numtracks].start);
446 // default track length to file length
447 t = file_len - ti[numtracks].start_offset / sector_size;
448 sec2msf(t, ti[numtracks].length);
450 if (numtracks > 1 && ti[numtracks].handle == NULL) {
451 // this track uses the same file as the last,
452 // start of this track is last track's end
453 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
454 sec2msf(t, ti[numtracks - 1].length);
456 if (numtracks > 1 && pregapOffset == -1)
457 pregapOffset = ti[numtracks].start_offset / sector_size;
459 else if (!strcmp(token, "PREGAP")) {
460 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
461 tok2msf(time, dummy);
462 sector_offs += msf2sec(dummy);
464 pregapOffset = -1; // mark to fill track start_offset
466 else if (!strcmp(token, "FILE")) {
467 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
469 sscanf(linebuf, " FILE %255s", tmpb);
471 tmp = strrchr(tmpb, '\\');
473 tmp = strrchr(tmpb, '/');
478 strncpy(incue_fname, tmp, incue_max_len);
479 ti[numtracks + 1].handle = fopen(filepath, "rb");
481 // update global offset if this is not first file in this .cue
482 if (numtracks + 1 > 1) {
484 sector_offs += file_len;
488 if (ti[numtracks + 1].handle == NULL) {
489 SysPrintf(_("\ncould not open: %s\n"), filepath);
492 file_len = get_size(ti[numtracks + 1].handle) / 2352;
499 // if there are no tracks detected, then it's not a cue file
503 // the data track handle is always in cdHandle
506 cdHandle = ti[1].handle;
512 // this function tries to get the .ccd file of the given .img
513 // the necessary data is put into the ti (trackinformation)-array
514 static int parseccd(const char *isofile) {
515 char ccdname[MAXPATHLEN];
522 // copy name of the iso and change extension from .img to .ccd
523 strncpy(ccdname, isofile, sizeof(ccdname));
524 ccdname[MAXPATHLEN - 1] = '\0';
525 if (strlen(ccdname) >= 4) {
526 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
532 if ((fi = fopen(ccdname, "r")) == NULL) {
536 memset(&ti, 0, sizeof(ti));
538 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
539 if (!strncmp(linebuf, "[TRACK", 6)){
542 else if (!strncmp(linebuf, "MODE=", 5)) {
543 sscanf(linebuf, "MODE=%d", &t);
544 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
546 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
547 sscanf(linebuf, "INDEX 1=%d", &t);
548 sec2msf(t + 2 * 75, ti[numtracks].start);
549 ti[numtracks].start_offset = t * 2352;
551 // If we've already seen another track, this is its end
553 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
554 sec2msf(t, ti[numtracks - 1].length);
561 // Fill out the last track's end based on size
562 if (numtracks >= 1) {
563 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
564 sec2msf(t, ti[numtracks].length);
570 // this function tries to get the .mds file of the given .mdf
571 // the necessary data is put into the ti (trackinformation)-array
572 static int parsemds(const char *isofile) {
573 char mdsname[MAXPATHLEN];
575 unsigned int offset, extra_offset, l, i;
580 // copy name of the iso and change extension from .mdf to .mds
581 strncpy(mdsname, isofile, sizeof(mdsname));
582 mdsname[MAXPATHLEN - 1] = '\0';
583 if (strlen(mdsname) >= 4) {
584 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
590 if ((fi = fopen(mdsname, "rb")) == NULL) {
594 memset(&ti, 0, sizeof(ti));
596 // check if it's a valid mds file
597 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
600 if (i != 0x4944454D) {
601 // not an valid mds file
606 // get offset to session block
607 fseek(fi, 0x50, SEEK_SET);
608 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
610 offset = SWAP32(offset);
612 // get total number of tracks
614 fseek(fi, offset, SEEK_SET);
615 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
620 // get offset to track blocks
621 fseek(fi, 4, SEEK_CUR);
622 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
624 offset = SWAP32(offset);
628 fseek(fi, offset + 4, SEEK_SET);
629 if (fgetc(fi) < 0xA0) {
635 // check if the image contains mixed subchannel data
636 fseek(fi, offset + 1, SEEK_SET);
637 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
640 for (i = 1; i <= numtracks; i++) {
641 fseek(fi, offset, SEEK_SET);
643 // get the track type
644 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
645 fseek(fi, 8, SEEK_CUR);
647 // get the track starting point
648 ti[i].start[0] = fgetc(fi);
649 ti[i].start[1] = fgetc(fi);
650 ti[i].start[2] = fgetc(fi);
652 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
654 extra_offset = SWAP32(extra_offset);
656 // get track start offset (in .mdf)
657 fseek(fi, offset + 0x28, SEEK_SET);
658 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
661 ti[i].start_offset = l;
664 fseek(fi, extra_offset, SEEK_SET);
665 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
669 pregapOffset = msf2sec(ti[i].start);
671 // get the track length
672 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
675 sec2msf(l, ti[i].length);
683 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
689 static int handlepbp(const char *isofile) {
692 unsigned int dontcare[8];
693 unsigned int psar_offs;
706 unsigned int dontcare[6];
709 off_t psisoimg_offs, cdimg_base;
710 unsigned int t, cd_length;
711 unsigned int offsettab[8];
712 unsigned int psar_offs, index_entry_size, index_entry_offset;
713 const char *ext = NULL;
716 if (strlen(isofile) >= 4)
717 ext = isofile + strlen(isofile) - 4;
718 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
723 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
724 if (ret != sizeof(pbp_hdr)) {
725 SysPrintf("failed to read pbp\n");
729 psar_offs = SWAP32(pbp_hdr.psar_offs);
731 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
733 SysPrintf("failed to seek to %x\n", psar_offs);
737 psisoimg_offs = psar_offs;
738 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
741 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
743 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
745 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
749 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
750 SysPrintf("failed to read offsettab\n");
754 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
755 if (offsettab[i] == 0)
758 cdrIsoMultidiskCount = i;
759 if (cdrIsoMultidiskCount == 0) {
760 SysPrintf("multidisk eboot has 0 images?\n");
764 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
765 cdrIsoMultidiskSelect = 0;
767 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
769 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
771 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
775 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
780 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
781 SysPrintf("bad psar_sig: %s\n", psar_sig);
786 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
788 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
792 // first 3 entries are special
793 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
794 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
796 numtracks = btoi(toc_entry.index1[0]);
798 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
800 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
801 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
803 for (i = 1; i <= numtracks; i++) {
804 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
807 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
809 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
810 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
811 ti[i].start_offset *= 2352;
812 ti[i].start[0] = btoi(toc_entry.index1[0]);
813 ti[i].start[1] = btoi(toc_entry.index1[1]);
814 ti[i].start[2] = btoi(toc_entry.index1[2]);
817 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
818 sec2msf(t, ti[i - 1].length);
821 t = cd_length - ti[numtracks].start_offset / 2352;
822 sec2msf(t, ti[numtracks].length);
825 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
827 SysPrintf("failed to seek to ISO index\n");
831 compr_img = calloc(1, sizeof(*compr_img));
832 if (compr_img == NULL)
835 compr_img->block_shift = 4;
836 compr_img->current_block = (unsigned int)-1;
838 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
839 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
840 if (compr_img->index_table == NULL)
843 cdimg_base = psisoimg_offs + 0x100000;
844 for (i = 0; i < compr_img->index_len; i++) {
845 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
846 if (ret != sizeof(index_entry)) {
847 SysPrintf("failed to read index_entry #%d\n", i);
851 index_entry_size = SWAP32(index_entry.size);
852 index_entry_offset = SWAP32(index_entry.offset);
854 if (index_entry_size == 0)
857 compr_img->index_table[i] = cdimg_base + index_entry_offset;
859 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
864 free(compr_img->index_table);
865 compr_img->index_table = NULL;
869 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
873 if (compr_img != NULL) {
880 static int handlecbin(const char *isofile) {
884 unsigned int header_size;
885 unsigned long long total_bytes;
886 unsigned int block_size;
887 unsigned char ver; // 1
889 unsigned char rsv_06[2];
891 const char *ext = NULL;
892 unsigned int *index_table = NULL;
893 unsigned int index = 0, plain;
896 if (strlen(isofile) >= 5)
897 ext = isofile + strlen(isofile) - 5;
898 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
901 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
902 if (ret != sizeof(ciso_hdr)) {
903 SysPrintf("failed to read ciso header\n");
907 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
908 SysPrintf("bad ciso header\n");
911 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
912 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
914 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
919 compr_img = calloc(1, sizeof(*compr_img));
920 if (compr_img == NULL)
923 compr_img->block_shift = 0;
924 compr_img->current_block = (unsigned int)-1;
926 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
927 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
928 if (index_table == NULL)
931 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
932 if (ret != compr_img->index_len) {
933 SysPrintf("failed to read index table\n");
937 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
938 if (compr_img->index_table == NULL)
941 for (i = 0; i < compr_img->index_len + 1; i++) {
942 index = index_table[i];
943 plain = index & 0x80000000;
945 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
947 compr_img->index_table[i] |= OFF_T_MSB;
955 if (compr_img != NULL) {
964 static int handlechd(const char *isofile) {
965 int frame_offset = 150;
968 chd_img = calloc(1, sizeof(*chd_img));
972 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
975 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
978 chd_img->header = chd_get_header(chd_img->chd);
980 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
981 if (chd_img->buffer == NULL)
984 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
985 chd_img->current_hunk[0] = (unsigned int)-1;
986 chd_img->current_hunk[1] = (unsigned int)-1;
988 cddaBigEndian = TRUE;
991 memset(ti, 0, sizeof(ti));
1006 uint32_t meta_size = 0;
1008 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1009 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1010 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1011 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1015 SysPrintf("chd: %s\n", meta);
1017 if (md.track == 1) {
1018 if (!strncmp(md.subtype, "RW", 2)) {
1019 subChanMixed = TRUE;
1020 if (!strcmp(md.subtype, "RW_RAW"))
1025 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1027 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1028 sec2msf(md.frames, ti[md.track].length);
1030 ti[md.track].start_offset = file_offset + md.pregap;
1032 // XXX: what about postgap?
1033 frame_offset += md.frames;
1034 file_offset += md.frames;
1042 if (chd_img != NULL) {
1043 free(chd_img->buffer);
1051 // this function tries to get the .sub file of the given .img
1052 static int opensubfile(const char *isoname) {
1053 char subname[MAXPATHLEN];
1055 // copy name of the iso and change extension from .img to .sub
1056 strncpy(subname, isoname, sizeof(subname));
1057 subname[MAXPATHLEN - 1] = '\0';
1058 if (strlen(subname) >= 4) {
1059 strcpy(subname + strlen(subname) - 4, ".sub");
1065 subHandle = fopen(subname, "rb");
1066 if (subHandle == NULL) {
1073 static int opensbifile(const char *isoname) {
1074 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1077 strncpy(sbiname, isoname, sizeof(sbiname));
1078 sbiname[MAXPATHLEN - 1] = '\0';
1079 if (strlen(sbiname) >= 4) {
1080 if (cdrIsoMultidiskCount > 1) {
1081 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1082 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1085 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1091 s = msf2sec(ti[1].length);
1093 return LoadSBI(sbiname, s);
1096 #if !USE_READ_THREAD
1097 static void readThreadStop() {}
1098 static void readThreadStart() {}
1100 static pthread_t read_thread_id;
1102 static pthread_cond_t read_thread_msg_avail;
1103 static pthread_cond_t read_thread_msg_done;
1104 static pthread_mutex_t read_thread_msg_lock;
1106 static pthread_cond_t sectorbuffer_cond;
1107 static pthread_mutex_t sectorbuffer_lock;
1109 static boolean read_thread_running = FALSE;
1110 static int read_thread_sector_start = -1;
1111 static int read_thread_sector_end = -1;
1116 unsigned char data[CD_FRAMESIZE_RAW];
1117 } SectorBufferEntry;
1119 #define SECTOR_BUFFER_SIZE 4096
1121 static SectorBufferEntry *sectorbuffer;
1122 static size_t sectorbuffer_index;
1124 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1125 unsigned char *(*sync_CDR_getBuffer)(void);
1127 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1128 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1130 static void *readThreadMain(void *param) {
1131 int max_sector = -1;
1132 int requested_sector_start = -1;
1133 int requested_sector_end = -1;
1134 int last_read_sector = -1;
1140 int speedmult_ra = 4;
1143 int how_far_ahead = 0;
1145 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1148 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1151 pthread_mutex_lock(&read_thread_msg_lock);
1153 // If we don't have readahead and we don't have a sector request, wait for one.
1154 // If we still have readahead to go, don't block, just keep going.
1155 // And if we ever have a sector request pending, acknowledge and reset it.
1158 if (read_thread_sector_start == -1 && read_thread_running) {
1159 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1163 if (read_thread_sector_start != -1) {
1164 requested_sector_start = read_thread_sector_start;
1165 requested_sector_end = read_thread_sector_end;
1166 read_thread_sector_start = -1;
1167 read_thread_sector_end = -1;
1168 pthread_cond_signal(&read_thread_msg_done);
1171 pthread_mutex_unlock(&read_thread_msg_lock);
1173 if (!read_thread_running)
1176 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1177 if (requested_sector_start != -1) {
1178 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1179 how_far_ahead = ra_sector - requested_sector_end;
1181 if(how_far_ahead <= max_ra)
1182 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1185 } else if (requested_sector_end != last_read_sector) {
1186 ra_sector = requested_sector_end;
1187 ra_count = initial_ra;
1190 last_read_sector = requested_sector_end;
1193 index = ra_sector % SECTOR_BUFFER_SIZE;
1195 // check for end of CD
1196 if (ra_count && ra_sector >= max_sector) {
1198 pthread_mutex_lock(§orbuffer_lock);
1199 sectorbuffer[index].ret = -1;
1200 sectorbuffer[index].sector = ra_sector;
1201 pthread_cond_signal(§orbuffer_cond);
1202 pthread_mutex_unlock(§orbuffer_lock);
1206 pthread_mutex_lock(§orbuffer_lock);
1207 if (sectorbuffer[index].sector != ra_sector) {
1208 pthread_mutex_unlock(§orbuffer_lock);
1210 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1212 pthread_mutex_lock(§orbuffer_lock);
1213 sectorbuffer[index].ret = ret;
1214 sectorbuffer[index].sector = ra_sector;
1215 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1217 pthread_cond_signal(§orbuffer_cond);
1218 pthread_mutex_unlock(§orbuffer_lock);
1228 static void readThreadStop() {
1229 if (read_thread_running == TRUE) {
1230 read_thread_running = FALSE;
1231 pthread_cond_signal(&read_thread_msg_avail);
1232 pthread_join(read_thread_id, NULL);
1235 pthread_cond_destroy(&read_thread_msg_done);
1236 pthread_cond_destroy(&read_thread_msg_avail);
1237 pthread_mutex_destroy(&read_thread_msg_lock);
1239 pthread_cond_destroy(§orbuffer_cond);
1240 pthread_mutex_destroy(§orbuffer_lock);
1242 CDR_getBuffer = sync_CDR_getBuffer;
1243 cdimg_read_func = sync_cdimg_read_func;
1246 sectorbuffer = NULL;
1249 static void readThreadStart() {
1250 SysPrintf("Starting async CD thread\n");
1252 if (read_thread_running == TRUE)
1255 read_thread_running = TRUE;
1256 read_thread_sector_start = -1;
1257 read_thread_sector_end = -1;
1258 sectorbuffer_index = 0;
1260 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1264 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1266 sync_CDR_getBuffer = CDR_getBuffer;
1267 CDR_getBuffer = ISOgetBuffer_async;
1268 sync_cdimg_read_func = cdimg_read_func;
1269 cdimg_read_func = cdread_async;
1271 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1272 pthread_cond_init(&read_thread_msg_done, NULL) ||
1273 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1274 pthread_cond_init(§orbuffer_cond, NULL) ||
1275 pthread_mutex_init(§orbuffer_lock, NULL) ||
1276 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1282 SysPrintf("Error starting async CD thread\n");
1283 SysPrintf("Falling back to sync\n");
1289 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1294 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1296 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1302 // often happens in cdda gaps of a split cue/bin, so not logged
1303 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1307 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1313 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1315 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1321 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1325 static int cdread_sub_sub_mixed(FILE *f, int sector)
1329 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1331 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1334 return SUB_FRAMESIZE;
1337 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1341 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1346 if (z.zalloc == NULL) {
1347 // XXX: one-time leak here..
1353 ret = inflateInit2(&z, -15);
1356 ret = inflateReset(&z);
1361 z.avail_in = in_size;
1363 z.avail_out = *out_size;
1365 ret = inflate(&z, Z_NO_FLUSH);
1368 *out_size -= z.avail_out;
1369 return ret == 1 ? 0 : ret;
1372 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1374 unsigned long cdbuffer_size, cdbuffer_size_expect;
1383 sector += base / 2352;
1385 block = sector >> compr_img->block_shift;
1386 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1388 if (block == compr_img->current_block) {
1389 //printf("hit sect %d\n", sector);
1393 if (sector >= compr_img->index_len * 16) {
1394 SysPrintf("sector %d is past img end\n", sector);
1398 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1399 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1400 SysPrintf("seek error for block %d at %llx: ",
1401 block, (long long)start_byte);
1406 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1407 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1408 if (size > sizeof(compr_img->buff_compressed)) {
1409 SysPrintf("block %d is too large: %u\n", block, size);
1413 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1414 1, size, cdHandle) != size) {
1415 SysPrintf("read error for block %d at %x: ", block, start_byte);
1420 if (is_compressed) {
1421 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1422 cdbuffer_size = cdbuffer_size_expect;
1423 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1425 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1426 ret, block, sector);
1429 if (cdbuffer_size != cdbuffer_size_expect)
1430 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1431 cdbuffer_size_expect, sector);
1435 compr_img->current_block = block;
1438 if (dest != cdbuffer) // copy avoid HACK
1439 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1441 return CD_FRAMESIZE_RAW;
1445 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1447 return chd_img->buffer
1448 + current_buffer * chd_img->header->hunkbytes
1449 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1452 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1458 hunk = sector / chd_img->sectors_per_hunk;
1459 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1461 if (hunk == chd_img->current_hunk[0])
1462 chd_img->current_buffer = 0;
1463 else if (hunk == chd_img->current_hunk[1])
1464 chd_img->current_buffer = 1;
1467 chd_read(chd_img->chd, hunk, chd_img->buffer +
1468 chd_img->current_buffer * chd_img->header->hunkbytes);
1469 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1472 if (dest != cdbuffer) // copy avoid HACK
1473 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1475 return CD_FRAMESIZE_RAW;
1478 static int cdread_sub_chd(FILE *f, int sector)
1480 unsigned int sector_in_hunk;
1481 unsigned int buffer;
1487 hunk = sector / chd_img->sectors_per_hunk;
1488 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1490 if (hunk == chd_img->current_hunk[0])
1492 else if (hunk == chd_img->current_hunk[1])
1496 buffer = chd_img->current_buffer ^ 1;
1497 chd_read(chd_img->chd, hunk, chd_img->buffer +
1498 buffer * chd_img->header->hunkbytes);
1499 chd_img->current_hunk[buffer] = hunk;
1502 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1503 return SUB_FRAMESIZE;
1507 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1513 fseeko(f, base + sector * 2048, SEEK_SET);
1514 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1516 // not really necessary, fake mode 2 header
1517 memset(cdbuffer, 0, 12 * 2);
1518 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1519 cdbuffer[12 + 3] = 1;
1526 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1527 boolean found = FALSE;
1528 int i = sector % SECTOR_BUFFER_SIZE;
1531 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1532 // Async reads are only supported for cdbuffer, so call the sync
1533 // function directly.
1534 return sync_cdimg_read_func(f, base, dest, sector);
1537 pthread_mutex_lock(&read_thread_msg_lock);
1539 // Only wait if we're not trying to read the next sector and
1540 // sector_start is set (meaning the last request hasn't been
1542 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1543 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1546 if (read_thread_sector_start == -1)
1547 read_thread_sector_start = sector;
1549 read_thread_sector_end = sector;
1550 pthread_cond_signal(&read_thread_msg_avail);
1551 pthread_mutex_unlock(&read_thread_msg_lock);
1554 pthread_mutex_lock(§orbuffer_lock);
1555 if (sectorbuffer[i].sector == sector) {
1556 sectorbuffer_index = i;
1557 ret = sectorbuffer[i].ret;
1562 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1564 pthread_mutex_unlock(§orbuffer_lock);
1572 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1573 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1577 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1578 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1583 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1584 unsigned char *buffer;
1585 pthread_mutex_lock(§orbuffer_lock);
1586 buffer = sectorbuffer[sectorbuffer_index].data;
1587 pthread_mutex_unlock(§orbuffer_lock);
1592 static unsigned char * CALLBACK ISOgetBuffer(void) {
1593 return cdbuffer + 12;
1596 static void PrintTracks(void) {
1599 for (i = 1; i <= numtracks; i++) {
1600 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1601 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
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) {
1754 if (compr_img != NULL) {
1755 free(compr_img->index_table);
1761 if (chd_img != NULL) {
1762 chd_close(chd_img->chd);
1763 free(chd_img->buffer);
1769 for (i = 1; i <= numtracks; i++) {
1770 if (ti[i].handle != NULL) {
1771 fclose(ti[i].handle);
1772 ti[i].handle = NULL;
1779 memset(cdbuffer, 0, sizeof(cdbuffer));
1780 CDR_getBuffer = ISOgetBuffer;
1782 if (Config.AsyncCD) {
1789 static long CALLBACK ISOinit(void) {
1790 assert(cdHandle == NULL);
1791 assert(subHandle == NULL);
1793 return 0; // do nothing
1796 static long CALLBACK ISOshutdown(void) {
1801 // return Starting and Ending Track
1803 // byte 0 - start track
1804 // byte 1 - end track
1805 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1808 if (numtracks > 0) {
1809 buffer[1] = numtracks;
1818 // return Track Time
1823 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1826 unsigned char time[3];
1827 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1828 sec2msf(sect, (char *)time);
1829 buffer[2] = time[0];
1830 buffer[1] = time[1];
1831 buffer[0] = time[2];
1833 else if (numtracks > 0 && track <= numtracks) {
1834 buffer[2] = ti[track].start[0];
1835 buffer[1] = ti[track].start[1];
1836 buffer[0] = ti[track].start[2];
1847 // decode 'raw' subchannel data ripped by cdrdao
1848 static void DecodeRawSubData(void) {
1849 unsigned char subQData[12];
1852 memset(subQData, 0, sizeof(subQData));
1854 for (i = 0; i < 8 * 12; i++) {
1855 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1856 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1860 memcpy(&subbuffer[12], subQData, 12);
1864 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1866 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1867 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1870 if (!cdHandle && !chd_img)
1873 if (pregapOffset && sector >= pregapOffset)
1876 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1877 if (ret < 12*2 + 2048)
1884 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1885 // does NOT uses bcd format
1886 static long CALLBACK ISOplay(unsigned char *time) {
1892 static long CALLBACK ISOstop(void) {
1897 // gets subchannel data
1898 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1899 if (pregapOffset && sector >= pregapOffset) {
1901 if (sector < pregapOffset) // ?
1905 if (cdimg_read_sub_func != NULL) {
1906 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1909 else if (subHandle != NULL) {
1910 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1912 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1919 if (subChanRaw) DecodeRawSubData();
1923 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1926 CDR__getStatus(stat);
1930 stat->Status |= 0x80;
1933 // BIOS - boot ID (CD type)
1934 stat->Type = ti[1].type;
1937 // relative -> absolute time
1939 sec2msf(sect, (char *)stat->Time);
1944 // read CDDA sector into buffer
1945 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1946 unsigned char msf[3] = {m, s, f};
1947 unsigned int track, track_start = 0;
1948 FILE *handle = cdHandle;
1951 cddaCurPos = msf2sec((char *)msf);
1953 // find current track index
1954 for (track = numtracks; ; track--) {
1955 track_start = msf2sec(ti[track].start);
1956 if (track_start <= cddaCurPos)
1962 // data tracks play silent
1963 if (ti[track].type != CDDA) {
1964 memset(buffer, 0, CD_FRAMESIZE_RAW);
1969 // find the file that contains this track
1971 for (file = track; file > 1; file--) {
1972 if (ti[file].handle != NULL) {
1973 handle = ti[file].handle;
1978 if (!handle && !chd_img) {
1979 memset(buffer, 0, CD_FRAMESIZE_RAW);
1983 ret = cdimg_read_func(handle, ti[track].start_offset,
1984 buffer, cddaCurPos - track_start);
1985 if (ret != CD_FRAMESIZE_RAW) {
1986 memset(buffer, 0, CD_FRAMESIZE_RAW);
1990 if (cddaBigEndian) {
1994 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1995 tmp = buffer[i * 2];
1996 buffer[i * 2] = buffer[i * 2 + 1];
1997 buffer[i * 2 + 1] = tmp;
2004 void cdrIsoInit(void) {
2006 CDR_shutdown = ISOshutdown;
2008 CDR_close = ISOclose;
2009 CDR_getTN = ISOgetTN;
2010 CDR_getTD = ISOgetTD;
2011 CDR_readTrack = ISOreadTrack;
2012 CDR_getBuffer = ISOgetBuffer;
2015 CDR_getBufferSub = ISOgetBufferSub;
2016 CDR_getStatus = ISOgetStatus;
2017 CDR_readCDDA = ISOreadCDDA;
2019 CDR_getDriveLetter = CDR__getDriveLetter;
2020 CDR_configure = CDR__configure;
2021 CDR_test = CDR__test;
2022 CDR_about = CDR__about;
2023 CDR_setfilename = CDR__setfilename;
2028 int cdrIsoActive(void) {
2029 return (cdHandle || chd_img);