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 <compat/fopen_utf8.h>
24 #include "psxcommon.h"
37 #define WIN32_LEAN_AND_MEAN
40 #define strcasecmp _stricmp
41 #define usleep(x) (Sleep((x) / 1000))
48 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
50 unsigned int cdrIsoMultidiskCount;
51 unsigned int cdrIsoMultidiskSelect;
53 static FILE *cdHandle = NULL;
54 static FILE *cddaHandle = NULL;
55 static FILE *subHandle = NULL;
57 static boolean subChanMixed = FALSE;
58 static boolean subChanRaw = FALSE;
59 static boolean subChanMissing = FALSE;
61 static boolean multifile = FALSE;
63 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
64 static unsigned char subbuffer[SUB_FRAMESIZE];
66 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
68 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
71 static HANDLE threadid;
73 static pthread_t threadid;
75 static unsigned int initial_offset = 0;
76 static boolean playing = FALSE;
77 static boolean cddaBigEndian = FALSE;
78 // cdda sectors in toc, byte offset in file
79 static unsigned int cdda_cur_sector;
80 static unsigned int cdda_first_sector;
81 static unsigned int cdda_file_offset;
82 /* Frame offset into CD image where pregap data would be found if it was there.
83 * If a game seeks there we must *not* return subchannel data since it's
84 * not in the CD image, so that cdrom code can fake subchannel data instead.
85 * XXX: there could be multiple pregaps but PSX dumps only have one? */
86 static unsigned int pregapOffset;
88 #define cddaCurPos cdda_cur_sector
90 // compressed image stuff
92 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
93 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
95 unsigned int index_len;
96 unsigned int block_shift;
97 unsigned int current_block;
98 unsigned int sector_in_blk;
103 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
105 const chd_header* header;
106 unsigned int sectors_per_hunk;
107 unsigned int current_hunk;
108 unsigned int sector_in_hunk;
112 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
114 char* CALLBACK CDR__getDriveLetter(void);
115 long CALLBACK CDR__configure(void);
116 long CALLBACK CDR__test(void);
117 void CALLBACK CDR__about(void);
118 long CALLBACK CDR__setfilename(char *filename);
119 long CALLBACK CDR__getStatus(struct CdrStat *stat);
121 static void DecodeRawSubData(void);
124 enum {DATA=1, CDDA} type;
125 char start[3]; // MSF-format
126 char length[3]; // MSF-format
127 FILE *handle; // for multi-track images CDDA
128 unsigned int start_offset; // byte offset from start of above file
131 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
133 static int numtracks = 0;
134 static struct trackinfo ti[MAXTRACKS];
136 // get a sector from a msf-array
137 static unsigned int msf2sec(char *msf) {
138 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
141 static void sec2msf(unsigned int s, char *msf) {
142 msf[0] = s / 75 / 60;
143 s = s - msf[0] * 75 * 60;
149 // divide a string of xx:yy:zz into m, s, f
150 static void tok2msf(char *time, char *msf) {
153 token = strtok(time, ":");
155 msf[0] = atoi(token);
161 token = strtok(NULL, ":");
163 msf[1] = atoi(token);
169 token = strtok(NULL, ":");
171 msf[2] = atoi(token);
179 static long GetTickCount(void) {
180 static time_t initial_time = 0;
183 gettimeofday(&now, NULL);
185 if (initial_time == 0) {
186 initial_time = now.tv_sec;
189 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
193 // this thread plays audio data
195 static void playthread(void *param)
197 static void *playthread(void *param)
200 long osleep, d, t, i, s;
202 int ret = 0, sector_offs;
208 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
209 sector_offs = cdda_cur_sector - cdda_first_sector;
210 if (sector_offs < 0) {
211 d = CD_FRAMESIZE_RAW;
212 memset(sndbuffer + s, 0, d);
215 d = cdimg_read_func(cddaHandle, cdda_file_offset,
216 sndbuffer + s, sector_offs);
217 if (d < CD_FRAMESIZE_RAW)
231 if (!cdr.Muted && playing) {
233 for (i = 0; i < s / 2; i++) {
234 tmp = sndbuffer[i * 2];
235 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
236 sndbuffer[i * 2 + 1] = tmp;
240 // can't do it yet due to readahead..
241 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
243 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
248 } while (ret == 0x7761 && playing); // rearmed_wait
251 if (ret != 0x676f) { // !rearmed_go
255 // HACK: stop feeding data while emu is paused
257 while (stop && playing)
262 now = GetTickCount();
268 else if (osleep > CDDA_FRAMETIME) {
269 osleep = CDDA_FRAMETIME;
273 usleep(osleep * 1000);
287 // stop the CDDA playback
288 static void stopCDDA() {
295 WaitForSingleObject(threadid, INFINITE);
297 pthread_join(threadid, NULL);
301 // start the CDDA playback
302 static void startCDDA(void) {
310 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
312 pthread_create(&threadid, NULL, playthread, NULL);
316 // this function tries to get the .toc file of the given .bin
317 // the necessary data is put into the ti (trackinformation)-array
318 static int parsetoc(const char *isofile) {
319 char tocname[MAXPATHLEN];
321 char linebuf[256], tmp[256], name[256];
323 char time[20], time2[20];
324 unsigned int t, sector_offs, sector_size;
325 unsigned int current_zero_gap = 0;
329 // copy name of the iso and change extension from .bin to .toc
330 strncpy(tocname, isofile, sizeof(tocname));
331 tocname[MAXPATHLEN - 1] = '\0';
332 if (strlen(tocname) >= 4) {
333 strcpy(tocname + strlen(tocname) - 4, ".toc");
339 if ((fi = fopen_utf8(tocname, "r")) == NULL) {
340 // try changing extension to .cue (to satisfy some stupid tutorials)
341 strcpy(tocname + strlen(tocname) - 4, ".cue");
342 if ((fi = fopen_utf8(tocname, "r")) == NULL) {
343 // if filename is image.toc.bin, try removing .bin (for Brasero)
344 strcpy(tocname, isofile);
346 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
347 tocname[t - 4] = '\0';
348 if ((fi = fopen_utf8(tocname, "r")) == NULL) {
356 // check if it's really a TOC named as a .cue
357 fgets(linebuf, sizeof(linebuf), fi);
358 token = strtok(linebuf, " ");
359 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
363 fseek(fi, 0, SEEK_SET);
366 memset(&ti, 0, sizeof(ti));
367 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
369 sector_size = CD_FRAMESIZE_RAW;
370 sector_offs = 2 * 75;
372 // parse the .toc file
373 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
375 strncpy(tmp, linebuf, sizeof(linebuf));
376 token = strtok(tmp, " ");
378 if (token == NULL) continue;
380 if (!strcmp(token, "TRACK")) {
381 sector_offs += current_zero_gap;
382 current_zero_gap = 0;
385 token = strtok(NULL, " ");
388 if (!strncmp(token, "MODE2_RAW", 9)) {
389 ti[numtracks].type = DATA;
390 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
392 // check if this image contains mixed subchannel data
393 token = strtok(NULL, " ");
394 if (token != NULL && !strncmp(token, "RW", 2)) {
395 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
397 if (!strncmp(token, "RW_RAW", 6))
401 else if (!strncmp(token, "AUDIO", 5)) {
402 ti[numtracks].type = CDDA;
405 else if (!strcmp(token, "DATAFILE")) {
406 if (ti[numtracks].type == CDDA) {
407 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
408 ti[numtracks].start_offset = t;
409 t = t / sector_size + sector_offs;
410 sec2msf(t, (char *)&ti[numtracks].start);
411 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
414 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
415 tok2msf((char *)&time, (char *)&ti[numtracks].length);
418 else if (!strcmp(token, "FILE")) {
419 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
420 tok2msf((char *)&time, (char *)&ti[numtracks].start);
421 t += msf2sec(ti[numtracks].start) * sector_size;
422 ti[numtracks].start_offset = t;
423 t = t / sector_size + sector_offs;
424 sec2msf(t, (char *)&ti[numtracks].start);
425 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
427 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
428 // skip unneeded optional fields
429 while (token != NULL) {
430 token = strtok(NULL, " ");
431 if (strchr(token, ':') != NULL)
436 current_zero_gap = msf2sec(tmp);
439 t = ti[numtracks - 1].start_offset;
441 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
444 else if (!strcmp(token, "START")) {
445 token = strtok(NULL, " ");
446 if (token != NULL && strchr(token, ':')) {
449 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
450 t = msf2sec(ti[numtracks].start) + t;
451 sec2msf(t, (char *)&ti[numtracks].start);
461 // this function tries to get the .cue file of the given .bin
462 // the necessary data is put into the ti (trackinformation)-array
463 static int parsecue(const char *isofile) {
464 char cuename[MAXPATHLEN];
465 char filepath[MAXPATHLEN];
471 char linebuf[256], tmpb[256], dummy[256];
472 unsigned int incue_max_len;
473 unsigned int t, file_len, mode, sector_offs;
474 unsigned int sector_size = 2352;
478 // copy name of the iso and change extension from .bin to .cue
479 strncpy(cuename, isofile, sizeof(cuename));
480 cuename[MAXPATHLEN - 1] = '\0';
481 if (strlen(cuename) >= 4) {
482 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
483 // and don't try to search the additional .cue file
484 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
485 strcpy(cuename + strlen(cuename) - 4, ".cue");
491 if ((fi = fopen_utf8(cuename, "r")) == NULL) {
495 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
496 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
498 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
499 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
500 // Don't proceed further, as this is actually a .toc file rather
503 return parsetoc(isofile);
505 fseek(fi, 0, SEEK_SET);
508 // build a path for files referenced in .cue
509 strncpy(filepath, cuename, sizeof(filepath));
510 tmp = strrchr(filepath, '/');
512 tmp = strrchr(filepath, '\\');
518 filepath[sizeof(filepath) - 1] = 0;
520 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
522 memset(&ti, 0, sizeof(ti));
525 sector_offs = 2 * 75;
527 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
528 strncpy(dummy, linebuf, sizeof(linebuf));
529 token = strtok(dummy, " ");
535 if (!strcmp(token, "TRACK")) {
539 if (strstr(linebuf, "AUDIO") != NULL) {
540 ti[numtracks].type = CDDA;
543 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
544 ti[numtracks].type = DATA;
546 SysPrintf(".cue: failed to parse TRACK\n");
547 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
549 if (sector_size == 0)
552 else if (!strcmp(token, "INDEX")) {
553 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
554 SysPrintf(".cue: failed to parse INDEX\n");
555 tok2msf(time, (char *)&ti[numtracks].start);
557 t = msf2sec(ti[numtracks].start);
558 ti[numtracks].start_offset = t * sector_size;
560 sec2msf(t, ti[numtracks].start);
562 // default track length to file length
563 t = file_len - ti[numtracks].start_offset / sector_size;
564 sec2msf(t, ti[numtracks].length);
566 if (numtracks > 1 && ti[numtracks].handle == NULL) {
567 // this track uses the same file as the last,
568 // start of this track is last track's end
569 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
570 sec2msf(t, ti[numtracks - 1].length);
572 if (numtracks > 1 && pregapOffset == -1)
573 pregapOffset = ti[numtracks].start_offset / sector_size;
575 else if (!strcmp(token, "PREGAP")) {
576 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
577 tok2msf(time, dummy);
578 sector_offs += msf2sec(dummy);
580 pregapOffset = -1; // mark to fill track start_offset
582 else if (!strcmp(token, "FILE")) {
583 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
585 sscanf(linebuf, " FILE %255s", tmpb);
587 tmp = strrchr(tmpb, '\\');
589 tmp = strrchr(tmpb, '/');
594 strncpy(incue_fname, tmp, incue_max_len);
595 ti[numtracks + 1].handle = fopen_utf8(filepath, "rb");
597 // update global offset if this is not first file in this .cue
598 if (numtracks + 1 > 1) {
600 sector_offs += file_len;
604 if (ti[numtracks + 1].handle == NULL) {
605 SysPrintf(_("\ncould not open: %s\n"), filepath);
608 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
609 file_len = ftell(ti[numtracks + 1].handle) / 2352;
611 if (numtracks == 0 && strlen(isofile) >= 4 &&
612 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
613 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
614 // user selected .cue/.cdX as image file, use it's data track instead
616 cdHandle = fopen_utf8(filepath, "rb");
623 // if there are no tracks detected, then it's not a cue file
630 // this function tries to get the .ccd file of the given .img
631 // the necessary data is put into the ti (trackinformation)-array
632 static int parseccd(const char *isofile) {
633 char ccdname[MAXPATHLEN];
640 // copy name of the iso and change extension from .img to .ccd
641 strncpy(ccdname, isofile, sizeof(ccdname));
642 ccdname[MAXPATHLEN - 1] = '\0';
643 if (strlen(ccdname) >= 4) {
644 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
650 if ((fi = fopen_utf8(ccdname, "r")) == NULL) {
654 memset(&ti, 0, sizeof(ti));
656 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
657 if (!strncmp(linebuf, "[TRACK", 6)){
660 else if (!strncmp(linebuf, "MODE=", 5)) {
661 sscanf(linebuf, "MODE=%d", &t);
662 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
664 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
665 sscanf(linebuf, "INDEX 1=%d", &t);
666 sec2msf(t + 2 * 75, ti[numtracks].start);
667 ti[numtracks].start_offset = t * 2352;
669 // If we've already seen another track, this is its end
671 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
672 sec2msf(t, ti[numtracks - 1].length);
679 // Fill out the last track's end based on size
680 if (numtracks >= 1) {
681 fseek(cdHandle, 0, SEEK_END);
682 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
683 sec2msf(t, ti[numtracks].length);
689 // this function tries to get the .mds file of the given .mdf
690 // the necessary data is put into the ti (trackinformation)-array
691 static int parsemds(const char *isofile) {
692 char mdsname[MAXPATHLEN];
694 unsigned int offset, extra_offset, l, i;
699 // copy name of the iso and change extension from .mdf to .mds
700 strncpy(mdsname, isofile, sizeof(mdsname));
701 mdsname[MAXPATHLEN - 1] = '\0';
702 if (strlen(mdsname) >= 4) {
703 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
709 if ((fi = fopen_utf8(mdsname, "rb")) == NULL) {
713 memset(&ti, 0, sizeof(ti));
715 // check if it's a valid mds file
716 fread(&i, 1, sizeof(unsigned int), fi);
718 if (i != 0x4944454D) {
719 // not an valid mds file
724 // get offset to session block
725 fseek(fi, 0x50, SEEK_SET);
726 fread(&offset, 1, sizeof(unsigned int), fi);
727 offset = SWAP32(offset);
729 // get total number of tracks
731 fseek(fi, offset, SEEK_SET);
732 fread(&s, 1, sizeof(unsigned short), fi);
736 // get offset to track blocks
737 fseek(fi, 4, SEEK_CUR);
738 fread(&offset, 1, sizeof(unsigned int), fi);
739 offset = SWAP32(offset);
743 fseek(fi, offset + 4, SEEK_SET);
744 if (fgetc(fi) < 0xA0) {
750 // check if the image contains mixed subchannel data
751 fseek(fi, offset + 1, SEEK_SET);
752 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
755 for (i = 1; i <= numtracks; i++) {
756 fseek(fi, offset, SEEK_SET);
758 // get the track type
759 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
760 fseek(fi, 8, SEEK_CUR);
762 // get the track starting point
763 ti[i].start[0] = fgetc(fi);
764 ti[i].start[1] = fgetc(fi);
765 ti[i].start[2] = fgetc(fi);
767 fread(&extra_offset, 1, sizeof(unsigned int), fi);
768 extra_offset = SWAP32(extra_offset);
770 // get track start offset (in .mdf)
771 fseek(fi, offset + 0x28, SEEK_SET);
772 fread(&l, 1, sizeof(unsigned int), fi);
774 ti[i].start_offset = l;
777 fseek(fi, extra_offset, SEEK_SET);
778 fread(&l, 1, sizeof(unsigned int), fi);
781 pregapOffset = msf2sec(ti[i].start);
783 // get the track length
784 fread(&l, 1, sizeof(unsigned int), fi);
786 sec2msf(l, ti[i].length);
795 static int handlepbp(const char *isofile) {
798 unsigned int dontcare[8];
799 unsigned int psar_offs;
812 unsigned int dontcare[6];
815 off_t psisoimg_offs, cdimg_base;
816 unsigned int t, cd_length;
817 unsigned int offsettab[8];
818 const char *ext = NULL;
821 if (strlen(isofile) >= 4)
822 ext = isofile + strlen(isofile) - 4;
823 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
826 fseeko(cdHandle, 0, SEEK_SET);
830 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
831 if (ret != sizeof(pbp_hdr)) {
832 SysPrintf("failed to read pbp\n");
836 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
838 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
842 psisoimg_offs = pbp_hdr.psar_offs;
843 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
845 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
847 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
849 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
853 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
854 SysPrintf("failed to read offsettab\n");
858 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
859 if (offsettab[i] == 0)
862 cdrIsoMultidiskCount = i;
863 if (cdrIsoMultidiskCount == 0) {
864 SysPrintf("multidisk eboot has 0 images?\n");
868 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
869 cdrIsoMultidiskSelect = 0;
871 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
873 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
875 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
879 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
883 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
884 SysPrintf("bad psar_sig: %s\n", psar_sig);
889 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
891 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
895 // first 3 entries are special
896 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
897 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
898 numtracks = btoi(toc_entry.index1[0]);
900 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
901 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
902 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
904 for (i = 1; i <= numtracks; i++) {
905 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
907 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
909 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
910 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
911 ti[i].start_offset *= 2352;
912 ti[i].start[0] = btoi(toc_entry.index1[0]);
913 ti[i].start[1] = btoi(toc_entry.index1[1]);
914 ti[i].start[2] = btoi(toc_entry.index1[2]);
917 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
918 sec2msf(t, ti[i - 1].length);
921 t = cd_length - ti[numtracks].start_offset / 2352;
922 sec2msf(t, ti[numtracks].length);
925 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
927 SysPrintf("failed to seek to ISO index\n");
931 compr_img = calloc(1, sizeof(*compr_img));
932 if (compr_img == NULL)
935 compr_img->block_shift = 4;
936 compr_img->current_block = (unsigned int)-1;
938 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
939 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
940 if (compr_img->index_table == NULL)
943 cdimg_base = psisoimg_offs + 0x100000;
944 for (i = 0; i < compr_img->index_len; i++) {
945 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
946 if (ret != sizeof(index_entry)) {
947 SysPrintf("failed to read index_entry #%d\n", i);
951 if (index_entry.size == 0)
954 compr_img->index_table[i] = cdimg_base + index_entry.offset;
956 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
961 free(compr_img->index_table);
962 compr_img->index_table = NULL;
964 if (compr_img != NULL) {
971 static int handlecbin(const char *isofile) {
975 unsigned int header_size;
976 unsigned long long total_bytes;
977 unsigned int block_size;
978 unsigned char ver; // 1
980 unsigned char rsv_06[2];
982 const char *ext = NULL;
983 unsigned int *index_table = NULL;
984 unsigned int index = 0, plain;
987 if (strlen(isofile) >= 5)
988 ext = isofile + strlen(isofile) - 5;
989 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
992 fseek(cdHandle, 0, SEEK_SET);
994 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
995 if (ret != sizeof(ciso_hdr)) {
996 SysPrintf("failed to read ciso header\n");
1000 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
1001 SysPrintf("bad ciso header\n");
1004 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
1005 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
1007 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
1012 compr_img = calloc(1, sizeof(*compr_img));
1013 if (compr_img == NULL)
1016 compr_img->block_shift = 0;
1017 compr_img->current_block = (unsigned int)-1;
1019 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
1020 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
1021 if (index_table == NULL)
1024 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1025 if (ret != compr_img->index_len) {
1026 SysPrintf("failed to read index table\n");
1030 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1031 if (compr_img->index_table == NULL)
1034 for (i = 0; i < compr_img->index_len + 1; i++) {
1035 index = index_table[i];
1036 plain = index & 0x80000000;
1037 index &= 0x7fffffff;
1038 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1040 compr_img->index_table[i] |= OFF_T_MSB;
1048 if (compr_img != NULL) {
1056 static int handlechd(const char *isofile) {
1057 chd_img = calloc(1, sizeof(*chd_img));
1058 if (chd_img == NULL)
1061 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
1064 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
1067 chd_img->header = chd_get_header(chd_img->chd);
1069 chd_img->buffer = malloc(chd_img->header->hunkbytes);
1070 if (chd_img->buffer == NULL)
1073 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1074 chd_img->current_hunk = (unsigned int)-1;
1076 cddaBigEndian = TRUE;
1079 int frame_offset = 0;
1080 int file_offset = 0;
1081 memset(ti, 0, sizeof(ti));
1096 uint32_t meta_size = 0;
1098 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1099 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1100 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1101 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1108 sec2msf(msf2sec(ti[md.track-1].length) + md.pregap, ti[md.track-1].length);
1110 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1112 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1113 sec2msf(md.frames, ti[md.track].length);
1115 ti[md.track].start_offset = file_offset;
1117 frame_offset += md.pregap + md.frames + md.postgap;
1118 file_offset += md.frames + md.postgap;
1126 if (chd_img != NULL) {
1127 free(chd_img->buffer);
1135 // this function tries to get the .sub file of the given .img
1136 static int opensubfile(const char *isoname) {
1137 char subname[MAXPATHLEN];
1139 // copy name of the iso and change extension from .img to .sub
1140 strncpy(subname, isoname, sizeof(subname));
1141 subname[MAXPATHLEN - 1] = '\0';
1142 if (strlen(subname) >= 4) {
1143 strcpy(subname + strlen(subname) - 4, ".sub");
1149 subHandle = fopen_utf8(subname, "rb");
1150 if (subHandle == NULL) {
1157 static int opensbifile(const char *isoname) {
1158 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1161 strncpy(sbiname, isoname, sizeof(sbiname));
1162 sbiname[MAXPATHLEN - 1] = '\0';
1163 if (strlen(sbiname) >= 4) {
1164 if (cdrIsoMultidiskCount > 1) {
1165 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1166 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1169 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1175 fseek(cdHandle, 0, SEEK_END);
1176 s = ftell(cdHandle) / 2352;
1178 return LoadSBI(sbiname, s);
1182 static void readThreadStop() {}
1183 static void readThreadStart() {}
1185 static pthread_t read_thread_id;
1187 static pthread_cond_t read_thread_msg_avail;
1188 static pthread_cond_t read_thread_msg_done;
1189 static pthread_mutex_t read_thread_msg_lock;
1191 static pthread_cond_t sectorbuffer_cond;
1192 static pthread_mutex_t sectorbuffer_lock;
1194 static boolean read_thread_running = FALSE;
1195 static int read_thread_sector_start = -1;
1196 static int read_thread_sector_end = -1;
1201 unsigned char data[CD_FRAMESIZE_RAW];
1202 } SectorBufferEntry;
1204 #define SECTOR_BUFFER_SIZE 4096
1206 static SectorBufferEntry *sectorbuffer;
1207 static size_t sectorbuffer_index;
1209 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1210 unsigned char *(*sync_CDR_getBuffer)(void);
1212 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1213 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1215 static void *readThreadMain(void *param) {
1216 int max_sector = -1;
1217 int requested_sector_start = -1;
1218 int requested_sector_end = -1;
1219 int last_read_sector = -1;
1225 int speedmult_ra = 4;
1228 int how_far_ahead = 0;
1230 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1233 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1236 pthread_mutex_lock(&read_thread_msg_lock);
1238 // If we don't have readahead and we don't have a sector request, wait for one.
1239 // If we still have readahead to go, don't block, just keep going.
1240 // And if we ever have a sector request pending, acknowledge and reset it.
1243 if (read_thread_sector_start == -1 && read_thread_running) {
1244 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1248 if (read_thread_sector_start != -1) {
1249 requested_sector_start = read_thread_sector_start;
1250 requested_sector_end = read_thread_sector_end;
1251 read_thread_sector_start = -1;
1252 read_thread_sector_end = -1;
1253 pthread_cond_signal(&read_thread_msg_done);
1256 pthread_mutex_unlock(&read_thread_msg_lock);
1258 if (!read_thread_running)
1261 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1262 if (requested_sector_start != -1) {
1263 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1264 how_far_ahead = ra_sector - requested_sector_end;
1266 if(how_far_ahead <= max_ra)
1267 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1270 } else if (requested_sector_end != last_read_sector) {
1271 ra_sector = requested_sector_end;
1272 ra_count = initial_ra;
1275 last_read_sector = requested_sector_end;
1278 index = ra_sector % SECTOR_BUFFER_SIZE;
1280 // check for end of CD
1281 if (ra_count && ra_sector >= max_sector) {
1283 pthread_mutex_lock(§orbuffer_lock);
1284 sectorbuffer[index].ret = -1;
1285 sectorbuffer[index].sector = ra_sector;
1286 pthread_cond_signal(§orbuffer_cond);
1287 pthread_mutex_unlock(§orbuffer_lock);
1291 pthread_mutex_lock(§orbuffer_lock);
1292 if (sectorbuffer[index].sector != ra_sector) {
1293 pthread_mutex_unlock(§orbuffer_lock);
1295 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1297 pthread_mutex_lock(§orbuffer_lock);
1298 sectorbuffer[index].ret = ret;
1299 sectorbuffer[index].sector = ra_sector;
1300 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1302 pthread_cond_signal(§orbuffer_cond);
1303 pthread_mutex_unlock(§orbuffer_lock);
1313 static void readThreadStop() {
1314 if (read_thread_running == TRUE) {
1315 read_thread_running = FALSE;
1316 pthread_cond_signal(&read_thread_msg_avail);
1317 pthread_join(read_thread_id, NULL);
1320 pthread_cond_destroy(&read_thread_msg_done);
1321 pthread_cond_destroy(&read_thread_msg_avail);
1322 pthread_mutex_destroy(&read_thread_msg_lock);
1324 pthread_cond_destroy(§orbuffer_cond);
1325 pthread_mutex_destroy(§orbuffer_lock);
1327 CDR_getBuffer = sync_CDR_getBuffer;
1328 cdimg_read_func = sync_cdimg_read_func;
1331 sectorbuffer = NULL;
1334 static void readThreadStart() {
1335 SysPrintf("Starting async CD thread\n");
1337 if (read_thread_running == TRUE)
1340 read_thread_running = TRUE;
1341 read_thread_sector_start = -1;
1342 read_thread_sector_end = -1;
1343 sectorbuffer_index = 0;
1345 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1349 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1351 sync_CDR_getBuffer = CDR_getBuffer;
1352 CDR_getBuffer = ISOgetBuffer_async;
1353 sync_cdimg_read_func = cdimg_read_func;
1354 cdimg_read_func = cdread_async;
1356 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1357 pthread_cond_init(&read_thread_msg_done, NULL) ||
1358 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1359 pthread_cond_init(§orbuffer_cond, NULL) ||
1360 pthread_mutex_init(§orbuffer_lock, NULL) ||
1361 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1367 SysPrintf("Error starting async CD thread\n");
1368 SysPrintf("Falling back to sync\n");
1374 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1376 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1377 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1380 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1384 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1385 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1386 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1388 if (subChanRaw) DecodeRawSubData();
1393 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1398 if (z.zalloc == NULL) {
1399 // XXX: one-time leak here..
1405 ret = inflateInit2(&z, -15);
1408 ret = inflateReset(&z);
1413 z.avail_in = in_size;
1415 z.avail_out = *out_size;
1417 ret = inflate(&z, Z_NO_FLUSH);
1420 *out_size -= z.avail_out;
1421 return ret == 1 ? 0 : ret;
1424 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1426 unsigned long cdbuffer_size, cdbuffer_size_expect;
1433 sector += base / 2352;
1435 block = sector >> compr_img->block_shift;
1436 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1438 if (block == compr_img->current_block) {
1439 //printf("hit sect %d\n", sector);
1443 if (sector >= compr_img->index_len * 16) {
1444 SysPrintf("sector %d is past img end\n", sector);
1448 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1449 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1450 SysPrintf("seek error for block %d at %llx: ",
1451 block, (long long)start_byte);
1456 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1457 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1458 if (size > sizeof(compr_img->buff_compressed)) {
1459 SysPrintf("block %d is too large: %u\n", block, size);
1463 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1464 1, size, cdHandle) != size) {
1465 SysPrintf("read error for block %d at %x: ", block, start_byte);
1470 if (is_compressed) {
1471 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1472 cdbuffer_size = cdbuffer_size_expect;
1473 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1475 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1476 ret, block, sector);
1479 if (cdbuffer_size != cdbuffer_size_expect)
1480 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1481 cdbuffer_size_expect, sector);
1485 compr_img->current_block = block;
1488 if (dest != cdbuffer) // copy avoid HACK
1489 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1491 return CD_FRAMESIZE_RAW;
1495 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1502 hunk = sector / chd_img->sectors_per_hunk;
1503 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1505 if (hunk != chd_img->current_hunk)
1507 chd_read(chd_img->chd, hunk, chd_img->buffer);
1508 chd_img->current_hunk = hunk;
1511 if (dest != cdbuffer) // copy avoid HACK
1512 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1514 return CD_FRAMESIZE_RAW;
1517 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1521 fseek(f, base + sector * 2048, SEEK_SET);
1522 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1524 // not really necessary, fake mode 2 header
1525 memset(cdbuffer, 0, 12 * 2);
1526 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1527 cdbuffer[12 + 3] = 1;
1534 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1535 boolean found = FALSE;
1536 int i = sector % SECTOR_BUFFER_SIZE;
1539 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1540 // Async reads are only supported for cdbuffer, so call the sync
1541 // function directly.
1542 return sync_cdimg_read_func(f, base, dest, sector);
1545 pthread_mutex_lock(&read_thread_msg_lock);
1547 // Only wait if we're not trying to read the next sector and
1548 // sector_start is set (meaning the last request hasn't been
1550 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1551 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1554 if (read_thread_sector_start == -1)
1555 read_thread_sector_start = sector;
1557 read_thread_sector_end = sector;
1558 pthread_cond_signal(&read_thread_msg_avail);
1559 pthread_mutex_unlock(&read_thread_msg_lock);
1562 pthread_mutex_lock(§orbuffer_lock);
1563 if (sectorbuffer[i].sector == sector) {
1564 sectorbuffer_index = i;
1565 ret = sectorbuffer[i].ret;
1570 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1572 pthread_mutex_unlock(§orbuffer_lock);
1580 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1581 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1585 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1586 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1591 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1592 unsigned char *buffer;
1593 pthread_mutex_lock(§orbuffer_lock);
1594 buffer = sectorbuffer[sectorbuffer_index].data;
1595 pthread_mutex_unlock(§orbuffer_lock);
1601 static unsigned char * CALLBACK ISOgetBuffer(void) {
1602 return cdbuffer + 12;
1605 static void PrintTracks(void) {
1608 for (i = 1; i <= numtracks; i++) {
1609 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1610 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1611 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1612 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1616 // This function is invoked by the front-end when opening an ISO
1617 // file for playback
1618 static long CALLBACK ISOopen(void) {
1619 boolean isMode1ISO = FALSE;
1620 char alt_bin_filename[MAXPATHLEN];
1621 const char *bin_filename;
1622 char image_str[1024] = {0};
1624 if (cdHandle != NULL) {
1625 return 0; // it's already open
1628 cdHandle = fopen_utf8(GetIsoFile(), "rb");
1629 if (cdHandle == NULL) {
1630 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1631 GetIsoFile(), strerror(errno));
1635 sprintf(image_str, "Loaded CD Image: %s", GetIsoFile());
1637 cddaBigEndian = FALSE;
1638 subChanMixed = FALSE;
1641 cdrIsoMultidiskCount = 1;
1644 CDR_getBuffer = ISOgetBuffer;
1645 cdimg_read_func = cdread_normal;
1647 if (parsetoc(GetIsoFile()) == 0) {
1648 strcat(image_str, "[+toc]");
1650 else if (parseccd(GetIsoFile()) == 0) {
1651 strcat(image_str, "[+ccd]");
1653 else if (parsemds(GetIsoFile()) == 0) {
1654 strcat(image_str, "[+mds]");
1656 else if (parsecue(GetIsoFile()) == 0) {
1657 strcat(image_str, "[+cue]");
1659 if (handlepbp(GetIsoFile()) == 0) {
1660 strcat(image_str, "[+pbp]");
1661 CDR_getBuffer = ISOgetBuffer_compr;
1662 cdimg_read_func = cdread_compressed;
1664 else if (handlecbin(GetIsoFile()) == 0) {
1665 strcat(image_str, "[+cbin]");
1666 CDR_getBuffer = ISOgetBuffer_compr;
1667 cdimg_read_func = cdread_compressed;
1670 else if (handlechd(GetIsoFile()) == 0) {
1671 strcat(image_str, "[+chd]");
1672 CDR_getBuffer = ISOgetBuffer_chd;
1673 cdimg_read_func = cdread_chd;
1677 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1678 strcat(image_str, "[+sub]");
1680 if (opensbifile(GetIsoFile()) == 0) {
1681 strcat(image_str, "[+sbi]");
1684 fseeko(cdHandle, 0, SEEK_END);
1686 // maybe user selected metadata file instead of main .bin ..
1687 bin_filename = GetIsoFile();
1688 if (ftello(cdHandle) < 2352 * 0x10) {
1689 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1694 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1695 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1696 if (strlen(alt_bin_filename) >= 4) {
1697 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1698 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1700 tmpf = fopen_utf8(alt_bin_filename, "rb");
1706 bin_filename = alt_bin_filename;
1709 fseeko(cdHandle, 0, SEEK_END);
1713 // guess whether it is mode1/2048
1714 if (ftello(cdHandle) % 2048 == 0) {
1715 unsigned int modeTest = 0;
1716 fseek(cdHandle, 0, SEEK_SET);
1717 fread(&modeTest, 4, 1, cdHandle);
1718 if (SWAP32(modeTest) != 0xffffff00) {
1719 strcat(image_str, "[2048]");
1723 fseek(cdHandle, 0, SEEK_SET);
1725 SysPrintf("%s.\n", image_str);
1730 cdimg_read_func = cdread_sub_mixed;
1731 else if (isMode1ISO)
1732 cdimg_read_func = cdread_2048;
1734 // make sure we have another handle open for cdda
1735 if (numtracks > 1 && ti[1].handle == NULL) {
1736 ti[1].handle = fopen_utf8(bin_filename, "rb");
1738 cdda_cur_sector = 0;
1739 cdda_file_offset = 0;
1741 if (Config.AsyncCD) {
1747 static long CALLBACK ISOclose(void) {
1750 if (cdHandle != NULL) {
1754 if (subHandle != NULL) {
1761 if (compr_img != NULL) {
1762 free(compr_img->index_table);
1768 if (chd_img != NULL) {
1769 chd_close(chd_img->chd);
1770 free(chd_img->buffer);
1776 for (i = 1; i <= numtracks; i++) {
1777 if (ti[i].handle != NULL) {
1778 fclose(ti[i].handle);
1779 ti[i].handle = NULL;
1786 memset(cdbuffer, 0, sizeof(cdbuffer));
1787 CDR_getBuffer = ISOgetBuffer;
1789 if (Config.AsyncCD) {
1796 static long CALLBACK ISOinit(void) {
1797 assert(cdHandle == NULL);
1798 assert(subHandle == NULL);
1800 return 0; // do nothing
1803 static long CALLBACK ISOshutdown(void) {
1808 // return Starting and Ending Track
1810 // byte 0 - start track
1811 // byte 1 - end track
1812 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1815 if (numtracks > 0) {
1816 buffer[1] = numtracks;
1825 // return Track Time
1830 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1833 unsigned char time[3];
1834 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1835 sec2msf(sect, (char *)time);
1836 buffer[2] = time[0];
1837 buffer[1] = time[1];
1838 buffer[0] = time[2];
1840 else if (numtracks > 0 && track <= numtracks) {
1841 buffer[2] = ti[track].start[0];
1842 buffer[1] = ti[track].start[1];
1843 buffer[0] = ti[track].start[2];
1854 // decode 'raw' subchannel data ripped by cdrdao
1855 static void DecodeRawSubData(void) {
1856 unsigned char subQData[12];
1859 memset(subQData, 0, sizeof(subQData));
1861 for (i = 0; i < 8 * 12; i++) {
1862 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1863 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1867 memcpy(&subbuffer[12], subQData, 12);
1871 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1873 static long CALLBACK ISOreadTrack(unsigned char *time) {
1874 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1877 if (cdHandle == NULL) {
1882 subChanMissing = FALSE;
1883 if (sector >= pregapOffset) {
1885 if (sector < pregapOffset)
1886 subChanMissing = TRUE;
1890 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1894 if (subHandle != NULL) {
1895 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1896 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1898 if (subChanRaw) DecodeRawSubData();
1905 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1906 // does NOT uses bcd format
1907 static long CALLBACK ISOplay(unsigned char *time) {
1914 cdda_cur_sector = msf2sec((char *)time);
1915 for (i = numtracks; i > 1; i--) {
1916 cdda_first_sector = msf2sec(ti[i].start);
1917 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1920 cdda_file_offset = ti[i].start_offset;
1922 // find the file that contains this track
1924 if (ti[i].handle != NULL)
1927 cddaHandle = ti[i].handle;
1929 if (SPU_playCDDAchannel != NULL)
1936 static long CALLBACK ISOstop(void) {
1941 // gets subchannel data
1942 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1943 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1950 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1953 CDR__getStatus(stat);
1957 stat->Status |= 0x80;
1960 // BIOS - boot ID (CD type)
1961 stat->Type = ti[1].type;
1964 // relative -> absolute time
1966 sec2msf(sect, (char *)stat->Time);
1971 // read CDDA sector into buffer
1972 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1973 unsigned char msf[3] = {m, s, f};
1974 unsigned int file, track, track_start = 0;
1977 cddaCurPos = msf2sec((char *)msf);
1979 // find current track index
1980 for (track = numtracks; ; track--) {
1981 track_start = msf2sec(ti[track].start);
1982 if (track_start <= cddaCurPos)
1988 // data tracks play silent
1989 if (ti[track].type != CDDA) {
1990 memset(buffer, 0, CD_FRAMESIZE_RAW);
1996 // find the file that contains this track
1997 for (file = track; file > 1; file--)
1998 if (ti[file].handle != NULL)
2002 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
2003 buffer, cddaCurPos - track_start);
2004 if (ret != CD_FRAMESIZE_RAW) {
2005 memset(buffer, 0, CD_FRAMESIZE_RAW);
2009 if (cddaBigEndian) {
2013 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
2014 tmp = buffer[i * 2];
2015 buffer[i * 2] = buffer[i * 2 + 1];
2016 buffer[i * 2 + 1] = tmp;
2023 void cdrIsoInit(void) {
2025 CDR_shutdown = ISOshutdown;
2027 CDR_close = ISOclose;
2028 CDR_getTN = ISOgetTN;
2029 CDR_getTD = ISOgetTD;
2030 CDR_readTrack = ISOreadTrack;
2031 CDR_getBuffer = ISOgetBuffer;
2034 CDR_getBufferSub = ISOgetBufferSub;
2035 CDR_getStatus = ISOgetStatus;
2036 CDR_readCDDA = ISOreadCDDA;
2038 CDR_getDriveLetter = CDR__getDriveLetter;
2039 CDR_configure = CDR__configure;
2040 CDR_test = CDR__test;
2041 CDR_about = CDR__about;
2042 CDR_setfilename = CDR__setfilename;
2047 int cdrIsoActive(void) {
2048 return (cdHandle != NULL);