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"
31 #include <libchdr/chd.h>
35 #define strcasecmp _stricmp
37 #include <sys/types.h>
42 #ifdef USE_LIBRETRO_VFS
43 #include <streams/file_stream_transforms.h>
49 #define rewind(f_) rfseek(f_, 0, SEEK_SET)
52 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
54 unsigned int cdrIsoMultidiskCount;
55 unsigned int cdrIsoMultidiskSelect;
57 static FILE *cdHandle = NULL;
58 static FILE *subHandle = NULL;
60 static boolean subChanMixed = FALSE;
61 static boolean subChanRaw = FALSE;
63 static boolean multifile = FALSE;
65 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
67 static boolean cddaBigEndian = FALSE;
69 // compressed image stuff
71 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
72 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
74 unsigned int index_len;
75 unsigned int block_shift;
76 unsigned int current_block;
77 unsigned int sector_in_blk;
82 unsigned char *buffer;
84 const chd_header* header;
85 unsigned int sectors_per_hunk;
86 unsigned int current_hunk[2];
87 unsigned int current_buffer;
88 unsigned int sector_in_hunk;
94 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
95 static int (*cdimg_read_sub_func)(FILE *f, int sector, void *dest);
97 static void DecodeRawSubData(unsigned char *subbuffer);
101 unsigned int start; // sector index in toc
102 unsigned int length; // readable sectors, excludes gaps
103 unsigned int start_offset; // byte offset from start of file (chd: sector offset)
104 FILE *handle; // for multi-track images
107 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
109 // 1-based array (indexed [1..numtracks])
110 static int numtracks = 0;
111 static struct trackinfo ti[MAXTRACKS];
113 // get a sector from a msf-array
114 static unsigned int msf2sec(const void *msf_) {
115 const unsigned char *msf = msf_;
116 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
119 static void sec2msf(unsigned int s, void *msf_) {
120 unsigned char *msf = msf_;
121 msf[0] = s / 75 / 60;
122 s = s - msf[0] * 75 * 60;
128 // divide a string of xx:yy:zz into m, s, f
129 static void tok2msf(char *time, char *msf) {
132 token = strtok(time, ":");
134 msf[0] = atoi(token);
140 token = strtok(NULL, ":");
142 msf[1] = atoi(token);
148 token = strtok(NULL, ":");
150 msf[2] = atoi(token);
157 static off_t get_size(FILE *f)
161 #if !defined(USE_LIBRETRO_VFS)
163 if (fstat(fileno(f), &st) == 0)
167 fseeko(f, 0, SEEK_END);
169 fseeko(f, old, SEEK_SET);
173 // Some c libs like newlib default buffering to just 1k which is less than
174 // cd sector size which is bad for performance.
175 // Note that NULL setvbuf() is implemented differently by different libs
176 // (newlib mallocs a buffer of given size and glibc ignores size and uses it's own).
177 static void set_static_stdio_buffer(FILE *f)
179 #if !defined(fopen) // no stdio redirect
180 static char buf[16 * 1024];
184 r = setvbuf(f, buf, _IOFBF, sizeof(buf));
186 SysPrintf("cdriso: setvbuf %d %d\n", r, errno);
191 // this function tries to get the .toc file of the given .bin
192 // the necessary data is put into the ti (trackinformation)-array
193 static int parsetoc(const char *isofile) {
194 char tocname[MAXPATHLEN];
196 char linebuf[256], tmp[256], name[256];
198 char time[20], time2[20];
199 unsigned int t, sector_offs, sector_size;
200 unsigned int current_zero_gap = 0;
204 // copy name of the iso and change extension from .bin to .toc
205 strncpy(tocname, isofile, sizeof(tocname));
206 tocname[MAXPATHLEN - 1] = '\0';
207 if (strlen(tocname) >= 4) {
208 strcpy(tocname + strlen(tocname) - 4, ".toc");
214 if ((fi = fopen(tocname, "r")) == NULL) {
215 // try changing extension to .cue (to satisfy some stupid tutorials)
216 strcpy(tocname + strlen(tocname) - 4, ".cue");
217 if ((fi = fopen(tocname, "r")) == NULL) {
218 // if filename is image.toc.bin, try removing .bin (for Brasero)
219 strcpy(tocname, isofile);
221 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
222 tocname[t - 4] = '\0';
223 if ((fi = fopen(tocname, "r")) == NULL) {
231 // check if it's really a TOC named as a .cue
232 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
233 token = strtok(linebuf, " ");
234 if (token && strncmp(token, "CD", 2) != 0) {
235 // && strcmp(token, "CATALOG") != 0) - valid for a real .cue
240 fseek(fi, 0, SEEK_SET);
243 memset(&ti, 0, sizeof(ti));
244 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
246 sector_size = CD_FRAMESIZE_RAW;
247 sector_offs = 2 * 75;
249 // parse the .toc file
250 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
252 strncpy(tmp, linebuf, sizeof(linebuf));
253 token = strtok(tmp, " ");
255 if (token == NULL) continue;
257 if (!strcmp(token, "TRACK")) {
258 sector_offs += current_zero_gap;
259 current_zero_gap = 0;
262 token = strtok(NULL, " ");
265 if (!strncmp(token, "MODE2_RAW", 9)) {
266 ti[numtracks].type = CDRT_DATA;
267 ti[numtracks].start = 2 * 75; // assume data track on 0:2:0
269 // check if this image contains mixed subchannel data
270 token = strtok(NULL, " ");
271 if (token != NULL && !strncmp(token, "RW", 2)) {
272 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
274 if (!strncmp(token, "RW_RAW", 6))
278 else if (!strncmp(token, "AUDIO", 5)) {
279 ti[numtracks].type = CDRT_CDDA;
282 else if (!strcmp(token, "DATAFILE")) {
284 if (ti[numtracks].type == CDRT_CDDA) {
285 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
286 ti[numtracks].start_offset = t;
287 ti[numtracks].start = t / sector_size + sector_offs;
290 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time2);
293 ti[numtracks].length = msf2sec(msf);
295 else if (!strcmp(token, "FILE")) {
297 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
299 t += msf2sec(msf) * sector_size;
300 ti[numtracks].start_offset = t;
301 ti[numtracks].start = t / sector_size + sector_offs;
303 ti[numtracks].length = msf2sec(msf);
305 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
306 // skip unneeded optional fields
307 while (token != NULL) {
308 token = strtok(NULL, " ");
309 if (strchr(token, ':') != NULL)
314 current_zero_gap = msf2sec(tmp);
317 t = ti[numtracks - 1].start_offset;
321 else if (!strcmp(token, "START")) {
322 token = strtok(NULL, " ");
323 if (token != NULL && strchr(token, ':')) {
326 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
327 ti[numtracks].start += t;
337 // this function tries to get the .cue file of the given .bin
338 // the necessary data is put into the ti (trackinformation)-array
339 static int parsecue(const char *isofile) {
340 char cuename[MAXPATHLEN];
341 char filepath[MAXPATHLEN];
348 char linebuf[256], tmpb[256], dummy[256];
349 unsigned int incue_max_len;
350 unsigned int t, mode, toc_sector;
352 int index[2], pregap, postgap, sector_size;
353 } tmpinfo[MAXTRACKS];
358 // copy name of the iso and change extension from .bin to .cue
359 strncpy(cuename, isofile, sizeof(cuename));
360 cuename[MAXPATHLEN - 1] = '\0';
361 if (strlen(cuename) < 4)
363 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
364 // it's already open as cdHandle
368 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
369 // and don't try to search the additional .cue file
370 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
371 strcpy(cuename + strlen(cuename) - 4, ".cue");
373 if ((ftmp = fopen(cuename, "r")) == NULL)
378 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
379 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
381 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
382 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
383 // Don't proceed further, as this is actually a .toc file rather
387 return parsetoc(isofile);
392 // build a path for files referenced in .cue
393 strncpy(filepath, cuename, sizeof(filepath));
394 tmp = strrchr(filepath, '/');
396 tmp = strrchr(filepath, '\\');
402 filepath[sizeof(filepath) - 1] = 0;
404 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
406 memset(&ti, 0, sizeof(ti));
408 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
409 strncpy(dummy, linebuf, sizeof(linebuf));
410 token = strtok(dummy, " ");
416 if (!strcmp(token, "TRACK")) {
417 if (numtracks >= MAXTRACKS - 1) {
418 SysPrintf(".cue: too many tracks?\n");
422 memset(&tmpinfo[numtracks], -1, sizeof(tmpinfo[numtracks]));
424 if (sscanf(linebuf, " TRACK %02d", &t) == 1 && t != numtracks)
425 SysPrintf(".cue: expected track %d, got %d?\n",
428 if (strstr(linebuf, "AUDIO") != NULL) {
429 ti[numtracks].type = CDRT_CDDA;
430 tmpinfo[numtracks].sector_size = 2352;
432 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode,
433 &tmpinfo[numtracks].sector_size) == 3)
434 ti[numtracks].type = CDRT_DATA;
436 SysPrintf(".cue: failed to parse TRACK\n");
437 ti[numtracks].type = numtracks == 1 ? CDRT_DATA : CDRT_CDDA;
439 if (tmpinfo[numtracks].sector_size <= 0)
440 tmpinfo[numtracks].sector_size = 2352;
442 else if (!strcmp(token, "INDEX")) {
445 if (sscanf(linebuf, " INDEX %02d %8s", &index, time) != 2) {
446 SysPrintf(".cue: failed to parse INDEX\n");
452 tmpinfo[numtracks].index[index] = msf2sec(msf);
454 else if (!strcmp(token, "PREGAP")) {
455 if (sscanf(linebuf, " PREGAP %8s", time) != 1) {
456 SysPrintf(".cue: failed to parse PREGAP\n");
459 tok2msf(time, dummy);
460 tmpinfo[numtracks].pregap = msf2sec(dummy);
462 else if (!strcmp(token, "POSTGAP")) {
463 if (sscanf(linebuf, " POSTGAP %8s", time) != 1) {
464 SysPrintf(".cue: failed to parse POSTGAP\n");
467 tok2msf(time, dummy);
468 tmpinfo[numtracks].postgap = msf2sec(dummy);
470 else if (!strcmp(token, "FILE")) {
471 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
473 sscanf(linebuf, " FILE %255s", tmpb);
476 ti[numtracks + 1].handle = fopen(tmpb, "rb");
477 if (ti[numtracks + 1].handle == NULL) {
479 tmp = strrchr(tmpb, '\\');
481 tmp = strrchr(tmpb, '/');
486 strncpy(incue_fname, tmp, incue_max_len);
487 ti[numtracks + 1].handle = fopen(filepath, "rb");
489 if (ti[numtracks + 1].handle == NULL) {
490 SysPrintf(_("\ncould not open: %s\n"), filepath);
494 if (numtracks + 1 > 1)
502 // if there are no tracks detected, then it's not a cue file
506 for (i = 1; i <= numtracks; i++) {
507 if (tmpinfo[i].index[1] == -1) {
508 SysPrintf(".cue: no INDEX 01 for track %d?\n", i);
509 tmpinfo[i].index[1] = 0;
510 if (tmpinfo[i].index[0] != -1)
511 tmpinfo[i].index[1] = tmpinfo[i].index[0] + 2 * 75;
515 // complete the actual toc
516 tmpinfo[0].postgap = -1;
519 for (i = 1; i <= numtracks; i++)
521 unsigned int pregap = 0, sector_size = tmpinfo[i].sector_size;
522 // various ways to specify pregap in a .cue
523 if (tmpinfo[i].pregap != -1)
524 pregap += tmpinfo[i].pregap;
525 if (tmpinfo[i-1].postgap != -1)
526 pregap += tmpinfo[i-1].postgap;
527 if (ti[i].handle && tmpinfo[i].index[0] != -1)
528 pregap += tmpinfo[i].index[1] - tmpinfo[i].index[0];
530 toc_sector += pregap;
531 ti[i].start = toc_sector;
532 ti[i].start_offset = tmpinfo[i].index[1] * sector_size;
536 if (i+1 <= numtracks && ti[i+1].handle == NULL) {
537 // this track and the next one share the backing file
538 ti[i].length = tmpinfo[i+1].index[1] - tmpinfo[i].index[1];
541 size_t file_size = get_size(ftmp);
542 long left = file_size - ti[i].start_offset;
544 ti[i].length = left / sector_size;
548 toc_sector += ti[i].length;
551 // the data track handle is always in cdHandle
554 cdHandle = ti[1].handle;
556 set_static_stdio_buffer(cdHandle);
561 // this function tries to get the .ccd file of the given .img
562 // the necessary data is put into the ti (trackinformation)-array
563 static int parseccd(const char *isofile) {
564 char ccdname[MAXPATHLEN];
571 // copy name of the iso and change extension from .img to .ccd
572 strncpy(ccdname, isofile, sizeof(ccdname));
573 ccdname[MAXPATHLEN - 1] = '\0';
574 if (strlen(ccdname) >= 4) {
575 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
581 if ((fi = fopen(ccdname, "r")) == NULL) {
585 memset(&ti, 0, sizeof(ti));
587 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
588 if (!strncmp(linebuf, "[TRACK", 6)){
591 else if (!strncmp(linebuf, "MODE=", 5)) {
592 sscanf(linebuf, "MODE=%d", &t);
593 ti[numtracks].type = (t == 0) ? CDRT_CDDA : CDRT_DATA;
595 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
596 sscanf(linebuf, "INDEX 1=%d", &t);
597 ti[numtracks].start = 2 * 75 + t;
598 ti[numtracks].start_offset = t * 2352;
600 // If we've already seen another track, this is its end
602 t = ti[numtracks].start - ti[numtracks - 1].start;
603 ti[numtracks - 1].length = t;
610 // Fill out the last track's end based on size
611 if (numtracks >= 1) {
612 t = get_size(cdHandle) / 2352 - ti[numtracks].start + 2 * 75;
613 ti[numtracks].length = t;
619 // this function tries to get the .mds file of the given .mdf
620 // the necessary data is put into the ti (trackinformation)-array
621 static int parsemds(const char *isofile) {
622 char mdsname[MAXPATHLEN];
624 unsigned int offset, extra_offset, l, i;
629 // copy name of the iso and change extension from .mdf to .mds
630 strncpy(mdsname, isofile, sizeof(mdsname));
631 mdsname[MAXPATHLEN - 1] = '\0';
632 if (strlen(mdsname) >= 4) {
633 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
639 if ((fi = fopen(mdsname, "rb")) == NULL) {
643 memset(&ti, 0, sizeof(ti));
645 // check if it's a valid mds file
646 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
649 if (i != 0x4944454D) {
650 // not an valid mds file
655 // get offset to session block
656 fseek(fi, 0x50, SEEK_SET);
657 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
659 offset = SWAP32(offset);
661 // get total number of tracks
663 fseek(fi, offset, SEEK_SET);
664 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
669 // get offset to track blocks
670 fseek(fi, 4, SEEK_CUR);
671 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
673 offset = SWAP32(offset);
677 fseek(fi, offset + 4, SEEK_SET);
678 if (fgetc(fi) < 0xA0) {
684 // check if the image contains mixed subchannel data
685 fseek(fi, offset + 1, SEEK_SET);
686 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
689 for (i = 1; i <= numtracks; i++) {
691 fseek(fi, offset, SEEK_SET);
693 // get the track type
694 ti[i].type = (fgetc(fi) == 0xA9) ? CDRT_CDDA : CDRT_DATA;
695 fseek(fi, 8, SEEK_CUR);
697 // get the track starting point
701 ti[i].start = msf2sec(msf);
703 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
705 extra_offset = SWAP32(extra_offset);
707 // get track start offset (in .mdf)
708 fseek(fi, offset + 0x28, SEEK_SET);
709 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
712 ti[i].start_offset = l;
715 fseek(fi, extra_offset, SEEK_SET);
716 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
720 // get the track length
721 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
723 ti[i].length = SWAP32(l);
731 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
737 static int handlepbp(const char *isofile) {
740 unsigned int dontcare[8];
741 unsigned int psar_offs;
754 unsigned int dontcare[6];
757 off_t psisoimg_offs, cdimg_base;
758 unsigned int cd_length;
759 unsigned int offsettab[8];
760 unsigned int psar_offs, index_entry_size, index_entry_offset;
761 const char *ext = NULL;
764 if (strlen(isofile) >= 4)
765 ext = isofile + strlen(isofile) - 4;
766 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
771 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
772 if (ret != sizeof(pbp_hdr)) {
773 SysPrintf("failed to read pbp\n");
777 psar_offs = SWAP32(pbp_hdr.psar_offs);
779 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
781 SysPrintf("failed to seek to %x\n", psar_offs);
785 psisoimg_offs = psar_offs;
786 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
789 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
791 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
793 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
797 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
798 SysPrintf("failed to read offsettab\n");
802 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
803 if (offsettab[i] == 0)
806 cdrIsoMultidiskCount = i;
807 if (cdrIsoMultidiskCount == 0) {
808 SysPrintf("multidisk eboot has 0 images?\n");
812 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
813 cdrIsoMultidiskSelect = 0;
815 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
817 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
819 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
823 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
828 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
829 SysPrintf("bad psar_sig: %s\n", psar_sig);
834 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
836 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
840 // first 3 entries are special
841 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
842 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
844 numtracks = btoi(toc_entry.index1[0]);
846 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
848 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
849 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
851 for (i = 1; i <= numtracks; i++) {
853 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
856 ti[i].type = (toc_entry.type == 1) ? CDRT_CDDA : CDRT_DATA;
858 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
859 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
860 ti[i].start_offset *= 2352;
861 msf[0] = btoi(toc_entry.index1[0]);
862 msf[1] = btoi(toc_entry.index1[1]);
863 msf[2] = btoi(toc_entry.index1[2]);
864 ti[i].start = msf2sec(msf);
867 ti[i - 1].length = ti[i].start - ti[i - 1].start;
869 ti[numtracks].length = cd_length - ti[numtracks].start_offset / 2352;
872 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
874 SysPrintf("failed to seek to ISO index\n");
878 compr_img = calloc(1, sizeof(*compr_img));
879 if (compr_img == NULL)
882 compr_img->block_shift = 4;
883 compr_img->current_block = (unsigned int)-1;
885 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
886 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
887 if (compr_img->index_table == NULL)
890 cdimg_base = psisoimg_offs + 0x100000;
891 for (i = 0; i < compr_img->index_len; i++) {
892 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
893 if (ret != sizeof(index_entry)) {
894 SysPrintf("failed to read index_entry #%d\n", i);
898 index_entry_size = SWAP32(index_entry.size);
899 index_entry_offset = SWAP32(index_entry.offset);
901 if (index_entry_size == 0)
904 compr_img->index_table[i] = cdimg_base + index_entry_offset;
906 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
911 free(compr_img->index_table);
912 compr_img->index_table = NULL;
916 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
920 if (compr_img != NULL) {
927 static int handlecbin(const char *isofile) {
931 unsigned int header_size;
932 unsigned long long total_bytes;
933 unsigned int block_size;
934 unsigned char ver; // 1
936 unsigned char rsv_06[2];
938 const char *ext = NULL;
939 unsigned int *index_table = NULL;
940 unsigned int index = 0, plain;
943 if (strlen(isofile) >= 5)
944 ext = isofile + strlen(isofile) - 5;
945 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
948 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
949 if (ret != sizeof(ciso_hdr)) {
950 SysPrintf("failed to read ciso header\n");
954 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
955 SysPrintf("bad ciso header\n");
958 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
959 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
961 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
966 compr_img = calloc(1, sizeof(*compr_img));
967 if (compr_img == NULL)
970 compr_img->block_shift = 0;
971 compr_img->current_block = (unsigned int)-1;
973 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
974 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
975 if (index_table == NULL)
978 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
979 if (ret != compr_img->index_len) {
980 SysPrintf("failed to read index table\n");
984 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
985 if (compr_img->index_table == NULL)
988 for (i = 0; i < compr_img->index_len + 1; i++) {
989 index = index_table[i];
990 plain = index & 0x80000000;
992 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
994 compr_img->index_table[i] |= OFF_T_MSB;
997 // fixup the toc and the last track length
998 if (numtracks == 0) {
1000 ti[1].type = CDRT_DATA;
1001 ti[1].start_offset = 0;
1002 ti[1].start = 2 * 75;
1004 ti[numtracks].length = (ciso_hdr.total_bytes - ti[numtracks].start_offset) / 2352;
1011 if (compr_img != NULL) {
1020 static int handlechd(const char *isofile) {
1021 int frame_offset = 150;
1022 int file_offset = 0;
1026 if (strlen(isofile) >= 3) {
1027 const char *ext = isofile + strlen(isofile) - 3;
1028 is_chd_ext = !strcasecmp(ext, "chd");
1030 chd_img = calloc(1, sizeof(*chd_img));
1031 if (chd_img == NULL)
1034 err = chd_open_file(cdHandle, CHD_OPEN_READ, NULL, &chd_img->chd);
1035 if (err != CHDERR_NONE) {
1037 SysPrintf("chd_open: %d\n", err);
1041 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
1044 chd_img->header = chd_get_header(chd_img->chd);
1046 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
1047 if (chd_img->buffer == NULL)
1050 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1051 chd_img->current_hunk[0] = (unsigned int)-1;
1052 chd_img->current_hunk[1] = (unsigned int)-1;
1054 cddaBigEndian = TRUE;
1057 memset(ti, 0, sizeof(ti));
1072 uint32_t meta_size = 0;
1074 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1075 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1076 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1077 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1081 SysPrintf("chd: %s\n", meta);
1083 if (md.track == 1) {
1084 if (!strncmp(md.subtype, "RW", 2)) {
1085 subChanMixed = TRUE;
1086 if (!strcmp(md.subtype, "RW_RAW"))
1091 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDRT_CDDA : CDRT_DATA;
1093 ti[md.track].start = frame_offset + md.pregap;
1094 ti[md.track].length = md.frames;
1096 ti[md.track].start_offset = file_offset + md.pregap;
1098 // XXX: what about postgap?
1099 frame_offset += md.frames;
1100 file_offset += md.frames;
1108 if (chd_img != NULL) {
1109 free(chd_img->buffer);
1117 // this function tries to get the .sub file of the given .img
1118 static int opensubfile(const char *isoname) {
1119 char subname[MAXPATHLEN];
1121 // copy name of the iso and change extension from .img to .sub
1122 strncpy(subname, isoname, sizeof(subname));
1123 subname[MAXPATHLEN - 1] = '\0';
1124 if (strlen(subname) >= 4) {
1125 strcpy(subname + strlen(subname) - 4, ".sub");
1131 subHandle = fopen(subname, "rb");
1132 if (subHandle == NULL)
1138 static int opensbifile(const char *isoname) {
1139 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1141 strncpy(sbiname, isoname, sizeof(sbiname));
1142 sbiname[MAXPATHLEN - 1] = '\0';
1143 if (strlen(sbiname) >= 4) {
1144 if (cdrIsoMultidiskCount > 1) {
1145 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1146 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1149 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1155 return LoadSBI(sbiname, ti[1].length);
1158 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1165 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1167 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1173 // often happens in cdda gaps of a split cue/bin, so not logged
1174 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1178 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1186 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1188 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1194 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1198 static int cdread_sub_sub_mixed(FILE *f, int sector, void *buffer)
1202 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1204 if (fread(buffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1210 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1214 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1219 if (z.zalloc == NULL) {
1220 // XXX: one-time leak here..
1226 ret = inflateInit2(&z, -15);
1229 ret = inflateReset(&z);
1234 z.avail_in = in_size;
1236 z.avail_out = *out_size;
1238 ret = inflate(&z, Z_NO_FLUSH);
1241 *out_size -= z.avail_out;
1242 return ret == 1 ? 0 : ret;
1245 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1247 unsigned long cdbuffer_size, cdbuffer_size_expect;
1256 sector += base / 2352;
1258 block = sector >> compr_img->block_shift;
1259 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1261 if (block == compr_img->current_block) {
1262 //printf("hit sect %d\n", sector);
1266 if (sector >= compr_img->index_len * 16) {
1267 SysPrintf("sector %d is past img end\n", sector);
1271 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1272 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1273 SysPrintf("seek error for block %d at %llx: ",
1274 block, (long long)start_byte);
1279 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1280 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1281 if (size > sizeof(compr_img->buff_compressed)) {
1282 SysPrintf("block %d is too large: %u\n", block, size);
1286 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1287 1, size, cdHandle) != size) {
1288 SysPrintf("read error for block %d at %lx: ", block, (long)start_byte);
1293 if (is_compressed) {
1294 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1295 cdbuffer_size = cdbuffer_size_expect;
1296 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1298 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1299 ret, block, sector);
1302 if (cdbuffer_size != cdbuffer_size_expect)
1303 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1304 cdbuffer_size_expect, sector);
1308 compr_img->current_block = block;
1312 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1314 return CD_FRAMESIZE_RAW;
1318 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1320 return chd_img->buffer
1321 + current_buffer * chd_img->header->hunkbytes
1322 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1325 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1331 hunk = sector / chd_img->sectors_per_hunk;
1332 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1334 if (hunk == chd_img->current_hunk[0])
1335 chd_img->current_buffer = 0;
1336 else if (hunk == chd_img->current_hunk[1])
1337 chd_img->current_buffer = 1;
1340 chd_read(chd_img->chd, hunk, chd_img->buffer +
1341 chd_img->current_buffer * chd_img->header->hunkbytes);
1342 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1346 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1348 return CD_FRAMESIZE_RAW;
1351 static int cdread_sub_chd(FILE *f, int sector, void *buffer_ptr)
1353 unsigned int sector_in_hunk;
1354 unsigned int buffer;
1360 hunk = sector / chd_img->sectors_per_hunk;
1361 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1363 if (hunk == chd_img->current_hunk[0])
1365 else if (hunk == chd_img->current_hunk[1])
1369 buffer = chd_img->current_buffer ^ 1;
1370 chd_read(chd_img->chd, hunk, chd_img->buffer +
1371 buffer * chd_img->header->hunkbytes);
1372 chd_img->current_hunk[buffer] = hunk;
1375 memcpy(buffer_ptr, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1380 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1382 unsigned char *dst = dest ? dest : cdbuffer;
1388 fseeko(f, base + sector * 2048, SEEK_SET);
1389 ret = fread(dst + 12 * 2, 1, 2048, f);
1391 // not really necessary, fake mode 2 header
1392 memset(dst, 0, 12 * 2);
1393 sec2msf(sector + 2 * 75, dst + 12);
1394 dst[12 + 0] = itob(dst[12 + 0]);
1395 dst[12 + 1] = itob(dst[12 + 1]);
1396 dst[12 + 2] = itob(dst[12 + 2]);
1402 static void * ISOgetBuffer_normal(void) {
1403 return cdbuffer + 12;
1406 static void * ISOgetBuffer_compr(void) {
1407 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1411 static void * ISOgetBuffer_chd(void) {
1412 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1416 void * (*ISOgetBuffer)(void) = ISOgetBuffer_normal;
1418 static void PrintTracks(void) {
1419 unsigned char msfe[3];
1422 for (i = 1; i <= numtracks; i++) {
1423 unsigned char start[3], length[3];
1424 sec2msf(ti[i].start, start);
1425 sec2msf(ti[i].length, length);
1426 SysPrintf(_("Track %.2d %s - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1427 i, (ti[i].type == CDRT_DATA ? "DATA " :
1428 (ti[i].type == CDRT_CDDA ? "AUDIO" : "UNKNOWN")),
1429 start[0], start[1], start[2], length[0], length[1], length[2]);
1431 i = ti[numtracks].start + ti[numtracks].length;
1433 SysPrintf("End %.2d:%.2d:%.2d (sector %d)\n", msfe[0], msfe[1], msfe[2], i);
1436 // This function is invoked by the front-end when opening an ISO
1437 // file for playback
1438 int ISOopen(const char *fname)
1440 boolean isMode1ISO = FALSE;
1441 char alt_bin_filename[MAXPATHLEN];
1442 const char *bin_filename;
1443 char image_str[1024];
1446 if (cdHandle || chd_img) {
1447 return 0; // it's already open
1450 cdHandle = fopen(fname, "rb");
1451 if (cdHandle == NULL) {
1452 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1453 fname, strerror(errno));
1456 set_static_stdio_buffer(cdHandle);
1457 size_main = get_size(cdHandle);
1459 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1460 "Loaded CD Image: %s", fname);
1462 cddaBigEndian = FALSE;
1463 subChanMixed = FALSE;
1465 cdrIsoMultidiskCount = 1;
1468 ISOgetBuffer = ISOgetBuffer_normal;
1469 cdimg_read_func = cdread_normal;
1470 cdimg_read_sub_func = NULL;
1472 if (parsetoc(fname) == 0) {
1473 strcat(image_str, "[+toc]");
1475 else if (parseccd(fname) == 0) {
1476 strcat(image_str, "[+ccd]");
1478 else if (parsemds(fname) == 0) {
1479 strcat(image_str, "[+mds]");
1481 else if (parsecue(fname) == 0) {
1482 strcat(image_str, "[+cue]");
1484 if (handlepbp(fname) == 0) {
1485 strcat(image_str, "[+pbp]");
1486 ISOgetBuffer = ISOgetBuffer_compr;
1487 cdimg_read_func = cdread_compressed;
1489 else if (handlecbin(fname) == 0) {
1490 strcat(image_str, "[+cbin]");
1491 ISOgetBuffer = ISOgetBuffer_compr;
1492 cdimg_read_func = cdread_compressed;
1495 else if (handlechd(fname) == 0) {
1496 strcat(image_str, "[+chd]");
1497 ISOgetBuffer = ISOgetBuffer_chd;
1498 cdimg_read_func = cdread_chd;
1499 cdimg_read_sub_func = cdread_sub_chd;
1503 if (!subChanMixed && opensubfile(fname) == 0) {
1504 strcat(image_str, "[+sub]");
1506 if (opensbifile(fname) == 0) {
1507 strcat(image_str, "[+sbi]");
1510 // maybe user selected metadata file instead of main .bin ..
1511 bin_filename = fname;
1512 if (cdHandle && size_main < 2352 * 0x10) {
1513 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1518 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1519 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1520 if (strlen(alt_bin_filename) >= 4) {
1521 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1522 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1524 tmpf = fopen(alt_bin_filename, "rb");
1530 bin_filename = alt_bin_filename;
1533 set_static_stdio_buffer(cdHandle);
1534 size_main = get_size(cdHandle);
1538 // guess whether it is mode1/2048
1539 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1540 unsigned int modeTest = 0;
1541 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1542 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1544 if (SWAP32(modeTest) != 0xffffff00) {
1545 strcat(image_str, "[2048]");
1549 if (cdHandle && numtracks == 0) {
1550 // assume some metadata-less format
1552 ti[1].type = CDRT_DATA;
1553 ti[1].start_offset = 0;
1554 ti[1].start = 2 * 75;
1555 ti[1].length = isMode1ISO ? size_main / 2048u : size_main / 2352u;
1558 SysPrintf("%s (%lld bytes).\n", image_str, (long long)size_main);
1562 if (subChanMixed && cdimg_read_func == cdread_normal) {
1563 cdimg_read_func = cdread_sub_mixed;
1564 cdimg_read_sub_func = cdread_sub_sub_mixed;
1566 else if (isMode1ISO) {
1567 cdimg_read_func = cdread_2048;
1568 cdimg_read_sub_func = NULL;
1578 if (cdHandle != NULL) {
1582 if (subHandle != NULL) {
1587 if (compr_img != NULL) {
1588 free(compr_img->index_table);
1594 if (chd_img != NULL) {
1595 chd_close(chd_img->chd);
1596 free(chd_img->buffer);
1602 for (i = 1; i <= numtracks; i++) {
1603 if (ti[i].handle != NULL) {
1604 fclose(ti[i].handle);
1605 ti[i].handle = NULL;
1609 ti[1].type = CDRT_UNKNOWN;
1612 memset(cdbuffer, 0, sizeof(cdbuffer));
1613 ISOgetBuffer = ISOgetBuffer_normal;
1620 assert(cdHandle == NULL);
1621 assert(subHandle == NULL);
1624 return 0; // do nothing
1627 int ISOshutdown(void)
1632 // return Starting and Ending Track
1634 // byte 0 - start track
1635 // byte 1 - end track
1636 int ISOgetTN(unsigned char *buffer)
1640 if (numtracks > 0) {
1641 buffer[1] = numtracks;
1650 // return Track Time
1655 int ISOgetTD(int track, unsigned char *buffer)
1658 sec2msf(ti[numtracks].start + ti[numtracks].length, buffer);
1660 else if (numtracks > 0 && track <= numtracks) {
1661 sec2msf(ti[track].start, buffer);
1672 // decode 'raw' subchannel data ripped by cdrdao
1673 static void DecodeRawSubData(unsigned char *subbuffer) {
1674 unsigned char subQData[12];
1677 memset(subQData, 0, sizeof(subQData));
1679 for (i = 0; i < 8 * 12; i++) {
1680 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1681 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1685 memcpy(&subbuffer[12], subQData, 12);
1689 // time: byte 0 - minute; byte 1 - second; byte 2 - frame (non-bcd)
1690 // buf: if NULL, data is kept in internal buffer accessible by ISOgetBuffer()
1691 int ISOreadTrack(const unsigned char *time, void *buf)
1693 int sector = msf2sec(time);
1696 if (!cdHandle && !chd_img)
1699 if (sector >= ti[1].start + ti[1].length &&
1700 numtracks > 1 && ti[2].type == CDRT_CDDA) {
1701 return ISOreadCDDA(time, buf);
1706 ret = cdimg_read_func(cdHandle, 0, buf, sector);
1707 if (ret < 12*2 + 2048)
1713 // read subchannel data
1714 int ISOreadSub(const unsigned char *time, void *buffer)
1716 int ret, sector = msf2sec(time);
1718 if (sector >= ti[1].start + ti[1].length) {
1719 // for tracks 2+ use the fake data, otherwise
1720 // it becomes too messy to handle all the gap stuff
1725 if (cdimg_read_sub_func != NULL) {
1726 if ((ret = cdimg_read_sub_func(cdHandle, sector, buffer)))
1729 else if (subHandle != NULL) {
1730 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1732 if (fread(buffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1740 DecodeRawSubData(buffer);
1744 int ISOgetStatus(struct CdrStat *stat)
1746 CDR__getStatus(stat);
1748 // BIOS - boot ID (CD type)
1749 stat->Type = ti[1].type;
1754 // read CDDA sector into buffer
1755 int ISOreadCDDA(const unsigned char *time, void *buffer)
1757 unsigned int track, track_start = 0;
1758 FILE *handle = cdHandle;
1759 unsigned int cddaCurPos;
1760 int ret, ret_clear = -1;
1762 cddaCurPos = msf2sec(time);
1764 // find current track index
1765 for (track = numtracks; ; track--) {
1766 track_start = ti[track].start;
1767 if (track_start <= cddaCurPos)
1773 if (track == numtracks && cddaCurPos >= ti[track].start + ti[track].length)
1775 if (ti[track].type != CDRT_CDDA) {
1776 // data tracks play silent
1780 if (track < numtracks && cddaCurPos >= ti[track].start + ti[track].length) {
1787 // find the file that contains this track
1789 for (file = track; file > 1; file--) {
1790 if (ti[file].handle != NULL) {
1791 handle = ti[file].handle;
1796 if (!handle && !chd_img)
1799 ret = cdimg_read_func(handle, ti[track].start_offset,
1800 buffer, cddaCurPos - track_start);
1801 if (ret != CD_FRAMESIZE_RAW)
1804 if (cddaBigEndian && buffer) {
1805 unsigned char tmp, *buf = buffer;
1808 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1810 buf[i * 2] = buf[i * 2 + 1];
1811 buf[i * 2 + 1] = tmp;
1819 memset(buffer, 0, CD_FRAMESIZE_RAW);