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 // to enable the USE_READ_THREAD code, fix:
46 // - https://github.com/notaz/pcsx_rearmed/issues/257
47 // - ISOgetBufferSub to not race with async code
48 #define USE_READ_THREAD 0 //P_HAVE_PTHREAD
50 #ifdef USE_LIBRETRO_VFS
51 #include <streams/file_stream_transforms.h>
58 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
60 unsigned int cdrIsoMultidiskCount;
61 unsigned int cdrIsoMultidiskSelect;
63 static FILE *cdHandle = NULL;
64 static FILE *cddaHandle = NULL;
65 static FILE *subHandle = NULL;
67 static boolean subChanMixed = FALSE;
68 static boolean subChanRaw = FALSE;
70 static boolean multifile = FALSE;
72 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
73 static unsigned char subbuffer[SUB_FRAMESIZE];
75 static boolean playing = FALSE;
76 static boolean cddaBigEndian = FALSE;
77 /* Frame offset into CD image where pregap data would be found if it was there.
78 * If a game seeks there we must *not* return subchannel data since it's
79 * not in the CD image, so that cdrom code can fake subchannel data instead.
80 * XXX: there could be multiple pregaps but PSX dumps only have one? */
81 static unsigned int pregapOffset;
83 static unsigned int cddaCurPos;
85 // compressed image stuff
87 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
88 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
90 unsigned int index_len;
91 unsigned int block_shift;
92 unsigned int current_block;
93 unsigned int sector_in_blk;
98 unsigned char *buffer;
100 const chd_header* header;
101 unsigned int sectors_per_hunk;
102 unsigned int current_hunk[2];
103 unsigned int current_buffer;
104 unsigned int sector_in_hunk;
108 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
109 static int (*cdimg_read_sub_func)(FILE *f, int sector);
111 char* CALLBACK CDR__getDriveLetter(void);
112 long CALLBACK CDR__configure(void);
113 long CALLBACK CDR__test(void);
114 void CALLBACK CDR__about(void);
115 long CALLBACK CDR__setfilename(char *filename);
116 long CALLBACK CDR__getStatus(struct CdrStat *stat);
118 static void DecodeRawSubData(void);
121 enum {DATA=1, CDDA} type;
122 char start[3]; // MSF-format
123 char length[3]; // MSF-format
124 FILE *handle; // for multi-track images CDDA
125 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
128 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
130 static int numtracks = 0;
131 static struct trackinfo ti[MAXTRACKS];
133 // get a sector from a msf-array
134 static unsigned int msf2sec(char *msf) {
135 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
138 static void sec2msf(unsigned int s, char *msf) {
139 msf[0] = s / 75 / 60;
140 s = s - msf[0] * 75 * 60;
146 // divide a string of xx:yy:zz into m, s, f
147 static void tok2msf(char *time, char *msf) {
150 token = strtok(time, ":");
152 msf[0] = atoi(token);
158 token = strtok(NULL, ":");
160 msf[1] = atoi(token);
166 token = strtok(NULL, ":");
168 msf[2] = atoi(token);
175 // this function tries to get the .toc file of the given .bin
176 // the necessary data is put into the ti (trackinformation)-array
177 static int parsetoc(const char *isofile) {
178 char tocname[MAXPATHLEN];
180 char linebuf[256], tmp[256], name[256];
182 char time[20], time2[20];
183 unsigned int t, sector_offs, sector_size;
184 unsigned int current_zero_gap = 0;
188 // copy name of the iso and change extension from .bin to .toc
189 strncpy(tocname, isofile, sizeof(tocname));
190 tocname[MAXPATHLEN - 1] = '\0';
191 if (strlen(tocname) >= 4) {
192 strcpy(tocname + strlen(tocname) - 4, ".toc");
198 if ((fi = fopen(tocname, "r")) == NULL) {
199 // try changing extension to .cue (to satisfy some stupid tutorials)
200 strcpy(tocname + strlen(tocname) - 4, ".cue");
201 if ((fi = fopen(tocname, "r")) == NULL) {
202 // if filename is image.toc.bin, try removing .bin (for Brasero)
203 strcpy(tocname, isofile);
205 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
206 tocname[t - 4] = '\0';
207 if ((fi = fopen(tocname, "r")) == NULL) {
215 // check if it's really a TOC named as a .cue
216 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
217 token = strtok(linebuf, " ");
218 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
223 fseek(fi, 0, SEEK_SET);
226 memset(&ti, 0, sizeof(ti));
227 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
229 sector_size = CD_FRAMESIZE_RAW;
230 sector_offs = 2 * 75;
232 // parse the .toc file
233 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
235 strncpy(tmp, linebuf, sizeof(linebuf));
236 token = strtok(tmp, " ");
238 if (token == NULL) continue;
240 if (!strcmp(token, "TRACK")) {
241 sector_offs += current_zero_gap;
242 current_zero_gap = 0;
245 token = strtok(NULL, " ");
248 if (!strncmp(token, "MODE2_RAW", 9)) {
249 ti[numtracks].type = DATA;
250 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
252 // check if this image contains mixed subchannel data
253 token = strtok(NULL, " ");
254 if (token != NULL && !strncmp(token, "RW", 2)) {
255 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
257 if (!strncmp(token, "RW_RAW", 6))
261 else if (!strncmp(token, "AUDIO", 5)) {
262 ti[numtracks].type = CDDA;
265 else if (!strcmp(token, "DATAFILE")) {
266 if (ti[numtracks].type == CDDA) {
267 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
268 ti[numtracks].start_offset = t;
269 t = t / sector_size + sector_offs;
270 sec2msf(t, (char *)&ti[numtracks].start);
271 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
274 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
275 tok2msf((char *)&time, (char *)&ti[numtracks].length);
278 else if (!strcmp(token, "FILE")) {
279 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
280 tok2msf((char *)&time, (char *)&ti[numtracks].start);
281 t += msf2sec(ti[numtracks].start) * sector_size;
282 ti[numtracks].start_offset = t;
283 t = t / sector_size + sector_offs;
284 sec2msf(t, (char *)&ti[numtracks].start);
285 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
287 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
288 // skip unneeded optional fields
289 while (token != NULL) {
290 token = strtok(NULL, " ");
291 if (strchr(token, ':') != NULL)
296 current_zero_gap = msf2sec(tmp);
299 t = ti[numtracks - 1].start_offset;
301 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
304 else if (!strcmp(token, "START")) {
305 token = strtok(NULL, " ");
306 if (token != NULL && strchr(token, ':')) {
309 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
310 t = msf2sec(ti[numtracks].start) + t;
311 sec2msf(t, (char *)&ti[numtracks].start);
321 // this function tries to get the .cue file of the given .bin
322 // the necessary data is put into the ti (trackinformation)-array
323 static int parsecue(const char *isofile) {
324 char cuename[MAXPATHLEN];
325 char filepath[MAXPATHLEN];
331 char linebuf[256], tmpb[256], dummy[256];
332 unsigned int incue_max_len;
333 unsigned int t, file_len, mode, sector_offs;
334 unsigned int sector_size = 2352;
338 // copy name of the iso and change extension from .bin to .cue
339 strncpy(cuename, isofile, sizeof(cuename));
340 cuename[MAXPATHLEN - 1] = '\0';
341 if (strlen(cuename) >= 4) {
342 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
343 // and don't try to search the additional .cue file
344 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
345 strcpy(cuename + strlen(cuename) - 4, ".cue");
351 if ((fi = fopen(cuename, "r")) == NULL) {
355 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
356 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
358 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
359 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
360 // Don't proceed further, as this is actually a .toc file rather
363 return parsetoc(isofile);
365 fseek(fi, 0, SEEK_SET);
368 // build a path for files referenced in .cue
369 strncpy(filepath, cuename, sizeof(filepath));
370 tmp = strrchr(filepath, '/');
372 tmp = strrchr(filepath, '\\');
378 filepath[sizeof(filepath) - 1] = 0;
380 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
382 memset(&ti, 0, sizeof(ti));
385 sector_offs = 2 * 75;
387 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
388 strncpy(dummy, linebuf, sizeof(linebuf));
389 token = strtok(dummy, " ");
395 if (!strcmp(token, "TRACK")) {
399 if (strstr(linebuf, "AUDIO") != NULL) {
400 ti[numtracks].type = CDDA;
403 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
404 ti[numtracks].type = DATA;
406 SysPrintf(".cue: failed to parse TRACK\n");
407 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
409 if (sector_size == 0)
412 else if (!strcmp(token, "INDEX")) {
413 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
414 SysPrintf(".cue: failed to parse INDEX\n");
415 tok2msf(time, (char *)&ti[numtracks].start);
417 t = msf2sec(ti[numtracks].start);
418 ti[numtracks].start_offset = t * sector_size;
420 sec2msf(t, ti[numtracks].start);
422 // default track length to file length
423 t = file_len - ti[numtracks].start_offset / sector_size;
424 sec2msf(t, ti[numtracks].length);
426 if (numtracks > 1 && ti[numtracks].handle == NULL) {
427 // this track uses the same file as the last,
428 // start of this track is last track's end
429 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
430 sec2msf(t, ti[numtracks - 1].length);
432 if (numtracks > 1 && pregapOffset == -1)
433 pregapOffset = ti[numtracks].start_offset / sector_size;
435 else if (!strcmp(token, "PREGAP")) {
436 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
437 tok2msf(time, dummy);
438 sector_offs += msf2sec(dummy);
440 pregapOffset = -1; // mark to fill track start_offset
442 else if (!strcmp(token, "FILE")) {
443 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
445 sscanf(linebuf, " FILE %255s", tmpb);
447 tmp = strrchr(tmpb, '\\');
449 tmp = strrchr(tmpb, '/');
454 strncpy(incue_fname, tmp, incue_max_len);
455 ti[numtracks + 1].handle = fopen(filepath, "rb");
457 // update global offset if this is not first file in this .cue
458 if (numtracks + 1 > 1) {
460 sector_offs += file_len;
464 if (ti[numtracks + 1].handle == NULL) {
465 SysPrintf(_("\ncould not open: %s\n"), filepath);
468 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
469 file_len = ftell(ti[numtracks + 1].handle) / 2352;
471 if (numtracks == 0 && strlen(isofile) >= 4 &&
472 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
473 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
474 // user selected .cue/.cdX as image file, use it's data track instead
476 cdHandle = fopen(filepath, "rb");
483 // if there are no tracks detected, then it's not a cue file
490 // this function tries to get the .ccd file of the given .img
491 // the necessary data is put into the ti (trackinformation)-array
492 static int parseccd(const char *isofile) {
493 char ccdname[MAXPATHLEN];
500 // copy name of the iso and change extension from .img to .ccd
501 strncpy(ccdname, isofile, sizeof(ccdname));
502 ccdname[MAXPATHLEN - 1] = '\0';
503 if (strlen(ccdname) >= 4) {
504 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
510 if ((fi = fopen(ccdname, "r")) == NULL) {
514 memset(&ti, 0, sizeof(ti));
516 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
517 if (!strncmp(linebuf, "[TRACK", 6)){
520 else if (!strncmp(linebuf, "MODE=", 5)) {
521 sscanf(linebuf, "MODE=%d", &t);
522 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
524 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
525 sscanf(linebuf, "INDEX 1=%d", &t);
526 sec2msf(t + 2 * 75, ti[numtracks].start);
527 ti[numtracks].start_offset = t * 2352;
529 // If we've already seen another track, this is its end
531 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
532 sec2msf(t, ti[numtracks - 1].length);
539 // Fill out the last track's end based on size
540 if (numtracks >= 1) {
541 fseek(cdHandle, 0, SEEK_END);
542 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
543 sec2msf(t, ti[numtracks].length);
549 // this function tries to get the .mds file of the given .mdf
550 // the necessary data is put into the ti (trackinformation)-array
551 static int parsemds(const char *isofile) {
552 char mdsname[MAXPATHLEN];
554 unsigned int offset, extra_offset, l, i;
559 // copy name of the iso and change extension from .mdf to .mds
560 strncpy(mdsname, isofile, sizeof(mdsname));
561 mdsname[MAXPATHLEN - 1] = '\0';
562 if (strlen(mdsname) >= 4) {
563 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
569 if ((fi = fopen(mdsname, "rb")) == NULL) {
573 memset(&ti, 0, sizeof(ti));
575 // check if it's a valid mds file
576 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
579 if (i != 0x4944454D) {
580 // not an valid mds file
585 // get offset to session block
586 fseek(fi, 0x50, SEEK_SET);
587 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
589 offset = SWAP32(offset);
591 // get total number of tracks
593 fseek(fi, offset, SEEK_SET);
594 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
599 // get offset to track blocks
600 fseek(fi, 4, SEEK_CUR);
601 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
603 offset = SWAP32(offset);
607 fseek(fi, offset + 4, SEEK_SET);
608 if (fgetc(fi) < 0xA0) {
614 // check if the image contains mixed subchannel data
615 fseek(fi, offset + 1, SEEK_SET);
616 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
619 for (i = 1; i <= numtracks; i++) {
620 fseek(fi, offset, SEEK_SET);
622 // get the track type
623 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
624 fseek(fi, 8, SEEK_CUR);
626 // get the track starting point
627 ti[i].start[0] = fgetc(fi);
628 ti[i].start[1] = fgetc(fi);
629 ti[i].start[2] = fgetc(fi);
631 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
633 extra_offset = SWAP32(extra_offset);
635 // get track start offset (in .mdf)
636 fseek(fi, offset + 0x28, SEEK_SET);
637 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
640 ti[i].start_offset = l;
643 fseek(fi, extra_offset, SEEK_SET);
644 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
648 pregapOffset = msf2sec(ti[i].start);
650 // get the track length
651 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
654 sec2msf(l, ti[i].length);
662 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
668 static int handlepbp(const char *isofile) {
671 unsigned int dontcare[8];
672 unsigned int psar_offs;
685 unsigned int dontcare[6];
688 off_t psisoimg_offs, cdimg_base;
689 unsigned int t, cd_length;
690 unsigned int offsettab[8];
691 unsigned int psar_offs, index_entry_size, index_entry_offset;
692 const char *ext = NULL;
695 if (strlen(isofile) >= 4)
696 ext = isofile + strlen(isofile) - 4;
697 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
700 fseeko(cdHandle, 0, SEEK_SET);
704 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
705 if (ret != sizeof(pbp_hdr)) {
706 SysPrintf("failed to read pbp\n");
710 psar_offs = SWAP32(pbp_hdr.psar_offs);
712 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
714 SysPrintf("failed to seek to %x\n", psar_offs);
718 psisoimg_offs = psar_offs;
719 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
722 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
724 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
726 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
730 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
731 SysPrintf("failed to read offsettab\n");
735 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
736 if (offsettab[i] == 0)
739 cdrIsoMultidiskCount = i;
740 if (cdrIsoMultidiskCount == 0) {
741 SysPrintf("multidisk eboot has 0 images?\n");
745 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
746 cdrIsoMultidiskSelect = 0;
748 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
750 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
752 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
756 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
761 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
762 SysPrintf("bad psar_sig: %s\n", psar_sig);
767 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
769 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
773 // first 3 entries are special
774 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
775 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
777 numtracks = btoi(toc_entry.index1[0]);
779 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
781 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
782 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
784 for (i = 1; i <= numtracks; i++) {
785 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
788 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
790 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
791 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
792 ti[i].start_offset *= 2352;
793 ti[i].start[0] = btoi(toc_entry.index1[0]);
794 ti[i].start[1] = btoi(toc_entry.index1[1]);
795 ti[i].start[2] = btoi(toc_entry.index1[2]);
798 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
799 sec2msf(t, ti[i - 1].length);
802 t = cd_length - ti[numtracks].start_offset / 2352;
803 sec2msf(t, ti[numtracks].length);
806 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
808 SysPrintf("failed to seek to ISO index\n");
812 compr_img = calloc(1, sizeof(*compr_img));
813 if (compr_img == NULL)
816 compr_img->block_shift = 4;
817 compr_img->current_block = (unsigned int)-1;
819 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
820 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
821 if (compr_img->index_table == NULL)
824 cdimg_base = psisoimg_offs + 0x100000;
825 for (i = 0; i < compr_img->index_len; i++) {
826 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
827 if (ret != sizeof(index_entry)) {
828 SysPrintf("failed to read index_entry #%d\n", i);
832 index_entry_size = SWAP32(index_entry.size);
833 index_entry_offset = SWAP32(index_entry.offset);
835 if (index_entry_size == 0)
838 compr_img->index_table[i] = cdimg_base + index_entry_offset;
840 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
845 free(compr_img->index_table);
846 compr_img->index_table = NULL;
851 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
855 if (compr_img != NULL) {
862 static int handlecbin(const char *isofile) {
866 unsigned int header_size;
867 unsigned long long total_bytes;
868 unsigned int block_size;
869 unsigned char ver; // 1
871 unsigned char rsv_06[2];
873 const char *ext = NULL;
874 unsigned int *index_table = NULL;
875 unsigned int index = 0, plain;
878 if (strlen(isofile) >= 5)
879 ext = isofile + strlen(isofile) - 5;
880 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
883 fseek(cdHandle, 0, SEEK_SET);
885 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
886 if (ret != sizeof(ciso_hdr)) {
887 SysPrintf("failed to read ciso header\n");
891 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
892 SysPrintf("bad ciso header\n");
895 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
896 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
898 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
903 compr_img = calloc(1, sizeof(*compr_img));
904 if (compr_img == NULL)
907 compr_img->block_shift = 0;
908 compr_img->current_block = (unsigned int)-1;
910 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
911 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
912 if (index_table == NULL)
915 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
916 if (ret != compr_img->index_len) {
917 SysPrintf("failed to read index table\n");
921 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
922 if (compr_img->index_table == NULL)
925 for (i = 0; i < compr_img->index_len + 1; i++) {
926 index = index_table[i];
927 plain = index & 0x80000000;
929 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
931 compr_img->index_table[i] |= OFF_T_MSB;
939 if (compr_img != NULL) {
947 static int handlechd(const char *isofile) {
948 int frame_offset = 150;
951 chd_img = calloc(1, sizeof(*chd_img));
955 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
958 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
961 chd_img->header = chd_get_header(chd_img->chd);
963 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
964 if (chd_img->buffer == NULL)
967 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
968 chd_img->current_hunk[0] = (unsigned int)-1;
969 chd_img->current_hunk[1] = (unsigned int)-1;
971 cddaBigEndian = TRUE;
974 memset(ti, 0, sizeof(ti));
989 uint32_t meta_size = 0;
991 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
992 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
993 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
994 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
998 SysPrintf("chd: %s\n", meta);
1000 if (md.track == 1) {
1001 if (!strncmp(md.subtype, "RW", 2)) {
1002 subChanMixed = TRUE;
1003 if (!strcmp(md.subtype, "RW_RAW"))
1008 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1010 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1011 sec2msf(md.frames, ti[md.track].length);
1013 ti[md.track].start_offset = file_offset + md.pregap;
1015 // XXX: what about postgap?
1016 frame_offset += md.frames;
1017 file_offset += md.frames;
1025 if (chd_img != NULL) {
1026 free(chd_img->buffer);
1034 // this function tries to get the .sub file of the given .img
1035 static int opensubfile(const char *isoname) {
1036 char subname[MAXPATHLEN];
1038 // copy name of the iso and change extension from .img to .sub
1039 strncpy(subname, isoname, sizeof(subname));
1040 subname[MAXPATHLEN - 1] = '\0';
1041 if (strlen(subname) >= 4) {
1042 strcpy(subname + strlen(subname) - 4, ".sub");
1048 subHandle = fopen(subname, "rb");
1049 if (subHandle == NULL) {
1056 static int opensbifile(const char *isoname) {
1057 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1060 strncpy(sbiname, isoname, sizeof(sbiname));
1061 sbiname[MAXPATHLEN - 1] = '\0';
1062 if (strlen(sbiname) >= 4) {
1063 if (cdrIsoMultidiskCount > 1) {
1064 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1065 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1068 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1074 fseek(cdHandle, 0, SEEK_END);
1075 s = ftell(cdHandle) / 2352;
1077 return LoadSBI(sbiname, s);
1080 #if !USE_READ_THREAD
1081 static void readThreadStop() {}
1082 static void readThreadStart() {}
1084 static pthread_t read_thread_id;
1086 static pthread_cond_t read_thread_msg_avail;
1087 static pthread_cond_t read_thread_msg_done;
1088 static pthread_mutex_t read_thread_msg_lock;
1090 static pthread_cond_t sectorbuffer_cond;
1091 static pthread_mutex_t sectorbuffer_lock;
1093 static boolean read_thread_running = FALSE;
1094 static int read_thread_sector_start = -1;
1095 static int read_thread_sector_end = -1;
1100 unsigned char data[CD_FRAMESIZE_RAW];
1101 } SectorBufferEntry;
1103 #define SECTOR_BUFFER_SIZE 4096
1105 static SectorBufferEntry *sectorbuffer;
1106 static size_t sectorbuffer_index;
1108 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1109 unsigned char *(*sync_CDR_getBuffer)(void);
1111 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1112 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1114 static void *readThreadMain(void *param) {
1115 int max_sector = -1;
1116 int requested_sector_start = -1;
1117 int requested_sector_end = -1;
1118 int last_read_sector = -1;
1124 int speedmult_ra = 4;
1127 int how_far_ahead = 0;
1129 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1132 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1135 pthread_mutex_lock(&read_thread_msg_lock);
1137 // If we don't have readahead and we don't have a sector request, wait for one.
1138 // If we still have readahead to go, don't block, just keep going.
1139 // And if we ever have a sector request pending, acknowledge and reset it.
1142 if (read_thread_sector_start == -1 && read_thread_running) {
1143 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1147 if (read_thread_sector_start != -1) {
1148 requested_sector_start = read_thread_sector_start;
1149 requested_sector_end = read_thread_sector_end;
1150 read_thread_sector_start = -1;
1151 read_thread_sector_end = -1;
1152 pthread_cond_signal(&read_thread_msg_done);
1155 pthread_mutex_unlock(&read_thread_msg_lock);
1157 if (!read_thread_running)
1160 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1161 if (requested_sector_start != -1) {
1162 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1163 how_far_ahead = ra_sector - requested_sector_end;
1165 if(how_far_ahead <= max_ra)
1166 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1169 } else if (requested_sector_end != last_read_sector) {
1170 ra_sector = requested_sector_end;
1171 ra_count = initial_ra;
1174 last_read_sector = requested_sector_end;
1177 index = ra_sector % SECTOR_BUFFER_SIZE;
1179 // check for end of CD
1180 if (ra_count && ra_sector >= max_sector) {
1182 pthread_mutex_lock(§orbuffer_lock);
1183 sectorbuffer[index].ret = -1;
1184 sectorbuffer[index].sector = ra_sector;
1185 pthread_cond_signal(§orbuffer_cond);
1186 pthread_mutex_unlock(§orbuffer_lock);
1190 pthread_mutex_lock(§orbuffer_lock);
1191 if (sectorbuffer[index].sector != ra_sector) {
1192 pthread_mutex_unlock(§orbuffer_lock);
1194 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1196 pthread_mutex_lock(§orbuffer_lock);
1197 sectorbuffer[index].ret = ret;
1198 sectorbuffer[index].sector = ra_sector;
1199 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1201 pthread_cond_signal(§orbuffer_cond);
1202 pthread_mutex_unlock(§orbuffer_lock);
1212 static void readThreadStop() {
1213 if (read_thread_running == TRUE) {
1214 read_thread_running = FALSE;
1215 pthread_cond_signal(&read_thread_msg_avail);
1216 pthread_join(read_thread_id, NULL);
1219 pthread_cond_destroy(&read_thread_msg_done);
1220 pthread_cond_destroy(&read_thread_msg_avail);
1221 pthread_mutex_destroy(&read_thread_msg_lock);
1223 pthread_cond_destroy(§orbuffer_cond);
1224 pthread_mutex_destroy(§orbuffer_lock);
1226 CDR_getBuffer = sync_CDR_getBuffer;
1227 cdimg_read_func = sync_cdimg_read_func;
1230 sectorbuffer = NULL;
1233 static void readThreadStart() {
1234 SysPrintf("Starting async CD thread\n");
1236 if (read_thread_running == TRUE)
1239 read_thread_running = TRUE;
1240 read_thread_sector_start = -1;
1241 read_thread_sector_end = -1;
1242 sectorbuffer_index = 0;
1244 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1248 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1250 sync_CDR_getBuffer = CDR_getBuffer;
1251 CDR_getBuffer = ISOgetBuffer_async;
1252 sync_cdimg_read_func = cdimg_read_func;
1253 cdimg_read_func = cdread_async;
1255 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1256 pthread_cond_init(&read_thread_msg_done, NULL) ||
1257 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1258 pthread_cond_init(§orbuffer_cond, NULL) ||
1259 pthread_mutex_init(§orbuffer_lock, NULL) ||
1260 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1266 SysPrintf("Error starting async CD thread\n");
1267 SysPrintf("Falling back to sync\n");
1273 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1276 if (fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1278 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1284 // often happens in cdda gaps of a split cue/bin, so not logged
1285 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1289 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1293 if (fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1295 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1301 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1305 static int cdread_sub_sub_mixed(FILE *f, int sector)
1307 if (fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1309 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1312 return SUB_FRAMESIZE;
1315 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1319 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1324 if (z.zalloc == NULL) {
1325 // XXX: one-time leak here..
1331 ret = inflateInit2(&z, -15);
1334 ret = inflateReset(&z);
1339 z.avail_in = in_size;
1341 z.avail_out = *out_size;
1343 ret = inflate(&z, Z_NO_FLUSH);
1346 *out_size -= z.avail_out;
1347 return ret == 1 ? 0 : ret;
1350 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1352 unsigned long cdbuffer_size, cdbuffer_size_expect;
1359 sector += base / 2352;
1361 block = sector >> compr_img->block_shift;
1362 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1364 if (block == compr_img->current_block) {
1365 //printf("hit sect %d\n", sector);
1369 if (sector >= compr_img->index_len * 16) {
1370 SysPrintf("sector %d is past img end\n", sector);
1374 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1375 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1376 SysPrintf("seek error for block %d at %llx: ",
1377 block, (long long)start_byte);
1382 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1383 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1384 if (size > sizeof(compr_img->buff_compressed)) {
1385 SysPrintf("block %d is too large: %u\n", block, size);
1389 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1390 1, size, cdHandle) != size) {
1391 SysPrintf("read error for block %d at %x: ", block, start_byte);
1396 if (is_compressed) {
1397 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1398 cdbuffer_size = cdbuffer_size_expect;
1399 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1401 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1402 ret, block, sector);
1405 if (cdbuffer_size != cdbuffer_size_expect)
1406 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1407 cdbuffer_size_expect, sector);
1411 compr_img->current_block = block;
1414 if (dest != cdbuffer) // copy avoid HACK
1415 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1417 return CD_FRAMESIZE_RAW;
1421 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1423 return chd_img->buffer
1424 + current_buffer * chd_img->header->hunkbytes
1425 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1428 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1434 hunk = sector / chd_img->sectors_per_hunk;
1435 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1437 if (hunk == chd_img->current_hunk[0])
1438 chd_img->current_buffer = 0;
1439 else if (hunk == chd_img->current_hunk[1])
1440 chd_img->current_buffer = 1;
1443 chd_read(chd_img->chd, hunk, chd_img->buffer +
1444 chd_img->current_buffer * chd_img->header->hunkbytes);
1445 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1448 if (dest != cdbuffer) // copy avoid HACK
1449 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1451 return CD_FRAMESIZE_RAW;
1454 static int cdread_sub_chd(FILE *f, int sector)
1456 unsigned int sector_in_hunk;
1457 unsigned int buffer;
1463 hunk = sector / chd_img->sectors_per_hunk;
1464 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1466 if (hunk == chd_img->current_hunk[0])
1468 else if (hunk == chd_img->current_hunk[1])
1472 buffer = chd_img->current_buffer ^ 1;
1473 chd_read(chd_img->chd, hunk, chd_img->buffer +
1474 buffer * chd_img->header->hunkbytes);
1475 chd_img->current_hunk[buffer] = hunk;
1478 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1479 return SUB_FRAMESIZE;
1483 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1487 fseek(f, base + sector * 2048, SEEK_SET);
1488 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1490 // not really necessary, fake mode 2 header
1491 memset(cdbuffer, 0, 12 * 2);
1492 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1493 cdbuffer[12 + 3] = 1;
1500 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1501 boolean found = FALSE;
1502 int i = sector % SECTOR_BUFFER_SIZE;
1505 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1506 // Async reads are only supported for cdbuffer, so call the sync
1507 // function directly.
1508 return sync_cdimg_read_func(f, base, dest, sector);
1511 pthread_mutex_lock(&read_thread_msg_lock);
1513 // Only wait if we're not trying to read the next sector and
1514 // sector_start is set (meaning the last request hasn't been
1516 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1517 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1520 if (read_thread_sector_start == -1)
1521 read_thread_sector_start = sector;
1523 read_thread_sector_end = sector;
1524 pthread_cond_signal(&read_thread_msg_avail);
1525 pthread_mutex_unlock(&read_thread_msg_lock);
1528 pthread_mutex_lock(§orbuffer_lock);
1529 if (sectorbuffer[i].sector == sector) {
1530 sectorbuffer_index = i;
1531 ret = sectorbuffer[i].ret;
1536 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1538 pthread_mutex_unlock(§orbuffer_lock);
1546 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1547 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1551 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1552 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1557 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1558 unsigned char *buffer;
1559 pthread_mutex_lock(§orbuffer_lock);
1560 buffer = sectorbuffer[sectorbuffer_index].data;
1561 pthread_mutex_unlock(§orbuffer_lock);
1566 static unsigned char * CALLBACK ISOgetBuffer(void) {
1567 return cdbuffer + 12;
1570 static void PrintTracks(void) {
1573 for (i = 1; i <= numtracks; i++) {
1574 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1575 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1576 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1577 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1581 // This function is invoked by the front-end when opening an ISO
1582 // file for playback
1583 static long CALLBACK ISOopen(void) {
1584 boolean isMode1ISO = FALSE;
1585 char alt_bin_filename[MAXPATHLEN];
1586 const char *bin_filename;
1587 char image_str[1024];
1589 if (cdHandle != NULL) {
1590 return 0; // it's already open
1593 cdHandle = fopen(GetIsoFile(), "rb");
1594 if (cdHandle == NULL) {
1595 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1596 GetIsoFile(), strerror(errno));
1600 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1601 "Loaded CD Image: %s", GetIsoFile());
1603 cddaBigEndian = FALSE;
1604 subChanMixed = FALSE;
1607 cdrIsoMultidiskCount = 1;
1610 CDR_getBuffer = ISOgetBuffer;
1611 cdimg_read_func = cdread_normal;
1612 cdimg_read_sub_func = NULL;
1614 if (parsetoc(GetIsoFile()) == 0) {
1615 strcat(image_str, "[+toc]");
1617 else if (parseccd(GetIsoFile()) == 0) {
1618 strcat(image_str, "[+ccd]");
1620 else if (parsemds(GetIsoFile()) == 0) {
1621 strcat(image_str, "[+mds]");
1623 else if (parsecue(GetIsoFile()) == 0) {
1624 strcat(image_str, "[+cue]");
1626 if (handlepbp(GetIsoFile()) == 0) {
1627 strcat(image_str, "[+pbp]");
1628 CDR_getBuffer = ISOgetBuffer_compr;
1629 cdimg_read_func = cdread_compressed;
1631 else if (handlecbin(GetIsoFile()) == 0) {
1632 strcat(image_str, "[+cbin]");
1633 CDR_getBuffer = ISOgetBuffer_compr;
1634 cdimg_read_func = cdread_compressed;
1637 else if (handlechd(GetIsoFile()) == 0) {
1638 strcat(image_str, "[+chd]");
1639 CDR_getBuffer = ISOgetBuffer_chd;
1640 cdimg_read_func = cdread_chd;
1641 cdimg_read_sub_func = cdread_sub_chd;
1645 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1646 strcat(image_str, "[+sub]");
1648 if (opensbifile(GetIsoFile()) == 0) {
1649 strcat(image_str, "[+sbi]");
1652 fseeko(cdHandle, 0, SEEK_END);
1654 // maybe user selected metadata file instead of main .bin ..
1655 bin_filename = GetIsoFile();
1656 if (ftello(cdHandle) < 2352 * 0x10) {
1657 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1662 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1663 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1664 if (strlen(alt_bin_filename) >= 4) {
1665 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1666 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1668 tmpf = fopen(alt_bin_filename, "rb");
1674 bin_filename = alt_bin_filename;
1677 fseeko(cdHandle, 0, SEEK_END);
1681 // guess whether it is mode1/2048
1682 if (cdimg_read_func == cdread_normal && ftello(cdHandle) % 2048 == 0) {
1683 unsigned int modeTest = 0;
1684 fseek(cdHandle, 0, SEEK_SET);
1685 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1686 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1688 if (SWAP32(modeTest) != 0xffffff00) {
1689 strcat(image_str, "[2048]");
1693 fseek(cdHandle, 0, SEEK_SET);
1695 SysPrintf("%s.\n", image_str);
1699 if (subChanMixed && cdimg_read_func == cdread_normal) {
1700 cdimg_read_func = cdread_sub_mixed;
1701 cdimg_read_sub_func = cdread_sub_sub_mixed;
1703 else if (isMode1ISO) {
1704 cdimg_read_func = cdread_2048;
1705 cdimg_read_sub_func = NULL;
1708 // make sure we have another handle open for cdda
1709 if (numtracks > 1 && ti[1].handle == NULL) {
1710 ti[1].handle = fopen(bin_filename, "rb");
1713 if (Config.AsyncCD) {
1719 static long CALLBACK ISOclose(void) {
1722 if (cdHandle != NULL) {
1726 if (subHandle != NULL) {
1733 if (compr_img != NULL) {
1734 free(compr_img->index_table);
1740 if (chd_img != NULL) {
1741 chd_close(chd_img->chd);
1742 free(chd_img->buffer);
1748 for (i = 1; i <= numtracks; i++) {
1749 if (ti[i].handle != NULL) {
1750 fclose(ti[i].handle);
1751 ti[i].handle = NULL;
1758 memset(cdbuffer, 0, sizeof(cdbuffer));
1759 CDR_getBuffer = ISOgetBuffer;
1761 if (Config.AsyncCD) {
1768 static long CALLBACK ISOinit(void) {
1769 assert(cdHandle == NULL);
1770 assert(subHandle == NULL);
1772 return 0; // do nothing
1775 static long CALLBACK ISOshutdown(void) {
1780 // return Starting and Ending Track
1782 // byte 0 - start track
1783 // byte 1 - end track
1784 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1787 if (numtracks > 0) {
1788 buffer[1] = numtracks;
1797 // return Track Time
1802 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1805 unsigned char time[3];
1806 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1807 sec2msf(sect, (char *)time);
1808 buffer[2] = time[0];
1809 buffer[1] = time[1];
1810 buffer[0] = time[2];
1812 else if (numtracks > 0 && track <= numtracks) {
1813 buffer[2] = ti[track].start[0];
1814 buffer[1] = ti[track].start[1];
1815 buffer[0] = ti[track].start[2];
1826 // decode 'raw' subchannel data ripped by cdrdao
1827 static void DecodeRawSubData(void) {
1828 unsigned char subQData[12];
1831 memset(subQData, 0, sizeof(subQData));
1833 for (i = 0; i < 8 * 12; i++) {
1834 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1835 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1839 memcpy(&subbuffer[12], subQData, 12);
1843 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1845 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1846 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1849 if (cdHandle == NULL) {
1853 if (pregapOffset && sector >= pregapOffset)
1856 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1857 if (ret < 12*2 + 2048)
1864 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1865 // does NOT uses bcd format
1866 static long CALLBACK ISOplay(unsigned char *time) {
1872 static long CALLBACK ISOstop(void) {
1877 // gets subchannel data
1878 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1879 if (pregapOffset && sector >= pregapOffset) {
1881 if (sector < pregapOffset) // ?
1885 if (cdimg_read_sub_func != NULL) {
1886 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1889 else if (subHandle != NULL) {
1890 if (fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1892 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1899 if (subChanRaw) DecodeRawSubData();
1903 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1906 CDR__getStatus(stat);
1910 stat->Status |= 0x80;
1913 // BIOS - boot ID (CD type)
1914 stat->Type = ti[1].type;
1917 // relative -> absolute time
1919 sec2msf(sect, (char *)stat->Time);
1924 // read CDDA sector into buffer
1925 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1926 unsigned char msf[3] = {m, s, f};
1927 unsigned int file, track, track_start = 0;
1930 cddaCurPos = msf2sec((char *)msf);
1932 // find current track index
1933 for (track = numtracks; ; track--) {
1934 track_start = msf2sec(ti[track].start);
1935 if (track_start <= cddaCurPos)
1941 // data tracks play silent
1942 if (ti[track].type != CDDA) {
1943 memset(buffer, 0, CD_FRAMESIZE_RAW);
1949 // find the file that contains this track
1950 for (file = track; file > 1; file--)
1951 if (ti[file].handle != NULL)
1955 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1956 buffer, cddaCurPos - track_start);
1957 if (ret != CD_FRAMESIZE_RAW) {
1958 memset(buffer, 0, CD_FRAMESIZE_RAW);
1962 if (cddaBigEndian) {
1966 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1967 tmp = buffer[i * 2];
1968 buffer[i * 2] = buffer[i * 2 + 1];
1969 buffer[i * 2 + 1] = tmp;
1976 void cdrIsoInit(void) {
1978 CDR_shutdown = ISOshutdown;
1980 CDR_close = ISOclose;
1981 CDR_getTN = ISOgetTN;
1982 CDR_getTD = ISOgetTD;
1983 CDR_readTrack = ISOreadTrack;
1984 CDR_getBuffer = ISOgetBuffer;
1987 CDR_getBufferSub = ISOgetBufferSub;
1988 CDR_getStatus = ISOgetStatus;
1989 CDR_readCDDA = ISOreadCDDA;
1991 CDR_getDriveLetter = CDR__getDriveLetter;
1992 CDR_configure = CDR__configure;
1993 CDR_test = CDR__test;
1994 CDR_about = CDR__about;
1995 CDR_setfilename = CDR__setfilename;
2000 int cdrIsoActive(void) {
2001 return (cdHandle != NULL);