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 playing = FALSE;
64 static boolean cddaBigEndian = FALSE;
65 /* Frame offset into CD image where pregap data would be found if it was there.
66 * If a game seeks there we must *not* return subchannel data since it's
67 * not in the CD image, so that cdrom code can fake subchannel data instead.
68 * XXX: there could be multiple pregaps but PSX dumps only have one? */
69 static unsigned int pregapOffset;
71 static unsigned int cddaCurPos;
73 // compressed image stuff
75 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
76 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
78 unsigned int index_len;
79 unsigned int block_shift;
80 unsigned int current_block;
81 unsigned int sector_in_blk;
86 unsigned char *buffer;
88 const chd_header* header;
89 unsigned int sectors_per_hunk;
90 unsigned int current_hunk[2];
91 unsigned int current_buffer;
92 unsigned int sector_in_hunk;
98 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
99 static int (*cdimg_read_sub_func)(FILE *f, int sector);
101 char* CALLBACK CDR__getDriveLetter(void);
102 long CALLBACK CDR__configure(void);
103 long CALLBACK CDR__test(void);
104 void CALLBACK CDR__about(void);
105 long CALLBACK CDR__setfilename(char *filename);
106 long CALLBACK CDR__getStatus(struct CdrStat *stat);
108 static void DecodeRawSubData(void);
111 enum {DATA=1, CDDA} type;
112 char start[3]; // MSF-format
113 char length[3]; // MSF-format
114 FILE *handle; // for multi-track images CDDA
115 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
118 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
120 static int numtracks = 0;
121 static struct trackinfo ti[MAXTRACKS];
123 // get a sector from a msf-array
124 static unsigned int msf2sec(char *msf) {
125 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
128 static void sec2msf(unsigned int s, char *msf) {
129 msf[0] = s / 75 / 60;
130 s = s - msf[0] * 75 * 60;
136 // divide a string of xx:yy:zz into m, s, f
137 static void tok2msf(char *time, char *msf) {
140 token = strtok(time, ":");
142 msf[0] = atoi(token);
148 token = strtok(NULL, ":");
150 msf[1] = atoi(token);
156 token = strtok(NULL, ":");
158 msf[2] = atoi(token);
165 static off_t get_size(FILE *f)
168 #if !defined(USE_LIBRETRO_VFS)
170 if (fstat(fileno(f), &st) == 0)
174 fseeko(f, 0, SEEK_END);
176 fseeko(f, old, SEEK_SET);
180 // this function tries to get the .toc file of the given .bin
181 // the necessary data is put into the ti (trackinformation)-array
182 static int parsetoc(const char *isofile) {
183 char tocname[MAXPATHLEN];
185 char linebuf[256], tmp[256], name[256];
187 char time[20], time2[20];
188 unsigned int t, sector_offs, sector_size;
189 unsigned int current_zero_gap = 0;
193 // copy name of the iso and change extension from .bin to .toc
194 strncpy(tocname, isofile, sizeof(tocname));
195 tocname[MAXPATHLEN - 1] = '\0';
196 if (strlen(tocname) >= 4) {
197 strcpy(tocname + strlen(tocname) - 4, ".toc");
203 if ((fi = fopen(tocname, "r")) == NULL) {
204 // try changing extension to .cue (to satisfy some stupid tutorials)
205 strcpy(tocname + strlen(tocname) - 4, ".cue");
206 if ((fi = fopen(tocname, "r")) == NULL) {
207 // if filename is image.toc.bin, try removing .bin (for Brasero)
208 strcpy(tocname, isofile);
210 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
211 tocname[t - 4] = '\0';
212 if ((fi = fopen(tocname, "r")) == NULL) {
220 // check if it's really a TOC named as a .cue
221 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
222 token = strtok(linebuf, " ");
223 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
228 fseek(fi, 0, SEEK_SET);
231 memset(&ti, 0, sizeof(ti));
232 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
234 sector_size = CD_FRAMESIZE_RAW;
235 sector_offs = 2 * 75;
237 // parse the .toc file
238 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
240 strncpy(tmp, linebuf, sizeof(linebuf));
241 token = strtok(tmp, " ");
243 if (token == NULL) continue;
245 if (!strcmp(token, "TRACK")) {
246 sector_offs += current_zero_gap;
247 current_zero_gap = 0;
250 token = strtok(NULL, " ");
253 if (!strncmp(token, "MODE2_RAW", 9)) {
254 ti[numtracks].type = DATA;
255 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
257 // check if this image contains mixed subchannel data
258 token = strtok(NULL, " ");
259 if (token != NULL && !strncmp(token, "RW", 2)) {
260 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
262 if (!strncmp(token, "RW_RAW", 6))
266 else if (!strncmp(token, "AUDIO", 5)) {
267 ti[numtracks].type = CDDA;
270 else if (!strcmp(token, "DATAFILE")) {
271 if (ti[numtracks].type == CDDA) {
272 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
273 ti[numtracks].start_offset = t;
274 t = t / sector_size + sector_offs;
275 sec2msf(t, (char *)&ti[numtracks].start);
276 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
279 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
280 tok2msf((char *)&time, (char *)&ti[numtracks].length);
283 else if (!strcmp(token, "FILE")) {
284 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
285 tok2msf((char *)&time, (char *)&ti[numtracks].start);
286 t += msf2sec(ti[numtracks].start) * sector_size;
287 ti[numtracks].start_offset = t;
288 t = t / sector_size + sector_offs;
289 sec2msf(t, (char *)&ti[numtracks].start);
290 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
292 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
293 // skip unneeded optional fields
294 while (token != NULL) {
295 token = strtok(NULL, " ");
296 if (strchr(token, ':') != NULL)
301 current_zero_gap = msf2sec(tmp);
304 t = ti[numtracks - 1].start_offset;
306 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
309 else if (!strcmp(token, "START")) {
310 token = strtok(NULL, " ");
311 if (token != NULL && strchr(token, ':')) {
314 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
315 t = msf2sec(ti[numtracks].start) + t;
316 sec2msf(t, (char *)&ti[numtracks].start);
326 // this function tries to get the .cue file of the given .bin
327 // the necessary data is put into the ti (trackinformation)-array
328 static int parsecue(const char *isofile) {
329 char cuename[MAXPATHLEN];
330 char filepath[MAXPATHLEN];
337 char linebuf[256], tmpb[256], dummy[256];
338 unsigned int incue_max_len;
339 unsigned int t, file_len, mode, sector_offs;
340 unsigned int sector_size = 2352;
344 // copy name of the iso and change extension from .bin to .cue
345 strncpy(cuename, isofile, sizeof(cuename));
346 cuename[MAXPATHLEN - 1] = '\0';
347 if (strlen(cuename) < 4)
349 if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
350 // it's already open as cdHandle
354 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
355 // and don't try to search the additional .cue file
356 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
357 strcpy(cuename + strlen(cuename) - 4, ".cue");
359 if ((ftmp = fopen(cuename, "r")) == NULL)
364 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
365 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
367 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
368 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
369 // Don't proceed further, as this is actually a .toc file rather
373 return parsetoc(isofile);
378 // build a path for files referenced in .cue
379 strncpy(filepath, cuename, sizeof(filepath));
380 tmp = strrchr(filepath, '/');
382 tmp = strrchr(filepath, '\\');
388 filepath[sizeof(filepath) - 1] = 0;
390 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
392 memset(&ti, 0, sizeof(ti));
395 sector_offs = 2 * 75;
397 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
398 strncpy(dummy, linebuf, sizeof(linebuf));
399 token = strtok(dummy, " ");
405 if (!strcmp(token, "TRACK")) {
409 if (strstr(linebuf, "AUDIO") != NULL) {
410 ti[numtracks].type = CDDA;
413 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
414 ti[numtracks].type = DATA;
416 SysPrintf(".cue: failed to parse TRACK\n");
417 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
419 if (sector_size == 0)
422 else if (!strcmp(token, "INDEX")) {
423 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
424 SysPrintf(".cue: failed to parse INDEX\n");
425 tok2msf(time, (char *)&ti[numtracks].start);
427 t = msf2sec(ti[numtracks].start);
428 ti[numtracks].start_offset = t * sector_size;
430 sec2msf(t, ti[numtracks].start);
432 // default track length to file length
433 t = file_len - ti[numtracks].start_offset / sector_size;
434 sec2msf(t, ti[numtracks].length);
436 if (numtracks > 1 && ti[numtracks].handle == NULL) {
437 // this track uses the same file as the last,
438 // start of this track is last track's end
439 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
440 sec2msf(t, ti[numtracks - 1].length);
442 if (numtracks > 1 && pregapOffset == -1)
443 pregapOffset = ti[numtracks].start_offset / sector_size;
445 else if (!strcmp(token, "PREGAP")) {
446 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
447 tok2msf(time, dummy);
448 sector_offs += msf2sec(dummy);
450 pregapOffset = -1; // mark to fill track start_offset
452 else if (!strcmp(token, "FILE")) {
453 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
455 sscanf(linebuf, " FILE %255s", tmpb);
458 ti[numtracks + 1].handle = fopen(tmpb, "rb");
459 if (ti[numtracks + 1].handle == NULL) {
461 tmp = strrchr(tmpb, '\\');
463 tmp = strrchr(tmpb, '/');
468 strncpy(incue_fname, tmp, incue_max_len);
469 ti[numtracks + 1].handle = fopen(filepath, "rb");
472 // update global offset if this is not first file in this .cue
473 if (numtracks + 1 > 1) {
475 sector_offs += file_len;
479 if (ti[numtracks + 1].handle == NULL) {
480 SysPrintf(_("\ncould not open: %s\n"), filepath);
483 file_len = get_size(ti[numtracks + 1].handle) / 2352;
490 // if there are no tracks detected, then it's not a cue file
494 // the data track handle is always in cdHandle
497 cdHandle = ti[1].handle;
503 // this function tries to get the .ccd file of the given .img
504 // the necessary data is put into the ti (trackinformation)-array
505 static int parseccd(const char *isofile) {
506 char ccdname[MAXPATHLEN];
513 // copy name of the iso and change extension from .img to .ccd
514 strncpy(ccdname, isofile, sizeof(ccdname));
515 ccdname[MAXPATHLEN - 1] = '\0';
516 if (strlen(ccdname) >= 4) {
517 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
523 if ((fi = fopen(ccdname, "r")) == NULL) {
527 memset(&ti, 0, sizeof(ti));
529 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
530 if (!strncmp(linebuf, "[TRACK", 6)){
533 else if (!strncmp(linebuf, "MODE=", 5)) {
534 sscanf(linebuf, "MODE=%d", &t);
535 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
537 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
538 sscanf(linebuf, "INDEX 1=%d", &t);
539 sec2msf(t + 2 * 75, ti[numtracks].start);
540 ti[numtracks].start_offset = t * 2352;
542 // If we've already seen another track, this is its end
544 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
545 sec2msf(t, ti[numtracks - 1].length);
552 // Fill out the last track's end based on size
553 if (numtracks >= 1) {
554 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
555 sec2msf(t, ti[numtracks].length);
561 // this function tries to get the .mds file of the given .mdf
562 // the necessary data is put into the ti (trackinformation)-array
563 static int parsemds(const char *isofile) {
564 char mdsname[MAXPATHLEN];
566 unsigned int offset, extra_offset, l, i;
571 // copy name of the iso and change extension from .mdf to .mds
572 strncpy(mdsname, isofile, sizeof(mdsname));
573 mdsname[MAXPATHLEN - 1] = '\0';
574 if (strlen(mdsname) >= 4) {
575 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
581 if ((fi = fopen(mdsname, "rb")) == NULL) {
585 memset(&ti, 0, sizeof(ti));
587 // check if it's a valid mds file
588 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
591 if (i != 0x4944454D) {
592 // not an valid mds file
597 // get offset to session block
598 fseek(fi, 0x50, SEEK_SET);
599 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
601 offset = SWAP32(offset);
603 // get total number of tracks
605 fseek(fi, offset, SEEK_SET);
606 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
611 // get offset to track blocks
612 fseek(fi, 4, SEEK_CUR);
613 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
615 offset = SWAP32(offset);
619 fseek(fi, offset + 4, SEEK_SET);
620 if (fgetc(fi) < 0xA0) {
626 // check if the image contains mixed subchannel data
627 fseek(fi, offset + 1, SEEK_SET);
628 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
631 for (i = 1; i <= numtracks; i++) {
632 fseek(fi, offset, SEEK_SET);
634 // get the track type
635 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
636 fseek(fi, 8, SEEK_CUR);
638 // get the track starting point
639 ti[i].start[0] = fgetc(fi);
640 ti[i].start[1] = fgetc(fi);
641 ti[i].start[2] = fgetc(fi);
643 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
645 extra_offset = SWAP32(extra_offset);
647 // get track start offset (in .mdf)
648 fseek(fi, offset + 0x28, SEEK_SET);
649 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
652 ti[i].start_offset = l;
655 fseek(fi, extra_offset, SEEK_SET);
656 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
660 pregapOffset = msf2sec(ti[i].start);
662 // get the track length
663 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
666 sec2msf(l, ti[i].length);
674 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
680 static int handlepbp(const char *isofile) {
683 unsigned int dontcare[8];
684 unsigned int psar_offs;
697 unsigned int dontcare[6];
700 off_t psisoimg_offs, cdimg_base;
701 unsigned int t, cd_length;
702 unsigned int offsettab[8];
703 unsigned int psar_offs, index_entry_size, index_entry_offset;
704 const char *ext = NULL;
707 if (strlen(isofile) >= 4)
708 ext = isofile + strlen(isofile) - 4;
709 if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
714 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
715 if (ret != sizeof(pbp_hdr)) {
716 SysPrintf("failed to read pbp\n");
720 psar_offs = SWAP32(pbp_hdr.psar_offs);
722 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
724 SysPrintf("failed to seek to %x\n", psar_offs);
728 psisoimg_offs = psar_offs;
729 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
732 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
734 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
736 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
740 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
741 SysPrintf("failed to read offsettab\n");
745 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
746 if (offsettab[i] == 0)
749 cdrIsoMultidiskCount = i;
750 if (cdrIsoMultidiskCount == 0) {
751 SysPrintf("multidisk eboot has 0 images?\n");
755 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
756 cdrIsoMultidiskSelect = 0;
758 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
760 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
762 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
766 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
771 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
772 SysPrintf("bad psar_sig: %s\n", psar_sig);
777 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
779 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
783 // first 3 entries are special
784 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
785 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
787 numtracks = btoi(toc_entry.index1[0]);
789 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
791 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
792 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
794 for (i = 1; i <= numtracks; i++) {
795 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
798 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
800 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
801 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
802 ti[i].start_offset *= 2352;
803 ti[i].start[0] = btoi(toc_entry.index1[0]);
804 ti[i].start[1] = btoi(toc_entry.index1[1]);
805 ti[i].start[2] = btoi(toc_entry.index1[2]);
808 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
809 sec2msf(t, ti[i - 1].length);
812 t = cd_length - ti[numtracks].start_offset / 2352;
813 sec2msf(t, ti[numtracks].length);
816 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
818 SysPrintf("failed to seek to ISO index\n");
822 compr_img = calloc(1, sizeof(*compr_img));
823 if (compr_img == NULL)
826 compr_img->block_shift = 4;
827 compr_img->current_block = (unsigned int)-1;
829 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
830 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
831 if (compr_img->index_table == NULL)
834 cdimg_base = psisoimg_offs + 0x100000;
835 for (i = 0; i < compr_img->index_len; i++) {
836 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
837 if (ret != sizeof(index_entry)) {
838 SysPrintf("failed to read index_entry #%d\n", i);
842 index_entry_size = SWAP32(index_entry.size);
843 index_entry_offset = SWAP32(index_entry.offset);
845 if (index_entry_size == 0)
848 compr_img->index_table[i] = cdimg_base + index_entry_offset;
850 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
855 free(compr_img->index_table);
856 compr_img->index_table = NULL;
860 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
864 if (compr_img != NULL) {
871 static int handlecbin(const char *isofile) {
875 unsigned int header_size;
876 unsigned long long total_bytes;
877 unsigned int block_size;
878 unsigned char ver; // 1
880 unsigned char rsv_06[2];
882 const char *ext = NULL;
883 unsigned int *index_table = NULL;
884 unsigned int index = 0, plain;
887 if (strlen(isofile) >= 5)
888 ext = isofile + strlen(isofile) - 5;
889 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
892 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
893 if (ret != sizeof(ciso_hdr)) {
894 SysPrintf("failed to read ciso header\n");
898 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
899 SysPrintf("bad ciso header\n");
902 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
903 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
905 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
910 compr_img = calloc(1, sizeof(*compr_img));
911 if (compr_img == NULL)
914 compr_img->block_shift = 0;
915 compr_img->current_block = (unsigned int)-1;
917 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
918 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
919 if (index_table == NULL)
922 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
923 if (ret != compr_img->index_len) {
924 SysPrintf("failed to read index table\n");
928 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
929 if (compr_img->index_table == NULL)
932 for (i = 0; i < compr_img->index_len + 1; i++) {
933 index = index_table[i];
934 plain = index & 0x80000000;
936 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
938 compr_img->index_table[i] |= OFF_T_MSB;
946 if (compr_img != NULL) {
955 static int handlechd(const char *isofile) {
956 int frame_offset = 150;
959 chd_img = calloc(1, sizeof(*chd_img));
963 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
966 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
969 chd_img->header = chd_get_header(chd_img->chd);
971 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
972 if (chd_img->buffer == NULL)
975 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
976 chd_img->current_hunk[0] = (unsigned int)-1;
977 chd_img->current_hunk[1] = (unsigned int)-1;
979 cddaBigEndian = TRUE;
982 memset(ti, 0, sizeof(ti));
997 uint32_t meta_size = 0;
999 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1000 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1001 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1002 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1006 SysPrintf("chd: %s\n", meta);
1008 if (md.track == 1) {
1009 if (!strncmp(md.subtype, "RW", 2)) {
1010 subChanMixed = TRUE;
1011 if (!strcmp(md.subtype, "RW_RAW"))
1016 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1018 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1019 sec2msf(md.frames, ti[md.track].length);
1021 ti[md.track].start_offset = file_offset + md.pregap;
1023 // XXX: what about postgap?
1024 frame_offset += md.frames;
1025 file_offset += md.frames;
1033 if (chd_img != NULL) {
1034 free(chd_img->buffer);
1042 // this function tries to get the .sub file of the given .img
1043 static int opensubfile(const char *isoname) {
1044 char subname[MAXPATHLEN];
1046 // copy name of the iso and change extension from .img to .sub
1047 strncpy(subname, isoname, sizeof(subname));
1048 subname[MAXPATHLEN - 1] = '\0';
1049 if (strlen(subname) >= 4) {
1050 strcpy(subname + strlen(subname) - 4, ".sub");
1056 subHandle = fopen(subname, "rb");
1057 if (subHandle == NULL) {
1064 static int opensbifile(const char *isoname) {
1065 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1068 strncpy(sbiname, isoname, sizeof(sbiname));
1069 sbiname[MAXPATHLEN - 1] = '\0';
1070 if (strlen(sbiname) >= 4) {
1071 if (cdrIsoMultidiskCount > 1) {
1072 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1073 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1076 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1082 s = msf2sec(ti[1].length);
1084 return LoadSBI(sbiname, s);
1087 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1092 if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1094 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1100 // often happens in cdda gaps of a split cue/bin, so not logged
1101 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1105 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1111 if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1113 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1119 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1123 static int cdread_sub_sub_mixed(FILE *f, int sector)
1127 if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1129 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1132 return SUB_FRAMESIZE;
1135 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1139 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1144 if (z.zalloc == NULL) {
1145 // XXX: one-time leak here..
1151 ret = inflateInit2(&z, -15);
1154 ret = inflateReset(&z);
1159 z.avail_in = in_size;
1161 z.avail_out = *out_size;
1163 ret = inflate(&z, Z_NO_FLUSH);
1166 *out_size -= z.avail_out;
1167 return ret == 1 ? 0 : ret;
1170 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1172 unsigned long cdbuffer_size, cdbuffer_size_expect;
1181 sector += base / 2352;
1183 block = sector >> compr_img->block_shift;
1184 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1186 if (block == compr_img->current_block) {
1187 //printf("hit sect %d\n", sector);
1191 if (sector >= compr_img->index_len * 16) {
1192 SysPrintf("sector %d is past img end\n", sector);
1196 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1197 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1198 SysPrintf("seek error for block %d at %llx: ",
1199 block, (long long)start_byte);
1204 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1205 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1206 if (size > sizeof(compr_img->buff_compressed)) {
1207 SysPrintf("block %d is too large: %u\n", block, size);
1211 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1212 1, size, cdHandle) != size) {
1213 SysPrintf("read error for block %d at %x: ", block, start_byte);
1218 if (is_compressed) {
1219 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1220 cdbuffer_size = cdbuffer_size_expect;
1221 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1223 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1224 ret, block, sector);
1227 if (cdbuffer_size != cdbuffer_size_expect)
1228 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1229 cdbuffer_size_expect, sector);
1233 compr_img->current_block = block;
1236 if (dest != cdbuffer) // copy avoid HACK
1237 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1239 return CD_FRAMESIZE_RAW;
1243 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1245 return chd_img->buffer
1246 + current_buffer * chd_img->header->hunkbytes
1247 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1250 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1256 hunk = sector / chd_img->sectors_per_hunk;
1257 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1259 if (hunk == chd_img->current_hunk[0])
1260 chd_img->current_buffer = 0;
1261 else if (hunk == chd_img->current_hunk[1])
1262 chd_img->current_buffer = 1;
1265 chd_read(chd_img->chd, hunk, chd_img->buffer +
1266 chd_img->current_buffer * chd_img->header->hunkbytes);
1267 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1270 if (dest != cdbuffer) // copy avoid HACK
1271 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1273 return CD_FRAMESIZE_RAW;
1276 static int cdread_sub_chd(FILE *f, int sector)
1278 unsigned int sector_in_hunk;
1279 unsigned int buffer;
1285 hunk = sector / chd_img->sectors_per_hunk;
1286 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1288 if (hunk == chd_img->current_hunk[0])
1290 else if (hunk == chd_img->current_hunk[1])
1294 buffer = chd_img->current_buffer ^ 1;
1295 chd_read(chd_img->chd, hunk, chd_img->buffer +
1296 buffer * chd_img->header->hunkbytes);
1297 chd_img->current_hunk[buffer] = hunk;
1300 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1301 return SUB_FRAMESIZE;
1305 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1311 fseeko(f, base + sector * 2048, SEEK_SET);
1312 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1314 // not really necessary, fake mode 2 header
1315 memset(cdbuffer, 0, 12 * 2);
1316 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1317 cdbuffer[12 + 3] = 1;
1322 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1323 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1327 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1328 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1332 static unsigned char * CALLBACK ISOgetBuffer(void) {
1333 return cdbuffer + 12;
1336 static void PrintTracks(void) {
1339 for (i = 1; i <= numtracks; i++) {
1340 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1341 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1342 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1343 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1347 // This function is invoked by the front-end when opening an ISO
1348 // file for playback
1349 static long CALLBACK ISOopen(void) {
1350 boolean isMode1ISO = FALSE;
1351 char alt_bin_filename[MAXPATHLEN];
1352 const char *bin_filename;
1353 char image_str[1024];
1356 if (cdHandle || chd_img) {
1357 return 0; // it's already open
1360 cdHandle = fopen(GetIsoFile(), "rb");
1361 if (cdHandle == NULL) {
1362 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1363 GetIsoFile(), strerror(errno));
1366 size_main = get_size(cdHandle);
1368 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1369 "Loaded CD Image: %s", GetIsoFile());
1371 cddaBigEndian = FALSE;
1372 subChanMixed = FALSE;
1375 cdrIsoMultidiskCount = 1;
1378 CDR_getBuffer = ISOgetBuffer;
1379 cdimg_read_func = cdread_normal;
1380 cdimg_read_sub_func = NULL;
1382 if (parsetoc(GetIsoFile()) == 0) {
1383 strcat(image_str, "[+toc]");
1385 else if (parseccd(GetIsoFile()) == 0) {
1386 strcat(image_str, "[+ccd]");
1388 else if (parsemds(GetIsoFile()) == 0) {
1389 strcat(image_str, "[+mds]");
1391 else if (parsecue(GetIsoFile()) == 0) {
1392 strcat(image_str, "[+cue]");
1394 if (handlepbp(GetIsoFile()) == 0) {
1395 strcat(image_str, "[+pbp]");
1396 CDR_getBuffer = ISOgetBuffer_compr;
1397 cdimg_read_func = cdread_compressed;
1399 else if (handlecbin(GetIsoFile()) == 0) {
1400 strcat(image_str, "[+cbin]");
1401 CDR_getBuffer = ISOgetBuffer_compr;
1402 cdimg_read_func = cdread_compressed;
1405 else if (handlechd(GetIsoFile()) == 0) {
1406 strcat(image_str, "[+chd]");
1407 CDR_getBuffer = ISOgetBuffer_chd;
1408 cdimg_read_func = cdread_chd;
1409 cdimg_read_sub_func = cdread_sub_chd;
1415 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1416 strcat(image_str, "[+sub]");
1418 if (opensbifile(GetIsoFile()) == 0) {
1419 strcat(image_str, "[+sbi]");
1422 // maybe user selected metadata file instead of main .bin ..
1423 bin_filename = GetIsoFile();
1424 if (cdHandle && size_main < 2352 * 0x10) {
1425 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1430 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1431 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1432 if (strlen(alt_bin_filename) >= 4) {
1433 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1434 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1436 tmpf = fopen(alt_bin_filename, "rb");
1442 bin_filename = alt_bin_filename;
1445 size_main = get_size(cdHandle);
1449 // guess whether it is mode1/2048
1450 if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1451 unsigned int modeTest = 0;
1452 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1453 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1455 if (SWAP32(modeTest) != 0xffffff00) {
1456 strcat(image_str, "[2048]");
1461 SysPrintf("%s.\n", image_str);
1465 if (subChanMixed && cdimg_read_func == cdread_normal) {
1466 cdimg_read_func = cdread_sub_mixed;
1467 cdimg_read_sub_func = cdread_sub_sub_mixed;
1469 else if (isMode1ISO) {
1470 cdimg_read_func = cdread_2048;
1471 cdimg_read_sub_func = NULL;
1477 static long CALLBACK ISOclose(void) {
1480 if (cdHandle != NULL) {
1484 if (subHandle != NULL) {
1491 if (compr_img != NULL) {
1492 free(compr_img->index_table);
1498 if (chd_img != NULL) {
1499 chd_close(chd_img->chd);
1500 free(chd_img->buffer);
1506 for (i = 1; i <= numtracks; i++) {
1507 if (ti[i].handle != NULL) {
1508 fclose(ti[i].handle);
1509 ti[i].handle = NULL;
1516 memset(cdbuffer, 0, sizeof(cdbuffer));
1517 CDR_getBuffer = ISOgetBuffer;
1522 static long CALLBACK ISOinit(void) {
1523 assert(cdHandle == NULL);
1524 assert(subHandle == NULL);
1526 return 0; // do nothing
1529 static long CALLBACK ISOshutdown(void) {
1534 // return Starting and Ending Track
1536 // byte 0 - start track
1537 // byte 1 - end track
1538 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1541 if (numtracks > 0) {
1542 buffer[1] = numtracks;
1551 // return Track Time
1556 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1559 unsigned char time[3];
1560 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1561 sec2msf(sect, (char *)time);
1562 buffer[2] = time[0];
1563 buffer[1] = time[1];
1564 buffer[0] = time[2];
1566 else if (numtracks > 0 && track <= numtracks) {
1567 buffer[2] = ti[track].start[0];
1568 buffer[1] = ti[track].start[1];
1569 buffer[0] = ti[track].start[2];
1580 // decode 'raw' subchannel data ripped by cdrdao
1581 static void DecodeRawSubData(void) {
1582 unsigned char subQData[12];
1585 memset(subQData, 0, sizeof(subQData));
1587 for (i = 0; i < 8 * 12; i++) {
1588 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1589 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1593 memcpy(&subbuffer[12], subQData, 12);
1597 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1599 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1600 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1603 if (!cdHandle && !chd_img)
1606 if (pregapOffset && sector >= pregapOffset)
1609 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1610 if (ret < 12*2 + 2048)
1617 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1618 // does NOT uses bcd format
1619 static long CALLBACK ISOplay(unsigned char *time) {
1625 static long CALLBACK ISOstop(void) {
1630 // gets subchannel data
1631 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1632 if (pregapOffset && sector >= pregapOffset) {
1634 if (sector < pregapOffset) // ?
1638 if (cdimg_read_sub_func != NULL) {
1639 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1642 else if (subHandle != NULL) {
1643 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1645 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1652 if (subChanRaw) DecodeRawSubData();
1656 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1659 CDR__getStatus(stat);
1663 stat->Status |= 0x80;
1666 // BIOS - boot ID (CD type)
1667 stat->Type = ti[1].type;
1670 // relative -> absolute time
1672 sec2msf(sect, (char *)stat->Time);
1677 // read CDDA sector into buffer
1678 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1679 unsigned char msf[3] = {m, s, f};
1680 unsigned int track, track_start = 0;
1681 FILE *handle = cdHandle;
1684 cddaCurPos = msf2sec((char *)msf);
1686 // find current track index
1687 for (track = numtracks; ; track--) {
1688 track_start = msf2sec(ti[track].start);
1689 if (track_start <= cddaCurPos)
1695 // data tracks play silent
1696 if (ti[track].type != CDDA) {
1697 memset(buffer, 0, CD_FRAMESIZE_RAW);
1702 // find the file that contains this track
1704 for (file = track; file > 1; file--) {
1705 if (ti[file].handle != NULL) {
1706 handle = ti[file].handle;
1712 memset(buffer, 0, CD_FRAMESIZE_RAW);
1716 ret = cdimg_read_func(handle, ti[track].start_offset,
1717 buffer, cddaCurPos - track_start);
1718 if (ret != CD_FRAMESIZE_RAW) {
1719 memset(buffer, 0, CD_FRAMESIZE_RAW);
1723 if (cddaBigEndian) {
1727 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1728 tmp = buffer[i * 2];
1729 buffer[i * 2] = buffer[i * 2 + 1];
1730 buffer[i * 2 + 1] = tmp;
1737 void cdrIsoInit(void) {
1739 CDR_shutdown = ISOshutdown;
1741 CDR_close = ISOclose;
1742 CDR_getTN = ISOgetTN;
1743 CDR_getTD = ISOgetTD;
1744 CDR_readTrack = ISOreadTrack;
1745 CDR_getBuffer = ISOgetBuffer;
1748 CDR_getBufferSub = ISOgetBufferSub;
1749 CDR_getStatus = ISOgetStatus;
1750 CDR_readCDDA = ISOreadCDDA;
1752 CDR_getDriveLetter = CDR__getDriveLetter;
1753 CDR_configure = CDR__configure;
1754 CDR_test = CDR__test;
1755 CDR_about = CDR__about;
1756 CDR_setfilename = CDR__setfilename;
1761 int cdrIsoActive(void) {
1762 return (cdHandle || chd_img);