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
45 #ifdef USE_LIBRETRO_VFS
46 #include <streams/file_stream_transforms.h>
53 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
55 unsigned int cdrIsoMultidiskCount;
56 unsigned int cdrIsoMultidiskSelect;
58 static FILE *cdHandle = NULL;
59 static FILE *cddaHandle = NULL;
60 static FILE *subHandle = NULL;
62 static boolean subChanMixed = FALSE;
63 static boolean subChanRaw = FALSE;
64 static boolean subChanMissing = FALSE;
66 static boolean multifile = FALSE;
68 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
69 static unsigned char subbuffer[SUB_FRAMESIZE];
71 static boolean playing = FALSE;
72 static boolean cddaBigEndian = FALSE;
73 // cdda sectors in toc, byte offset in file
74 static unsigned int cdda_cur_sector;
75 static unsigned int cdda_file_offset;
76 /* Frame offset into CD image where pregap data would be found if it was there.
77 * If a game seeks there we must *not* return subchannel data since it's
78 * not in the CD image, so that cdrom code can fake subchannel data instead.
79 * XXX: there could be multiple pregaps but PSX dumps only have one? */
80 static unsigned int pregapOffset;
82 #define cddaCurPos cdda_cur_sector
84 // compressed image stuff
86 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
87 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
89 unsigned int index_len;
90 unsigned int block_shift;
91 unsigned int current_block;
92 unsigned int sector_in_blk;
97 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
99 const chd_header* header;
100 unsigned int sectors_per_hunk;
101 unsigned int current_hunk;
102 unsigned int sector_in_hunk;
106 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
108 char* CALLBACK CDR__getDriveLetter(void);
109 long CALLBACK CDR__configure(void);
110 long CALLBACK CDR__test(void);
111 void CALLBACK CDR__about(void);
112 long CALLBACK CDR__setfilename(char *filename);
113 long CALLBACK CDR__getStatus(struct CdrStat *stat);
115 static void DecodeRawSubData(void);
118 enum {DATA=1, CDDA} type;
119 char start[3]; // MSF-format
120 char length[3]; // MSF-format
121 FILE *handle; // for multi-track images CDDA
122 unsigned int start_offset; // byte offset from start of above file
125 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
127 static int numtracks = 0;
128 static struct trackinfo ti[MAXTRACKS];
130 // get a sector from a msf-array
131 static unsigned int msf2sec(char *msf) {
132 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
135 static void sec2msf(unsigned int s, char *msf) {
136 msf[0] = s / 75 / 60;
137 s = s - msf[0] * 75 * 60;
143 // divide a string of xx:yy:zz into m, s, f
144 static void tok2msf(char *time, char *msf) {
147 token = strtok(time, ":");
149 msf[0] = atoi(token);
155 token = strtok(NULL, ":");
157 msf[1] = atoi(token);
163 token = strtok(NULL, ":");
165 msf[2] = atoi(token);
172 // this function tries to get the .toc file of the given .bin
173 // the necessary data is put into the ti (trackinformation)-array
174 static int parsetoc(const char *isofile) {
175 char tocname[MAXPATHLEN];
177 char linebuf[256], tmp[256], name[256];
179 char time[20], time2[20];
180 unsigned int t, sector_offs, sector_size;
181 unsigned int current_zero_gap = 0;
185 // copy name of the iso and change extension from .bin to .toc
186 strncpy(tocname, isofile, sizeof(tocname));
187 tocname[MAXPATHLEN - 1] = '\0';
188 if (strlen(tocname) >= 4) {
189 strcpy(tocname + strlen(tocname) - 4, ".toc");
195 if ((fi = fopen(tocname, "r")) == NULL) {
196 // try changing extension to .cue (to satisfy some stupid tutorials)
197 strcpy(tocname + strlen(tocname) - 4, ".cue");
198 if ((fi = fopen(tocname, "r")) == NULL) {
199 // if filename is image.toc.bin, try removing .bin (for Brasero)
200 strcpy(tocname, isofile);
202 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
203 tocname[t - 4] = '\0';
204 if ((fi = fopen(tocname, "r")) == NULL) {
212 // check if it's really a TOC named as a .cue
213 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
214 token = strtok(linebuf, " ");
215 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
220 fseek(fi, 0, SEEK_SET);
223 memset(&ti, 0, sizeof(ti));
224 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
226 sector_size = CD_FRAMESIZE_RAW;
227 sector_offs = 2 * 75;
229 // parse the .toc file
230 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
232 strncpy(tmp, linebuf, sizeof(linebuf));
233 token = strtok(tmp, " ");
235 if (token == NULL) continue;
237 if (!strcmp(token, "TRACK")) {
238 sector_offs += current_zero_gap;
239 current_zero_gap = 0;
242 token = strtok(NULL, " ");
245 if (!strncmp(token, "MODE2_RAW", 9)) {
246 ti[numtracks].type = DATA;
247 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
249 // check if this image contains mixed subchannel data
250 token = strtok(NULL, " ");
251 if (token != NULL && !strncmp(token, "RW", 2)) {
252 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
254 if (!strncmp(token, "RW_RAW", 6))
258 else if (!strncmp(token, "AUDIO", 5)) {
259 ti[numtracks].type = CDDA;
262 else if (!strcmp(token, "DATAFILE")) {
263 if (ti[numtracks].type == CDDA) {
264 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
265 ti[numtracks].start_offset = t;
266 t = t / sector_size + sector_offs;
267 sec2msf(t, (char *)&ti[numtracks].start);
268 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
271 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
272 tok2msf((char *)&time, (char *)&ti[numtracks].length);
275 else if (!strcmp(token, "FILE")) {
276 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
277 tok2msf((char *)&time, (char *)&ti[numtracks].start);
278 t += msf2sec(ti[numtracks].start) * sector_size;
279 ti[numtracks].start_offset = t;
280 t = t / sector_size + sector_offs;
281 sec2msf(t, (char *)&ti[numtracks].start);
282 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
284 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
285 // skip unneeded optional fields
286 while (token != NULL) {
287 token = strtok(NULL, " ");
288 if (strchr(token, ':') != NULL)
293 current_zero_gap = msf2sec(tmp);
296 t = ti[numtracks - 1].start_offset;
298 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
301 else if (!strcmp(token, "START")) {
302 token = strtok(NULL, " ");
303 if (token != NULL && strchr(token, ':')) {
306 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
307 t = msf2sec(ti[numtracks].start) + t;
308 sec2msf(t, (char *)&ti[numtracks].start);
318 // this function tries to get the .cue file of the given .bin
319 // the necessary data is put into the ti (trackinformation)-array
320 static int parsecue(const char *isofile) {
321 char cuename[MAXPATHLEN];
322 char filepath[MAXPATHLEN];
328 char linebuf[256], tmpb[256], dummy[256];
329 unsigned int incue_max_len;
330 unsigned int t, file_len, mode, sector_offs;
331 unsigned int sector_size = 2352;
335 // copy name of the iso and change extension from .bin to .cue
336 strncpy(cuename, isofile, sizeof(cuename));
337 cuename[MAXPATHLEN - 1] = '\0';
338 if (strlen(cuename) >= 4) {
339 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
340 // and don't try to search the additional .cue file
341 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
342 strcpy(cuename + strlen(cuename) - 4, ".cue");
348 if ((fi = fopen(cuename, "r")) == NULL) {
352 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
353 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
355 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
356 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
357 // Don't proceed further, as this is actually a .toc file rather
360 return parsetoc(isofile);
362 fseek(fi, 0, SEEK_SET);
365 // build a path for files referenced in .cue
366 strncpy(filepath, cuename, sizeof(filepath));
367 tmp = strrchr(filepath, '/');
369 tmp = strrchr(filepath, '\\');
375 filepath[sizeof(filepath) - 1] = 0;
377 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
379 memset(&ti, 0, sizeof(ti));
382 sector_offs = 2 * 75;
384 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
385 strncpy(dummy, linebuf, sizeof(linebuf));
386 token = strtok(dummy, " ");
392 if (!strcmp(token, "TRACK")) {
396 if (strstr(linebuf, "AUDIO") != NULL) {
397 ti[numtracks].type = CDDA;
400 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
401 ti[numtracks].type = DATA;
403 SysPrintf(".cue: failed to parse TRACK\n");
404 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
406 if (sector_size == 0)
409 else if (!strcmp(token, "INDEX")) {
410 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
411 SysPrintf(".cue: failed to parse INDEX\n");
412 tok2msf(time, (char *)&ti[numtracks].start);
414 t = msf2sec(ti[numtracks].start);
415 ti[numtracks].start_offset = t * sector_size;
417 sec2msf(t, ti[numtracks].start);
419 // default track length to file length
420 t = file_len - ti[numtracks].start_offset / sector_size;
421 sec2msf(t, ti[numtracks].length);
423 if (numtracks > 1 && ti[numtracks].handle == NULL) {
424 // this track uses the same file as the last,
425 // start of this track is last track's end
426 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
427 sec2msf(t, ti[numtracks - 1].length);
429 if (numtracks > 1 && pregapOffset == -1)
430 pregapOffset = ti[numtracks].start_offset / sector_size;
432 else if (!strcmp(token, "PREGAP")) {
433 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
434 tok2msf(time, dummy);
435 sector_offs += msf2sec(dummy);
437 pregapOffset = -1; // mark to fill track start_offset
439 else if (!strcmp(token, "FILE")) {
440 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
442 sscanf(linebuf, " FILE %255s", tmpb);
444 tmp = strrchr(tmpb, '\\');
446 tmp = strrchr(tmpb, '/');
451 strncpy(incue_fname, tmp, incue_max_len);
452 ti[numtracks + 1].handle = fopen(filepath, "rb");
454 // update global offset if this is not first file in this .cue
455 if (numtracks + 1 > 1) {
457 sector_offs += file_len;
461 if (ti[numtracks + 1].handle == NULL) {
462 SysPrintf(_("\ncould not open: %s\n"), filepath);
465 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
466 file_len = ftell(ti[numtracks + 1].handle) / 2352;
468 if (numtracks == 0 && strlen(isofile) >= 4 &&
469 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
470 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
471 // user selected .cue/.cdX as image file, use it's data track instead
473 cdHandle = fopen(filepath, "rb");
480 // if there are no tracks detected, then it's not a cue file
487 // this function tries to get the .ccd file of the given .img
488 // the necessary data is put into the ti (trackinformation)-array
489 static int parseccd(const char *isofile) {
490 char ccdname[MAXPATHLEN];
497 // copy name of the iso and change extension from .img to .ccd
498 strncpy(ccdname, isofile, sizeof(ccdname));
499 ccdname[MAXPATHLEN - 1] = '\0';
500 if (strlen(ccdname) >= 4) {
501 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
507 if ((fi = fopen(ccdname, "r")) == NULL) {
511 memset(&ti, 0, sizeof(ti));
513 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
514 if (!strncmp(linebuf, "[TRACK", 6)){
517 else if (!strncmp(linebuf, "MODE=", 5)) {
518 sscanf(linebuf, "MODE=%d", &t);
519 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
521 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
522 sscanf(linebuf, "INDEX 1=%d", &t);
523 sec2msf(t + 2 * 75, ti[numtracks].start);
524 ti[numtracks].start_offset = t * 2352;
526 // If we've already seen another track, this is its end
528 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
529 sec2msf(t, ti[numtracks - 1].length);
536 // Fill out the last track's end based on size
537 if (numtracks >= 1) {
538 fseek(cdHandle, 0, SEEK_END);
539 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
540 sec2msf(t, ti[numtracks].length);
546 // this function tries to get the .mds file of the given .mdf
547 // the necessary data is put into the ti (trackinformation)-array
548 static int parsemds(const char *isofile) {
549 char mdsname[MAXPATHLEN];
551 unsigned int offset, extra_offset, l, i;
556 // copy name of the iso and change extension from .mdf to .mds
557 strncpy(mdsname, isofile, sizeof(mdsname));
558 mdsname[MAXPATHLEN - 1] = '\0';
559 if (strlen(mdsname) >= 4) {
560 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
566 if ((fi = fopen(mdsname, "rb")) == NULL) {
570 memset(&ti, 0, sizeof(ti));
572 // check if it's a valid mds file
573 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
576 if (i != 0x4944454D) {
577 // not an valid mds file
582 // get offset to session block
583 fseek(fi, 0x50, SEEK_SET);
584 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
586 offset = SWAP32(offset);
588 // get total number of tracks
590 fseek(fi, offset, SEEK_SET);
591 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
596 // get offset to track blocks
597 fseek(fi, 4, SEEK_CUR);
598 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
600 offset = SWAP32(offset);
604 fseek(fi, offset + 4, SEEK_SET);
605 if (fgetc(fi) < 0xA0) {
611 // check if the image contains mixed subchannel data
612 fseek(fi, offset + 1, SEEK_SET);
613 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
616 for (i = 1; i <= numtracks; i++) {
617 fseek(fi, offset, SEEK_SET);
619 // get the track type
620 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
621 fseek(fi, 8, SEEK_CUR);
623 // get the track starting point
624 ti[i].start[0] = fgetc(fi);
625 ti[i].start[1] = fgetc(fi);
626 ti[i].start[2] = fgetc(fi);
628 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
630 extra_offset = SWAP32(extra_offset);
632 // get track start offset (in .mdf)
633 fseek(fi, offset + 0x28, SEEK_SET);
634 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
637 ti[i].start_offset = l;
640 fseek(fi, extra_offset, SEEK_SET);
641 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
645 pregapOffset = msf2sec(ti[i].start);
647 // get the track length
648 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
651 sec2msf(l, ti[i].length);
659 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
665 static int handlepbp(const char *isofile) {
668 unsigned int dontcare[8];
669 unsigned int psar_offs;
682 unsigned int dontcare[6];
685 off_t psisoimg_offs, cdimg_base;
686 unsigned int t, cd_length;
687 unsigned int offsettab[8];
688 const char *ext = NULL;
691 if (strlen(isofile) >= 4)
692 ext = isofile + strlen(isofile) - 4;
693 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
696 fseeko(cdHandle, 0, SEEK_SET);
700 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
701 if (ret != sizeof(pbp_hdr)) {
702 SysPrintf("failed to read pbp\n");
706 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
708 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
712 psisoimg_offs = pbp_hdr.psar_offs;
713 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
716 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
718 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
720 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
724 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
725 SysPrintf("failed to read offsettab\n");
729 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
730 if (offsettab[i] == 0)
733 cdrIsoMultidiskCount = i;
734 if (cdrIsoMultidiskCount == 0) {
735 SysPrintf("multidisk eboot has 0 images?\n");
739 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
740 cdrIsoMultidiskSelect = 0;
742 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
744 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
746 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
750 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
755 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
756 SysPrintf("bad psar_sig: %s\n", psar_sig);
761 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
763 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
767 // first 3 entries are special
768 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
769 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
771 numtracks = btoi(toc_entry.index1[0]);
773 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
775 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
776 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
778 for (i = 1; i <= numtracks; i++) {
779 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
782 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
784 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
785 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
786 ti[i].start_offset *= 2352;
787 ti[i].start[0] = btoi(toc_entry.index1[0]);
788 ti[i].start[1] = btoi(toc_entry.index1[1]);
789 ti[i].start[2] = btoi(toc_entry.index1[2]);
792 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
793 sec2msf(t, ti[i - 1].length);
796 t = cd_length - ti[numtracks].start_offset / 2352;
797 sec2msf(t, ti[numtracks].length);
800 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
802 SysPrintf("failed to seek to ISO index\n");
806 compr_img = calloc(1, sizeof(*compr_img));
807 if (compr_img == NULL)
810 compr_img->block_shift = 4;
811 compr_img->current_block = (unsigned int)-1;
813 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
814 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
815 if (compr_img->index_table == NULL)
818 cdimg_base = psisoimg_offs + 0x100000;
819 for (i = 0; i < compr_img->index_len; i++) {
820 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
821 if (ret != sizeof(index_entry)) {
822 SysPrintf("failed to read index_entry #%d\n", i);
826 if (index_entry.size == 0)
829 compr_img->index_table[i] = cdimg_base + index_entry.offset;
831 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
836 free(compr_img->index_table);
837 compr_img->index_table = NULL;
842 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
846 if (compr_img != NULL) {
853 static int handlecbin(const char *isofile) {
857 unsigned int header_size;
858 unsigned long long total_bytes;
859 unsigned int block_size;
860 unsigned char ver; // 1
862 unsigned char rsv_06[2];
864 const char *ext = NULL;
865 unsigned int *index_table = NULL;
866 unsigned int index = 0, plain;
869 if (strlen(isofile) >= 5)
870 ext = isofile + strlen(isofile) - 5;
871 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
874 fseek(cdHandle, 0, SEEK_SET);
876 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
877 if (ret != sizeof(ciso_hdr)) {
878 SysPrintf("failed to read ciso header\n");
882 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
883 SysPrintf("bad ciso header\n");
886 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
887 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
889 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
894 compr_img = calloc(1, sizeof(*compr_img));
895 if (compr_img == NULL)
898 compr_img->block_shift = 0;
899 compr_img->current_block = (unsigned int)-1;
901 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
902 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
903 if (index_table == NULL)
906 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
907 if (ret != compr_img->index_len) {
908 SysPrintf("failed to read index table\n");
912 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
913 if (compr_img->index_table == NULL)
916 for (i = 0; i < compr_img->index_len + 1; i++) {
917 index = index_table[i];
918 plain = index & 0x80000000;
920 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
922 compr_img->index_table[i] |= OFF_T_MSB;
930 if (compr_img != NULL) {
938 static int handlechd(const char *isofile) {
939 chd_img = calloc(1, sizeof(*chd_img));
943 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
946 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
949 chd_img->header = chd_get_header(chd_img->chd);
951 chd_img->buffer = malloc(chd_img->header->hunkbytes);
952 if (chd_img->buffer == NULL)
955 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
956 chd_img->current_hunk = (unsigned int)-1;
958 cddaBigEndian = TRUE;
961 int frame_offset = 0;
963 memset(ti, 0, sizeof(ti));
978 uint32_t meta_size = 0;
980 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
981 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
982 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
983 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
987 SysPrintf("chd: %s\n", meta);
991 if (!strncmp(md.subtype, "RW", 2)) {
993 if (!strcmp(md.subtype, "RW_RAW"))
998 sec2msf(msf2sec(ti[md.track-1].length) + md.pregap, ti[md.track-1].length);
1000 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1002 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1003 sec2msf(md.frames, ti[md.track].length);
1005 ti[md.track].start_offset = file_offset;
1007 frame_offset += md.pregap + md.frames + md.postgap;
1008 file_offset += md.frames + md.postgap;
1016 if (chd_img != NULL) {
1017 free(chd_img->buffer);
1025 // this function tries to get the .sub file of the given .img
1026 static int opensubfile(const char *isoname) {
1027 char subname[MAXPATHLEN];
1029 // copy name of the iso and change extension from .img to .sub
1030 strncpy(subname, isoname, sizeof(subname));
1031 subname[MAXPATHLEN - 1] = '\0';
1032 if (strlen(subname) >= 4) {
1033 strcpy(subname + strlen(subname) - 4, ".sub");
1039 subHandle = fopen(subname, "rb");
1040 if (subHandle == NULL) {
1047 static int opensbifile(const char *isoname) {
1048 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1051 strncpy(sbiname, isoname, sizeof(sbiname));
1052 sbiname[MAXPATHLEN - 1] = '\0';
1053 if (strlen(sbiname) >= 4) {
1054 if (cdrIsoMultidiskCount > 1) {
1055 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1056 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1059 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1065 fseek(cdHandle, 0, SEEK_END);
1066 s = ftell(cdHandle) / 2352;
1068 return LoadSBI(sbiname, s);
1072 static void readThreadStop() {}
1073 static void readThreadStart() {}
1075 static pthread_t read_thread_id;
1077 static pthread_cond_t read_thread_msg_avail;
1078 static pthread_cond_t read_thread_msg_done;
1079 static pthread_mutex_t read_thread_msg_lock;
1081 static pthread_cond_t sectorbuffer_cond;
1082 static pthread_mutex_t sectorbuffer_lock;
1084 static boolean read_thread_running = FALSE;
1085 static int read_thread_sector_start = -1;
1086 static int read_thread_sector_end = -1;
1091 unsigned char data[CD_FRAMESIZE_RAW];
1092 } SectorBufferEntry;
1094 #define SECTOR_BUFFER_SIZE 4096
1096 static SectorBufferEntry *sectorbuffer;
1097 static size_t sectorbuffer_index;
1099 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1100 unsigned char *(*sync_CDR_getBuffer)(void);
1102 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1103 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1105 static void *readThreadMain(void *param) {
1106 int max_sector = -1;
1107 int requested_sector_start = -1;
1108 int requested_sector_end = -1;
1109 int last_read_sector = -1;
1115 int speedmult_ra = 4;
1118 int how_far_ahead = 0;
1120 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1123 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1126 pthread_mutex_lock(&read_thread_msg_lock);
1128 // If we don't have readahead and we don't have a sector request, wait for one.
1129 // If we still have readahead to go, don't block, just keep going.
1130 // And if we ever have a sector request pending, acknowledge and reset it.
1133 if (read_thread_sector_start == -1 && read_thread_running) {
1134 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1138 if (read_thread_sector_start != -1) {
1139 requested_sector_start = read_thread_sector_start;
1140 requested_sector_end = read_thread_sector_end;
1141 read_thread_sector_start = -1;
1142 read_thread_sector_end = -1;
1143 pthread_cond_signal(&read_thread_msg_done);
1146 pthread_mutex_unlock(&read_thread_msg_lock);
1148 if (!read_thread_running)
1151 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1152 if (requested_sector_start != -1) {
1153 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1154 how_far_ahead = ra_sector - requested_sector_end;
1156 if(how_far_ahead <= max_ra)
1157 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1160 } else if (requested_sector_end != last_read_sector) {
1161 ra_sector = requested_sector_end;
1162 ra_count = initial_ra;
1165 last_read_sector = requested_sector_end;
1168 index = ra_sector % SECTOR_BUFFER_SIZE;
1170 // check for end of CD
1171 if (ra_count && ra_sector >= max_sector) {
1173 pthread_mutex_lock(§orbuffer_lock);
1174 sectorbuffer[index].ret = -1;
1175 sectorbuffer[index].sector = ra_sector;
1176 pthread_cond_signal(§orbuffer_cond);
1177 pthread_mutex_unlock(§orbuffer_lock);
1181 pthread_mutex_lock(§orbuffer_lock);
1182 if (sectorbuffer[index].sector != ra_sector) {
1183 pthread_mutex_unlock(§orbuffer_lock);
1185 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1187 pthread_mutex_lock(§orbuffer_lock);
1188 sectorbuffer[index].ret = ret;
1189 sectorbuffer[index].sector = ra_sector;
1190 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1192 pthread_cond_signal(§orbuffer_cond);
1193 pthread_mutex_unlock(§orbuffer_lock);
1203 static void readThreadStop() {
1204 if (read_thread_running == TRUE) {
1205 read_thread_running = FALSE;
1206 pthread_cond_signal(&read_thread_msg_avail);
1207 pthread_join(read_thread_id, NULL);
1210 pthread_cond_destroy(&read_thread_msg_done);
1211 pthread_cond_destroy(&read_thread_msg_avail);
1212 pthread_mutex_destroy(&read_thread_msg_lock);
1214 pthread_cond_destroy(§orbuffer_cond);
1215 pthread_mutex_destroy(§orbuffer_lock);
1217 CDR_getBuffer = sync_CDR_getBuffer;
1218 cdimg_read_func = sync_cdimg_read_func;
1221 sectorbuffer = NULL;
1224 static void readThreadStart() {
1225 SysPrintf("Starting async CD thread\n");
1227 if (read_thread_running == TRUE)
1230 read_thread_running = TRUE;
1231 read_thread_sector_start = -1;
1232 read_thread_sector_end = -1;
1233 sectorbuffer_index = 0;
1235 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1239 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1241 sync_CDR_getBuffer = CDR_getBuffer;
1242 CDR_getBuffer = ISOgetBuffer_async;
1243 sync_cdimg_read_func = cdimg_read_func;
1244 cdimg_read_func = cdread_async;
1246 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1247 pthread_cond_init(&read_thread_msg_done, NULL) ||
1248 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1249 pthread_cond_init(§orbuffer_cond, NULL) ||
1250 pthread_mutex_init(§orbuffer_lock, NULL) ||
1251 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1257 SysPrintf("Error starting async CD thread\n");
1258 SysPrintf("Falling back to sync\n");
1264 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1266 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1267 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1270 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1274 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1275 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1276 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1279 if (subChanRaw) DecodeRawSubData();
1284 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1291 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1296 if (z.zalloc == NULL) {
1297 // XXX: one-time leak here..
1303 ret = inflateInit2(&z, -15);
1306 ret = inflateReset(&z);
1311 z.avail_in = in_size;
1313 z.avail_out = *out_size;
1315 ret = inflate(&z, Z_NO_FLUSH);
1318 *out_size -= z.avail_out;
1319 return ret == 1 ? 0 : ret;
1322 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1324 unsigned long cdbuffer_size, cdbuffer_size_expect;
1331 sector += base / 2352;
1333 block = sector >> compr_img->block_shift;
1334 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1336 if (block == compr_img->current_block) {
1337 //printf("hit sect %d\n", sector);
1341 if (sector >= compr_img->index_len * 16) {
1342 SysPrintf("sector %d is past img end\n", sector);
1346 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1347 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1348 SysPrintf("seek error for block %d at %llx: ",
1349 block, (long long)start_byte);
1354 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1355 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1356 if (size > sizeof(compr_img->buff_compressed)) {
1357 SysPrintf("block %d is too large: %u\n", block, size);
1361 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1362 1, size, cdHandle) != size) {
1363 SysPrintf("read error for block %d at %x: ", block, start_byte);
1368 if (is_compressed) {
1369 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1370 cdbuffer_size = cdbuffer_size_expect;
1371 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1373 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1374 ret, block, sector);
1377 if (cdbuffer_size != cdbuffer_size_expect)
1378 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1379 cdbuffer_size_expect, sector);
1383 compr_img->current_block = block;
1386 if (dest != cdbuffer) // copy avoid HACK
1387 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1389 return CD_FRAMESIZE_RAW;
1393 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1400 hunk = sector / chd_img->sectors_per_hunk;
1401 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1403 if (hunk != chd_img->current_hunk)
1405 chd_read(chd_img->chd, hunk, chd_img->buffer);
1406 chd_img->current_hunk = hunk;
1409 if (dest != cdbuffer) // copy avoid HACK
1410 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1413 memcpy(subbuffer, chd_img->buffer[chd_img->sector_in_hunk] + CD_FRAMESIZE_RAW,
1418 return CD_FRAMESIZE_RAW;
1421 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1425 fseek(f, base + sector * 2048, SEEK_SET);
1426 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1428 // not really necessary, fake mode 2 header
1429 memset(cdbuffer, 0, 12 * 2);
1430 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1431 cdbuffer[12 + 3] = 1;
1438 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1439 boolean found = FALSE;
1440 int i = sector % SECTOR_BUFFER_SIZE;
1443 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1444 // Async reads are only supported for cdbuffer, so call the sync
1445 // function directly.
1446 return sync_cdimg_read_func(f, base, dest, sector);
1449 pthread_mutex_lock(&read_thread_msg_lock);
1451 // Only wait if we're not trying to read the next sector and
1452 // sector_start is set (meaning the last request hasn't been
1454 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1455 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1458 if (read_thread_sector_start == -1)
1459 read_thread_sector_start = sector;
1461 read_thread_sector_end = sector;
1462 pthread_cond_signal(&read_thread_msg_avail);
1463 pthread_mutex_unlock(&read_thread_msg_lock);
1466 pthread_mutex_lock(§orbuffer_lock);
1467 if (sectorbuffer[i].sector == sector) {
1468 sectorbuffer_index = i;
1469 ret = sectorbuffer[i].ret;
1474 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1476 pthread_mutex_unlock(§orbuffer_lock);
1484 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1485 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1489 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1490 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1495 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1496 unsigned char *buffer;
1497 pthread_mutex_lock(§orbuffer_lock);
1498 buffer = sectorbuffer[sectorbuffer_index].data;
1499 pthread_mutex_unlock(§orbuffer_lock);
1505 static unsigned char * CALLBACK ISOgetBuffer(void) {
1506 return cdbuffer + 12;
1509 static void PrintTracks(void) {
1512 for (i = 1; i <= numtracks; i++) {
1513 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1514 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1515 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1516 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1520 // This function is invoked by the front-end when opening an ISO
1521 // file for playback
1522 static long CALLBACK ISOopen(void) {
1523 boolean isMode1ISO = FALSE;
1524 char alt_bin_filename[MAXPATHLEN];
1525 const char *bin_filename;
1526 char image_str[1024];
1529 if (cdHandle != NULL) {
1530 return 0; // it's already open
1533 cdHandle = fopen(GetIsoFile(), "rb");
1534 if (cdHandle == NULL) {
1535 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1536 GetIsoFile(), strerror(errno));
1540 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1541 "Loaded CD Image: %s", GetIsoFile());
1543 cddaBigEndian = FALSE;
1544 subChanMixed = FALSE;
1547 cdrIsoMultidiskCount = 1;
1550 CDR_getBuffer = ISOgetBuffer;
1551 cdimg_read_func = cdread_normal;
1553 if (parsetoc(GetIsoFile()) == 0) {
1554 strcat(image_str, "[+toc]");
1556 else if (parseccd(GetIsoFile()) == 0) {
1557 strcat(image_str, "[+ccd]");
1559 else if (parsemds(GetIsoFile()) == 0) {
1560 strcat(image_str, "[+mds]");
1562 else if (parsecue(GetIsoFile()) == 0) {
1563 strcat(image_str, "[+cue]");
1565 if (handlepbp(GetIsoFile()) == 0) {
1566 strcat(image_str, "[+pbp]");
1567 CDR_getBuffer = ISOgetBuffer_compr;
1568 cdimg_read_func = cdread_compressed;
1570 else if (handlecbin(GetIsoFile()) == 0) {
1571 strcat(image_str, "[+cbin]");
1572 CDR_getBuffer = ISOgetBuffer_compr;
1573 cdimg_read_func = cdread_compressed;
1576 else if (handlechd(GetIsoFile()) == 0) {
1577 strcat(image_str, "[+chd]");
1578 CDR_getBuffer = ISOgetBuffer_chd;
1579 cdimg_read_func = cdread_chd;
1584 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1585 strcat(image_str, "[+sub]");
1587 if (opensbifile(GetIsoFile()) == 0) {
1588 strcat(image_str, "[+sbi]");
1591 fseeko(cdHandle, 0, SEEK_END);
1593 // maybe user selected metadata file instead of main .bin ..
1594 bin_filename = GetIsoFile();
1595 if (ftello(cdHandle) < 2352 * 0x10) {
1596 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1601 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1602 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1603 if (strlen(alt_bin_filename) >= 4) {
1604 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1605 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1607 tmpf = fopen(alt_bin_filename, "rb");
1613 bin_filename = alt_bin_filename;
1616 fseeko(cdHandle, 0, SEEK_END);
1620 // guess whether it is mode1/2048
1621 if (ftello(cdHandle) % 2048 == 0) {
1622 unsigned int modeTest = 0;
1623 fseek(cdHandle, 0, SEEK_SET);
1624 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1626 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1630 if (SWAP32(modeTest) != 0xffffff00) {
1631 strcat(image_str, "[2048]");
1635 fseek(cdHandle, 0, SEEK_SET);
1637 SysPrintf("%s.\n", image_str);
1641 if (subChanMixed && !is_chd)
1642 cdimg_read_func = cdread_sub_mixed;
1643 else if (isMode1ISO)
1644 cdimg_read_func = cdread_2048;
1646 // make sure we have another handle open for cdda
1647 if (numtracks > 1 && ti[1].handle == NULL) {
1648 ti[1].handle = fopen(bin_filename, "rb");
1650 cdda_cur_sector = 0;
1651 cdda_file_offset = 0;
1653 if (Config.AsyncCD) {
1659 static long CALLBACK ISOclose(void) {
1662 if (cdHandle != NULL) {
1666 if (subHandle != NULL) {
1673 if (compr_img != NULL) {
1674 free(compr_img->index_table);
1680 if (chd_img != NULL) {
1681 chd_close(chd_img->chd);
1682 free(chd_img->buffer);
1688 for (i = 1; i <= numtracks; i++) {
1689 if (ti[i].handle != NULL) {
1690 fclose(ti[i].handle);
1691 ti[i].handle = NULL;
1698 memset(cdbuffer, 0, sizeof(cdbuffer));
1699 CDR_getBuffer = ISOgetBuffer;
1701 if (Config.AsyncCD) {
1708 static long CALLBACK ISOinit(void) {
1709 assert(cdHandle == NULL);
1710 assert(subHandle == NULL);
1712 return 0; // do nothing
1715 static long CALLBACK ISOshutdown(void) {
1720 // return Starting and Ending Track
1722 // byte 0 - start track
1723 // byte 1 - end track
1724 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1727 if (numtracks > 0) {
1728 buffer[1] = numtracks;
1737 // return Track Time
1742 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1745 unsigned char time[3];
1746 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1747 sec2msf(sect, (char *)time);
1748 buffer[2] = time[0];
1749 buffer[1] = time[1];
1750 buffer[0] = time[2];
1752 else if (numtracks > 0 && track <= numtracks) {
1753 buffer[2] = ti[track].start[0];
1754 buffer[1] = ti[track].start[1];
1755 buffer[0] = ti[track].start[2];
1766 // decode 'raw' subchannel data ripped by cdrdao
1767 static void DecodeRawSubData(void) {
1768 unsigned char subQData[12];
1771 memset(subQData, 0, sizeof(subQData));
1773 for (i = 0; i < 8 * 12; i++) {
1774 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1775 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1779 memcpy(&subbuffer[12], subQData, 12);
1783 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1785 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1786 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1789 if (cdHandle == NULL) {
1794 subChanMissing = FALSE;
1795 if (sector >= pregapOffset) {
1797 if (sector < pregapOffset)
1798 subChanMissing = TRUE;
1802 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1806 if (subHandle != NULL) {
1807 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1808 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1809 /* Faulty subchannel data shouldn't cause a read failure */
1812 if (subChanRaw) DecodeRawSubData();
1819 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1820 // does NOT uses bcd format
1821 static long CALLBACK ISOplay(void) {
1827 static long CALLBACK ISOstop(void) {
1832 // gets subchannel data
1833 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1834 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1841 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1844 CDR__getStatus(stat);
1848 stat->Status |= 0x80;
1851 // BIOS - boot ID (CD type)
1852 stat->Type = ti[1].type;
1855 // relative -> absolute time
1857 sec2msf(sect, (char *)stat->Time);
1862 // read CDDA sector into buffer
1863 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1864 unsigned char msf[3] = {m, s, f};
1865 unsigned int file, track, track_start = 0;
1868 cddaCurPos = msf2sec((char *)msf);
1870 // find current track index
1871 for (track = numtracks; ; track--) {
1872 track_start = msf2sec(ti[track].start);
1873 if (track_start <= cddaCurPos)
1879 // data tracks play silent
1880 if (ti[track].type != CDDA) {
1881 memset(buffer, 0, CD_FRAMESIZE_RAW);
1887 // find the file that contains this track
1888 for (file = track; file > 1; file--)
1889 if (ti[file].handle != NULL)
1893 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1894 buffer, cddaCurPos - track_start);
1895 if (ret != CD_FRAMESIZE_RAW) {
1896 memset(buffer, 0, CD_FRAMESIZE_RAW);
1900 if (cddaBigEndian) {
1904 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1905 tmp = buffer[i * 2];
1906 buffer[i * 2] = buffer[i * 2 + 1];
1907 buffer[i * 2 + 1] = tmp;
1914 void cdrIsoInit(void) {
1916 CDR_shutdown = ISOshutdown;
1918 CDR_close = ISOclose;
1919 CDR_getTN = ISOgetTN;
1920 CDR_getTD = ISOgetTD;
1921 CDR_readTrack = ISOreadTrack;
1922 CDR_getBuffer = ISOgetBuffer;
1925 CDR_getBufferSub = ISOgetBufferSub;
1926 CDR_getStatus = ISOgetStatus;
1927 CDR_readCDDA = ISOreadCDDA;
1929 CDR_getDriveLetter = CDR__getDriveLetter;
1930 CDR_configure = CDR__configure;
1931 CDR_test = CDR__test;
1932 CDR_about = CDR__about;
1933 CDR_setfilename = CDR__setfilename;
1938 int cdrIsoActive(void) {
1939 return (cdHandle != NULL);