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 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
48 unsigned int cdrIsoMultidiskCount;
49 unsigned int cdrIsoMultidiskSelect;
51 static FILE *cdHandle = NULL;
52 static FILE *cddaHandle = NULL;
53 static FILE *subHandle = NULL;
55 static boolean subChanMixed = FALSE;
56 static boolean subChanRaw = FALSE;
57 static boolean subChanMissing = FALSE;
59 static boolean multifile = FALSE;
61 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
62 static unsigned char subbuffer[SUB_FRAMESIZE];
64 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
66 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
69 static HANDLE threadid;
71 static pthread_t threadid;
73 static unsigned int initial_offset = 0;
74 static boolean playing = FALSE;
75 static boolean cddaBigEndian = FALSE;
76 // cdda sectors in toc, byte offset in file
77 static unsigned int cdda_cur_sector;
78 static unsigned int cdda_first_sector;
79 static unsigned int cdda_file_offset;
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 #define cddaCurPos cdda_cur_sector
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)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
103 const chd_header* header;
104 unsigned int sectors_per_hunk;
105 unsigned int current_hunk;
106 unsigned int sector_in_hunk;
110 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
112 char* CALLBACK CDR__getDriveLetter(void);
113 long CALLBACK CDR__configure(void);
114 long CALLBACK CDR__test(void);
115 void CALLBACK CDR__about(void);
116 long CALLBACK CDR__setfilename(char *filename);
117 long CALLBACK CDR__getStatus(struct CdrStat *stat);
119 static void DecodeRawSubData(void);
122 enum {DATA=1, CDDA} type;
123 char start[3]; // MSF-format
124 char length[3]; // MSF-format
125 FILE *handle; // for multi-track images CDDA
126 unsigned int start_offset; // byte offset from start of above file
129 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
131 static int numtracks = 0;
132 static struct trackinfo ti[MAXTRACKS];
134 // get a sector from a msf-array
135 static unsigned int msf2sec(char *msf) {
136 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
139 static void sec2msf(unsigned int s, char *msf) {
140 msf[0] = s / 75 / 60;
141 s = s - msf[0] * 75 * 60;
147 // divide a string of xx:yy:zz into m, s, f
148 static void tok2msf(char *time, char *msf) {
151 token = strtok(time, ":");
153 msf[0] = atoi(token);
159 token = strtok(NULL, ":");
161 msf[1] = atoi(token);
167 token = strtok(NULL, ":");
169 msf[2] = atoi(token);
177 static long GetTickCount(void) {
178 static time_t initial_time = 0;
181 gettimeofday(&now, NULL);
183 if (initial_time == 0) {
184 initial_time = now.tv_sec;
187 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
191 // this thread plays audio data
193 static void playthread(void *param)
195 static void *playthread(void *param)
198 long osleep, d, t, i, s;
200 int ret = 0, sector_offs;
206 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
207 sector_offs = cdda_cur_sector - cdda_first_sector;
208 if (sector_offs < 0) {
209 d = CD_FRAMESIZE_RAW;
210 memset(sndbuffer + s, 0, d);
213 d = cdimg_read_func(cddaHandle, cdda_file_offset,
214 sndbuffer + s, sector_offs);
215 if (d < CD_FRAMESIZE_RAW)
229 if (!cdr.Muted && playing) {
231 for (i = 0; i < s / 2; i++) {
232 tmp = sndbuffer[i * 2];
233 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
234 sndbuffer[i * 2 + 1] = tmp;
238 // can't do it yet due to readahead..
239 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
241 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
246 } while (ret == 0x7761 && playing); // rearmed_wait
249 if (ret != 0x676f) { // !rearmed_go
253 // HACK: stop feeding data while emu is paused
255 while (stop && playing)
260 now = GetTickCount();
266 else if (osleep > CDDA_FRAMETIME) {
267 osleep = CDDA_FRAMETIME;
271 usleep(osleep * 1000);
285 // stop the CDDA playback
286 static void stopCDDA() {
293 WaitForSingleObject(threadid, INFINITE);
295 pthread_join(threadid, NULL);
299 // start the CDDA playback
300 static void startCDDA(void) {
308 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
310 pthread_create(&threadid, NULL, playthread, NULL);
314 // this function tries to get the .toc file of the given .bin
315 // the necessary data is put into the ti (trackinformation)-array
316 static int parsetoc(const char *isofile) {
317 char tocname[MAXPATHLEN];
319 char linebuf[256], tmp[256], name[256];
321 char time[20], time2[20];
322 unsigned int t, sector_offs, sector_size;
323 unsigned int current_zero_gap = 0;
327 // copy name of the iso and change extension from .bin to .toc
328 strncpy(tocname, isofile, sizeof(tocname));
329 tocname[MAXPATHLEN - 1] = '\0';
330 if (strlen(tocname) >= 4) {
331 strcpy(tocname + strlen(tocname) - 4, ".toc");
337 if ((fi = fopen(tocname, "r")) == NULL) {
338 // try changing extension to .cue (to satisfy some stupid tutorials)
339 strcpy(tocname + strlen(tocname) - 4, ".cue");
340 if ((fi = fopen(tocname, "r")) == NULL) {
341 // if filename is image.toc.bin, try removing .bin (for Brasero)
342 strcpy(tocname, isofile);
344 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
345 tocname[t - 4] = '\0';
346 if ((fi = fopen(tocname, "r")) == NULL) {
354 // check if it's really a TOC named as a .cue
355 fgets(linebuf, sizeof(linebuf), fi);
356 token = strtok(linebuf, " ");
357 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
361 fseek(fi, 0, SEEK_SET);
364 memset(&ti, 0, sizeof(ti));
365 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
367 sector_size = CD_FRAMESIZE_RAW;
368 sector_offs = 2 * 75;
370 // parse the .toc file
371 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
373 strncpy(tmp, linebuf, sizeof(linebuf));
374 token = strtok(tmp, " ");
376 if (token == NULL) continue;
378 if (!strcmp(token, "TRACK")) {
379 sector_offs += current_zero_gap;
380 current_zero_gap = 0;
383 token = strtok(NULL, " ");
386 if (!strncmp(token, "MODE2_RAW", 9)) {
387 ti[numtracks].type = DATA;
388 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
390 // check if this image contains mixed subchannel data
391 token = strtok(NULL, " ");
392 if (token != NULL && !strncmp(token, "RW", 2)) {
393 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
395 if (!strncmp(token, "RW_RAW", 6))
399 else if (!strncmp(token, "AUDIO", 5)) {
400 ti[numtracks].type = CDDA;
403 else if (!strcmp(token, "DATAFILE")) {
404 if (ti[numtracks].type == CDDA) {
405 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
406 ti[numtracks].start_offset = t;
407 t = t / sector_size + sector_offs;
408 sec2msf(t, (char *)&ti[numtracks].start);
409 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
412 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
413 tok2msf((char *)&time, (char *)&ti[numtracks].length);
416 else if (!strcmp(token, "FILE")) {
417 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
418 tok2msf((char *)&time, (char *)&ti[numtracks].start);
419 t += msf2sec(ti[numtracks].start) * sector_size;
420 ti[numtracks].start_offset = t;
421 t = t / sector_size + sector_offs;
422 sec2msf(t, (char *)&ti[numtracks].start);
423 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
425 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
426 // skip unneeded optional fields
427 while (token != NULL) {
428 token = strtok(NULL, " ");
429 if (strchr(token, ':') != NULL)
434 current_zero_gap = msf2sec(tmp);
437 t = ti[numtracks - 1].start_offset;
439 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
442 else if (!strcmp(token, "START")) {
443 token = strtok(NULL, " ");
444 if (token != NULL && strchr(token, ':')) {
447 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
448 t = msf2sec(ti[numtracks].start) + t;
449 sec2msf(t, (char *)&ti[numtracks].start);
459 // this function tries to get the .cue file of the given .bin
460 // the necessary data is put into the ti (trackinformation)-array
461 static int parsecue(const char *isofile) {
462 char cuename[MAXPATHLEN];
463 char filepath[MAXPATHLEN];
469 char linebuf[256], tmpb[256], dummy[256];
470 unsigned int incue_max_len;
471 unsigned int t, file_len, mode, sector_offs;
472 unsigned int sector_size = 2352;
476 // copy name of the iso and change extension from .bin to .cue
477 strncpy(cuename, isofile, sizeof(cuename));
478 cuename[MAXPATHLEN - 1] = '\0';
479 if (strlen(cuename) >= 4) {
480 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
481 // and don't try to search the additional .cue file
482 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
483 strcpy(cuename + strlen(cuename) - 4, ".cue");
489 if ((fi = fopen(cuename, "r")) == NULL) {
493 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
494 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
496 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
497 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
498 // Don't proceed further, as this is actually a .toc file rather
501 return parsetoc(isofile);
503 fseek(fi, 0, SEEK_SET);
506 // build a path for files referenced in .cue
507 strncpy(filepath, cuename, sizeof(filepath));
508 tmp = strrchr(filepath, '/');
510 tmp = strrchr(filepath, '\\');
516 filepath[sizeof(filepath) - 1] = 0;
518 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
520 memset(&ti, 0, sizeof(ti));
523 sector_offs = 2 * 75;
525 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
526 strncpy(dummy, linebuf, sizeof(linebuf));
527 token = strtok(dummy, " ");
533 if (!strcmp(token, "TRACK")) {
537 if (strstr(linebuf, "AUDIO") != NULL) {
538 ti[numtracks].type = CDDA;
541 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
542 ti[numtracks].type = DATA;
544 SysPrintf(".cue: failed to parse TRACK\n");
545 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
547 if (sector_size == 0)
550 else if (!strcmp(token, "INDEX")) {
551 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
552 SysPrintf(".cue: failed to parse INDEX\n");
553 tok2msf(time, (char *)&ti[numtracks].start);
555 t = msf2sec(ti[numtracks].start);
556 ti[numtracks].start_offset = t * sector_size;
558 sec2msf(t, ti[numtracks].start);
560 // default track length to file length
561 t = file_len - ti[numtracks].start_offset / sector_size;
562 sec2msf(t, ti[numtracks].length);
564 if (numtracks > 1 && ti[numtracks].handle == NULL) {
565 // this track uses the same file as the last,
566 // start of this track is last track's end
567 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
568 sec2msf(t, ti[numtracks - 1].length);
570 if (numtracks > 1 && pregapOffset == -1)
571 pregapOffset = ti[numtracks].start_offset / sector_size;
573 else if (!strcmp(token, "PREGAP")) {
574 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
575 tok2msf(time, dummy);
576 sector_offs += msf2sec(dummy);
578 pregapOffset = -1; // mark to fill track start_offset
580 else if (!strcmp(token, "FILE")) {
581 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
583 sscanf(linebuf, " FILE %255s", tmpb);
585 tmp = strrchr(tmpb, '\\');
587 tmp = strrchr(tmpb, '/');
592 strncpy(incue_fname, tmp, incue_max_len);
593 ti[numtracks + 1].handle = fopen(filepath, "rb");
595 // update global offset if this is not first file in this .cue
596 if (numtracks + 1 > 1) {
598 sector_offs += file_len;
602 if (ti[numtracks + 1].handle == NULL) {
603 SysPrintf(_("\ncould not open: %s\n"), filepath);
606 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
607 file_len = ftell(ti[numtracks + 1].handle) / 2352;
609 if (numtracks == 0 && strlen(isofile) >= 4 &&
610 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
611 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
612 // user selected .cue/.cdX as image file, use it's data track instead
614 cdHandle = fopen(filepath, "rb");
621 // if there are no tracks detected, then it's not a cue file
628 // this function tries to get the .ccd file of the given .img
629 // the necessary data is put into the ti (trackinformation)-array
630 static int parseccd(const char *isofile) {
631 char ccdname[MAXPATHLEN];
638 // copy name of the iso and change extension from .img to .ccd
639 strncpy(ccdname, isofile, sizeof(ccdname));
640 ccdname[MAXPATHLEN - 1] = '\0';
641 if (strlen(ccdname) >= 4) {
642 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
648 if ((fi = fopen(ccdname, "r")) == NULL) {
652 memset(&ti, 0, sizeof(ti));
654 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
655 if (!strncmp(linebuf, "[TRACK", 6)){
658 else if (!strncmp(linebuf, "MODE=", 5)) {
659 sscanf(linebuf, "MODE=%d", &t);
660 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
662 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
663 sscanf(linebuf, "INDEX 1=%d", &t);
664 sec2msf(t + 2 * 75, ti[numtracks].start);
665 ti[numtracks].start_offset = t * 2352;
667 // If we've already seen another track, this is its end
669 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
670 sec2msf(t, ti[numtracks - 1].length);
677 // Fill out the last track's end based on size
678 if (numtracks >= 1) {
679 fseek(cdHandle, 0, SEEK_END);
680 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
681 sec2msf(t, ti[numtracks].length);
687 // this function tries to get the .mds file of the given .mdf
688 // the necessary data is put into the ti (trackinformation)-array
689 static int parsemds(const char *isofile) {
690 char mdsname[MAXPATHLEN];
692 unsigned int offset, extra_offset, l, i;
697 // copy name of the iso and change extension from .mdf to .mds
698 strncpy(mdsname, isofile, sizeof(mdsname));
699 mdsname[MAXPATHLEN - 1] = '\0';
700 if (strlen(mdsname) >= 4) {
701 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
707 if ((fi = fopen(mdsname, "rb")) == NULL) {
711 memset(&ti, 0, sizeof(ti));
713 // check if it's a valid mds file
714 fread(&i, 1, sizeof(unsigned int), fi);
716 if (i != 0x4944454D) {
717 // not an valid mds file
722 // get offset to session block
723 fseek(fi, 0x50, SEEK_SET);
724 fread(&offset, 1, sizeof(unsigned int), fi);
725 offset = SWAP32(offset);
727 // get total number of tracks
729 fseek(fi, offset, SEEK_SET);
730 fread(&s, 1, sizeof(unsigned short), fi);
734 // get offset to track blocks
735 fseek(fi, 4, SEEK_CUR);
736 fread(&offset, 1, sizeof(unsigned int), fi);
737 offset = SWAP32(offset);
741 fseek(fi, offset + 4, SEEK_SET);
742 if (fgetc(fi) < 0xA0) {
748 // check if the image contains mixed subchannel data
749 fseek(fi, offset + 1, SEEK_SET);
750 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
753 for (i = 1; i <= numtracks; i++) {
754 fseek(fi, offset, SEEK_SET);
756 // get the track type
757 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
758 fseek(fi, 8, SEEK_CUR);
760 // get the track starting point
761 ti[i].start[0] = fgetc(fi);
762 ti[i].start[1] = fgetc(fi);
763 ti[i].start[2] = fgetc(fi);
765 fread(&extra_offset, 1, sizeof(unsigned int), fi);
766 extra_offset = SWAP32(extra_offset);
768 // get track start offset (in .mdf)
769 fseek(fi, offset + 0x28, SEEK_SET);
770 fread(&l, 1, sizeof(unsigned int), fi);
772 ti[i].start_offset = l;
775 fseek(fi, extra_offset, SEEK_SET);
776 fread(&l, 1, sizeof(unsigned int), fi);
779 pregapOffset = msf2sec(ti[i].start);
781 // get the track length
782 fread(&l, 1, sizeof(unsigned int), fi);
784 sec2msf(l, ti[i].length);
793 static int handlepbp(const char *isofile) {
796 unsigned int dontcare[8];
797 unsigned int psar_offs;
810 unsigned int dontcare[6];
813 off_t psisoimg_offs, cdimg_base;
814 unsigned int t, cd_length;
815 unsigned int offsettab[8];
816 const char *ext = NULL;
819 if (strlen(isofile) >= 4)
820 ext = isofile + strlen(isofile) - 4;
821 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
824 fseeko(cdHandle, 0, SEEK_SET);
828 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
829 if (ret != sizeof(pbp_hdr)) {
830 SysPrintf("failed to read pbp\n");
834 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
836 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
840 psisoimg_offs = pbp_hdr.psar_offs;
841 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
843 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
845 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
847 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
851 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
852 SysPrintf("failed to read offsettab\n");
856 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
857 if (offsettab[i] == 0)
860 cdrIsoMultidiskCount = i;
861 if (cdrIsoMultidiskCount == 0) {
862 SysPrintf("multidisk eboot has 0 images?\n");
866 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
867 cdrIsoMultidiskSelect = 0;
869 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
871 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
873 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
877 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
881 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
882 SysPrintf("bad psar_sig: %s\n", psar_sig);
887 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
889 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
893 // first 3 entries are special
894 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
895 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
896 numtracks = btoi(toc_entry.index1[0]);
898 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
899 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
900 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
902 for (i = 1; i <= numtracks; i++) {
903 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
905 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
907 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
908 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
909 ti[i].start_offset *= 2352;
910 ti[i].start[0] = btoi(toc_entry.index1[0]);
911 ti[i].start[1] = btoi(toc_entry.index1[1]);
912 ti[i].start[2] = btoi(toc_entry.index1[2]);
915 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
916 sec2msf(t, ti[i - 1].length);
919 t = cd_length - ti[numtracks].start_offset / 2352;
920 sec2msf(t, ti[numtracks].length);
923 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
925 SysPrintf("failed to seek to ISO index\n");
929 compr_img = calloc(1, sizeof(*compr_img));
930 if (compr_img == NULL)
933 compr_img->block_shift = 4;
934 compr_img->current_block = (unsigned int)-1;
936 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
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 cdimg_base = psisoimg_offs + 0x100000;
942 for (i = 0; i < compr_img->index_len; i++) {
943 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
944 if (ret != sizeof(index_entry)) {
945 SysPrintf("failed to read index_entry #%d\n", i);
949 if (index_entry.size == 0)
952 compr_img->index_table[i] = cdimg_base + index_entry.offset;
954 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
959 free(compr_img->index_table);
960 compr_img->index_table = NULL;
962 if (compr_img != NULL) {
969 static int handlecbin(const char *isofile) {
973 unsigned int header_size;
974 unsigned long long total_bytes;
975 unsigned int block_size;
976 unsigned char ver; // 1
978 unsigned char rsv_06[2];
980 const char *ext = NULL;
981 unsigned int *index_table = NULL;
982 unsigned int index = 0, plain;
985 if (strlen(isofile) >= 5)
986 ext = isofile + strlen(isofile) - 5;
987 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
990 fseek(cdHandle, 0, SEEK_SET);
992 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
993 if (ret != sizeof(ciso_hdr)) {
994 SysPrintf("failed to read ciso header\n");
998 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
999 SysPrintf("bad ciso header\n");
1002 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
1003 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
1005 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
1010 compr_img = calloc(1, sizeof(*compr_img));
1011 if (compr_img == NULL)
1014 compr_img->block_shift = 0;
1015 compr_img->current_block = (unsigned int)-1;
1017 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
1018 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
1019 if (index_table == NULL)
1022 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1023 if (ret != compr_img->index_len) {
1024 SysPrintf("failed to read index table\n");
1028 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1029 if (compr_img->index_table == NULL)
1032 for (i = 0; i < compr_img->index_len + 1; i++) {
1033 index = index_table[i];
1034 plain = index & 0x80000000;
1035 index &= 0x7fffffff;
1036 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1038 compr_img->index_table[i] |= OFF_T_MSB;
1046 if (compr_img != NULL) {
1054 static int handlechd(const char *isofile) {
1055 chd_img = calloc(1, sizeof(*chd_img));
1056 if (chd_img == NULL)
1059 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
1062 chd_img->header = chd_get_header(chd_img->chd);
1064 chd_img->buffer = malloc(chd_img->header->hunkbytes);
1065 if (chd_img->buffer == NULL)
1068 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1069 chd_img->current_hunk = (unsigned int)-1;
1071 cddaBigEndian = TRUE;
1074 int frame_offset = 150;
1075 memset(ti, 0, sizeof(ti));
1090 uint32_t meta_size = 0;
1092 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1093 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1094 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1095 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1099 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1101 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1102 sec2msf(md.frames - md.pregap, ti[md.track].length);
1104 if (!strcmp(md.type, md.pgtype))
1105 frame_offset += md.pregap;
1107 ti[md.track].start_offset = frame_offset * CD_FRAMESIZE_RAW;
1109 frame_offset += md.frames;
1110 frame_offset += md.postgap;
1118 if (chd_img != NULL) {
1119 free(chd_img->buffer);
1127 // this function tries to get the .sub file of the given .img
1128 static int opensubfile(const char *isoname) {
1129 char subname[MAXPATHLEN];
1131 // copy name of the iso and change extension from .img to .sub
1132 strncpy(subname, isoname, sizeof(subname));
1133 subname[MAXPATHLEN - 1] = '\0';
1134 if (strlen(subname) >= 4) {
1135 strcpy(subname + strlen(subname) - 4, ".sub");
1141 subHandle = fopen(subname, "rb");
1142 if (subHandle == NULL) {
1149 static int opensbifile(const char *isoname) {
1150 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1153 strncpy(sbiname, isoname, sizeof(sbiname));
1154 sbiname[MAXPATHLEN - 1] = '\0';
1155 if (strlen(sbiname) >= 4) {
1156 if (cdrIsoMultidiskCount > 1) {
1157 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1158 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1161 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1167 fseek(cdHandle, 0, SEEK_END);
1168 s = ftell(cdHandle) / 2352;
1170 return LoadSBI(sbiname, s);
1174 static void readThreadStop() {}
1175 static void readThreadStart() {}
1177 static pthread_t read_thread_id;
1179 static pthread_cond_t read_thread_msg_avail;
1180 static pthread_cond_t read_thread_msg_done;
1181 static pthread_mutex_t read_thread_msg_lock;
1183 static pthread_cond_t sectorbuffer_cond;
1184 static pthread_mutex_t sectorbuffer_lock;
1186 static boolean read_thread_running = FALSE;
1187 static int read_thread_sector_start = -1;
1188 static int read_thread_sector_end = -1;
1193 unsigned char data[CD_FRAMESIZE_RAW];
1194 } SectorBufferEntry;
1196 #define SECTOR_BUFFER_SIZE 4096
1198 static SectorBufferEntry *sectorbuffer;
1199 static size_t sectorbuffer_index;
1201 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1202 unsigned char *(*sync_CDR_getBuffer)(void);
1204 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1205 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1207 static void *readThreadMain(void *param) {
1208 int max_sector = -1;
1209 int requested_sector_start = -1;
1210 int requested_sector_end = -1;
1211 int last_read_sector = -1;
1217 int speedmult_ra = 4;
1220 int how_far_ahead = 0;
1222 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1225 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1228 pthread_mutex_lock(&read_thread_msg_lock);
1230 // If we don't have readahead and we don't have a sector request, wait for one.
1231 // If we still have readahead to go, don't block, just keep going.
1232 // And if we ever have a sector request pending, acknowledge and reset it.
1235 if (read_thread_sector_start == -1 && read_thread_running) {
1236 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1240 if (read_thread_sector_start != -1) {
1241 requested_sector_start = read_thread_sector_start;
1242 requested_sector_end = read_thread_sector_end;
1243 read_thread_sector_start = -1;
1244 read_thread_sector_end = -1;
1245 pthread_cond_signal(&read_thread_msg_done);
1248 pthread_mutex_unlock(&read_thread_msg_lock);
1250 if (!read_thread_running)
1253 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1254 if (requested_sector_start != -1) {
1255 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1256 how_far_ahead = ra_sector - requested_sector_end;
1258 if(how_far_ahead <= max_ra)
1259 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1262 } else if (requested_sector_end != last_read_sector) {
1263 ra_sector = requested_sector_end;
1264 ra_count = initial_ra;
1267 last_read_sector = requested_sector_end;
1270 index = ra_sector % SECTOR_BUFFER_SIZE;
1272 // check for end of CD
1273 if (ra_count && ra_sector >= max_sector) {
1275 pthread_mutex_lock(§orbuffer_lock);
1276 sectorbuffer[index].ret = -1;
1277 sectorbuffer[index].sector = ra_sector;
1278 pthread_cond_signal(§orbuffer_cond);
1279 pthread_mutex_unlock(§orbuffer_lock);
1283 pthread_mutex_lock(§orbuffer_lock);
1284 if (sectorbuffer[index].sector != ra_sector) {
1285 pthread_mutex_unlock(§orbuffer_lock);
1287 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1289 pthread_mutex_lock(§orbuffer_lock);
1290 sectorbuffer[index].ret = ret;
1291 sectorbuffer[index].sector = ra_sector;
1292 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1294 pthread_cond_signal(§orbuffer_cond);
1295 pthread_mutex_unlock(§orbuffer_lock);
1305 static void readThreadStop() {
1306 if (read_thread_running == TRUE) {
1307 read_thread_running = FALSE;
1308 pthread_cond_signal(&read_thread_msg_avail);
1309 pthread_join(read_thread_id, NULL);
1312 pthread_cond_destroy(&read_thread_msg_done);
1313 pthread_cond_destroy(&read_thread_msg_avail);
1314 pthread_mutex_destroy(&read_thread_msg_lock);
1316 pthread_cond_destroy(§orbuffer_cond);
1317 pthread_mutex_destroy(§orbuffer_lock);
1319 CDR_getBuffer = sync_CDR_getBuffer;
1320 cdimg_read_func = sync_cdimg_read_func;
1323 sectorbuffer = NULL;
1326 static void readThreadStart() {
1327 SysPrintf("Starting async CD thread\n");
1329 if (read_thread_running == TRUE)
1332 read_thread_running = TRUE;
1333 read_thread_sector_start = -1;
1334 read_thread_sector_end = -1;
1335 sectorbuffer_index = 0;
1337 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1341 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1343 sync_CDR_getBuffer = CDR_getBuffer;
1344 CDR_getBuffer = ISOgetBuffer_async;
1345 sync_cdimg_read_func = cdimg_read_func;
1346 cdimg_read_func = cdread_async;
1348 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1349 pthread_cond_init(&read_thread_msg_done, NULL) ||
1350 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1351 pthread_cond_init(§orbuffer_cond, NULL) ||
1352 pthread_mutex_init(§orbuffer_lock, NULL) ||
1353 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1359 SysPrintf("Error starting async CD thread\n");
1360 SysPrintf("Falling back to sync\n");
1366 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1368 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1369 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1372 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1376 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1377 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1378 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1380 if (subChanRaw) DecodeRawSubData();
1385 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1390 if (z.zalloc == NULL) {
1391 // XXX: one-time leak here..
1397 ret = inflateInit2(&z, -15);
1400 ret = inflateReset(&z);
1405 z.avail_in = in_size;
1407 z.avail_out = *out_size;
1409 ret = inflate(&z, Z_NO_FLUSH);
1412 *out_size -= z.avail_out;
1413 return ret == 1 ? 0 : ret;
1416 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1418 unsigned long cdbuffer_size, cdbuffer_size_expect;
1425 sector += base / 2352;
1427 block = sector >> compr_img->block_shift;
1428 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1430 if (block == compr_img->current_block) {
1431 //printf("hit sect %d\n", sector);
1435 if (sector >= compr_img->index_len * 16) {
1436 SysPrintf("sector %d is past img end\n", sector);
1440 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1441 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1442 SysPrintf("seek error for block %d at %llx: ",
1443 block, (long long)start_byte);
1448 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1449 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1450 if (size > sizeof(compr_img->buff_compressed)) {
1451 SysPrintf("block %d is too large: %u\n", block, size);
1455 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1456 1, size, cdHandle) != size) {
1457 SysPrintf("read error for block %d at %x: ", block, start_byte);
1462 if (is_compressed) {
1463 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1464 cdbuffer_size = cdbuffer_size_expect;
1465 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1467 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1468 ret, block, sector);
1471 if (cdbuffer_size != cdbuffer_size_expect)
1472 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1473 cdbuffer_size_expect, sector);
1477 compr_img->current_block = block;
1480 if (dest != cdbuffer) // copy avoid HACK
1481 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1483 return CD_FRAMESIZE_RAW;
1487 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1492 sector += base / CD_FRAMESIZE_RAW;
1494 hunk = sector / chd_img->sectors_per_hunk;
1495 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1497 if (hunk == chd_img->current_hunk)
1500 chd_read(chd_img->chd, hunk, chd_img->buffer);
1502 chd_img->current_hunk = hunk;
1505 if (dest != cdbuffer) // copy avoid HACK
1506 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1508 return CD_FRAMESIZE_RAW;
1511 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1515 fseek(f, base + sector * 2048, SEEK_SET);
1516 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1518 // not really necessary, fake mode 2 header
1519 memset(cdbuffer, 0, 12 * 2);
1520 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1521 cdbuffer[12 + 3] = 1;
1528 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1529 boolean found = FALSE;
1530 int i = sector % SECTOR_BUFFER_SIZE;
1533 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1534 // Async reads are only supported for cdbuffer, so call the sync
1535 // function directly.
1536 return sync_cdimg_read_func(f, base, dest, sector);
1539 pthread_mutex_lock(&read_thread_msg_lock);
1541 // Only wait if we're not trying to read the next sector and
1542 // sector_start is set (meaning the last request hasn't been
1544 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1545 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1548 if (read_thread_sector_start == -1)
1549 read_thread_sector_start = sector;
1551 read_thread_sector_end = sector;
1552 pthread_cond_signal(&read_thread_msg_avail);
1553 pthread_mutex_unlock(&read_thread_msg_lock);
1556 pthread_mutex_lock(§orbuffer_lock);
1557 if (sectorbuffer[i].sector == sector) {
1558 sectorbuffer_index = i;
1559 ret = sectorbuffer[i].ret;
1564 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1566 pthread_mutex_unlock(§orbuffer_lock);
1574 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1575 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1579 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1580 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1585 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1586 unsigned char *buffer;
1587 pthread_mutex_lock(§orbuffer_lock);
1588 buffer = sectorbuffer[sectorbuffer_index].data;
1589 pthread_mutex_unlock(§orbuffer_lock);
1595 static unsigned char * CALLBACK ISOgetBuffer(void) {
1596 return cdbuffer + 12;
1599 static void PrintTracks(void) {
1602 for (i = 1; i <= numtracks; i++) {
1603 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1604 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1605 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1606 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1610 // This function is invoked by the front-end when opening an ISO
1611 // file for playback
1612 static long CALLBACK ISOopen(void) {
1613 boolean isMode1ISO = FALSE;
1614 char alt_bin_filename[MAXPATHLEN];
1615 const char *bin_filename;
1616 char image_str[1024] = {0};
1618 if (cdHandle != NULL) {
1619 return 0; // it's already open
1622 cdHandle = fopen(GetIsoFile(), "rb");
1623 if (cdHandle == NULL) {
1624 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1625 GetIsoFile(), strerror(errno));
1629 sprintf(image_str, "Loaded CD Image: %s", GetIsoFile());
1631 cddaBigEndian = FALSE;
1632 subChanMixed = FALSE;
1635 cdrIsoMultidiskCount = 1;
1638 CDR_getBuffer = ISOgetBuffer;
1639 cdimg_read_func = cdread_normal;
1641 if (parsetoc(GetIsoFile()) == 0) {
1642 strcat(image_str, "[+toc]");
1644 else if (parseccd(GetIsoFile()) == 0) {
1645 strcat(image_str, "[+ccd]");
1647 else if (parsemds(GetIsoFile()) == 0) {
1648 strcat(image_str, "[+mds]");
1650 else if (parsecue(GetIsoFile()) == 0) {
1651 strcat(image_str, "[+cue]");
1653 if (handlepbp(GetIsoFile()) == 0) {
1654 strcat(image_str, "[+pbp]");
1655 CDR_getBuffer = ISOgetBuffer_compr;
1656 cdimg_read_func = cdread_compressed;
1658 else if (handlecbin(GetIsoFile()) == 0) {
1659 strcat(image_str, "[+cbin]");
1660 CDR_getBuffer = ISOgetBuffer_compr;
1661 cdimg_read_func = cdread_compressed;
1664 else if (handlechd(GetIsoFile()) == 0) {
1665 strcat(image_str, "[+chd]");
1666 CDR_getBuffer = ISOgetBuffer_chd;
1667 cdimg_read_func = cdread_chd;
1671 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1672 strcat(image_str, "[+sub]");
1674 if (opensbifile(GetIsoFile()) == 0) {
1675 strcat(image_str, "[+sbi]");
1678 fseeko(cdHandle, 0, SEEK_END);
1680 // maybe user selected metadata file instead of main .bin ..
1681 bin_filename = GetIsoFile();
1682 if (ftello(cdHandle) < 2352 * 0x10) {
1683 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1688 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1689 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1690 if (strlen(alt_bin_filename) >= 4) {
1691 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1692 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1694 tmpf = fopen(alt_bin_filename, "rb");
1700 bin_filename = alt_bin_filename;
1703 fseeko(cdHandle, 0, SEEK_END);
1707 // guess whether it is mode1/2048
1708 if (ftello(cdHandle) % 2048 == 0) {
1709 unsigned int modeTest = 0;
1710 fseek(cdHandle, 0, SEEK_SET);
1711 fread(&modeTest, 4, 1, cdHandle);
1712 if (SWAP32(modeTest) != 0xffffff00) {
1713 strcat(image_str, "[2048]");
1717 fseek(cdHandle, 0, SEEK_SET);
1719 SysPrintf("%s.\n", image_str);
1724 cdimg_read_func = cdread_sub_mixed;
1725 else if (isMode1ISO)
1726 cdimg_read_func = cdread_2048;
1728 // make sure we have another handle open for cdda
1729 if (numtracks > 1 && ti[1].handle == NULL) {
1730 ti[1].handle = fopen(bin_filename, "rb");
1732 cdda_cur_sector = 0;
1733 cdda_file_offset = 0;
1735 if (Config.AsyncCD) {
1741 static long CALLBACK ISOclose(void) {
1744 if (cdHandle != NULL) {
1748 if (subHandle != NULL) {
1755 if (compr_img != NULL) {
1756 free(compr_img->index_table);
1762 if (chd_img != NULL) {
1763 chd_close(chd_img->chd);
1764 free(chd_img->buffer);
1770 for (i = 1; i <= numtracks; i++) {
1771 if (ti[i].handle != NULL) {
1772 fclose(ti[i].handle);
1773 ti[i].handle = NULL;
1780 memset(cdbuffer, 0, sizeof(cdbuffer));
1781 CDR_getBuffer = ISOgetBuffer;
1783 if (Config.AsyncCD) {
1790 static long CALLBACK ISOinit(void) {
1791 assert(cdHandle == NULL);
1792 assert(subHandle == NULL);
1794 return 0; // do nothing
1797 static long CALLBACK ISOshutdown(void) {
1802 // return Starting and Ending Track
1804 // byte 0 - start track
1805 // byte 1 - end track
1806 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1809 if (numtracks > 0) {
1810 buffer[1] = numtracks;
1819 // return Track Time
1824 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1827 unsigned char time[3];
1828 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1829 sec2msf(sect, (char *)time);
1830 buffer[2] = time[0];
1831 buffer[1] = time[1];
1832 buffer[0] = time[2];
1834 else if (numtracks > 0 && track <= numtracks) {
1835 buffer[2] = ti[track].start[0];
1836 buffer[1] = ti[track].start[1];
1837 buffer[0] = ti[track].start[2];
1848 // decode 'raw' subchannel data ripped by cdrdao
1849 static void DecodeRawSubData(void) {
1850 unsigned char subQData[12];
1853 memset(subQData, 0, sizeof(subQData));
1855 for (i = 0; i < 8 * 12; i++) {
1856 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1857 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1861 memcpy(&subbuffer[12], subQData, 12);
1865 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1867 static long CALLBACK ISOreadTrack(unsigned char *time) {
1868 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1871 if (cdHandle == NULL) {
1876 subChanMissing = FALSE;
1877 if (sector >= pregapOffset) {
1879 if (sector < pregapOffset)
1880 subChanMissing = TRUE;
1884 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1888 if (subHandle != NULL) {
1889 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1890 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1892 if (subChanRaw) DecodeRawSubData();
1899 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1900 // does NOT uses bcd format
1901 static long CALLBACK ISOplay(unsigned char *time) {
1908 cdda_cur_sector = msf2sec((char *)time);
1909 for (i = numtracks; i > 1; i--) {
1910 cdda_first_sector = msf2sec(ti[i].start);
1911 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1914 cdda_file_offset = ti[i].start_offset;
1916 // find the file that contains this track
1918 if (ti[i].handle != NULL)
1921 cddaHandle = ti[i].handle;
1923 if (SPU_playCDDAchannel != NULL)
1930 static long CALLBACK ISOstop(void) {
1935 // gets subchannel data
1936 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1937 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1944 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1947 CDR__getStatus(stat);
1951 stat->Status |= 0x80;
1954 // BIOS - boot ID (CD type)
1955 stat->Type = ti[1].type;
1958 // relative -> absolute time
1960 sec2msf(sect, (char *)stat->Time);
1965 // read CDDA sector into buffer
1966 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1967 unsigned char msf[3] = {m, s, f};
1968 unsigned int file, track, track_start = 0;
1971 cddaCurPos = msf2sec((char *)msf);
1973 // find current track index
1974 for (track = numtracks; ; track--) {
1975 track_start = msf2sec(ti[track].start);
1976 if (track_start <= cddaCurPos)
1982 // data tracks play silent
1983 if (ti[track].type != CDDA) {
1984 memset(buffer, 0, CD_FRAMESIZE_RAW);
1990 // find the file that contains this track
1991 for (file = track; file > 1; file--)
1992 if (ti[file].handle != NULL)
1996 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1997 buffer, cddaCurPos - track_start);
1998 if (ret != CD_FRAMESIZE_RAW) {
1999 memset(buffer, 0, CD_FRAMESIZE_RAW);
2003 if (cddaBigEndian) {
2007 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
2008 tmp = buffer[i * 2];
2009 buffer[i * 2] = buffer[i * 2 + 1];
2010 buffer[i * 2 + 1] = tmp;
2017 void cdrIsoInit(void) {
2019 CDR_shutdown = ISOshutdown;
2021 CDR_close = ISOclose;
2022 CDR_getTN = ISOgetTN;
2023 CDR_getTD = ISOgetTD;
2024 CDR_readTrack = ISOreadTrack;
2025 CDR_getBuffer = ISOgetBuffer;
2028 CDR_getBufferSub = ISOgetBufferSub;
2029 CDR_getStatus = ISOgetStatus;
2030 CDR_readCDDA = ISOreadCDDA;
2032 CDR_getDriveLetter = CDR__getDriveLetter;
2033 CDR_configure = CDR__configure;
2034 CDR_test = CDR__test;
2035 CDR_about = CDR__about;
2036 CDR_setfilename = CDR__setfilename;
2041 int cdrIsoActive(void) {
2042 return (cdHandle != NULL);