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
39 #define usleep(x) (Sleep((x) / 1000))
46 #ifdef USE_LIBRETRO_VFS
47 #include <streams/file_stream_transforms.h>
54 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
56 unsigned int cdrIsoMultidiskCount;
57 unsigned int cdrIsoMultidiskSelect;
59 static FILE *cdHandle = NULL;
60 static FILE *cddaHandle = NULL;
61 static FILE *subHandle = NULL;
63 static boolean subChanMixed = FALSE;
64 static boolean subChanRaw = FALSE;
65 static boolean subChanMissing = FALSE;
67 static boolean multifile = FALSE;
69 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
70 static unsigned char subbuffer[SUB_FRAMESIZE];
72 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
74 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
77 static HANDLE threadid;
79 static pthread_t threadid;
81 static unsigned int initial_offset = 0;
82 static boolean playing = FALSE;
83 static boolean cddaBigEndian = FALSE;
84 // cdda sectors in toc, byte offset in file
85 static unsigned int cdda_cur_sector;
86 static unsigned int cdda_first_sector;
87 static unsigned int cdda_file_offset;
88 /* Frame offset into CD image where pregap data would be found if it was there.
89 * If a game seeks there we must *not* return subchannel data since it's
90 * not in the CD image, so that cdrom code can fake subchannel data instead.
91 * XXX: there could be multiple pregaps but PSX dumps only have one? */
92 static unsigned int pregapOffset;
94 #define cddaCurPos cdda_cur_sector
96 // compressed image stuff
98 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
99 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
101 unsigned int index_len;
102 unsigned int block_shift;
103 unsigned int current_block;
104 unsigned int sector_in_blk;
109 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
111 const chd_header* header;
112 unsigned int sectors_per_hunk;
113 unsigned int current_hunk;
114 unsigned int sector_in_hunk;
118 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
120 char* CALLBACK CDR__getDriveLetter(void);
121 long CALLBACK CDR__configure(void);
122 long CALLBACK CDR__test(void);
123 void CALLBACK CDR__about(void);
124 long CALLBACK CDR__setfilename(char *filename);
125 long CALLBACK CDR__getStatus(struct CdrStat *stat);
127 static void DecodeRawSubData(void);
130 enum {DATA=1, CDDA} type;
131 char start[3]; // MSF-format
132 char length[3]; // MSF-format
133 FILE *handle; // for multi-track images CDDA
134 unsigned int start_offset; // byte offset from start of above file
137 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
139 static int numtracks = 0;
140 static struct trackinfo ti[MAXTRACKS];
142 // get a sector from a msf-array
143 static unsigned int msf2sec(char *msf) {
144 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
147 static void sec2msf(unsigned int s, char *msf) {
148 msf[0] = s / 75 / 60;
149 s = s - msf[0] * 75 * 60;
155 // divide a string of xx:yy:zz into m, s, f
156 static void tok2msf(char *time, char *msf) {
159 token = strtok(time, ":");
161 msf[0] = atoi(token);
167 token = strtok(NULL, ":");
169 msf[1] = atoi(token);
175 token = strtok(NULL, ":");
177 msf[2] = atoi(token);
185 static long GetTickCount(void) {
186 static time_t initial_time = 0;
189 gettimeofday(&now, NULL);
191 if (initial_time == 0) {
192 initial_time = now.tv_sec;
195 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
199 // this thread plays audio data
201 static void playthread(void *param)
203 static void *playthread(void *param)
206 long osleep, d, t, i, s;
208 int ret = 0, sector_offs;
214 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
215 sector_offs = cdda_cur_sector - cdda_first_sector;
216 if (sector_offs < 0) {
217 d = CD_FRAMESIZE_RAW;
218 memset(sndbuffer + s, 0, d);
221 d = cdimg_read_func(cddaHandle, cdda_file_offset,
222 sndbuffer + s, sector_offs);
223 if (d < CD_FRAMESIZE_RAW)
237 if (!cdr.Muted && playing) {
239 for (i = 0; i < s / 2; i++) {
240 tmp = sndbuffer[i * 2];
241 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
242 sndbuffer[i * 2 + 1] = tmp;
246 // can't do it yet due to readahead..
247 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
249 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
254 } while (ret == 0x7761 && playing); // rearmed_wait
257 if (ret != 0x676f) { // !rearmed_go
261 // HACK: stop feeding data while emu is paused
263 while (stop && playing)
268 now = GetTickCount();
274 else if (osleep > CDDA_FRAMETIME) {
275 osleep = CDDA_FRAMETIME;
279 usleep(osleep * 1000);
293 // stop the CDDA playback
294 static void stopCDDA() {
301 WaitForSingleObject(threadid, INFINITE);
303 pthread_join(threadid, NULL);
307 // start the CDDA playback
308 static void startCDDA(void) {
316 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
318 pthread_create(&threadid, NULL, playthread, NULL);
322 // this function tries to get the .toc file of the given .bin
323 // the necessary data is put into the ti (trackinformation)-array
324 static int parsetoc(const char *isofile) {
325 char tocname[MAXPATHLEN];
327 char linebuf[256], tmp[256], name[256];
329 char time[20], time2[20];
330 unsigned int t, sector_offs, sector_size;
331 unsigned int current_zero_gap = 0;
335 // copy name of the iso and change extension from .bin to .toc
336 strncpy(tocname, isofile, sizeof(tocname));
337 tocname[MAXPATHLEN - 1] = '\0';
338 if (strlen(tocname) >= 4) {
339 strcpy(tocname + strlen(tocname) - 4, ".toc");
345 if ((fi = fopen(tocname, "r")) == NULL) {
346 // try changing extension to .cue (to satisfy some stupid tutorials)
347 strcpy(tocname + strlen(tocname) - 4, ".cue");
348 if ((fi = fopen(tocname, "r")) == NULL) {
349 // if filename is image.toc.bin, try removing .bin (for Brasero)
350 strcpy(tocname, isofile);
352 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
353 tocname[t - 4] = '\0';
354 if ((fi = fopen(tocname, "r")) == NULL) {
362 // check if it's really a TOC named as a .cue
363 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
364 token = strtok(linebuf, " ");
365 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
370 fseek(fi, 0, SEEK_SET);
373 memset(&ti, 0, sizeof(ti));
374 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
376 sector_size = CD_FRAMESIZE_RAW;
377 sector_offs = 2 * 75;
379 // parse the .toc file
380 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
382 strncpy(tmp, linebuf, sizeof(linebuf));
383 token = strtok(tmp, " ");
385 if (token == NULL) continue;
387 if (!strcmp(token, "TRACK")) {
388 sector_offs += current_zero_gap;
389 current_zero_gap = 0;
392 token = strtok(NULL, " ");
395 if (!strncmp(token, "MODE2_RAW", 9)) {
396 ti[numtracks].type = DATA;
397 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
399 // check if this image contains mixed subchannel data
400 token = strtok(NULL, " ");
401 if (token != NULL && !strncmp(token, "RW", 2)) {
402 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
404 if (!strncmp(token, "RW_RAW", 6))
408 else if (!strncmp(token, "AUDIO", 5)) {
409 ti[numtracks].type = CDDA;
412 else if (!strcmp(token, "DATAFILE")) {
413 if (ti[numtracks].type == CDDA) {
414 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
415 ti[numtracks].start_offset = t;
416 t = t / sector_size + sector_offs;
417 sec2msf(t, (char *)&ti[numtracks].start);
418 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
421 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
422 tok2msf((char *)&time, (char *)&ti[numtracks].length);
425 else if (!strcmp(token, "FILE")) {
426 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
427 tok2msf((char *)&time, (char *)&ti[numtracks].start);
428 t += msf2sec(ti[numtracks].start) * sector_size;
429 ti[numtracks].start_offset = t;
430 t = t / sector_size + sector_offs;
431 sec2msf(t, (char *)&ti[numtracks].start);
432 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
434 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
435 // skip unneeded optional fields
436 while (token != NULL) {
437 token = strtok(NULL, " ");
438 if (strchr(token, ':') != NULL)
443 current_zero_gap = msf2sec(tmp);
446 t = ti[numtracks - 1].start_offset;
448 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
451 else if (!strcmp(token, "START")) {
452 token = strtok(NULL, " ");
453 if (token != NULL && strchr(token, ':')) {
456 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
457 t = msf2sec(ti[numtracks].start) + t;
458 sec2msf(t, (char *)&ti[numtracks].start);
468 // this function tries to get the .cue file of the given .bin
469 // the necessary data is put into the ti (trackinformation)-array
470 static int parsecue(const char *isofile) {
471 char cuename[MAXPATHLEN];
472 char filepath[MAXPATHLEN];
478 char linebuf[256], tmpb[256], dummy[256];
479 unsigned int incue_max_len;
480 unsigned int t, file_len, mode, sector_offs;
481 unsigned int sector_size = 2352;
485 // copy name of the iso and change extension from .bin to .cue
486 strncpy(cuename, isofile, sizeof(cuename));
487 cuename[MAXPATHLEN - 1] = '\0';
488 if (strlen(cuename) >= 4) {
489 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
490 // and don't try to search the additional .cue file
491 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
492 strcpy(cuename + strlen(cuename) - 4, ".cue");
498 if ((fi = fopen(cuename, "r")) == NULL) {
502 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
503 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
505 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
506 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
507 // Don't proceed further, as this is actually a .toc file rather
510 return parsetoc(isofile);
512 fseek(fi, 0, SEEK_SET);
515 // build a path for files referenced in .cue
516 strncpy(filepath, cuename, sizeof(filepath));
517 tmp = strrchr(filepath, '/');
519 tmp = strrchr(filepath, '\\');
525 filepath[sizeof(filepath) - 1] = 0;
527 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
529 memset(&ti, 0, sizeof(ti));
532 sector_offs = 2 * 75;
534 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
535 strncpy(dummy, linebuf, sizeof(linebuf));
536 token = strtok(dummy, " ");
542 if (!strcmp(token, "TRACK")) {
546 if (strstr(linebuf, "AUDIO") != NULL) {
547 ti[numtracks].type = CDDA;
550 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
551 ti[numtracks].type = DATA;
553 SysPrintf(".cue: failed to parse TRACK\n");
554 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
556 if (sector_size == 0)
559 else if (!strcmp(token, "INDEX")) {
560 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
561 SysPrintf(".cue: failed to parse INDEX\n");
562 tok2msf(time, (char *)&ti[numtracks].start);
564 t = msf2sec(ti[numtracks].start);
565 ti[numtracks].start_offset = t * sector_size;
567 sec2msf(t, ti[numtracks].start);
569 // default track length to file length
570 t = file_len - ti[numtracks].start_offset / sector_size;
571 sec2msf(t, ti[numtracks].length);
573 if (numtracks > 1 && ti[numtracks].handle == NULL) {
574 // this track uses the same file as the last,
575 // start of this track is last track's end
576 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
577 sec2msf(t, ti[numtracks - 1].length);
579 if (numtracks > 1 && pregapOffset == -1)
580 pregapOffset = ti[numtracks].start_offset / sector_size;
582 else if (!strcmp(token, "PREGAP")) {
583 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
584 tok2msf(time, dummy);
585 sector_offs += msf2sec(dummy);
587 pregapOffset = -1; // mark to fill track start_offset
589 else if (!strcmp(token, "FILE")) {
590 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
592 sscanf(linebuf, " FILE %255s", tmpb);
594 tmp = strrchr(tmpb, '\\');
596 tmp = strrchr(tmpb, '/');
601 strncpy(incue_fname, tmp, incue_max_len);
602 ti[numtracks + 1].handle = fopen(filepath, "rb");
604 // update global offset if this is not first file in this .cue
605 if (numtracks + 1 > 1) {
607 sector_offs += file_len;
611 if (ti[numtracks + 1].handle == NULL) {
612 SysPrintf(_("\ncould not open: %s\n"), filepath);
615 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
616 file_len = ftell(ti[numtracks + 1].handle) / 2352;
618 if (numtracks == 0 && strlen(isofile) >= 4 &&
619 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
620 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
621 // user selected .cue/.cdX as image file, use it's data track instead
623 cdHandle = fopen(filepath, "rb");
630 // if there are no tracks detected, then it's not a cue file
637 // this function tries to get the .ccd file of the given .img
638 // the necessary data is put into the ti (trackinformation)-array
639 static int parseccd(const char *isofile) {
640 char ccdname[MAXPATHLEN];
647 // copy name of the iso and change extension from .img to .ccd
648 strncpy(ccdname, isofile, sizeof(ccdname));
649 ccdname[MAXPATHLEN - 1] = '\0';
650 if (strlen(ccdname) >= 4) {
651 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
657 if ((fi = fopen(ccdname, "r")) == NULL) {
661 memset(&ti, 0, sizeof(ti));
663 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
664 if (!strncmp(linebuf, "[TRACK", 6)){
667 else if (!strncmp(linebuf, "MODE=", 5)) {
668 sscanf(linebuf, "MODE=%d", &t);
669 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
671 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
672 sscanf(linebuf, "INDEX 1=%d", &t);
673 sec2msf(t + 2 * 75, ti[numtracks].start);
674 ti[numtracks].start_offset = t * 2352;
676 // If we've already seen another track, this is its end
678 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
679 sec2msf(t, ti[numtracks - 1].length);
686 // Fill out the last track's end based on size
687 if (numtracks >= 1) {
688 fseek(cdHandle, 0, SEEK_END);
689 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
690 sec2msf(t, ti[numtracks].length);
696 // this function tries to get the .mds file of the given .mdf
697 // the necessary data is put into the ti (trackinformation)-array
698 static int parsemds(const char *isofile) {
699 char mdsname[MAXPATHLEN];
701 unsigned int offset, extra_offset, l, i;
706 // copy name of the iso and change extension from .mdf to .mds
707 strncpy(mdsname, isofile, sizeof(mdsname));
708 mdsname[MAXPATHLEN - 1] = '\0';
709 if (strlen(mdsname) >= 4) {
710 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
716 if ((fi = fopen(mdsname, "rb")) == NULL) {
720 memset(&ti, 0, sizeof(ti));
722 // check if it's a valid mds file
723 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
726 if (i != 0x4944454D) {
727 // not an valid mds file
732 // get offset to session block
733 fseek(fi, 0x50, SEEK_SET);
734 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
736 offset = SWAP32(offset);
738 // get total number of tracks
740 fseek(fi, offset, SEEK_SET);
741 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
746 // get offset to track blocks
747 fseek(fi, 4, SEEK_CUR);
748 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
750 offset = SWAP32(offset);
754 fseek(fi, offset + 4, SEEK_SET);
755 if (fgetc(fi) < 0xA0) {
761 // check if the image contains mixed subchannel data
762 fseek(fi, offset + 1, SEEK_SET);
763 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
766 for (i = 1; i <= numtracks; i++) {
767 fseek(fi, offset, SEEK_SET);
769 // get the track type
770 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
771 fseek(fi, 8, SEEK_CUR);
773 // get the track starting point
774 ti[i].start[0] = fgetc(fi);
775 ti[i].start[1] = fgetc(fi);
776 ti[i].start[2] = fgetc(fi);
778 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
780 extra_offset = SWAP32(extra_offset);
782 // get track start offset (in .mdf)
783 fseek(fi, offset + 0x28, SEEK_SET);
784 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
787 ti[i].start_offset = l;
790 fseek(fi, extra_offset, SEEK_SET);
791 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
795 pregapOffset = msf2sec(ti[i].start);
797 // get the track length
798 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
801 sec2msf(l, ti[i].length);
809 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
815 static int handlepbp(const char *isofile) {
818 unsigned int dontcare[8];
819 unsigned int psar_offs;
832 unsigned int dontcare[6];
835 off_t psisoimg_offs, cdimg_base;
836 unsigned int t, cd_length;
837 unsigned int offsettab[8];
838 const char *ext = NULL;
841 if (strlen(isofile) >= 4)
842 ext = isofile + strlen(isofile) - 4;
843 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
846 fseeko(cdHandle, 0, SEEK_SET);
850 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
851 if (ret != sizeof(pbp_hdr)) {
852 SysPrintf("failed to read pbp\n");
856 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
858 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
862 psisoimg_offs = pbp_hdr.psar_offs;
863 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
866 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
868 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
870 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
874 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
875 SysPrintf("failed to read offsettab\n");
879 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
880 if (offsettab[i] == 0)
883 cdrIsoMultidiskCount = i;
884 if (cdrIsoMultidiskCount == 0) {
885 SysPrintf("multidisk eboot has 0 images?\n");
889 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
890 cdrIsoMultidiskSelect = 0;
892 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
894 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
896 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
900 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
905 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
906 SysPrintf("bad psar_sig: %s\n", psar_sig);
911 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
913 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
917 // first 3 entries are special
918 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
919 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
921 numtracks = btoi(toc_entry.index1[0]);
923 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
925 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
926 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
928 for (i = 1; i <= numtracks; i++) {
929 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
932 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
934 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
935 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
936 ti[i].start_offset *= 2352;
937 ti[i].start[0] = btoi(toc_entry.index1[0]);
938 ti[i].start[1] = btoi(toc_entry.index1[1]);
939 ti[i].start[2] = btoi(toc_entry.index1[2]);
942 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
943 sec2msf(t, ti[i - 1].length);
946 t = cd_length - ti[numtracks].start_offset / 2352;
947 sec2msf(t, ti[numtracks].length);
950 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
952 SysPrintf("failed to seek to ISO index\n");
956 compr_img = calloc(1, sizeof(*compr_img));
957 if (compr_img == NULL)
960 compr_img->block_shift = 4;
961 compr_img->current_block = (unsigned int)-1;
963 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
964 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
965 if (compr_img->index_table == NULL)
968 cdimg_base = psisoimg_offs + 0x100000;
969 for (i = 0; i < compr_img->index_len; i++) {
970 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
971 if (ret != sizeof(index_entry)) {
972 SysPrintf("failed to read index_entry #%d\n", i);
976 if (index_entry.size == 0)
979 compr_img->index_table[i] = cdimg_base + index_entry.offset;
981 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
986 free(compr_img->index_table);
987 compr_img->index_table = NULL;
992 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
996 if (compr_img != NULL) {
1003 static int handlecbin(const char *isofile) {
1007 unsigned int header_size;
1008 unsigned long long total_bytes;
1009 unsigned int block_size;
1010 unsigned char ver; // 1
1011 unsigned char align;
1012 unsigned char rsv_06[2];
1014 const char *ext = NULL;
1015 unsigned int *index_table = NULL;
1016 unsigned int index = 0, plain;
1019 if (strlen(isofile) >= 5)
1020 ext = isofile + strlen(isofile) - 5;
1021 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
1024 fseek(cdHandle, 0, SEEK_SET);
1026 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
1027 if (ret != sizeof(ciso_hdr)) {
1028 SysPrintf("failed to read ciso header\n");
1032 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
1033 SysPrintf("bad ciso header\n");
1036 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
1037 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
1039 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
1044 compr_img = calloc(1, sizeof(*compr_img));
1045 if (compr_img == NULL)
1048 compr_img->block_shift = 0;
1049 compr_img->current_block = (unsigned int)-1;
1051 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
1052 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
1053 if (index_table == NULL)
1056 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1057 if (ret != compr_img->index_len) {
1058 SysPrintf("failed to read index table\n");
1062 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1063 if (compr_img->index_table == NULL)
1066 for (i = 0; i < compr_img->index_len + 1; i++) {
1067 index = index_table[i];
1068 plain = index & 0x80000000;
1069 index &= 0x7fffffff;
1070 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1072 compr_img->index_table[i] |= OFF_T_MSB;
1080 if (compr_img != NULL) {
1088 static int handlechd(const char *isofile) {
1089 chd_img = calloc(1, sizeof(*chd_img));
1090 if (chd_img == NULL)
1093 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
1096 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
1099 chd_img->header = chd_get_header(chd_img->chd);
1101 chd_img->buffer = malloc(chd_img->header->hunkbytes);
1102 if (chd_img->buffer == NULL)
1105 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1106 chd_img->current_hunk = (unsigned int)-1;
1108 cddaBigEndian = TRUE;
1111 int frame_offset = 0;
1112 int file_offset = 0;
1113 memset(ti, 0, sizeof(ti));
1128 uint32_t meta_size = 0;
1130 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1131 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1132 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1133 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1140 sec2msf(msf2sec(ti[md.track-1].length) + md.pregap, ti[md.track-1].length);
1142 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1144 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1145 sec2msf(md.frames, ti[md.track].length);
1147 ti[md.track].start_offset = file_offset;
1149 frame_offset += md.pregap + md.frames + md.postgap;
1150 file_offset += md.frames + md.postgap;
1158 if (chd_img != NULL) {
1159 free(chd_img->buffer);
1167 // this function tries to get the .sub file of the given .img
1168 static int opensubfile(const char *isoname) {
1169 char subname[MAXPATHLEN];
1171 // copy name of the iso and change extension from .img to .sub
1172 strncpy(subname, isoname, sizeof(subname));
1173 subname[MAXPATHLEN - 1] = '\0';
1174 if (strlen(subname) >= 4) {
1175 strcpy(subname + strlen(subname) - 4, ".sub");
1181 subHandle = fopen(subname, "rb");
1182 if (subHandle == NULL) {
1189 static int opensbifile(const char *isoname) {
1190 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1193 strncpy(sbiname, isoname, sizeof(sbiname));
1194 sbiname[MAXPATHLEN - 1] = '\0';
1195 if (strlen(sbiname) >= 4) {
1196 if (cdrIsoMultidiskCount > 1) {
1197 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1198 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1201 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1207 fseek(cdHandle, 0, SEEK_END);
1208 s = ftell(cdHandle) / 2352;
1210 return LoadSBI(sbiname, s);
1214 static void readThreadStop() {}
1215 static void readThreadStart() {}
1217 static pthread_t read_thread_id;
1219 static pthread_cond_t read_thread_msg_avail;
1220 static pthread_cond_t read_thread_msg_done;
1221 static pthread_mutex_t read_thread_msg_lock;
1223 static pthread_cond_t sectorbuffer_cond;
1224 static pthread_mutex_t sectorbuffer_lock;
1226 static boolean read_thread_running = FALSE;
1227 static int read_thread_sector_start = -1;
1228 static int read_thread_sector_end = -1;
1233 unsigned char data[CD_FRAMESIZE_RAW];
1234 } SectorBufferEntry;
1236 #define SECTOR_BUFFER_SIZE 4096
1238 static SectorBufferEntry *sectorbuffer;
1239 static size_t sectorbuffer_index;
1241 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1242 unsigned char *(*sync_CDR_getBuffer)(void);
1244 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1245 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1247 static void *readThreadMain(void *param) {
1248 int max_sector = -1;
1249 int requested_sector_start = -1;
1250 int requested_sector_end = -1;
1251 int last_read_sector = -1;
1257 int speedmult_ra = 4;
1260 int how_far_ahead = 0;
1262 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1265 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1268 pthread_mutex_lock(&read_thread_msg_lock);
1270 // If we don't have readahead and we don't have a sector request, wait for one.
1271 // If we still have readahead to go, don't block, just keep going.
1272 // And if we ever have a sector request pending, acknowledge and reset it.
1275 if (read_thread_sector_start == -1 && read_thread_running) {
1276 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1280 if (read_thread_sector_start != -1) {
1281 requested_sector_start = read_thread_sector_start;
1282 requested_sector_end = read_thread_sector_end;
1283 read_thread_sector_start = -1;
1284 read_thread_sector_end = -1;
1285 pthread_cond_signal(&read_thread_msg_done);
1288 pthread_mutex_unlock(&read_thread_msg_lock);
1290 if (!read_thread_running)
1293 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1294 if (requested_sector_start != -1) {
1295 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1296 how_far_ahead = ra_sector - requested_sector_end;
1298 if(how_far_ahead <= max_ra)
1299 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1302 } else if (requested_sector_end != last_read_sector) {
1303 ra_sector = requested_sector_end;
1304 ra_count = initial_ra;
1307 last_read_sector = requested_sector_end;
1310 index = ra_sector % SECTOR_BUFFER_SIZE;
1312 // check for end of CD
1313 if (ra_count && ra_sector >= max_sector) {
1315 pthread_mutex_lock(§orbuffer_lock);
1316 sectorbuffer[index].ret = -1;
1317 sectorbuffer[index].sector = ra_sector;
1318 pthread_cond_signal(§orbuffer_cond);
1319 pthread_mutex_unlock(§orbuffer_lock);
1323 pthread_mutex_lock(§orbuffer_lock);
1324 if (sectorbuffer[index].sector != ra_sector) {
1325 pthread_mutex_unlock(§orbuffer_lock);
1327 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1329 pthread_mutex_lock(§orbuffer_lock);
1330 sectorbuffer[index].ret = ret;
1331 sectorbuffer[index].sector = ra_sector;
1332 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1334 pthread_cond_signal(§orbuffer_cond);
1335 pthread_mutex_unlock(§orbuffer_lock);
1345 static void readThreadStop() {
1346 if (read_thread_running == TRUE) {
1347 read_thread_running = FALSE;
1348 pthread_cond_signal(&read_thread_msg_avail);
1349 pthread_join(read_thread_id, NULL);
1352 pthread_cond_destroy(&read_thread_msg_done);
1353 pthread_cond_destroy(&read_thread_msg_avail);
1354 pthread_mutex_destroy(&read_thread_msg_lock);
1356 pthread_cond_destroy(§orbuffer_cond);
1357 pthread_mutex_destroy(§orbuffer_lock);
1359 CDR_getBuffer = sync_CDR_getBuffer;
1360 cdimg_read_func = sync_cdimg_read_func;
1363 sectorbuffer = NULL;
1366 static void readThreadStart() {
1367 SysPrintf("Starting async CD thread\n");
1369 if (read_thread_running == TRUE)
1372 read_thread_running = TRUE;
1373 read_thread_sector_start = -1;
1374 read_thread_sector_end = -1;
1375 sectorbuffer_index = 0;
1377 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1381 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1383 sync_CDR_getBuffer = CDR_getBuffer;
1384 CDR_getBuffer = ISOgetBuffer_async;
1385 sync_cdimg_read_func = cdimg_read_func;
1386 cdimg_read_func = cdread_async;
1388 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1389 pthread_cond_init(&read_thread_msg_done, NULL) ||
1390 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1391 pthread_cond_init(§orbuffer_cond, NULL) ||
1392 pthread_mutex_init(§orbuffer_lock, NULL) ||
1393 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1399 SysPrintf("Error starting async CD thread\n");
1400 SysPrintf("Falling back to sync\n");
1406 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1408 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1409 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1412 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1416 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1417 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1418 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1421 if (subChanRaw) DecodeRawSubData();
1426 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1433 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1438 if (z.zalloc == NULL) {
1439 // XXX: one-time leak here..
1445 ret = inflateInit2(&z, -15);
1448 ret = inflateReset(&z);
1453 z.avail_in = in_size;
1455 z.avail_out = *out_size;
1457 ret = inflate(&z, Z_NO_FLUSH);
1460 *out_size -= z.avail_out;
1461 return ret == 1 ? 0 : ret;
1464 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1466 unsigned long cdbuffer_size, cdbuffer_size_expect;
1473 sector += base / 2352;
1475 block = sector >> compr_img->block_shift;
1476 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1478 if (block == compr_img->current_block) {
1479 //printf("hit sect %d\n", sector);
1483 if (sector >= compr_img->index_len * 16) {
1484 SysPrintf("sector %d is past img end\n", sector);
1488 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1489 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1490 SysPrintf("seek error for block %d at %llx: ",
1491 block, (long long)start_byte);
1496 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1497 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1498 if (size > sizeof(compr_img->buff_compressed)) {
1499 SysPrintf("block %d is too large: %u\n", block, size);
1503 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1504 1, size, cdHandle) != size) {
1505 SysPrintf("read error for block %d at %x: ", block, start_byte);
1510 if (is_compressed) {
1511 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1512 cdbuffer_size = cdbuffer_size_expect;
1513 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1515 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1516 ret, block, sector);
1519 if (cdbuffer_size != cdbuffer_size_expect)
1520 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1521 cdbuffer_size_expect, sector);
1525 compr_img->current_block = block;
1528 if (dest != cdbuffer) // copy avoid HACK
1529 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1531 return CD_FRAMESIZE_RAW;
1535 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1542 hunk = sector / chd_img->sectors_per_hunk;
1543 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1545 if (hunk != chd_img->current_hunk)
1547 chd_read(chd_img->chd, hunk, chd_img->buffer);
1548 chd_img->current_hunk = hunk;
1551 if (dest != cdbuffer) // copy avoid HACK
1552 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1554 return CD_FRAMESIZE_RAW;
1557 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1561 fseek(f, base + sector * 2048, SEEK_SET);
1562 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1564 // not really necessary, fake mode 2 header
1565 memset(cdbuffer, 0, 12 * 2);
1566 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1567 cdbuffer[12 + 3] = 1;
1574 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1575 boolean found = FALSE;
1576 int i = sector % SECTOR_BUFFER_SIZE;
1579 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1580 // Async reads are only supported for cdbuffer, so call the sync
1581 // function directly.
1582 return sync_cdimg_read_func(f, base, dest, sector);
1585 pthread_mutex_lock(&read_thread_msg_lock);
1587 // Only wait if we're not trying to read the next sector and
1588 // sector_start is set (meaning the last request hasn't been
1590 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1591 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1594 if (read_thread_sector_start == -1)
1595 read_thread_sector_start = sector;
1597 read_thread_sector_end = sector;
1598 pthread_cond_signal(&read_thread_msg_avail);
1599 pthread_mutex_unlock(&read_thread_msg_lock);
1602 pthread_mutex_lock(§orbuffer_lock);
1603 if (sectorbuffer[i].sector == sector) {
1604 sectorbuffer_index = i;
1605 ret = sectorbuffer[i].ret;
1610 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1612 pthread_mutex_unlock(§orbuffer_lock);
1620 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1621 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1625 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1626 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1631 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1632 unsigned char *buffer;
1633 pthread_mutex_lock(§orbuffer_lock);
1634 buffer = sectorbuffer[sectorbuffer_index].data;
1635 pthread_mutex_unlock(§orbuffer_lock);
1641 static unsigned char * CALLBACK ISOgetBuffer(void) {
1642 return cdbuffer + 12;
1645 static void PrintTracks(void) {
1648 for (i = 1; i <= numtracks; i++) {
1649 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1650 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1651 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1652 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1656 // This function is invoked by the front-end when opening an ISO
1657 // file for playback
1658 static long CALLBACK ISOopen(void) {
1659 boolean isMode1ISO = FALSE;
1660 char alt_bin_filename[MAXPATHLEN];
1661 const char *bin_filename;
1662 char image_str[1024] = {0};
1664 if (cdHandle != NULL) {
1665 return 0; // it's already open
1668 cdHandle = fopen(GetIsoFile(), "rb");
1669 if (cdHandle == NULL) {
1670 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1671 GetIsoFile(), strerror(errno));
1675 sprintf(image_str, "Loaded CD Image: %s", GetIsoFile());
1677 cddaBigEndian = FALSE;
1678 subChanMixed = FALSE;
1681 cdrIsoMultidiskCount = 1;
1684 CDR_getBuffer = ISOgetBuffer;
1685 cdimg_read_func = cdread_normal;
1687 if (parsetoc(GetIsoFile()) == 0) {
1688 strcat(image_str, "[+toc]");
1690 else if (parseccd(GetIsoFile()) == 0) {
1691 strcat(image_str, "[+ccd]");
1693 else if (parsemds(GetIsoFile()) == 0) {
1694 strcat(image_str, "[+mds]");
1696 else if (parsecue(GetIsoFile()) == 0) {
1697 strcat(image_str, "[+cue]");
1699 if (handlepbp(GetIsoFile()) == 0) {
1700 strcat(image_str, "[+pbp]");
1701 CDR_getBuffer = ISOgetBuffer_compr;
1702 cdimg_read_func = cdread_compressed;
1704 else if (handlecbin(GetIsoFile()) == 0) {
1705 strcat(image_str, "[+cbin]");
1706 CDR_getBuffer = ISOgetBuffer_compr;
1707 cdimg_read_func = cdread_compressed;
1710 else if (handlechd(GetIsoFile()) == 0) {
1711 strcat(image_str, "[+chd]");
1712 CDR_getBuffer = ISOgetBuffer_chd;
1713 cdimg_read_func = cdread_chd;
1717 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1718 strcat(image_str, "[+sub]");
1720 if (opensbifile(GetIsoFile()) == 0) {
1721 strcat(image_str, "[+sbi]");
1724 fseeko(cdHandle, 0, SEEK_END);
1726 // maybe user selected metadata file instead of main .bin ..
1727 bin_filename = GetIsoFile();
1728 if (ftello(cdHandle) < 2352 * 0x10) {
1729 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1734 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1735 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1736 if (strlen(alt_bin_filename) >= 4) {
1737 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1738 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1740 tmpf = fopen(alt_bin_filename, "rb");
1746 bin_filename = alt_bin_filename;
1749 fseeko(cdHandle, 0, SEEK_END);
1753 // guess whether it is mode1/2048
1754 if (ftello(cdHandle) % 2048 == 0) {
1755 unsigned int modeTest = 0;
1756 fseek(cdHandle, 0, SEEK_SET);
1757 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1759 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1763 if (SWAP32(modeTest) != 0xffffff00) {
1764 strcat(image_str, "[2048]");
1768 fseek(cdHandle, 0, SEEK_SET);
1770 SysPrintf("%s.\n", image_str);
1775 cdimg_read_func = cdread_sub_mixed;
1776 else if (isMode1ISO)
1777 cdimg_read_func = cdread_2048;
1779 // make sure we have another handle open for cdda
1780 if (numtracks > 1 && ti[1].handle == NULL) {
1781 ti[1].handle = fopen(bin_filename, "rb");
1783 cdda_cur_sector = 0;
1784 cdda_file_offset = 0;
1786 if (Config.AsyncCD) {
1792 static long CALLBACK ISOclose(void) {
1795 if (cdHandle != NULL) {
1799 if (subHandle != NULL) {
1806 if (compr_img != NULL) {
1807 free(compr_img->index_table);
1813 if (chd_img != NULL) {
1814 chd_close(chd_img->chd);
1815 free(chd_img->buffer);
1821 for (i = 1; i <= numtracks; i++) {
1822 if (ti[i].handle != NULL) {
1823 fclose(ti[i].handle);
1824 ti[i].handle = NULL;
1831 memset(cdbuffer, 0, sizeof(cdbuffer));
1832 CDR_getBuffer = ISOgetBuffer;
1834 if (Config.AsyncCD) {
1841 static long CALLBACK ISOinit(void) {
1842 assert(cdHandle == NULL);
1843 assert(subHandle == NULL);
1845 return 0; // do nothing
1848 static long CALLBACK ISOshutdown(void) {
1853 // return Starting and Ending Track
1855 // byte 0 - start track
1856 // byte 1 - end track
1857 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1860 if (numtracks > 0) {
1861 buffer[1] = numtracks;
1870 // return Track Time
1875 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1878 unsigned char time[3];
1879 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1880 sec2msf(sect, (char *)time);
1881 buffer[2] = time[0];
1882 buffer[1] = time[1];
1883 buffer[0] = time[2];
1885 else if (numtracks > 0 && track <= numtracks) {
1886 buffer[2] = ti[track].start[0];
1887 buffer[1] = ti[track].start[1];
1888 buffer[0] = ti[track].start[2];
1899 // decode 'raw' subchannel data ripped by cdrdao
1900 static void DecodeRawSubData(void) {
1901 unsigned char subQData[12];
1904 memset(subQData, 0, sizeof(subQData));
1906 for (i = 0; i < 8 * 12; i++) {
1907 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1908 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1912 memcpy(&subbuffer[12], subQData, 12);
1916 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1918 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1919 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1922 if (cdHandle == NULL) {
1927 subChanMissing = FALSE;
1928 if (sector >= pregapOffset) {
1930 if (sector < pregapOffset)
1931 subChanMissing = TRUE;
1935 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1939 if (subHandle != NULL) {
1940 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1941 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1942 /* Faulty subchannel data shouldn't cause a read failure */
1945 if (subChanRaw) DecodeRawSubData();
1952 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1953 // does NOT uses bcd format
1954 static long CALLBACK ISOplay(unsigned char *time) {
1961 cdda_cur_sector = msf2sec((char *)time);
1962 for (i = numtracks; i > 1; i--) {
1963 cdda_first_sector = msf2sec(ti[i].start);
1964 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1967 cdda_file_offset = ti[i].start_offset;
1969 // find the file that contains this track
1971 if (ti[i].handle != NULL)
1974 cddaHandle = ti[i].handle;
1976 if (SPU_playCDDAchannel != NULL)
1983 static long CALLBACK ISOstop(void) {
1988 // gets subchannel data
1989 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1990 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1997 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
2000 CDR__getStatus(stat);
2004 stat->Status |= 0x80;
2007 // BIOS - boot ID (CD type)
2008 stat->Type = ti[1].type;
2011 // relative -> absolute time
2013 sec2msf(sect, (char *)stat->Time);
2018 // read CDDA sector into buffer
2019 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
2020 unsigned char msf[3] = {m, s, f};
2021 unsigned int file, track, track_start = 0;
2024 cddaCurPos = msf2sec((char *)msf);
2026 // find current track index
2027 for (track = numtracks; ; track--) {
2028 track_start = msf2sec(ti[track].start);
2029 if (track_start <= cddaCurPos)
2035 // data tracks play silent
2036 if (ti[track].type != CDDA) {
2037 memset(buffer, 0, CD_FRAMESIZE_RAW);
2043 // find the file that contains this track
2044 for (file = track; file > 1; file--)
2045 if (ti[file].handle != NULL)
2049 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
2050 buffer, cddaCurPos - track_start);
2051 if (ret != CD_FRAMESIZE_RAW) {
2052 memset(buffer, 0, CD_FRAMESIZE_RAW);
2056 if (cddaBigEndian) {
2060 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
2061 tmp = buffer[i * 2];
2062 buffer[i * 2] = buffer[i * 2 + 1];
2063 buffer[i * 2 + 1] = tmp;
2070 void cdrIsoInit(void) {
2072 CDR_shutdown = ISOshutdown;
2074 CDR_close = ISOclose;
2075 CDR_getTN = ISOgetTN;
2076 CDR_getTD = ISOgetTD;
2077 CDR_readTrack = ISOreadTrack;
2078 CDR_getBuffer = ISOgetBuffer;
2081 CDR_getBufferSub = ISOgetBufferSub;
2082 CDR_getStatus = ISOgetStatus;
2083 CDR_readCDDA = ISOreadCDDA;
2085 CDR_getDriveLetter = CDR__getDriveLetter;
2086 CDR_configure = CDR__configure;
2087 CDR_test = CDR__test;
2088 CDR_about = CDR__about;
2089 CDR_setfilename = CDR__setfilename;
2094 int cdrIsoActive(void) {
2095 return (cdHandle != NULL);