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);
104 static void DecodeRawSubData(void);
107 enum {DATA=1, CDDA} type;
108 char start[3]; // MSF-format
109 char length[3]; // MSF-format
110 FILE *handle; // for multi-track images CDDA
111 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
114 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
116 static int numtracks = 0;
117 static struct trackinfo ti[MAXTRACKS];
119 // get a sector from a msf-array
120 static unsigned int msf2sec(char *msf) {
121 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
124 static void sec2msf(unsigned int s, char *msf) {
125 msf[0] = s / 75 / 60;
126 s = s - msf[0] * 75 * 60;
132 // divide a string of xx:yy:zz into m, s, f
133 static void tok2msf(char *time, char *msf) {
136 token = strtok(time, ":");
138 msf[0] = atoi(token);
144 token = strtok(NULL, ":");
146 msf[1] = atoi(token);
152 token = strtok(NULL, ":");
154 msf[2] = atoi(token);
161 static off_t get_size(FILE *f)
164 #if !defined(USE_LIBRETRO_VFS)
166 if (fstat(fileno(f), &st) == 0)
170 fseeko(f, 0, SEEK_END);
172 fseeko(f, old, SEEK_SET);
176 // this function tries to get the .toc file of the given .bin
177 // the necessary data is put into the ti (trackinformation)-array
178 static int parsetoc(const char *isofile) {
179 char tocname[MAXPATHLEN];
181 char linebuf[256], tmp[256], name[256];
183 char time[20], time2[20];
184 unsigned int t, sector_offs, sector_size;
185 unsigned int current_zero_gap = 0;
189 // copy name of the iso and change extension from .bin to .toc
190 strncpy(tocname, isofile, sizeof(tocname));
191 tocname[MAXPATHLEN - 1] = '\0';
192 if (strlen(tocname) >= 4) {
193 strcpy(tocname + strlen(tocname) - 4, ".toc");
199 if ((fi = fopen(tocname, "r")) == NULL) {
200 // try changing extension to .cue (to satisfy some stupid tutorials)
201 strcpy(tocname + strlen(tocname) - 4, ".cue");
202 if ((fi = fopen(tocname, "r")) == NULL) {
203 // if filename is image.toc.bin, try removing .bin (for Brasero)
204 strcpy(tocname, isofile);
206 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
207 tocname[t - 4] = '\0';
208 if ((fi = fopen(tocname, "r")) == NULL) {
216 // check if it's really a TOC named as a .cue
217 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
218 token = strtok(linebuf, " ");
219 if (token && strncmp(token, "CD", 2) != 0) {
220 // && strcmp(token, "CATALOG") != 0) - valid for a real .cue
225 fseek(fi, 0, SEEK_SET);
228 memset(&ti, 0, sizeof(ti));
229 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
231 sector_size = CD_FRAMESIZE_RAW;
232 sector_offs = 2 * 75;
234 // parse the .toc file
235 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
237 strncpy(tmp, linebuf, sizeof(linebuf));
238 token = strtok(tmp, " ");
240 if (token == NULL) continue;
242 if (!strcmp(token, "TRACK")) {
243 sector_offs += current_zero_gap;
244 current_zero_gap = 0;
247 token = strtok(NULL, " ");
250 if (!strncmp(token, "MODE2_RAW", 9)) {
251 ti[numtracks].type = DATA;
252 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
254 // check if this image contains mixed subchannel data
255 token = strtok(NULL, " ");
256 if (token != NULL && !strncmp(token, "RW", 2)) {
257 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
259 if (!strncmp(token, "RW_RAW", 6))
263 else if (!strncmp(token, "AUDIO", 5)) {
264 ti[numtracks].type = CDDA;
267 else if (!strcmp(token, "DATAFILE")) {
268 if (ti[numtracks].type == CDDA) {
269 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
270 ti[numtracks].start_offset = t;
271 t = t / sector_size + sector_offs;
272 sec2msf(t, (char *)&ti[numtracks].start);
273 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
276 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
277 tok2msf((char *)&time, (char *)&ti[numtracks].length);
280 else if (!strcmp(token, "FILE")) {
281 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
282 tok2msf((char *)&time, (char *)&ti[numtracks].start);
283 t += msf2sec(ti[numtracks].start) * sector_size;
284 ti[numtracks].start_offset = t;
285 t = t / sector_size + sector_offs;
286 sec2msf(t, (char *)&ti[numtracks].start);
287 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
289 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
290 // skip unneeded optional fields
291 while (token != NULL) {
292 token = strtok(NULL, " ");
293 if (strchr(token, ':') != NULL)
298 current_zero_gap = msf2sec(tmp);
301 t = ti[numtracks - 1].start_offset;
303 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
306 else if (!strcmp(token, "START")) {
307 token = strtok(NULL, " ");
308 if (token != NULL && strchr(token, ':')) {
311 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
312 t = msf2sec(ti[numtracks].start) + t;
313 sec2msf(t, (char *)&ti[numtracks].start);
323 // this function tries to get the .cue file of the given .bin
324 // the necessary data is put into the ti (trackinformation)-array
325 static int parsecue(const char *isofile) {
326 char cuename[MAXPATHLEN];
327 char filepath[MAXPATHLEN];
334 char linebuf[256], tmpb[256], dummy[256];
335 unsigned int incue_max_len;
336 unsigned int t, file_len, mode, sector_offs;
337 unsigned int sector_size = 2352;
341 // copy name of the iso and change extension from .bin to .cue
342 strncpy(cuename, isofile, sizeof(cuename));
343 cuename[MAXPATHLEN - 1] = '\0';
344 if (strlen(cuename) < 4)
346 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
347 // it's already open as cdHandle
351 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
352 // and don't try to search the additional .cue file
353 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
354 strcpy(cuename + strlen(cuename) - 4, ".cue");
356 if ((ftmp = fopen(cuename, "r")) == NULL)
361 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
362 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
364 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
365 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
366 // Don't proceed further, as this is actually a .toc file rather
370 return parsetoc(isofile);
375 // build a path for files referenced in .cue
376 strncpy(filepath, cuename, sizeof(filepath));
377 tmp = strrchr(filepath, '/');
379 tmp = strrchr(filepath, '\\');
385 filepath[sizeof(filepath) - 1] = 0;
387 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
389 memset(&ti, 0, sizeof(ti));
392 sector_offs = 2 * 75;
394 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
395 strncpy(dummy, linebuf, sizeof(linebuf));
396 token = strtok(dummy, " ");
402 if (!strcmp(token, "TRACK")) {
406 if (strstr(linebuf, "AUDIO") != NULL) {
407 ti[numtracks].type = CDDA;
410 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
411 ti[numtracks].type = DATA;
413 SysPrintf(".cue: failed to parse TRACK\n");
414 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
416 if (sector_size == 0)
419 else if (!strcmp(token, "INDEX")) {
420 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
421 SysPrintf(".cue: failed to parse INDEX\n");
422 tok2msf(time, (char *)&ti[numtracks].start);
424 t = msf2sec(ti[numtracks].start);
425 ti[numtracks].start_offset = t * sector_size;
427 sec2msf(t, ti[numtracks].start);
429 // default track length to file length
430 t = file_len - ti[numtracks].start_offset / sector_size;
431 sec2msf(t, ti[numtracks].length);
433 if (numtracks > 1 && ti[numtracks].handle == NULL) {
434 // this track uses the same file as the last,
435 // start of this track is last track's end
436 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
437 sec2msf(t, ti[numtracks - 1].length);
439 if (numtracks > 1 && pregapOffset == -1)
440 pregapOffset = ti[numtracks].start_offset / sector_size;
442 else if (!strcmp(token, "PREGAP")) {
443 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
444 tok2msf(time, dummy);
445 sector_offs += msf2sec(dummy);
447 pregapOffset = -1; // mark to fill track start_offset
449 else if (!strcmp(token, "FILE")) {
450 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
452 sscanf(linebuf, " FILE %255s", tmpb);
455 ti[numtracks + 1].handle = fopen(tmpb, "rb");
456 if (ti[numtracks + 1].handle == NULL) {
458 tmp = strrchr(tmpb, '\\');
460 tmp = strrchr(tmpb, '/');
465 strncpy(incue_fname, tmp, incue_max_len);
466 ti[numtracks + 1].handle = fopen(filepath, "rb");
469 // update global offset if this is not first file in this .cue
470 if (numtracks + 1 > 1) {
472 sector_offs += file_len;
476 if (ti[numtracks + 1].handle == NULL) {
477 SysPrintf(_("\ncould not open: %s\n"), filepath);
480 file_len = get_size(ti[numtracks + 1].handle) / 2352;
487 // if there are no tracks detected, then it's not a cue file
491 // the data track handle is always in cdHandle
494 cdHandle = ti[1].handle;
500 // this function tries to get the .ccd file of the given .img
501 // the necessary data is put into the ti (trackinformation)-array
502 static int parseccd(const char *isofile) {
503 char ccdname[MAXPATHLEN];
510 // copy name of the iso and change extension from .img to .ccd
511 strncpy(ccdname, isofile, sizeof(ccdname));
512 ccdname[MAXPATHLEN - 1] = '\0';
513 if (strlen(ccdname) >= 4) {
514 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
520 if ((fi = fopen(ccdname, "r")) == NULL) {
524 memset(&ti, 0, sizeof(ti));
526 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
527 if (!strncmp(linebuf, "[TRACK", 6)){
530 else if (!strncmp(linebuf, "MODE=", 5)) {
531 sscanf(linebuf, "MODE=%d", &t);
532 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
534 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
535 sscanf(linebuf, "INDEX 1=%d", &t);
536 sec2msf(t + 2 * 75, ti[numtracks].start);
537 ti[numtracks].start_offset = t * 2352;
539 // If we've already seen another track, this is its end
541 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
542 sec2msf(t, ti[numtracks - 1].length);
549 // Fill out the last track's end based on size
550 if (numtracks >= 1) {
551 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
552 sec2msf(t, ti[numtracks].length);
558 // this function tries to get the .mds file of the given .mdf
559 // the necessary data is put into the ti (trackinformation)-array
560 static int parsemds(const char *isofile) {
561 char mdsname[MAXPATHLEN];
563 unsigned int offset, extra_offset, l, i;
568 // copy name of the iso and change extension from .mdf to .mds
569 strncpy(mdsname, isofile, sizeof(mdsname));
570 mdsname[MAXPATHLEN - 1] = '\0';
571 if (strlen(mdsname) >= 4) {
572 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
578 if ((fi = fopen(mdsname, "rb")) == NULL) {
582 memset(&ti, 0, sizeof(ti));
584 // check if it's a valid mds file
585 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
588 if (i != 0x4944454D) {
589 // not an valid mds file
594 // get offset to session block
595 fseek(fi, 0x50, SEEK_SET);
596 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
598 offset = SWAP32(offset);
600 // get total number of tracks
602 fseek(fi, offset, SEEK_SET);
603 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
608 // get offset to track blocks
609 fseek(fi, 4, SEEK_CUR);
610 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
612 offset = SWAP32(offset);
616 fseek(fi, offset + 4, SEEK_SET);
617 if (fgetc(fi) < 0xA0) {
623 // check if the image contains mixed subchannel data
624 fseek(fi, offset + 1, SEEK_SET);
625 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
628 for (i = 1; i <= numtracks; i++) {
629 fseek(fi, offset, SEEK_SET);
631 // get the track type
632 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
633 fseek(fi, 8, SEEK_CUR);
635 // get the track starting point
636 ti[i].start[0] = fgetc(fi);
637 ti[i].start[1] = fgetc(fi);
638 ti[i].start[2] = fgetc(fi);
640 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
642 extra_offset = SWAP32(extra_offset);
644 // get track start offset (in .mdf)
645 fseek(fi, offset + 0x28, SEEK_SET);
646 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
649 ti[i].start_offset = l;
652 fseek(fi, extra_offset, SEEK_SET);
653 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
657 pregapOffset = msf2sec(ti[i].start);
659 // get the track length
660 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
663 sec2msf(l, ti[i].length);
671 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
677 static int handlepbp(const char *isofile) {
680 unsigned int dontcare[8];
681 unsigned int psar_offs;
694 unsigned int dontcare[6];
697 off_t psisoimg_offs, cdimg_base;
698 unsigned int t, cd_length;
699 unsigned int offsettab[8];
700 unsigned int psar_offs, index_entry_size, index_entry_offset;
701 const char *ext = NULL;
704 if (strlen(isofile) >= 4)
705 ext = isofile + strlen(isofile) - 4;
706 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
711 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
712 if (ret != sizeof(pbp_hdr)) {
713 SysPrintf("failed to read pbp\n");
717 psar_offs = SWAP32(pbp_hdr.psar_offs);
719 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
721 SysPrintf("failed to seek to %x\n", psar_offs);
725 psisoimg_offs = psar_offs;
726 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
729 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
731 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
733 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
737 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
738 SysPrintf("failed to read offsettab\n");
742 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
743 if (offsettab[i] == 0)
746 cdrIsoMultidiskCount = i;
747 if (cdrIsoMultidiskCount == 0) {
748 SysPrintf("multidisk eboot has 0 images?\n");
752 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
753 cdrIsoMultidiskSelect = 0;
755 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
757 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
759 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
763 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
768 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
769 SysPrintf("bad psar_sig: %s\n", psar_sig);
774 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
776 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
780 // first 3 entries are special
781 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
782 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
784 numtracks = btoi(toc_entry.index1[0]);
786 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
788 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
789 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
791 for (i = 1; i <= numtracks; i++) {
792 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
795 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
797 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
798 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
799 ti[i].start_offset *= 2352;
800 ti[i].start[0] = btoi(toc_entry.index1[0]);
801 ti[i].start[1] = btoi(toc_entry.index1[1]);
802 ti[i].start[2] = btoi(toc_entry.index1[2]);
805 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
806 sec2msf(t, ti[i - 1].length);
809 t = cd_length - ti[numtracks].start_offset / 2352;
810 sec2msf(t, ti[numtracks].length);
813 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
815 SysPrintf("failed to seek to ISO index\n");
819 compr_img = calloc(1, sizeof(*compr_img));
820 if (compr_img == NULL)
823 compr_img->block_shift = 4;
824 compr_img->current_block = (unsigned int)-1;
826 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
827 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
828 if (compr_img->index_table == NULL)
831 cdimg_base = psisoimg_offs + 0x100000;
832 for (i = 0; i < compr_img->index_len; i++) {
833 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
834 if (ret != sizeof(index_entry)) {
835 SysPrintf("failed to read index_entry #%d\n", i);
839 index_entry_size = SWAP32(index_entry.size);
840 index_entry_offset = SWAP32(index_entry.offset);
842 if (index_entry_size == 0)
845 compr_img->index_table[i] = cdimg_base + index_entry_offset;
847 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
852 free(compr_img->index_table);
853 compr_img->index_table = NULL;
857 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
861 if (compr_img != NULL) {
868 static int handlecbin(const char *isofile) {
872 unsigned int header_size;
873 unsigned long long total_bytes;
874 unsigned int block_size;
875 unsigned char ver; // 1
877 unsigned char rsv_06[2];
879 const char *ext = NULL;
880 unsigned int *index_table = NULL;
881 unsigned int index = 0, plain;
884 if (strlen(isofile) >= 5)
885 ext = isofile + strlen(isofile) - 5;
886 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
889 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
890 if (ret != sizeof(ciso_hdr)) {
891 SysPrintf("failed to read ciso header\n");
895 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
896 SysPrintf("bad ciso header\n");
899 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
900 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
902 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
907 compr_img = calloc(1, sizeof(*compr_img));
908 if (compr_img == NULL)
911 compr_img->block_shift = 0;
912 compr_img->current_block = (unsigned int)-1;
914 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
915 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
916 if (index_table == NULL)
919 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
920 if (ret != compr_img->index_len) {
921 SysPrintf("failed to read index table\n");
925 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
926 if (compr_img->index_table == NULL)
929 for (i = 0; i < compr_img->index_len + 1; i++) {
930 index = index_table[i];
931 plain = index & 0x80000000;
933 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
935 compr_img->index_table[i] |= OFF_T_MSB;
943 if (compr_img != NULL) {
952 static int handlechd(const char *isofile) {
953 int frame_offset = 150;
956 chd_img = calloc(1, sizeof(*chd_img));
960 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
963 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
966 chd_img->header = chd_get_header(chd_img->chd);
968 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
969 if (chd_img->buffer == NULL)
972 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
973 chd_img->current_hunk[0] = (unsigned int)-1;
974 chd_img->current_hunk[1] = (unsigned int)-1;
976 cddaBigEndian = TRUE;
979 memset(ti, 0, sizeof(ti));
994 uint32_t meta_size = 0;
996 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
997 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
998 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
999 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1003 SysPrintf("chd: %s\n", meta);
1005 if (md.track == 1) {
1006 if (!strncmp(md.subtype, "RW", 2)) {
1007 subChanMixed = TRUE;
1008 if (!strcmp(md.subtype, "RW_RAW"))
1013 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1015 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1016 sec2msf(md.frames, ti[md.track].length);
1018 ti[md.track].start_offset = file_offset + md.pregap;
1020 // XXX: what about postgap?
1021 frame_offset += md.frames;
1022 file_offset += md.frames;
1030 if (chd_img != NULL) {
1031 free(chd_img->buffer);
1039 // this function tries to get the .sub file of the given .img
1040 static int opensubfile(const char *isoname) {
1041 char subname[MAXPATHLEN];
1043 // copy name of the iso and change extension from .img to .sub
1044 strncpy(subname, isoname, sizeof(subname));
1045 subname[MAXPATHLEN - 1] = '\0';
1046 if (strlen(subname) >= 4) {
1047 strcpy(subname + strlen(subname) - 4, ".sub");
1053 subHandle = fopen(subname, "rb");
1054 if (subHandle == NULL) {
1061 static int opensbifile(const char *isoname) {
1062 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1065 strncpy(sbiname, isoname, sizeof(sbiname));
1066 sbiname[MAXPATHLEN - 1] = '\0';
1067 if (strlen(sbiname) >= 4) {
1068 if (cdrIsoMultidiskCount > 1) {
1069 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1070 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1073 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1079 s = msf2sec(ti[1].length);
1081 return LoadSBI(sbiname, s);
1084 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1089 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1091 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1097 // often happens in cdda gaps of a split cue/bin, so not logged
1098 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1102 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1108 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1110 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1116 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1120 static int cdread_sub_sub_mixed(FILE *f, int sector)
1124 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1126 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1129 return SUB_FRAMESIZE;
1132 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1136 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1141 if (z.zalloc == NULL) {
1142 // XXX: one-time leak here..
1148 ret = inflateInit2(&z, -15);
1151 ret = inflateReset(&z);
1156 z.avail_in = in_size;
1158 z.avail_out = *out_size;
1160 ret = inflate(&z, Z_NO_FLUSH);
1163 *out_size -= z.avail_out;
1164 return ret == 1 ? 0 : ret;
1167 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1169 unsigned long cdbuffer_size, cdbuffer_size_expect;
1178 sector += base / 2352;
1180 block = sector >> compr_img->block_shift;
1181 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1183 if (block == compr_img->current_block) {
1184 //printf("hit sect %d\n", sector);
1188 if (sector >= compr_img->index_len * 16) {
1189 SysPrintf("sector %d is past img end\n", sector);
1193 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1194 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1195 SysPrintf("seek error for block %d at %llx: ",
1196 block, (long long)start_byte);
1201 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1202 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1203 if (size > sizeof(compr_img->buff_compressed)) {
1204 SysPrintf("block %d is too large: %u\n", block, size);
1208 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1209 1, size, cdHandle) != size) {
1210 SysPrintf("read error for block %d at %x: ", block, start_byte);
1215 if (is_compressed) {
1216 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1217 cdbuffer_size = cdbuffer_size_expect;
1218 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1220 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1221 ret, block, sector);
1224 if (cdbuffer_size != cdbuffer_size_expect)
1225 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1226 cdbuffer_size_expect, sector);
1230 compr_img->current_block = block;
1233 if (dest != cdbuffer) // copy avoid HACK
1234 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1236 return CD_FRAMESIZE_RAW;
1240 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1242 return chd_img->buffer
1243 + current_buffer * chd_img->header->hunkbytes
1244 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1247 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1253 hunk = sector / chd_img->sectors_per_hunk;
1254 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1256 if (hunk == chd_img->current_hunk[0])
1257 chd_img->current_buffer = 0;
1258 else if (hunk == chd_img->current_hunk[1])
1259 chd_img->current_buffer = 1;
1262 chd_read(chd_img->chd, hunk, chd_img->buffer +
1263 chd_img->current_buffer * chd_img->header->hunkbytes);
1264 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1267 if (dest != cdbuffer) // copy avoid HACK
1268 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1270 return CD_FRAMESIZE_RAW;
1273 static int cdread_sub_chd(FILE *f, int sector)
1275 unsigned int sector_in_hunk;
1276 unsigned int buffer;
1282 hunk = sector / chd_img->sectors_per_hunk;
1283 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1285 if (hunk == chd_img->current_hunk[0])
1287 else if (hunk == chd_img->current_hunk[1])
1291 buffer = chd_img->current_buffer ^ 1;
1292 chd_read(chd_img->chd, hunk, chd_img->buffer +
1293 buffer * chd_img->header->hunkbytes);
1294 chd_img->current_hunk[buffer] = hunk;
1297 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1298 return SUB_FRAMESIZE;
1302 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1308 fseeko(f, base + sector * 2048, SEEK_SET);
1309 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1311 // not really necessary, fake mode 2 header
1312 memset(cdbuffer, 0, 12 * 2);
1313 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1314 cdbuffer[12 + 3] = 1;
1319 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1320 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1324 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1325 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1329 static unsigned char * CALLBACK ISOgetBuffer(void) {
1330 return cdbuffer + 12;
1333 static void PrintTracks(void) {
1336 for (i = 1; i <= numtracks; i++) {
1337 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1338 i, (ti[i].type == DATA ? "DATA" :
1339 (ti[i].type == CDDA ? "AUDIO" : "UNKNOWN")),
1340 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1341 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1345 // This function is invoked by the front-end when opening an ISO
1346 // file for playback
1347 static long CALLBACK ISOopen(void) {
1348 boolean isMode1ISO = FALSE;
1349 char alt_bin_filename[MAXPATHLEN];
1350 const char *bin_filename;
1351 char image_str[1024];
1354 if (cdHandle || chd_img) {
1355 return 0; // it's already open
1358 cdHandle = fopen(GetIsoFile(), "rb");
1359 if (cdHandle == NULL) {
1360 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1361 GetIsoFile(), strerror(errno));
1364 size_main = get_size(cdHandle);
1366 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1367 "Loaded CD Image: %s", GetIsoFile());
1369 cddaBigEndian = FALSE;
1370 subChanMixed = FALSE;
1373 cdrIsoMultidiskCount = 1;
1376 CDR_getBuffer = ISOgetBuffer;
1377 cdimg_read_func = cdread_normal;
1378 cdimg_read_sub_func = NULL;
1380 if (parsetoc(GetIsoFile()) == 0) {
1381 strcat(image_str, "[+toc]");
1383 else if (parseccd(GetIsoFile()) == 0) {
1384 strcat(image_str, "[+ccd]");
1386 else if (parsemds(GetIsoFile()) == 0) {
1387 strcat(image_str, "[+mds]");
1389 else if (parsecue(GetIsoFile()) == 0) {
1390 strcat(image_str, "[+cue]");
1392 if (handlepbp(GetIsoFile()) == 0) {
1393 strcat(image_str, "[+pbp]");
1394 CDR_getBuffer = ISOgetBuffer_compr;
1395 cdimg_read_func = cdread_compressed;
1397 else if (handlecbin(GetIsoFile()) == 0) {
1398 strcat(image_str, "[+cbin]");
1399 CDR_getBuffer = ISOgetBuffer_compr;
1400 cdimg_read_func = cdread_compressed;
1403 else if (handlechd(GetIsoFile()) == 0) {
1404 strcat(image_str, "[+chd]");
1405 CDR_getBuffer = ISOgetBuffer_chd;
1406 cdimg_read_func = cdread_chd;
1407 cdimg_read_sub_func = cdread_sub_chd;
1413 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1414 strcat(image_str, "[+sub]");
1416 if (opensbifile(GetIsoFile()) == 0) {
1417 strcat(image_str, "[+sbi]");
1420 // maybe user selected metadata file instead of main .bin ..
1421 bin_filename = GetIsoFile();
1422 if (cdHandle && size_main < 2352 * 0x10) {
1423 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1428 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1429 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1430 if (strlen(alt_bin_filename) >= 4) {
1431 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1432 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1434 tmpf = fopen(alt_bin_filename, "rb");
1440 bin_filename = alt_bin_filename;
1443 size_main = get_size(cdHandle);
1447 // guess whether it is mode1/2048
1448 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1449 unsigned int modeTest = 0;
1450 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1451 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1453 if (SWAP32(modeTest) != 0xffffff00) {
1454 strcat(image_str, "[2048]");
1459 SysPrintf("%s.\n", image_str);
1463 if (subChanMixed && cdimg_read_func == cdread_normal) {
1464 cdimg_read_func = cdread_sub_mixed;
1465 cdimg_read_sub_func = cdread_sub_sub_mixed;
1467 else if (isMode1ISO) {
1468 cdimg_read_func = cdread_2048;
1469 cdimg_read_sub_func = NULL;
1475 static long CALLBACK ISOclose(void) {
1478 if (cdHandle != NULL) {
1482 if (subHandle != NULL) {
1488 if (compr_img != NULL) {
1489 free(compr_img->index_table);
1495 if (chd_img != NULL) {
1496 chd_close(chd_img->chd);
1497 free(chd_img->buffer);
1503 for (i = 1; i <= numtracks; i++) {
1504 if (ti[i].handle != NULL) {
1505 fclose(ti[i].handle);
1506 ti[i].handle = NULL;
1513 memset(cdbuffer, 0, sizeof(cdbuffer));
1514 CDR_getBuffer = ISOgetBuffer;
1519 static long CALLBACK ISOinit(void) {
1520 assert(cdHandle == NULL);
1521 assert(subHandle == NULL);
1523 return 0; // do nothing
1526 static long CALLBACK ISOshutdown(void) {
1531 // return Starting and Ending Track
1533 // byte 0 - start track
1534 // byte 1 - end track
1535 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1538 if (numtracks > 0) {
1539 buffer[1] = numtracks;
1548 // return Track Time
1553 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1556 unsigned char time[3];
1557 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1558 sec2msf(sect, (char *)time);
1559 buffer[2] = time[0];
1560 buffer[1] = time[1];
1561 buffer[0] = time[2];
1563 else if (numtracks > 0 && track <= numtracks) {
1564 buffer[2] = ti[track].start[0];
1565 buffer[1] = ti[track].start[1];
1566 buffer[0] = ti[track].start[2];
1577 // decode 'raw' subchannel data ripped by cdrdao
1578 static void DecodeRawSubData(void) {
1579 unsigned char subQData[12];
1582 memset(subQData, 0, sizeof(subQData));
1584 for (i = 0; i < 8 * 12; i++) {
1585 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1586 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1590 memcpy(&subbuffer[12], subQData, 12);
1594 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1596 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1597 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1600 if (!cdHandle && !chd_img)
1603 if (pregapOffset && sector >= pregapOffset)
1606 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1607 if (ret < 12*2 + 2048)
1614 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1615 // does NOT uses bcd format
1616 static long CALLBACK ISOplay(unsigned char *time) {
1621 static long CALLBACK ISOstop(void) {
1625 // gets subchannel data
1626 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1627 if (pregapOffset && sector >= pregapOffset) {
1629 if (sector < pregapOffset) // ?
1633 if (cdimg_read_sub_func != NULL) {
1634 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1637 else if (subHandle != NULL) {
1638 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1640 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1647 if (subChanRaw) DecodeRawSubData();
1651 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1652 CDR__getStatus(stat);
1654 // BIOS - boot ID (CD type)
1655 stat->Type = ti[1].type;
1660 // read CDDA sector into buffer
1661 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1662 unsigned char msf[3] = {m, s, f};
1663 unsigned int track, track_start = 0;
1664 FILE *handle = cdHandle;
1665 unsigned int cddaCurPos;
1668 cddaCurPos = msf2sec((char *)msf);
1670 // find current track index
1671 for (track = numtracks; ; track--) {
1672 track_start = msf2sec(ti[track].start);
1673 if (track_start <= cddaCurPos)
1679 // data tracks play silent
1680 if (ti[track].type != CDDA) {
1681 memset(buffer, 0, CD_FRAMESIZE_RAW);
1686 // find the file that contains this track
1688 for (file = track; file > 1; file--) {
1689 if (ti[file].handle != NULL) {
1690 handle = ti[file].handle;
1695 if (!handle && !chd_img) {
1696 memset(buffer, 0, CD_FRAMESIZE_RAW);
1700 ret = cdimg_read_func(handle, ti[track].start_offset,
1701 buffer, cddaCurPos - track_start);
1702 if (ret != CD_FRAMESIZE_RAW) {
1703 memset(buffer, 0, CD_FRAMESIZE_RAW);
1707 if (cddaBigEndian) {
1711 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1712 tmp = buffer[i * 2];
1713 buffer[i * 2] = buffer[i * 2 + 1];
1714 buffer[i * 2 + 1] = tmp;
1721 void cdrIsoInit(void) {
1723 CDR_shutdown = ISOshutdown;
1725 CDR_close = ISOclose;
1726 CDR_getTN = ISOgetTN;
1727 CDR_getTD = ISOgetTD;
1728 CDR_readTrack = ISOreadTrack;
1729 CDR_getBuffer = ISOgetBuffer;
1732 CDR_getBufferSub = ISOgetBufferSub;
1733 CDR_getStatus = ISOgetStatus;
1734 CDR_readCDDA = ISOreadCDDA;
1736 CDR_getDriveLetter = CDR__getDriveLetter;
1737 CDR_configure = CDR__configure;
1738 CDR_test = CDR__test;
1739 CDR_about = CDR__about;
1740 CDR_setfilename = CDR__setfilename;
1745 int cdrIsoActive(void) {
1746 return (cdHandle || chd_img);