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 strcasecmp _stricmp
37 #include <sys/types.h>
46 // to enable the USE_READ_THREAD code, fix:
47 // - https://github.com/notaz/pcsx_rearmed/issues/257
48 // - ISOgetBufferSub to not race with async code
49 #define USE_READ_THREAD 0 //P_HAVE_PTHREAD
51 #ifdef USE_LIBRETRO_VFS
52 #include <streams/file_stream_transforms.h>
58 #define rewind(f_) rfseek(f_, 0, SEEK_SET)
61 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
63 unsigned int cdrIsoMultidiskCount;
64 unsigned int cdrIsoMultidiskSelect;
66 static FILE *cdHandle = NULL;
67 static FILE *cddaHandle = NULL;
68 static FILE *subHandle = NULL;
70 static boolean subChanMixed = FALSE;
71 static boolean subChanRaw = FALSE;
73 static boolean multifile = FALSE;
75 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
76 static unsigned char subbuffer[SUB_FRAMESIZE];
78 static boolean playing = FALSE;
79 static boolean cddaBigEndian = FALSE;
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 static unsigned int cddaCurPos;
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;
103 const chd_header* header;
104 unsigned int sectors_per_hunk;
105 unsigned int current_hunk[2];
106 unsigned int current_buffer;
107 unsigned int sector_in_hunk;
113 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
114 static int (*cdimg_read_sub_func)(FILE *f, int sector);
116 char* CALLBACK CDR__getDriveLetter(void);
117 long CALLBACK CDR__configure(void);
118 long CALLBACK CDR__test(void);
119 void CALLBACK CDR__about(void);
120 long CALLBACK CDR__setfilename(char *filename);
121 long CALLBACK CDR__getStatus(struct CdrStat *stat);
123 static void DecodeRawSubData(void);
126 enum {DATA=1, CDDA} type;
127 char start[3]; // MSF-format
128 char length[3]; // MSF-format
129 FILE *handle; // for multi-track images CDDA
130 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
133 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
135 static int numtracks = 0;
136 static struct trackinfo ti[MAXTRACKS];
138 // get a sector from a msf-array
139 static unsigned int msf2sec(char *msf) {
140 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
143 static void sec2msf(unsigned int s, char *msf) {
144 msf[0] = s / 75 / 60;
145 s = s - msf[0] * 75 * 60;
151 // divide a string of xx:yy:zz into m, s, f
152 static void tok2msf(char *time, char *msf) {
155 token = strtok(time, ":");
157 msf[0] = atoi(token);
163 token = strtok(NULL, ":");
165 msf[1] = atoi(token);
171 token = strtok(NULL, ":");
173 msf[2] = atoi(token);
180 static off_t get_size(FILE *f)
183 #if !defined(USE_LIBRETRO_VFS)
185 if (fstat(fileno(f), &st) == 0)
189 fseeko(f, 0, SEEK_END);
191 fseeko(f, old, SEEK_SET);
195 // this function tries to get the .toc file of the given .bin
196 // the necessary data is put into the ti (trackinformation)-array
197 static int parsetoc(const char *isofile) {
198 char tocname[MAXPATHLEN];
200 char linebuf[256], tmp[256], name[256];
202 char time[20], time2[20];
203 unsigned int t, sector_offs, sector_size;
204 unsigned int current_zero_gap = 0;
208 // copy name of the iso and change extension from .bin to .toc
209 strncpy(tocname, isofile, sizeof(tocname));
210 tocname[MAXPATHLEN - 1] = '\0';
211 if (strlen(tocname) >= 4) {
212 strcpy(tocname + strlen(tocname) - 4, ".toc");
218 if ((fi = fopen(tocname, "r")) == NULL) {
219 // try changing extension to .cue (to satisfy some stupid tutorials)
220 strcpy(tocname + strlen(tocname) - 4, ".cue");
221 if ((fi = fopen(tocname, "r")) == NULL) {
222 // if filename is image.toc.bin, try removing .bin (for Brasero)
223 strcpy(tocname, isofile);
225 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
226 tocname[t - 4] = '\0';
227 if ((fi = fopen(tocname, "r")) == NULL) {
235 // check if it's really a TOC named as a .cue
236 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
237 token = strtok(linebuf, " ");
238 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
243 fseek(fi, 0, SEEK_SET);
246 memset(&ti, 0, sizeof(ti));
247 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
249 sector_size = CD_FRAMESIZE_RAW;
250 sector_offs = 2 * 75;
252 // parse the .toc file
253 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
255 strncpy(tmp, linebuf, sizeof(linebuf));
256 token = strtok(tmp, " ");
258 if (token == NULL) continue;
260 if (!strcmp(token, "TRACK")) {
261 sector_offs += current_zero_gap;
262 current_zero_gap = 0;
265 token = strtok(NULL, " ");
268 if (!strncmp(token, "MODE2_RAW", 9)) {
269 ti[numtracks].type = DATA;
270 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
272 // check if this image contains mixed subchannel data
273 token = strtok(NULL, " ");
274 if (token != NULL && !strncmp(token, "RW", 2)) {
275 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
277 if (!strncmp(token, "RW_RAW", 6))
281 else if (!strncmp(token, "AUDIO", 5)) {
282 ti[numtracks].type = CDDA;
285 else if (!strcmp(token, "DATAFILE")) {
286 if (ti[numtracks].type == CDDA) {
287 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
288 ti[numtracks].start_offset = t;
289 t = t / sector_size + sector_offs;
290 sec2msf(t, (char *)&ti[numtracks].start);
291 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
294 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
295 tok2msf((char *)&time, (char *)&ti[numtracks].length);
298 else if (!strcmp(token, "FILE")) {
299 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
300 tok2msf((char *)&time, (char *)&ti[numtracks].start);
301 t += msf2sec(ti[numtracks].start) * sector_size;
302 ti[numtracks].start_offset = t;
303 t = t / sector_size + sector_offs;
304 sec2msf(t, (char *)&ti[numtracks].start);
305 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
307 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
308 // skip unneeded optional fields
309 while (token != NULL) {
310 token = strtok(NULL, " ");
311 if (strchr(token, ':') != NULL)
316 current_zero_gap = msf2sec(tmp);
319 t = ti[numtracks - 1].start_offset;
321 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
324 else if (!strcmp(token, "START")) {
325 token = strtok(NULL, " ");
326 if (token != NULL && strchr(token, ':')) {
329 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
330 t = msf2sec(ti[numtracks].start) + t;
331 sec2msf(t, (char *)&ti[numtracks].start);
341 // this function tries to get the .cue file of the given .bin
342 // the necessary data is put into the ti (trackinformation)-array
343 static int parsecue(const char *isofile) {
344 char cuename[MAXPATHLEN];
345 char filepath[MAXPATHLEN];
352 char linebuf[256], tmpb[256], dummy[256];
353 unsigned int incue_max_len;
354 unsigned int t, file_len, mode, sector_offs;
355 unsigned int sector_size = 2352;
359 // copy name of the iso and change extension from .bin to .cue
360 strncpy(cuename, isofile, sizeof(cuename));
361 cuename[MAXPATHLEN - 1] = '\0';
362 if (strlen(cuename) < 4)
364 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
365 // it's already open as cdHandle
369 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
370 // and don't try to search the additional .cue file
371 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
372 strcpy(cuename + strlen(cuename) - 4, ".cue");
374 if ((ftmp = fopen(cuename, "r")) == NULL)
379 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
380 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
382 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
383 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
384 // Don't proceed further, as this is actually a .toc file rather
388 return parsetoc(isofile);
393 // build a path for files referenced in .cue
394 strncpy(filepath, cuename, sizeof(filepath));
395 tmp = strrchr(filepath, '/');
397 tmp = strrchr(filepath, '\\');
403 filepath[sizeof(filepath) - 1] = 0;
405 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
407 memset(&ti, 0, sizeof(ti));
410 sector_offs = 2 * 75;
412 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
413 strncpy(dummy, linebuf, sizeof(linebuf));
414 token = strtok(dummy, " ");
420 if (!strcmp(token, "TRACK")) {
424 if (strstr(linebuf, "AUDIO") != NULL) {
425 ti[numtracks].type = CDDA;
428 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
429 ti[numtracks].type = DATA;
431 SysPrintf(".cue: failed to parse TRACK\n");
432 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
434 if (sector_size == 0)
437 else if (!strcmp(token, "INDEX")) {
438 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
439 SysPrintf(".cue: failed to parse INDEX\n");
440 tok2msf(time, (char *)&ti[numtracks].start);
442 t = msf2sec(ti[numtracks].start);
443 ti[numtracks].start_offset = t * sector_size;
445 sec2msf(t, ti[numtracks].start);
447 // default track length to file length
448 t = file_len - ti[numtracks].start_offset / sector_size;
449 sec2msf(t, ti[numtracks].length);
451 if (numtracks > 1 && ti[numtracks].handle == NULL) {
452 // this track uses the same file as the last,
453 // start of this track is last track's end
454 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
455 sec2msf(t, ti[numtracks - 1].length);
457 if (numtracks > 1 && pregapOffset == -1)
458 pregapOffset = ti[numtracks].start_offset / sector_size;
460 else if (!strcmp(token, "PREGAP")) {
461 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
462 tok2msf(time, dummy);
463 sector_offs += msf2sec(dummy);
465 pregapOffset = -1; // mark to fill track start_offset
467 else if (!strcmp(token, "FILE")) {
468 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
470 sscanf(linebuf, " FILE %255s", tmpb);
472 tmp = strrchr(tmpb, '\\');
474 tmp = strrchr(tmpb, '/');
479 strncpy(incue_fname, tmp, incue_max_len);
480 ti[numtracks + 1].handle = fopen(filepath, "rb");
482 // update global offset if this is not first file in this .cue
483 if (numtracks + 1 > 1) {
485 sector_offs += file_len;
489 if (ti[numtracks + 1].handle == NULL) {
490 SysPrintf(_("\ncould not open: %s\n"), filepath);
493 file_len = get_size(ti[numtracks + 1].handle) / 2352;
500 // if there are no tracks detected, then it's not a cue file
504 // the data track handle is always in cdHandle
507 cdHandle = ti[1].handle;
513 // this function tries to get the .ccd file of the given .img
514 // the necessary data is put into the ti (trackinformation)-array
515 static int parseccd(const char *isofile) {
516 char ccdname[MAXPATHLEN];
523 // copy name of the iso and change extension from .img to .ccd
524 strncpy(ccdname, isofile, sizeof(ccdname));
525 ccdname[MAXPATHLEN - 1] = '\0';
526 if (strlen(ccdname) >= 4) {
527 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
533 if ((fi = fopen(ccdname, "r")) == NULL) {
537 memset(&ti, 0, sizeof(ti));
539 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
540 if (!strncmp(linebuf, "[TRACK", 6)){
543 else if (!strncmp(linebuf, "MODE=", 5)) {
544 sscanf(linebuf, "MODE=%d", &t);
545 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
547 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
548 sscanf(linebuf, "INDEX 1=%d", &t);
549 sec2msf(t + 2 * 75, ti[numtracks].start);
550 ti[numtracks].start_offset = t * 2352;
552 // If we've already seen another track, this is its end
554 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
555 sec2msf(t, ti[numtracks - 1].length);
562 // Fill out the last track's end based on size
563 if (numtracks >= 1) {
564 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
565 sec2msf(t, ti[numtracks].length);
571 // this function tries to get the .mds file of the given .mdf
572 // the necessary data is put into the ti (trackinformation)-array
573 static int parsemds(const char *isofile) {
574 char mdsname[MAXPATHLEN];
576 unsigned int offset, extra_offset, l, i;
581 // copy name of the iso and change extension from .mdf to .mds
582 strncpy(mdsname, isofile, sizeof(mdsname));
583 mdsname[MAXPATHLEN - 1] = '\0';
584 if (strlen(mdsname) >= 4) {
585 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
591 if ((fi = fopen(mdsname, "rb")) == NULL) {
595 memset(&ti, 0, sizeof(ti));
597 // check if it's a valid mds file
598 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
601 if (i != 0x4944454D) {
602 // not an valid mds file
607 // get offset to session block
608 fseek(fi, 0x50, SEEK_SET);
609 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
611 offset = SWAP32(offset);
613 // get total number of tracks
615 fseek(fi, offset, SEEK_SET);
616 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
621 // get offset to track blocks
622 fseek(fi, 4, SEEK_CUR);
623 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
625 offset = SWAP32(offset);
629 fseek(fi, offset + 4, SEEK_SET);
630 if (fgetc(fi) < 0xA0) {
636 // check if the image contains mixed subchannel data
637 fseek(fi, offset + 1, SEEK_SET);
638 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
641 for (i = 1; i <= numtracks; i++) {
642 fseek(fi, offset, SEEK_SET);
644 // get the track type
645 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
646 fseek(fi, 8, SEEK_CUR);
648 // get the track starting point
649 ti[i].start[0] = fgetc(fi);
650 ti[i].start[1] = fgetc(fi);
651 ti[i].start[2] = fgetc(fi);
653 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
655 extra_offset = SWAP32(extra_offset);
657 // get track start offset (in .mdf)
658 fseek(fi, offset + 0x28, SEEK_SET);
659 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
662 ti[i].start_offset = l;
665 fseek(fi, extra_offset, SEEK_SET);
666 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
670 pregapOffset = msf2sec(ti[i].start);
672 // get the track length
673 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
676 sec2msf(l, ti[i].length);
684 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
690 static int handlepbp(const char *isofile) {
693 unsigned int dontcare[8];
694 unsigned int psar_offs;
707 unsigned int dontcare[6];
710 off_t psisoimg_offs, cdimg_base;
711 unsigned int t, cd_length;
712 unsigned int offsettab[8];
713 unsigned int psar_offs, index_entry_size, index_entry_offset;
714 const char *ext = NULL;
717 if (strlen(isofile) >= 4)
718 ext = isofile + strlen(isofile) - 4;
719 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
724 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
725 if (ret != sizeof(pbp_hdr)) {
726 SysPrintf("failed to read pbp\n");
730 psar_offs = SWAP32(pbp_hdr.psar_offs);
732 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
734 SysPrintf("failed to seek to %x\n", psar_offs);
738 psisoimg_offs = psar_offs;
739 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
742 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
744 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
746 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
750 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
751 SysPrintf("failed to read offsettab\n");
755 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
756 if (offsettab[i] == 0)
759 cdrIsoMultidiskCount = i;
760 if (cdrIsoMultidiskCount == 0) {
761 SysPrintf("multidisk eboot has 0 images?\n");
765 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
766 cdrIsoMultidiskSelect = 0;
768 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
770 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
772 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
776 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
781 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
782 SysPrintf("bad psar_sig: %s\n", psar_sig);
787 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
789 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
793 // first 3 entries are special
794 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
795 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
797 numtracks = btoi(toc_entry.index1[0]);
799 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
801 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
802 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
804 for (i = 1; i <= numtracks; i++) {
805 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
808 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
810 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
811 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
812 ti[i].start_offset *= 2352;
813 ti[i].start[0] = btoi(toc_entry.index1[0]);
814 ti[i].start[1] = btoi(toc_entry.index1[1]);
815 ti[i].start[2] = btoi(toc_entry.index1[2]);
818 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
819 sec2msf(t, ti[i - 1].length);
822 t = cd_length - ti[numtracks].start_offset / 2352;
823 sec2msf(t, ti[numtracks].length);
826 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
828 SysPrintf("failed to seek to ISO index\n");
832 compr_img = calloc(1, sizeof(*compr_img));
833 if (compr_img == NULL)
836 compr_img->block_shift = 4;
837 compr_img->current_block = (unsigned int)-1;
839 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
840 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
841 if (compr_img->index_table == NULL)
844 cdimg_base = psisoimg_offs + 0x100000;
845 for (i = 0; i < compr_img->index_len; i++) {
846 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
847 if (ret != sizeof(index_entry)) {
848 SysPrintf("failed to read index_entry #%d\n", i);
852 index_entry_size = SWAP32(index_entry.size);
853 index_entry_offset = SWAP32(index_entry.offset);
855 if (index_entry_size == 0)
858 compr_img->index_table[i] = cdimg_base + index_entry_offset;
860 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
865 free(compr_img->index_table);
866 compr_img->index_table = NULL;
870 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
874 if (compr_img != NULL) {
881 static int handlecbin(const char *isofile) {
885 unsigned int header_size;
886 unsigned long long total_bytes;
887 unsigned int block_size;
888 unsigned char ver; // 1
890 unsigned char rsv_06[2];
892 const char *ext = NULL;
893 unsigned int *index_table = NULL;
894 unsigned int index = 0, plain;
897 if (strlen(isofile) >= 5)
898 ext = isofile + strlen(isofile) - 5;
899 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
902 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
903 if (ret != sizeof(ciso_hdr)) {
904 SysPrintf("failed to read ciso header\n");
908 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
909 SysPrintf("bad ciso header\n");
912 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
913 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
915 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
920 compr_img = calloc(1, sizeof(*compr_img));
921 if (compr_img == NULL)
924 compr_img->block_shift = 0;
925 compr_img->current_block = (unsigned int)-1;
927 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
928 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
929 if (index_table == NULL)
932 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
933 if (ret != compr_img->index_len) {
934 SysPrintf("failed to read index table\n");
938 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
939 if (compr_img->index_table == NULL)
942 for (i = 0; i < compr_img->index_len + 1; i++) {
943 index = index_table[i];
944 plain = index & 0x80000000;
946 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
948 compr_img->index_table[i] |= OFF_T_MSB;
956 if (compr_img != NULL) {
965 static int handlechd(const char *isofile) {
966 int frame_offset = 150;
969 chd_img = calloc(1, sizeof(*chd_img));
973 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
976 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
979 chd_img->header = chd_get_header(chd_img->chd);
981 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
982 if (chd_img->buffer == NULL)
985 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
986 chd_img->current_hunk[0] = (unsigned int)-1;
987 chd_img->current_hunk[1] = (unsigned int)-1;
989 cddaBigEndian = TRUE;
992 memset(ti, 0, sizeof(ti));
1007 uint32_t meta_size = 0;
1009 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1010 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1011 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1012 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1016 SysPrintf("chd: %s\n", meta);
1018 if (md.track == 1) {
1019 if (!strncmp(md.subtype, "RW", 2)) {
1020 subChanMixed = TRUE;
1021 if (!strcmp(md.subtype, "RW_RAW"))
1026 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1028 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1029 sec2msf(md.frames, ti[md.track].length);
1031 ti[md.track].start_offset = file_offset + md.pregap;
1033 // XXX: what about postgap?
1034 frame_offset += md.frames;
1035 file_offset += md.frames;
1043 if (chd_img != NULL) {
1044 free(chd_img->buffer);
1052 // this function tries to get the .sub file of the given .img
1053 static int opensubfile(const char *isoname) {
1054 char subname[MAXPATHLEN];
1056 // copy name of the iso and change extension from .img to .sub
1057 strncpy(subname, isoname, sizeof(subname));
1058 subname[MAXPATHLEN - 1] = '\0';
1059 if (strlen(subname) >= 4) {
1060 strcpy(subname + strlen(subname) - 4, ".sub");
1066 subHandle = fopen(subname, "rb");
1067 if (subHandle == NULL) {
1074 static int opensbifile(const char *isoname) {
1075 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1078 strncpy(sbiname, isoname, sizeof(sbiname));
1079 sbiname[MAXPATHLEN - 1] = '\0';
1080 if (strlen(sbiname) >= 4) {
1081 if (cdrIsoMultidiskCount > 1) {
1082 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1083 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1086 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1092 s = msf2sec(ti[1].length);
1094 return LoadSBI(sbiname, s);
1097 #if !USE_READ_THREAD
1098 static void readThreadStop() {}
1099 static void readThreadStart() {}
1101 static pthread_t read_thread_id;
1103 static pthread_cond_t read_thread_msg_avail;
1104 static pthread_cond_t read_thread_msg_done;
1105 static pthread_mutex_t read_thread_msg_lock;
1107 static pthread_cond_t sectorbuffer_cond;
1108 static pthread_mutex_t sectorbuffer_lock;
1110 static boolean read_thread_running = FALSE;
1111 static int read_thread_sector_start = -1;
1112 static int read_thread_sector_end = -1;
1117 unsigned char data[CD_FRAMESIZE_RAW];
1118 } SectorBufferEntry;
1120 #define SECTOR_BUFFER_SIZE 4096
1122 static SectorBufferEntry *sectorbuffer;
1123 static size_t sectorbuffer_index;
1125 int (*sync_cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
1126 unsigned char *(*sync_CDR_getBuffer)(void);
1128 static unsigned char * CALLBACK ISOgetBuffer_async(void);
1129 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector);
1131 static void *readThreadMain(void *param) {
1132 int max_sector = -1;
1133 int requested_sector_start = -1;
1134 int requested_sector_end = -1;
1135 int last_read_sector = -1;
1141 int speedmult_ra = 4;
1144 int how_far_ahead = 0;
1146 unsigned char tmpdata[CD_FRAMESIZE_RAW];
1149 max_sector = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1152 pthread_mutex_lock(&read_thread_msg_lock);
1154 // If we don't have readahead and we don't have a sector request, wait for one.
1155 // If we still have readahead to go, don't block, just keep going.
1156 // And if we ever have a sector request pending, acknowledge and reset it.
1159 if (read_thread_sector_start == -1 && read_thread_running) {
1160 pthread_cond_wait(&read_thread_msg_avail, &read_thread_msg_lock);
1164 if (read_thread_sector_start != -1) {
1165 requested_sector_start = read_thread_sector_start;
1166 requested_sector_end = read_thread_sector_end;
1167 read_thread_sector_start = -1;
1168 read_thread_sector_end = -1;
1169 pthread_cond_signal(&read_thread_msg_done);
1172 pthread_mutex_unlock(&read_thread_msg_lock);
1174 if (!read_thread_running)
1177 // Readahead code, based on the implementation in mednafen psx's cdromif.cpp
1178 if (requested_sector_start != -1) {
1179 if (last_read_sector != -1 && last_read_sector == (requested_sector_start - 1)) {
1180 how_far_ahead = ra_sector - requested_sector_end;
1182 if(how_far_ahead <= max_ra)
1183 ra_count = (max_ra - how_far_ahead + 1 ? max_ra - how_far_ahead + 1 : speedmult_ra);
1186 } else if (requested_sector_end != last_read_sector) {
1187 ra_sector = requested_sector_end;
1188 ra_count = initial_ra;
1191 last_read_sector = requested_sector_end;
1194 index = ra_sector % SECTOR_BUFFER_SIZE;
1196 // check for end of CD
1197 if (ra_count && ra_sector >= max_sector) {
1199 pthread_mutex_lock(§orbuffer_lock);
1200 sectorbuffer[index].ret = -1;
1201 sectorbuffer[index].sector = ra_sector;
1202 pthread_cond_signal(§orbuffer_cond);
1203 pthread_mutex_unlock(§orbuffer_lock);
1207 pthread_mutex_lock(§orbuffer_lock);
1208 if (sectorbuffer[index].sector != ra_sector) {
1209 pthread_mutex_unlock(§orbuffer_lock);
1211 ret = sync_cdimg_read_func(cdHandle, 0, tmpdata, ra_sector);
1213 pthread_mutex_lock(§orbuffer_lock);
1214 sectorbuffer[index].ret = ret;
1215 sectorbuffer[index].sector = ra_sector;
1216 memcpy(sectorbuffer[index].data, tmpdata, CD_FRAMESIZE_RAW);
1218 pthread_cond_signal(§orbuffer_cond);
1219 pthread_mutex_unlock(§orbuffer_lock);
1229 static void readThreadStop() {
1230 if (read_thread_running == TRUE) {
1231 read_thread_running = FALSE;
1232 pthread_cond_signal(&read_thread_msg_avail);
1233 pthread_join(read_thread_id, NULL);
1236 pthread_cond_destroy(&read_thread_msg_done);
1237 pthread_cond_destroy(&read_thread_msg_avail);
1238 pthread_mutex_destroy(&read_thread_msg_lock);
1240 pthread_cond_destroy(§orbuffer_cond);
1241 pthread_mutex_destroy(§orbuffer_lock);
1243 CDR_getBuffer = sync_CDR_getBuffer;
1244 cdimg_read_func = sync_cdimg_read_func;
1247 sectorbuffer = NULL;
1250 static void readThreadStart() {
1251 SysPrintf("Starting async CD thread\n");
1253 if (read_thread_running == TRUE)
1256 read_thread_running = TRUE;
1257 read_thread_sector_start = -1;
1258 read_thread_sector_end = -1;
1259 sectorbuffer_index = 0;
1261 sectorbuffer = calloc(SECTOR_BUFFER_SIZE, sizeof(SectorBufferEntry));
1265 sectorbuffer[0].sector = -1; // Otherwise we might think we've already fetched sector 0!
1267 sync_CDR_getBuffer = CDR_getBuffer;
1268 CDR_getBuffer = ISOgetBuffer_async;
1269 sync_cdimg_read_func = cdimg_read_func;
1270 cdimg_read_func = cdread_async;
1272 if (pthread_cond_init(&read_thread_msg_avail, NULL) ||
1273 pthread_cond_init(&read_thread_msg_done, NULL) ||
1274 pthread_mutex_init(&read_thread_msg_lock, NULL) ||
1275 pthread_cond_init(§orbuffer_cond, NULL) ||
1276 pthread_mutex_init(§orbuffer_lock, NULL) ||
1277 pthread_create(&read_thread_id, NULL, readThreadMain, NULL))
1283 SysPrintf("Error starting async CD thread\n");
1284 SysPrintf("Falling back to sync\n");
1290 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1295 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1297 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1303 // often happens in cdda gaps of a split cue/bin, so not logged
1304 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1308 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1314 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1316 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1322 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1326 static int cdread_sub_sub_mixed(FILE *f, int sector)
1330 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1332 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1335 return SUB_FRAMESIZE;
1338 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1342 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1347 if (z.zalloc == NULL) {
1348 // XXX: one-time leak here..
1354 ret = inflateInit2(&z, -15);
1357 ret = inflateReset(&z);
1362 z.avail_in = in_size;
1364 z.avail_out = *out_size;
1366 ret = inflate(&z, Z_NO_FLUSH);
1369 *out_size -= z.avail_out;
1370 return ret == 1 ? 0 : ret;
1373 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1375 unsigned long cdbuffer_size, cdbuffer_size_expect;
1384 sector += base / 2352;
1386 block = sector >> compr_img->block_shift;
1387 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1389 if (block == compr_img->current_block) {
1390 //printf("hit sect %d\n", sector);
1394 if (sector >= compr_img->index_len * 16) {
1395 SysPrintf("sector %d is past img end\n", sector);
1399 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1400 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1401 SysPrintf("seek error for block %d at %llx: ",
1402 block, (long long)start_byte);
1407 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1408 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1409 if (size > sizeof(compr_img->buff_compressed)) {
1410 SysPrintf("block %d is too large: %u\n", block, size);
1414 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1415 1, size, cdHandle) != size) {
1416 SysPrintf("read error for block %d at %x: ", block, start_byte);
1421 if (is_compressed) {
1422 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1423 cdbuffer_size = cdbuffer_size_expect;
1424 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1426 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1427 ret, block, sector);
1430 if (cdbuffer_size != cdbuffer_size_expect)
1431 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1432 cdbuffer_size_expect, sector);
1436 compr_img->current_block = block;
1439 if (dest != cdbuffer) // copy avoid HACK
1440 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1442 return CD_FRAMESIZE_RAW;
1446 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1448 return chd_img->buffer
1449 + current_buffer * chd_img->header->hunkbytes
1450 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1453 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1459 hunk = sector / chd_img->sectors_per_hunk;
1460 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1462 if (hunk == chd_img->current_hunk[0])
1463 chd_img->current_buffer = 0;
1464 else if (hunk == chd_img->current_hunk[1])
1465 chd_img->current_buffer = 1;
1468 chd_read(chd_img->chd, hunk, chd_img->buffer +
1469 chd_img->current_buffer * chd_img->header->hunkbytes);
1470 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1473 if (dest != cdbuffer) // copy avoid HACK
1474 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1476 return CD_FRAMESIZE_RAW;
1479 static int cdread_sub_chd(FILE *f, int sector)
1481 unsigned int sector_in_hunk;
1482 unsigned int buffer;
1488 hunk = sector / chd_img->sectors_per_hunk;
1489 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1491 if (hunk == chd_img->current_hunk[0])
1493 else if (hunk == chd_img->current_hunk[1])
1497 buffer = chd_img->current_buffer ^ 1;
1498 chd_read(chd_img->chd, hunk, chd_img->buffer +
1499 buffer * chd_img->header->hunkbytes);
1500 chd_img->current_hunk[buffer] = hunk;
1503 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1504 return SUB_FRAMESIZE;
1508 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1514 fseeko(f, base + sector * 2048, SEEK_SET);
1515 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1517 // not really necessary, fake mode 2 header
1518 memset(cdbuffer, 0, 12 * 2);
1519 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1520 cdbuffer[12 + 3] = 1;
1527 static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1528 boolean found = FALSE;
1529 int i = sector % SECTOR_BUFFER_SIZE;
1532 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1533 // Async reads are only supported for cdbuffer, so call the sync
1534 // function directly.
1535 return sync_cdimg_read_func(f, base, dest, sector);
1538 pthread_mutex_lock(&read_thread_msg_lock);
1540 // Only wait if we're not trying to read the next sector and
1541 // sector_start is set (meaning the last request hasn't been
1543 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1544 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1547 if (read_thread_sector_start == -1)
1548 read_thread_sector_start = sector;
1550 read_thread_sector_end = sector;
1551 pthread_cond_signal(&read_thread_msg_avail);
1552 pthread_mutex_unlock(&read_thread_msg_lock);
1555 pthread_mutex_lock(§orbuffer_lock);
1556 if (sectorbuffer[i].sector == sector) {
1557 sectorbuffer_index = i;
1558 ret = sectorbuffer[i].ret;
1563 pthread_cond_wait(§orbuffer_cond, §orbuffer_lock);
1565 pthread_mutex_unlock(§orbuffer_lock);
1573 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1574 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1578 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1579 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1584 static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1585 unsigned char *buffer;
1586 pthread_mutex_lock(§orbuffer_lock);
1587 buffer = sectorbuffer[sectorbuffer_index].data;
1588 pthread_mutex_unlock(§orbuffer_lock);
1593 static unsigned char * CALLBACK ISOgetBuffer(void) {
1594 return cdbuffer + 12;
1597 static void PrintTracks(void) {
1600 for (i = 1; i <= numtracks; i++) {
1601 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1602 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1603 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1604 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1608 // This function is invoked by the front-end when opening an ISO
1609 // file for playback
1610 static long CALLBACK ISOopen(void) {
1611 boolean isMode1ISO = FALSE;
1612 char alt_bin_filename[MAXPATHLEN];
1613 const char *bin_filename;
1614 char image_str[1024];
1617 if (cdHandle || chd_img) {
1618 return 0; // it's already open
1621 cdHandle = fopen(GetIsoFile(), "rb");
1622 if (cdHandle == NULL) {
1623 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1624 GetIsoFile(), strerror(errno));
1627 size_main = get_size(cdHandle);
1629 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1630 "Loaded CD Image: %s", GetIsoFile());
1632 cddaBigEndian = FALSE;
1633 subChanMixed = FALSE;
1636 cdrIsoMultidiskCount = 1;
1639 CDR_getBuffer = ISOgetBuffer;
1640 cdimg_read_func = cdread_normal;
1641 cdimg_read_sub_func = NULL;
1643 if (parsetoc(GetIsoFile()) == 0) {
1644 strcat(image_str, "[+toc]");
1646 else if (parseccd(GetIsoFile()) == 0) {
1647 strcat(image_str, "[+ccd]");
1649 else if (parsemds(GetIsoFile()) == 0) {
1650 strcat(image_str, "[+mds]");
1652 else if (parsecue(GetIsoFile()) == 0) {
1653 strcat(image_str, "[+cue]");
1655 if (handlepbp(GetIsoFile()) == 0) {
1656 strcat(image_str, "[+pbp]");
1657 CDR_getBuffer = ISOgetBuffer_compr;
1658 cdimg_read_func = cdread_compressed;
1660 else if (handlecbin(GetIsoFile()) == 0) {
1661 strcat(image_str, "[+cbin]");
1662 CDR_getBuffer = ISOgetBuffer_compr;
1663 cdimg_read_func = cdread_compressed;
1666 else if (handlechd(GetIsoFile()) == 0) {
1667 strcat(image_str, "[+chd]");
1668 CDR_getBuffer = ISOgetBuffer_chd;
1669 cdimg_read_func = cdread_chd;
1670 cdimg_read_sub_func = cdread_sub_chd;
1676 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1677 strcat(image_str, "[+sub]");
1679 if (opensbifile(GetIsoFile()) == 0) {
1680 strcat(image_str, "[+sbi]");
1683 // maybe user selected metadata file instead of main .bin ..
1684 bin_filename = GetIsoFile();
1685 if (cdHandle && size_main < 2352 * 0x10) {
1686 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1691 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1692 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1693 if (strlen(alt_bin_filename) >= 4) {
1694 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1695 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1697 tmpf = fopen(alt_bin_filename, "rb");
1703 bin_filename = alt_bin_filename;
1706 size_main = get_size(cdHandle);
1710 // guess whether it is mode1/2048
1711 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1712 unsigned int modeTest = 0;
1713 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1714 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1716 if (SWAP32(modeTest) != 0xffffff00) {
1717 strcat(image_str, "[2048]");
1722 SysPrintf("%s.\n", image_str);
1726 if (subChanMixed && cdimg_read_func == cdread_normal) {
1727 cdimg_read_func = cdread_sub_mixed;
1728 cdimg_read_sub_func = cdread_sub_sub_mixed;
1730 else if (isMode1ISO) {
1731 cdimg_read_func = cdread_2048;
1732 cdimg_read_sub_func = NULL;
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 boolean CALLBACK ISOreadTrack(unsigned char *time) {
1868 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1871 if (!cdHandle && !chd_img)
1874 if (pregapOffset && sector >= pregapOffset)
1877 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1878 if (ret < 12*2 + 2048)
1885 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1886 // does NOT uses bcd format
1887 static long CALLBACK ISOplay(unsigned char *time) {
1893 static long CALLBACK ISOstop(void) {
1898 // gets subchannel data
1899 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1900 if (pregapOffset && sector >= pregapOffset) {
1902 if (sector < pregapOffset) // ?
1906 if (cdimg_read_sub_func != NULL) {
1907 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1910 else if (subHandle != NULL) {
1911 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1913 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1920 if (subChanRaw) DecodeRawSubData();
1924 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1927 CDR__getStatus(stat);
1931 stat->Status |= 0x80;
1934 // BIOS - boot ID (CD type)
1935 stat->Type = ti[1].type;
1938 // relative -> absolute time
1940 sec2msf(sect, (char *)stat->Time);
1945 // read CDDA sector into buffer
1946 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1947 unsigned char msf[3] = {m, s, f};
1948 unsigned int track, track_start = 0;
1949 FILE *handle = cdHandle;
1952 cddaCurPos = msf2sec((char *)msf);
1954 // find current track index
1955 for (track = numtracks; ; track--) {
1956 track_start = msf2sec(ti[track].start);
1957 if (track_start <= cddaCurPos)
1963 // data tracks play silent
1964 if (ti[track].type != CDDA) {
1965 memset(buffer, 0, CD_FRAMESIZE_RAW);
1970 // find the file that contains this track
1972 for (file = track; file > 1; file--) {
1973 if (ti[file].handle != NULL) {
1974 handle = ti[file].handle;
1980 memset(buffer, 0, CD_FRAMESIZE_RAW);
1984 ret = cdimg_read_func(handle, ti[track].start_offset,
1985 buffer, cddaCurPos - track_start);
1986 if (ret != CD_FRAMESIZE_RAW) {
1987 memset(buffer, 0, CD_FRAMESIZE_RAW);
1991 if (cddaBigEndian) {
1995 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1996 tmp = buffer[i * 2];
1997 buffer[i * 2] = buffer[i * 2 + 1];
1998 buffer[i * 2 + 1] = tmp;
2005 void cdrIsoInit(void) {
2007 CDR_shutdown = ISOshutdown;
2009 CDR_close = ISOclose;
2010 CDR_getTN = ISOgetTN;
2011 CDR_getTD = ISOgetTD;
2012 CDR_readTrack = ISOreadTrack;
2013 CDR_getBuffer = ISOgetBuffer;
2016 CDR_getBufferSub = ISOgetBufferSub;
2017 CDR_getStatus = ISOgetStatus;
2018 CDR_readCDDA = ISOreadCDDA;
2020 CDR_getDriveLetter = CDR__getDriveLetter;
2021 CDR_configure = CDR__configure;
2022 CDR_test = CDR__test;
2023 CDR_about = CDR__about;
2024 CDR_setfilename = CDR__setfilename;
2029 int cdrIsoActive(void) {
2030 return (cdHandle || chd_img);