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"
29 #define strcasecmp _stricmp
31 #include <sys/types.h>
43 #include "libchdr/chd.h"
46 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
48 unsigned int cdrIsoMultidiskCount;
49 unsigned int cdrIsoMultidiskSelect;
51 static FILE *cdHandle = NULL;
52 static FILE *cddaHandle = NULL;
53 static FILE *subHandle = NULL;
55 static boolean subChanMixed = FALSE;
56 static boolean subChanRaw = FALSE;
58 static boolean multifile = FALSE;
60 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
61 static unsigned char subbuffer[SUB_FRAMESIZE];
63 static boolean cddaBigEndian = FALSE;
64 /* Frame offset into CD image where pregap data would be found if it was there.
65 * If a game seeks there we must *not* return subchannel data since it's
66 * not in the CD image, so that cdrom code can fake subchannel data instead.
67 * XXX: there could be multiple pregaps but PSX dumps only have one? */
68 static unsigned int pregapOffset;
70 // compressed image stuff
72 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
73 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
75 unsigned int index_len;
76 unsigned int block_shift;
77 unsigned int current_block;
78 unsigned int sector_in_blk;
83 unsigned char *buffer;
85 const chd_header* header;
86 unsigned int sectors_per_hunk;
87 unsigned int current_hunk[2];
88 unsigned int current_buffer;
89 unsigned int sector_in_hunk;
95 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
96 static int (*cdimg_read_sub_func)(FILE *f, int sector);
98 char* CALLBACK CDR__getDriveLetter(void);
99 long CALLBACK CDR__configure(void);
100 long CALLBACK CDR__test(void);
101 void CALLBACK CDR__about(void);
102 long CALLBACK CDR__setfilename(char *filename);
103 long CALLBACK CDR__prefetch(u8 m, u8 s, u8 f);
105 static void DecodeRawSubData(void);
108 enum {DATA=1, CDDA} type;
109 char start[3]; // MSF-format
110 char length[3]; // MSF-format
111 FILE *handle; // for multi-track images CDDA
112 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
115 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
117 static int numtracks = 0;
118 static struct trackinfo ti[MAXTRACKS];
120 // get a sector from a msf-array
121 static unsigned int msf2sec(char *msf) {
122 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
125 static void sec2msf(unsigned int s, char *msf) {
126 msf[0] = s / 75 / 60;
127 s = s - msf[0] * 75 * 60;
133 // divide a string of xx:yy:zz into m, s, f
134 static void tok2msf(char *time, char *msf) {
137 token = strtok(time, ":");
139 msf[0] = atoi(token);
145 token = strtok(NULL, ":");
147 msf[1] = atoi(token);
153 token = strtok(NULL, ":");
155 msf[2] = atoi(token);
162 static off_t get_size(FILE *f)
165 #if !defined(USE_LIBRETRO_VFS)
167 if (fstat(fileno(f), &st) == 0)
171 fseeko(f, 0, SEEK_END);
173 fseeko(f, old, SEEK_SET);
177 // this function tries to get the .toc file of the given .bin
178 // the necessary data is put into the ti (trackinformation)-array
179 static int parsetoc(const char *isofile) {
180 char tocname[MAXPATHLEN];
182 char linebuf[256], tmp[256], name[256];
184 char time[20], time2[20];
185 unsigned int t, sector_offs, sector_size;
186 unsigned int current_zero_gap = 0;
190 // copy name of the iso and change extension from .bin to .toc
191 strncpy(tocname, isofile, sizeof(tocname));
192 tocname[MAXPATHLEN - 1] = '\0';
193 if (strlen(tocname) >= 4) {
194 strcpy(tocname + strlen(tocname) - 4, ".toc");
200 if ((fi = fopen(tocname, "r")) == NULL) {
201 // try changing extension to .cue (to satisfy some stupid tutorials)
202 strcpy(tocname + strlen(tocname) - 4, ".cue");
203 if ((fi = fopen(tocname, "r")) == NULL) {
204 // if filename is image.toc.bin, try removing .bin (for Brasero)
205 strcpy(tocname, isofile);
207 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
208 tocname[t - 4] = '\0';
209 if ((fi = fopen(tocname, "r")) == NULL) {
217 // check if it's really a TOC named as a .cue
218 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
219 token = strtok(linebuf, " ");
220 if (token && strncmp(token, "CD", 2) != 0) {
221 // && strcmp(token, "CATALOG") != 0) - valid for a real .cue
226 fseek(fi, 0, SEEK_SET);
229 memset(&ti, 0, sizeof(ti));
230 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
232 sector_size = CD_FRAMESIZE_RAW;
233 sector_offs = 2 * 75;
235 // parse the .toc file
236 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
238 strncpy(tmp, linebuf, sizeof(linebuf));
239 token = strtok(tmp, " ");
241 if (token == NULL) continue;
243 if (!strcmp(token, "TRACK")) {
244 sector_offs += current_zero_gap;
245 current_zero_gap = 0;
248 token = strtok(NULL, " ");
251 if (!strncmp(token, "MODE2_RAW", 9)) {
252 ti[numtracks].type = DATA;
253 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
255 // check if this image contains mixed subchannel data
256 token = strtok(NULL, " ");
257 if (token != NULL && !strncmp(token, "RW", 2)) {
258 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
260 if (!strncmp(token, "RW_RAW", 6))
264 else if (!strncmp(token, "AUDIO", 5)) {
265 ti[numtracks].type = CDDA;
268 else if (!strcmp(token, "DATAFILE")) {
269 if (ti[numtracks].type == CDDA) {
270 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
271 ti[numtracks].start_offset = t;
272 t = t / sector_size + sector_offs;
273 sec2msf(t, (char *)&ti[numtracks].start);
274 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
277 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
278 tok2msf((char *)&time, (char *)&ti[numtracks].length);
281 else if (!strcmp(token, "FILE")) {
282 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
283 tok2msf((char *)&time, (char *)&ti[numtracks].start);
284 t += msf2sec(ti[numtracks].start) * sector_size;
285 ti[numtracks].start_offset = t;
286 t = t / sector_size + sector_offs;
287 sec2msf(t, (char *)&ti[numtracks].start);
288 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
290 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
291 // skip unneeded optional fields
292 while (token != NULL) {
293 token = strtok(NULL, " ");
294 if (strchr(token, ':') != NULL)
299 current_zero_gap = msf2sec(tmp);
302 t = ti[numtracks - 1].start_offset;
304 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
307 else if (!strcmp(token, "START")) {
308 token = strtok(NULL, " ");
309 if (token != NULL && strchr(token, ':')) {
312 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
313 t = msf2sec(ti[numtracks].start) + t;
314 sec2msf(t, (char *)&ti[numtracks].start);
324 // this function tries to get the .cue file of the given .bin
325 // the necessary data is put into the ti (trackinformation)-array
326 static int parsecue(const char *isofile) {
327 char cuename[MAXPATHLEN];
328 char filepath[MAXPATHLEN];
335 char linebuf[256], tmpb[256], dummy[256];
336 unsigned int incue_max_len;
337 unsigned int t, file_len, mode, sector_offs;
338 unsigned int sector_size = 2352;
342 // copy name of the iso and change extension from .bin to .cue
343 strncpy(cuename, isofile, sizeof(cuename));
344 cuename[MAXPATHLEN - 1] = '\0';
345 if (strlen(cuename) < 4)
347 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
348 // it's already open as cdHandle
352 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
353 // and don't try to search the additional .cue file
354 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
355 strcpy(cuename + strlen(cuename) - 4, ".cue");
357 if ((ftmp = fopen(cuename, "r")) == NULL)
362 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
363 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
365 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
366 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
367 // Don't proceed further, as this is actually a .toc file rather
371 return parsetoc(isofile);
376 // build a path for files referenced in .cue
377 strncpy(filepath, cuename, sizeof(filepath));
378 tmp = strrchr(filepath, '/');
380 tmp = strrchr(filepath, '\\');
386 filepath[sizeof(filepath) - 1] = 0;
388 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
390 memset(&ti, 0, sizeof(ti));
393 sector_offs = 2 * 75;
395 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
396 strncpy(dummy, linebuf, sizeof(linebuf));
397 token = strtok(dummy, " ");
403 if (!strcmp(token, "TRACK")) {
407 if (strstr(linebuf, "AUDIO") != NULL) {
408 ti[numtracks].type = CDDA;
411 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
412 ti[numtracks].type = DATA;
414 SysPrintf(".cue: failed to parse TRACK\n");
415 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
417 if (sector_size == 0)
420 else if (!strcmp(token, "INDEX")) {
421 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
422 SysPrintf(".cue: failed to parse INDEX\n");
423 tok2msf(time, (char *)&ti[numtracks].start);
425 t = msf2sec(ti[numtracks].start);
426 ti[numtracks].start_offset = t * sector_size;
428 sec2msf(t, ti[numtracks].start);
430 // default track length to file length
431 t = file_len - ti[numtracks].start_offset / sector_size;
432 sec2msf(t, ti[numtracks].length);
434 if (numtracks > 1 && ti[numtracks].handle == NULL) {
435 // this track uses the same file as the last,
436 // start of this track is last track's end
437 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
438 sec2msf(t, ti[numtracks - 1].length);
440 if (numtracks > 1 && pregapOffset == -1)
441 pregapOffset = ti[numtracks].start_offset / sector_size;
443 else if (!strcmp(token, "PREGAP")) {
444 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
445 tok2msf(time, dummy);
446 sector_offs += msf2sec(dummy);
448 pregapOffset = -1; // mark to fill track start_offset
450 else if (!strcmp(token, "FILE")) {
451 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
453 sscanf(linebuf, " FILE %255s", tmpb);
456 ti[numtracks + 1].handle = fopen(tmpb, "rb");
457 if (ti[numtracks + 1].handle == NULL) {
459 tmp = strrchr(tmpb, '\\');
461 tmp = strrchr(tmpb, '/');
466 strncpy(incue_fname, tmp, incue_max_len);
467 ti[numtracks + 1].handle = fopen(filepath, "rb");
470 // update global offset if this is not first file in this .cue
471 if (numtracks + 1 > 1) {
473 sector_offs += file_len;
477 if (ti[numtracks + 1].handle == NULL) {
478 SysPrintf(_("\ncould not open: %s\n"), filepath);
481 file_len = get_size(ti[numtracks + 1].handle) / 2352;
488 // if there are no tracks detected, then it's not a cue file
492 // the data track handle is always in cdHandle
495 cdHandle = ti[1].handle;
501 // this function tries to get the .ccd file of the given .img
502 // the necessary data is put into the ti (trackinformation)-array
503 static int parseccd(const char *isofile) {
504 char ccdname[MAXPATHLEN];
511 // copy name of the iso and change extension from .img to .ccd
512 strncpy(ccdname, isofile, sizeof(ccdname));
513 ccdname[MAXPATHLEN - 1] = '\0';
514 if (strlen(ccdname) >= 4) {
515 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
521 if ((fi = fopen(ccdname, "r")) == NULL) {
525 memset(&ti, 0, sizeof(ti));
527 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
528 if (!strncmp(linebuf, "[TRACK", 6)){
531 else if (!strncmp(linebuf, "MODE=", 5)) {
532 sscanf(linebuf, "MODE=%d", &t);
533 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
535 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
536 sscanf(linebuf, "INDEX 1=%d", &t);
537 sec2msf(t + 2 * 75, ti[numtracks].start);
538 ti[numtracks].start_offset = t * 2352;
540 // If we've already seen another track, this is its end
542 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
543 sec2msf(t, ti[numtracks - 1].length);
550 // Fill out the last track's end based on size
551 if (numtracks >= 1) {
552 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
553 sec2msf(t, ti[numtracks].length);
559 // this function tries to get the .mds file of the given .mdf
560 // the necessary data is put into the ti (trackinformation)-array
561 static int parsemds(const char *isofile) {
562 char mdsname[MAXPATHLEN];
564 unsigned int offset, extra_offset, l, i;
569 // copy name of the iso and change extension from .mdf to .mds
570 strncpy(mdsname, isofile, sizeof(mdsname));
571 mdsname[MAXPATHLEN - 1] = '\0';
572 if (strlen(mdsname) >= 4) {
573 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
579 if ((fi = fopen(mdsname, "rb")) == NULL) {
583 memset(&ti, 0, sizeof(ti));
585 // check if it's a valid mds file
586 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
589 if (i != 0x4944454D) {
590 // not an valid mds file
595 // get offset to session block
596 fseek(fi, 0x50, SEEK_SET);
597 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
599 offset = SWAP32(offset);
601 // get total number of tracks
603 fseek(fi, offset, SEEK_SET);
604 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
609 // get offset to track blocks
610 fseek(fi, 4, SEEK_CUR);
611 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
613 offset = SWAP32(offset);
617 fseek(fi, offset + 4, SEEK_SET);
618 if (fgetc(fi) < 0xA0) {
624 // check if the image contains mixed subchannel data
625 fseek(fi, offset + 1, SEEK_SET);
626 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
629 for (i = 1; i <= numtracks; i++) {
630 fseek(fi, offset, SEEK_SET);
632 // get the track type
633 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
634 fseek(fi, 8, SEEK_CUR);
636 // get the track starting point
637 ti[i].start[0] = fgetc(fi);
638 ti[i].start[1] = fgetc(fi);
639 ti[i].start[2] = fgetc(fi);
641 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
643 extra_offset = SWAP32(extra_offset);
645 // get track start offset (in .mdf)
646 fseek(fi, offset + 0x28, SEEK_SET);
647 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
650 ti[i].start_offset = l;
653 fseek(fi, extra_offset, SEEK_SET);
654 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
658 pregapOffset = msf2sec(ti[i].start);
660 // get the track length
661 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
664 sec2msf(l, ti[i].length);
672 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
678 static int handlepbp(const char *isofile) {
681 unsigned int dontcare[8];
682 unsigned int psar_offs;
695 unsigned int dontcare[6];
698 off_t psisoimg_offs, cdimg_base;
699 unsigned int t, cd_length;
700 unsigned int offsettab[8];
701 unsigned int psar_offs, index_entry_size, index_entry_offset;
702 const char *ext = NULL;
705 if (strlen(isofile) >= 4)
706 ext = isofile + strlen(isofile) - 4;
707 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
712 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
713 if (ret != sizeof(pbp_hdr)) {
714 SysPrintf("failed to read pbp\n");
718 psar_offs = SWAP32(pbp_hdr.psar_offs);
720 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
722 SysPrintf("failed to seek to %x\n", psar_offs);
726 psisoimg_offs = psar_offs;
727 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
730 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
732 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
734 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
738 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
739 SysPrintf("failed to read offsettab\n");
743 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
744 if (offsettab[i] == 0)
747 cdrIsoMultidiskCount = i;
748 if (cdrIsoMultidiskCount == 0) {
749 SysPrintf("multidisk eboot has 0 images?\n");
753 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
754 cdrIsoMultidiskSelect = 0;
756 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
758 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
760 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
764 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
769 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
770 SysPrintf("bad psar_sig: %s\n", psar_sig);
775 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
777 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
781 // first 3 entries are special
782 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
783 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
785 numtracks = btoi(toc_entry.index1[0]);
787 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
789 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
790 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
792 for (i = 1; i <= numtracks; i++) {
793 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
796 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
798 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
799 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
800 ti[i].start_offset *= 2352;
801 ti[i].start[0] = btoi(toc_entry.index1[0]);
802 ti[i].start[1] = btoi(toc_entry.index1[1]);
803 ti[i].start[2] = btoi(toc_entry.index1[2]);
806 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
807 sec2msf(t, ti[i - 1].length);
810 t = cd_length - ti[numtracks].start_offset / 2352;
811 sec2msf(t, ti[numtracks].length);
814 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
816 SysPrintf("failed to seek to ISO index\n");
820 compr_img = calloc(1, sizeof(*compr_img));
821 if (compr_img == NULL)
824 compr_img->block_shift = 4;
825 compr_img->current_block = (unsigned int)-1;
827 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
828 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
829 if (compr_img->index_table == NULL)
832 cdimg_base = psisoimg_offs + 0x100000;
833 for (i = 0; i < compr_img->index_len; i++) {
834 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
835 if (ret != sizeof(index_entry)) {
836 SysPrintf("failed to read index_entry #%d\n", i);
840 index_entry_size = SWAP32(index_entry.size);
841 index_entry_offset = SWAP32(index_entry.offset);
843 if (index_entry_size == 0)
846 compr_img->index_table[i] = cdimg_base + index_entry_offset;
848 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
853 free(compr_img->index_table);
854 compr_img->index_table = NULL;
858 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
862 if (compr_img != NULL) {
869 static int handlecbin(const char *isofile) {
873 unsigned int header_size;
874 unsigned long long total_bytes;
875 unsigned int block_size;
876 unsigned char ver; // 1
878 unsigned char rsv_06[2];
880 const char *ext = NULL;
881 unsigned int *index_table = NULL;
882 unsigned int index = 0, plain;
885 if (strlen(isofile) >= 5)
886 ext = isofile + strlen(isofile) - 5;
887 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
890 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
891 if (ret != sizeof(ciso_hdr)) {
892 SysPrintf("failed to read ciso header\n");
896 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
897 SysPrintf("bad ciso header\n");
900 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
901 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
903 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
908 compr_img = calloc(1, sizeof(*compr_img));
909 if (compr_img == NULL)
912 compr_img->block_shift = 0;
913 compr_img->current_block = (unsigned int)-1;
915 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
916 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
917 if (index_table == NULL)
920 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
921 if (ret != compr_img->index_len) {
922 SysPrintf("failed to read index table\n");
926 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
927 if (compr_img->index_table == NULL)
930 for (i = 0; i < compr_img->index_len + 1; i++) {
931 index = index_table[i];
932 plain = index & 0x80000000;
934 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
936 compr_img->index_table[i] |= OFF_T_MSB;
944 if (compr_img != NULL) {
953 static int handlechd(const char *isofile) {
954 int frame_offset = 150;
957 chd_img = calloc(1, sizeof(*chd_img));
961 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
964 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
967 chd_img->header = chd_get_header(chd_img->chd);
969 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
970 if (chd_img->buffer == NULL)
973 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
974 chd_img->current_hunk[0] = (unsigned int)-1;
975 chd_img->current_hunk[1] = (unsigned int)-1;
977 cddaBigEndian = TRUE;
980 memset(ti, 0, sizeof(ti));
995 uint32_t meta_size = 0;
997 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
998 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
999 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1000 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1004 SysPrintf("chd: %s\n", meta);
1006 if (md.track == 1) {
1007 if (!strncmp(md.subtype, "RW", 2)) {
1008 subChanMixed = TRUE;
1009 if (!strcmp(md.subtype, "RW_RAW"))
1014 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1016 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1017 sec2msf(md.frames, ti[md.track].length);
1019 ti[md.track].start_offset = file_offset + md.pregap;
1021 // XXX: what about postgap?
1022 frame_offset += md.frames;
1023 file_offset += md.frames;
1031 if (chd_img != NULL) {
1032 free(chd_img->buffer);
1040 // this function tries to get the .sub file of the given .img
1041 static int opensubfile(const char *isoname) {
1042 char subname[MAXPATHLEN];
1044 // copy name of the iso and change extension from .img to .sub
1045 strncpy(subname, isoname, sizeof(subname));
1046 subname[MAXPATHLEN - 1] = '\0';
1047 if (strlen(subname) >= 4) {
1048 strcpy(subname + strlen(subname) - 4, ".sub");
1054 subHandle = fopen(subname, "rb");
1055 if (subHandle == NULL) {
1062 static int opensbifile(const char *isoname) {
1063 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1066 strncpy(sbiname, isoname, sizeof(sbiname));
1067 sbiname[MAXPATHLEN - 1] = '\0';
1068 if (strlen(sbiname) >= 4) {
1069 if (cdrIsoMultidiskCount > 1) {
1070 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1071 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1074 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1080 s = msf2sec(ti[1].length);
1082 return LoadSBI(sbiname, s);
1085 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1090 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1092 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1098 // often happens in cdda gaps of a split cue/bin, so not logged
1099 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1103 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1109 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1111 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1117 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1121 static int cdread_sub_sub_mixed(FILE *f, int sector)
1125 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1127 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1130 return SUB_FRAMESIZE;
1133 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1137 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1142 if (z.zalloc == NULL) {
1143 // XXX: one-time leak here..
1149 ret = inflateInit2(&z, -15);
1152 ret = inflateReset(&z);
1157 z.avail_in = in_size;
1159 z.avail_out = *out_size;
1161 ret = inflate(&z, Z_NO_FLUSH);
1164 *out_size -= z.avail_out;
1165 return ret == 1 ? 0 : ret;
1168 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1170 unsigned long cdbuffer_size, cdbuffer_size_expect;
1179 sector += base / 2352;
1181 block = sector >> compr_img->block_shift;
1182 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1184 if (block == compr_img->current_block) {
1185 //printf("hit sect %d\n", sector);
1189 if (sector >= compr_img->index_len * 16) {
1190 SysPrintf("sector %d is past img end\n", sector);
1194 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1195 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1196 SysPrintf("seek error for block %d at %llx: ",
1197 block, (long long)start_byte);
1202 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1203 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1204 if (size > sizeof(compr_img->buff_compressed)) {
1205 SysPrintf("block %d is too large: %u\n", block, size);
1209 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1210 1, size, cdHandle) != size) {
1211 SysPrintf("read error for block %d at %x: ", block, start_byte);
1216 if (is_compressed) {
1217 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1218 cdbuffer_size = cdbuffer_size_expect;
1219 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1221 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1222 ret, block, sector);
1225 if (cdbuffer_size != cdbuffer_size_expect)
1226 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1227 cdbuffer_size_expect, sector);
1231 compr_img->current_block = block;
1234 if (dest != cdbuffer) // copy avoid HACK
1235 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1237 return CD_FRAMESIZE_RAW;
1241 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1243 return chd_img->buffer
1244 + current_buffer * chd_img->header->hunkbytes
1245 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1248 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1254 hunk = sector / chd_img->sectors_per_hunk;
1255 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1257 if (hunk == chd_img->current_hunk[0])
1258 chd_img->current_buffer = 0;
1259 else if (hunk == chd_img->current_hunk[1])
1260 chd_img->current_buffer = 1;
1263 chd_read(chd_img->chd, hunk, chd_img->buffer +
1264 chd_img->current_buffer * chd_img->header->hunkbytes);
1265 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1268 if (dest != cdbuffer) // copy avoid HACK
1269 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1271 return CD_FRAMESIZE_RAW;
1274 static int cdread_sub_chd(FILE *f, int sector)
1276 unsigned int sector_in_hunk;
1277 unsigned int buffer;
1283 hunk = sector / chd_img->sectors_per_hunk;
1284 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1286 if (hunk == chd_img->current_hunk[0])
1288 else if (hunk == chd_img->current_hunk[1])
1292 buffer = chd_img->current_buffer ^ 1;
1293 chd_read(chd_img->chd, hunk, chd_img->buffer +
1294 buffer * chd_img->header->hunkbytes);
1295 chd_img->current_hunk[buffer] = hunk;
1298 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1299 return SUB_FRAMESIZE;
1303 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1309 fseeko(f, base + sector * 2048, SEEK_SET);
1310 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1312 // not really necessary, fake mode 2 header
1313 memset(cdbuffer, 0, 12 * 2);
1314 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1315 cdbuffer[12 + 3] = 1;
1320 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1321 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1325 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1326 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1330 unsigned char * CALLBACK ISOgetBuffer(void) {
1331 return cdbuffer + 12;
1334 static void PrintTracks(void) {
1337 for (i = 1; i <= numtracks; i++) {
1338 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1339 i, (ti[i].type == DATA ? "DATA" :
1340 (ti[i].type == CDDA ? "AUDIO" : "UNKNOWN")),
1341 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1342 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1346 // This function is invoked by the front-end when opening an ISO
1347 // file for playback
1348 static long CALLBACK ISOopen(void) {
1349 boolean isMode1ISO = FALSE;
1350 char alt_bin_filename[MAXPATHLEN];
1351 const char *bin_filename;
1352 char image_str[1024];
1355 if (cdHandle || chd_img) {
1356 return 0; // it's already open
1359 cdHandle = fopen(GetIsoFile(), "rb");
1360 if (cdHandle == NULL) {
1361 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1362 GetIsoFile(), strerror(errno));
1365 size_main = get_size(cdHandle);
1367 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1368 "Loaded CD Image: %s", GetIsoFile());
1370 cddaBigEndian = FALSE;
1371 subChanMixed = FALSE;
1374 cdrIsoMultidiskCount = 1;
1377 CDR_getBuffer = ISOgetBuffer;
1378 cdimg_read_func = cdread_normal;
1379 cdimg_read_sub_func = NULL;
1381 if (parsetoc(GetIsoFile()) == 0) {
1382 strcat(image_str, "[+toc]");
1384 else if (parseccd(GetIsoFile()) == 0) {
1385 strcat(image_str, "[+ccd]");
1387 else if (parsemds(GetIsoFile()) == 0) {
1388 strcat(image_str, "[+mds]");
1390 else if (parsecue(GetIsoFile()) == 0) {
1391 strcat(image_str, "[+cue]");
1393 if (handlepbp(GetIsoFile()) == 0) {
1394 strcat(image_str, "[+pbp]");
1395 CDR_getBuffer = ISOgetBuffer_compr;
1396 cdimg_read_func = cdread_compressed;
1398 else if (handlecbin(GetIsoFile()) == 0) {
1399 strcat(image_str, "[+cbin]");
1400 CDR_getBuffer = ISOgetBuffer_compr;
1401 cdimg_read_func = cdread_compressed;
1404 else if (handlechd(GetIsoFile()) == 0) {
1405 strcat(image_str, "[+chd]");
1406 CDR_getBuffer = ISOgetBuffer_chd;
1407 cdimg_read_func = cdread_chd;
1408 cdimg_read_sub_func = cdread_sub_chd;
1414 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1415 strcat(image_str, "[+sub]");
1417 if (opensbifile(GetIsoFile()) == 0) {
1418 strcat(image_str, "[+sbi]");
1421 // maybe user selected metadata file instead of main .bin ..
1422 bin_filename = GetIsoFile();
1423 if (cdHandle && size_main < 2352 * 0x10) {
1424 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1429 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1430 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1431 if (strlen(alt_bin_filename) >= 4) {
1432 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1433 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1435 tmpf = fopen(alt_bin_filename, "rb");
1441 bin_filename = alt_bin_filename;
1444 size_main = get_size(cdHandle);
1448 // guess whether it is mode1/2048
1449 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1450 unsigned int modeTest = 0;
1451 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1452 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1454 if (SWAP32(modeTest) != 0xffffff00) {
1455 strcat(image_str, "[2048]");
1460 SysPrintf("%s.\n", image_str);
1464 if (subChanMixed && cdimg_read_func == cdread_normal) {
1465 cdimg_read_func = cdread_sub_mixed;
1466 cdimg_read_sub_func = cdread_sub_sub_mixed;
1468 else if (isMode1ISO) {
1469 cdimg_read_func = cdread_2048;
1470 cdimg_read_sub_func = NULL;
1476 static long CALLBACK ISOclose(void) {
1479 if (cdHandle != NULL) {
1483 if (subHandle != NULL) {
1489 if (compr_img != NULL) {
1490 free(compr_img->index_table);
1496 if (chd_img != NULL) {
1497 chd_close(chd_img->chd);
1498 free(chd_img->buffer);
1504 for (i = 1; i <= numtracks; i++) {
1505 if (ti[i].handle != NULL) {
1506 fclose(ti[i].handle);
1507 ti[i].handle = NULL;
1514 memset(cdbuffer, 0, sizeof(cdbuffer));
1515 CDR_getBuffer = ISOgetBuffer;
1520 static long CALLBACK ISOinit(void) {
1521 assert(cdHandle == NULL);
1522 assert(subHandle == NULL);
1524 return 0; // do nothing
1527 static long CALLBACK ISOshutdown(void) {
1532 // return Starting and Ending Track
1534 // byte 0 - start track
1535 // byte 1 - end track
1536 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1539 if (numtracks > 0) {
1540 buffer[1] = numtracks;
1549 // return Track Time
1554 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1557 unsigned char time[3];
1558 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1559 sec2msf(sect, (char *)time);
1560 buffer[2] = time[0];
1561 buffer[1] = time[1];
1562 buffer[0] = time[2];
1564 else if (numtracks > 0 && track <= numtracks) {
1565 buffer[2] = ti[track].start[0];
1566 buffer[1] = ti[track].start[1];
1567 buffer[0] = ti[track].start[2];
1578 // decode 'raw' subchannel data ripped by cdrdao
1579 static void DecodeRawSubData(void) {
1580 unsigned char subQData[12];
1583 memset(subQData, 0, sizeof(subQData));
1585 for (i = 0; i < 8 * 12; i++) {
1586 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1587 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1591 memcpy(&subbuffer[12], subQData, 12);
1595 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1597 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1598 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1601 if (!cdHandle && !chd_img)
1604 if (pregapOffset && sector >= pregapOffset)
1607 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1608 if (ret < 12*2 + 2048)
1615 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1616 // does NOT uses bcd format
1617 static long CALLBACK ISOplay(unsigned char *time) {
1622 static long CALLBACK ISOstop(void) {
1626 // gets subchannel data
1627 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1628 if (pregapOffset && sector >= pregapOffset) {
1630 if (sector < pregapOffset) // ?
1634 if (cdimg_read_sub_func != NULL) {
1635 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1638 else if (subHandle != NULL) {
1639 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1641 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1648 if (subChanRaw) DecodeRawSubData();
1652 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1653 CDR__getStatus(stat);
1655 // BIOS - boot ID (CD type)
1656 stat->Type = ti[1].type;
1661 // read CDDA sector into buffer
1662 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1663 unsigned char msf[3] = {m, s, f};
1664 unsigned int track, track_start = 0;
1665 FILE *handle = cdHandle;
1666 unsigned int cddaCurPos;
1669 cddaCurPos = msf2sec((char *)msf);
1671 // find current track index
1672 for (track = numtracks; ; track--) {
1673 track_start = msf2sec(ti[track].start);
1674 if (track_start <= cddaCurPos)
1680 // data tracks play silent
1681 if (ti[track].type != CDDA) {
1682 memset(buffer, 0, CD_FRAMESIZE_RAW);
1687 // find the file that contains this track
1689 for (file = track; file > 1; file--) {
1690 if (ti[file].handle != NULL) {
1691 handle = ti[file].handle;
1696 if (!handle && !chd_img) {
1697 memset(buffer, 0, CD_FRAMESIZE_RAW);
1701 ret = cdimg_read_func(handle, ti[track].start_offset,
1702 buffer, cddaCurPos - track_start);
1703 if (ret != CD_FRAMESIZE_RAW) {
1704 memset(buffer, 0, CD_FRAMESIZE_RAW);
1708 if (cddaBigEndian) {
1712 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1713 tmp = buffer[i * 2];
1714 buffer[i * 2] = buffer[i * 2 + 1];
1715 buffer[i * 2 + 1] = tmp;
1722 void cdrIsoInit(void) {
1724 CDR_shutdown = ISOshutdown;
1726 CDR_close = ISOclose;
1727 CDR_getTN = ISOgetTN;
1728 CDR_getTD = ISOgetTD;
1729 CDR_readTrack = ISOreadTrack;
1730 CDR_getBuffer = ISOgetBuffer;
1733 CDR_getBufferSub = ISOgetBufferSub;
1734 CDR_getStatus = ISOgetStatus;
1735 CDR_readCDDA = ISOreadCDDA;
1737 CDR_getDriveLetter = CDR__getDriveLetter;
1738 CDR_configure = CDR__configure;
1739 CDR_test = CDR__test;
1740 CDR_about = CDR__about;
1741 CDR_setfilename = CDR__setfilename;
1742 CDR_prefetch = CDR__prefetch;
1747 int cdrIsoActive(void) {
1748 return (cdHandle || chd_img);