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 WIN32_LEAN_AND_MEAN
32 #define strcasecmp _stricmp
33 #define usleep(x) Sleep((x) / 1000)
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;
96 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
97 static int (*cdimg_read_sub_func)(FILE *f, int sector);
99 char* CALLBACK CDR__getDriveLetter(void);
100 long CALLBACK CDR__configure(void);
101 long CALLBACK CDR__test(void);
102 void CALLBACK CDR__about(void);
103 long CALLBACK CDR__setfilename(char *filename);
104 long CALLBACK CDR__getStatus(struct CdrStat *stat);
106 static void DecodeRawSubData(void);
109 enum {DATA=1, CDDA} type;
110 char start[3]; // MSF-format
111 char length[3]; // MSF-format
112 FILE *handle; // for multi-track images CDDA
113 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
116 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
118 static int numtracks = 0;
119 static struct trackinfo ti[MAXTRACKS];
121 // get a sector from a msf-array
122 static unsigned int msf2sec(char *msf) {
123 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
126 static void sec2msf(unsigned int s, char *msf) {
127 msf[0] = s / 75 / 60;
128 s = s - msf[0] * 75 * 60;
134 // divide a string of xx:yy:zz into m, s, f
135 static void tok2msf(char *time, char *msf) {
138 token = strtok(time, ":");
140 msf[0] = atoi(token);
146 token = strtok(NULL, ":");
148 msf[1] = atoi(token);
154 token = strtok(NULL, ":");
156 msf[2] = atoi(token);
163 // this function tries to get the .toc file of the given .bin
164 // the necessary data is put into the ti (trackinformation)-array
165 static int parsetoc(const char *isofile) {
166 char tocname[MAXPATHLEN];
168 char linebuf[256], tmp[256], name[256];
170 char time[20], time2[20];
171 unsigned int t, sector_offs, sector_size;
172 unsigned int current_zero_gap = 0;
176 // copy name of the iso and change extension from .bin to .toc
177 strncpy(tocname, isofile, sizeof(tocname));
178 tocname[MAXPATHLEN - 1] = '\0';
179 if (strlen(tocname) >= 4) {
180 strcpy(tocname + strlen(tocname) - 4, ".toc");
186 if ((fi = fopen(tocname, "r")) == NULL) {
187 // try changing extension to .cue (to satisfy some stupid tutorials)
188 strcpy(tocname + strlen(tocname) - 4, ".cue");
189 if ((fi = fopen(tocname, "r")) == NULL) {
190 // if filename is image.toc.bin, try removing .bin (for Brasero)
191 strcpy(tocname, isofile);
193 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
194 tocname[t - 4] = '\0';
195 if ((fi = fopen(tocname, "r")) == NULL) {
203 // check if it's really a TOC named as a .cue
204 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
205 token = strtok(linebuf, " ");
206 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
211 fseek(fi, 0, SEEK_SET);
214 memset(&ti, 0, sizeof(ti));
215 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
217 sector_size = CD_FRAMESIZE_RAW;
218 sector_offs = 2 * 75;
220 // parse the .toc file
221 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
223 strncpy(tmp, linebuf, sizeof(linebuf));
224 token = strtok(tmp, " ");
226 if (token == NULL) continue;
228 if (!strcmp(token, "TRACK")) {
229 sector_offs += current_zero_gap;
230 current_zero_gap = 0;
233 token = strtok(NULL, " ");
236 if (!strncmp(token, "MODE2_RAW", 9)) {
237 ti[numtracks].type = DATA;
238 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
240 // check if this image contains mixed subchannel data
241 token = strtok(NULL, " ");
242 if (token != NULL && !strncmp(token, "RW", 2)) {
243 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
245 if (!strncmp(token, "RW_RAW", 6))
249 else if (!strncmp(token, "AUDIO", 5)) {
250 ti[numtracks].type = CDDA;
253 else if (!strcmp(token, "DATAFILE")) {
254 if (ti[numtracks].type == CDDA) {
255 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
256 ti[numtracks].start_offset = t;
257 t = t / sector_size + sector_offs;
258 sec2msf(t, (char *)&ti[numtracks].start);
259 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
262 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
263 tok2msf((char *)&time, (char *)&ti[numtracks].length);
266 else if (!strcmp(token, "FILE")) {
267 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
268 tok2msf((char *)&time, (char *)&ti[numtracks].start);
269 t += msf2sec(ti[numtracks].start) * sector_size;
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);
275 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
276 // skip unneeded optional fields
277 while (token != NULL) {
278 token = strtok(NULL, " ");
279 if (strchr(token, ':') != NULL)
284 current_zero_gap = msf2sec(tmp);
287 t = ti[numtracks - 1].start_offset;
289 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
292 else if (!strcmp(token, "START")) {
293 token = strtok(NULL, " ");
294 if (token != NULL && strchr(token, ':')) {
297 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
298 t = msf2sec(ti[numtracks].start) + t;
299 sec2msf(t, (char *)&ti[numtracks].start);
309 // this function tries to get the .cue file of the given .bin
310 // the necessary data is put into the ti (trackinformation)-array
311 static int parsecue(const char *isofile) {
312 char cuename[MAXPATHLEN];
313 char filepath[MAXPATHLEN];
319 char linebuf[256], tmpb[256], dummy[256];
320 unsigned int incue_max_len;
321 unsigned int t, file_len, mode, sector_offs;
322 unsigned int sector_size = 2352;
326 // copy name of the iso and change extension from .bin to .cue
327 strncpy(cuename, isofile, sizeof(cuename));
328 cuename[MAXPATHLEN - 1] = '\0';
329 if (strlen(cuename) >= 4) {
330 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
331 // and don't try to search the additional .cue file
332 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
333 strcpy(cuename + strlen(cuename) - 4, ".cue");
339 if ((fi = fopen(cuename, "r")) == NULL) {
343 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
344 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
346 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
347 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
348 // Don't proceed further, as this is actually a .toc file rather
351 return parsetoc(isofile);
353 fseek(fi, 0, SEEK_SET);
356 // build a path for files referenced in .cue
357 strncpy(filepath, cuename, sizeof(filepath));
358 tmp = strrchr(filepath, '/');
360 tmp = strrchr(filepath, '\\');
366 filepath[sizeof(filepath) - 1] = 0;
368 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
370 memset(&ti, 0, sizeof(ti));
373 sector_offs = 2 * 75;
375 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
376 strncpy(dummy, linebuf, sizeof(linebuf));
377 token = strtok(dummy, " ");
383 if (!strcmp(token, "TRACK")) {
387 if (strstr(linebuf, "AUDIO") != NULL) {
388 ti[numtracks].type = CDDA;
391 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
392 ti[numtracks].type = DATA;
394 SysPrintf(".cue: failed to parse TRACK\n");
395 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
397 if (sector_size == 0)
400 else if (!strcmp(token, "INDEX")) {
401 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
402 SysPrintf(".cue: failed to parse INDEX\n");
403 tok2msf(time, (char *)&ti[numtracks].start);
405 t = msf2sec(ti[numtracks].start);
406 ti[numtracks].start_offset = t * sector_size;
408 sec2msf(t, ti[numtracks].start);
410 // default track length to file length
411 t = file_len - ti[numtracks].start_offset / sector_size;
412 sec2msf(t, ti[numtracks].length);
414 if (numtracks > 1 && ti[numtracks].handle == NULL) {
415 // this track uses the same file as the last,
416 // start of this track is last track's end
417 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
418 sec2msf(t, ti[numtracks - 1].length);
420 if (numtracks > 1 && pregapOffset == -1)
421 pregapOffset = ti[numtracks].start_offset / sector_size;
423 else if (!strcmp(token, "PREGAP")) {
424 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
425 tok2msf(time, dummy);
426 sector_offs += msf2sec(dummy);
428 pregapOffset = -1; // mark to fill track start_offset
430 else if (!strcmp(token, "FILE")) {
431 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
433 sscanf(linebuf, " FILE %255s", tmpb);
436 ti[numtracks + 1].handle = fopen(tmpb, "rb");
437 if (ti[numtracks + 1].handle == NULL) {
439 tmp = strrchr(tmpb, '\\');
441 tmp = strrchr(tmpb, '/');
446 strncpy(incue_fname, tmp, incue_max_len);
447 ti[numtracks + 1].handle = fopen(filepath, "rb");
450 // update global offset if this is not first file in this .cue
451 if (numtracks + 1 > 1) {
453 sector_offs += file_len;
457 if (ti[numtracks + 1].handle == NULL) {
458 SysPrintf(_("\ncould not open: %s\n"), filepath);
461 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
462 file_len = ftell(ti[numtracks + 1].handle) / 2352;
464 if (numtracks == 0 && strlen(isofile) >= 4 &&
465 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
466 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
467 // user selected .cue/.cdX as image file, use it's data track instead
469 cdHandle = fopen(filepath, "rb");
476 // if there are no tracks detected, then it's not a cue file
483 // this function tries to get the .ccd file of the given .img
484 // the necessary data is put into the ti (trackinformation)-array
485 static int parseccd(const char *isofile) {
486 char ccdname[MAXPATHLEN];
493 // copy name of the iso and change extension from .img to .ccd
494 strncpy(ccdname, isofile, sizeof(ccdname));
495 ccdname[MAXPATHLEN - 1] = '\0';
496 if (strlen(ccdname) >= 4) {
497 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
503 if ((fi = fopen(ccdname, "r")) == NULL) {
507 memset(&ti, 0, sizeof(ti));
509 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
510 if (!strncmp(linebuf, "[TRACK", 6)){
513 else if (!strncmp(linebuf, "MODE=", 5)) {
514 sscanf(linebuf, "MODE=%d", &t);
515 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
517 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
518 sscanf(linebuf, "INDEX 1=%d", &t);
519 sec2msf(t + 2 * 75, ti[numtracks].start);
520 ti[numtracks].start_offset = t * 2352;
522 // If we've already seen another track, this is its end
524 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
525 sec2msf(t, ti[numtracks - 1].length);
532 // Fill out the last track's end based on size
533 if (numtracks >= 1) {
534 fseek(cdHandle, 0, SEEK_END);
535 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
536 sec2msf(t, ti[numtracks].length);
542 // this function tries to get the .mds file of the given .mdf
543 // the necessary data is put into the ti (trackinformation)-array
544 static int parsemds(const char *isofile) {
545 char mdsname[MAXPATHLEN];
547 unsigned int offset, extra_offset, l, i;
552 // copy name of the iso and change extension from .mdf to .mds
553 strncpy(mdsname, isofile, sizeof(mdsname));
554 mdsname[MAXPATHLEN - 1] = '\0';
555 if (strlen(mdsname) >= 4) {
556 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
562 if ((fi = fopen(mdsname, "rb")) == NULL) {
566 memset(&ti, 0, sizeof(ti));
568 // check if it's a valid mds file
569 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
572 if (i != 0x4944454D) {
573 // not an valid mds file
578 // get offset to session block
579 fseek(fi, 0x50, SEEK_SET);
580 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
582 offset = SWAP32(offset);
584 // get total number of tracks
586 fseek(fi, offset, SEEK_SET);
587 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
592 // get offset to track blocks
593 fseek(fi, 4, SEEK_CUR);
594 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
596 offset = SWAP32(offset);
600 fseek(fi, offset + 4, SEEK_SET);
601 if (fgetc(fi) < 0xA0) {
607 // check if the image contains mixed subchannel data
608 fseek(fi, offset + 1, SEEK_SET);
609 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
612 for (i = 1; i <= numtracks; i++) {
613 fseek(fi, offset, SEEK_SET);
615 // get the track type
616 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
617 fseek(fi, 8, SEEK_CUR);
619 // get the track starting point
620 ti[i].start[0] = fgetc(fi);
621 ti[i].start[1] = fgetc(fi);
622 ti[i].start[2] = fgetc(fi);
624 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
626 extra_offset = SWAP32(extra_offset);
628 // get track start offset (in .mdf)
629 fseek(fi, offset + 0x28, SEEK_SET);
630 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
633 ti[i].start_offset = l;
636 fseek(fi, extra_offset, SEEK_SET);
637 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
641 pregapOffset = msf2sec(ti[i].start);
643 // get the track length
644 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
647 sec2msf(l, ti[i].length);
655 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
661 static int handlepbp(const char *isofile) {
664 unsigned int dontcare[8];
665 unsigned int psar_offs;
678 unsigned int dontcare[6];
681 off_t psisoimg_offs, cdimg_base;
682 unsigned int t, cd_length;
683 unsigned int offsettab[8];
684 unsigned int psar_offs, index_entry_size, index_entry_offset;
685 const char *ext = NULL;
688 if (strlen(isofile) >= 4)
689 ext = isofile + strlen(isofile) - 4;
690 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
693 fseeko(cdHandle, 0, SEEK_SET);
697 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
698 if (ret != sizeof(pbp_hdr)) {
699 SysPrintf("failed to read pbp\n");
703 psar_offs = SWAP32(pbp_hdr.psar_offs);
705 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
707 SysPrintf("failed to seek to %x\n", psar_offs);
711 psisoimg_offs = psar_offs;
712 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
715 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
717 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
719 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
723 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
724 SysPrintf("failed to read offsettab\n");
728 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
729 if (offsettab[i] == 0)
732 cdrIsoMultidiskCount = i;
733 if (cdrIsoMultidiskCount == 0) {
734 SysPrintf("multidisk eboot has 0 images?\n");
738 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
739 cdrIsoMultidiskSelect = 0;
741 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
743 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
745 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
749 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
754 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
755 SysPrintf("bad psar_sig: %s\n", psar_sig);
760 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
762 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
766 // first 3 entries are special
767 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
768 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
770 numtracks = btoi(toc_entry.index1[0]);
772 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
774 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
775 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
777 for (i = 1; i <= numtracks; i++) {
778 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
781 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
783 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
784 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
785 ti[i].start_offset *= 2352;
786 ti[i].start[0] = btoi(toc_entry.index1[0]);
787 ti[i].start[1] = btoi(toc_entry.index1[1]);
788 ti[i].start[2] = btoi(toc_entry.index1[2]);
791 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
792 sec2msf(t, ti[i - 1].length);
795 t = cd_length - ti[numtracks].start_offset / 2352;
796 sec2msf(t, ti[numtracks].length);
799 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
801 SysPrintf("failed to seek to ISO index\n");
805 compr_img = calloc(1, sizeof(*compr_img));
806 if (compr_img == NULL)
809 compr_img->block_shift = 4;
810 compr_img->current_block = (unsigned int)-1;
812 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
813 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
814 if (compr_img->index_table == NULL)
817 cdimg_base = psisoimg_offs + 0x100000;
818 for (i = 0; i < compr_img->index_len; i++) {
819 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
820 if (ret != sizeof(index_entry)) {
821 SysPrintf("failed to read index_entry #%d\n", i);
825 index_entry_size = SWAP32(index_entry.size);
826 index_entry_offset = SWAP32(index_entry.offset);
828 if (index_entry_size == 0)
831 compr_img->index_table[i] = cdimg_base + index_entry_offset;
833 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
838 free(compr_img->index_table);
839 compr_img->index_table = NULL;
844 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
848 if (compr_img != NULL) {
855 static int handlecbin(const char *isofile) {
859 unsigned int header_size;
860 unsigned long long total_bytes;
861 unsigned int block_size;
862 unsigned char ver; // 1
864 unsigned char rsv_06[2];
866 const char *ext = NULL;
867 unsigned int *index_table = NULL;
868 unsigned int index = 0, plain;
871 if (strlen(isofile) >= 5)
872 ext = isofile + strlen(isofile) - 5;
873 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
876 fseek(cdHandle, 0, SEEK_SET);
878 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
879 if (ret != sizeof(ciso_hdr)) {
880 SysPrintf("failed to read ciso header\n");
884 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
885 SysPrintf("bad ciso header\n");
888 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
889 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
891 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
896 compr_img = calloc(1, sizeof(*compr_img));
897 if (compr_img == NULL)
900 compr_img->block_shift = 0;
901 compr_img->current_block = (unsigned int)-1;
903 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
904 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
905 if (index_table == NULL)
908 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
909 if (ret != compr_img->index_len) {
910 SysPrintf("failed to read index table\n");
914 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
915 if (compr_img->index_table == NULL)
918 for (i = 0; i < compr_img->index_len + 1; i++) {
919 index = index_table[i];
920 plain = index & 0x80000000;
922 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
924 compr_img->index_table[i] |= OFF_T_MSB;
932 if (compr_img != NULL) {
940 static int handlechd(const char *isofile) {
941 int frame_offset = 150;
944 chd_img = calloc(1, sizeof(*chd_img));
948 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
951 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
954 chd_img->header = chd_get_header(chd_img->chd);
956 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
957 if (chd_img->buffer == NULL)
960 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
961 chd_img->current_hunk[0] = (unsigned int)-1;
962 chd_img->current_hunk[1] = (unsigned int)-1;
964 cddaBigEndian = TRUE;
967 memset(ti, 0, sizeof(ti));
982 uint32_t meta_size = 0;
984 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
985 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
986 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
987 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
991 SysPrintf("chd: %s\n", meta);
994 if (!strncmp(md.subtype, "RW", 2)) {
996 if (!strcmp(md.subtype, "RW_RAW"))
1001 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1003 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1004 sec2msf(md.frames, ti[md.track].length);
1006 ti[md.track].start_offset = file_offset + md.pregap;
1008 // XXX: what about postgap?
1009 frame_offset += md.frames;
1010 file_offset += md.frames;
1018 if (chd_img != NULL) {
1019 free(chd_img->buffer);
1027 // this function tries to get the .sub file of the given .img
1028 static int opensubfile(const char *isoname) {
1029 char subname[MAXPATHLEN];
1031 // copy name of the iso and change extension from .img to .sub
1032 strncpy(subname, isoname, sizeof(subname));
1033 subname[MAXPATHLEN - 1] = '\0';
1034 if (strlen(subname) >= 4) {
1035 strcpy(subname + strlen(subname) - 4, ".sub");
1041 subHandle = fopen(subname, "rb");
1042 if (subHandle == NULL) {
1049 static int opensbifile(const char *isoname) {
1050 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1053 strncpy(sbiname, isoname, sizeof(sbiname));
1054 sbiname[MAXPATHLEN - 1] = '\0';
1055 if (strlen(sbiname) >= 4) {
1056 if (cdrIsoMultidiskCount > 1) {
1057 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1058 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1061 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1067 fseek(cdHandle, 0, SEEK_END);
1068 s = ftell(cdHandle) / 2352;
1070 return LoadSBI(sbiname, s);
1073 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1076 if (fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1078 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1084 // often happens in cdda gaps of a split cue/bin, so not logged
1085 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1089 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1093 if (fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1095 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1101 //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1105 static int cdread_sub_sub_mixed(FILE *f, int sector)
1107 if (fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1109 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1112 return SUB_FRAMESIZE;
1115 SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1119 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1124 if (z.zalloc == NULL) {
1125 // XXX: one-time leak here..
1131 ret = inflateInit2(&z, -15);
1134 ret = inflateReset(&z);
1139 z.avail_in = in_size;
1141 z.avail_out = *out_size;
1143 ret = inflate(&z, Z_NO_FLUSH);
1146 *out_size -= z.avail_out;
1147 return ret == 1 ? 0 : ret;
1150 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1152 unsigned long cdbuffer_size, cdbuffer_size_expect;
1159 sector += base / 2352;
1161 block = sector >> compr_img->block_shift;
1162 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1164 if (block == compr_img->current_block) {
1165 //printf("hit sect %d\n", sector);
1169 if (sector >= compr_img->index_len * 16) {
1170 SysPrintf("sector %d is past img end\n", sector);
1174 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1175 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1176 SysPrintf("seek error for block %d at %llx: ",
1177 block, (long long)start_byte);
1182 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1183 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1184 if (size > sizeof(compr_img->buff_compressed)) {
1185 SysPrintf("block %d is too large: %u\n", block, size);
1189 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1190 1, size, cdHandle) != size) {
1191 SysPrintf("read error for block %d at %x: ", block, start_byte);
1196 if (is_compressed) {
1197 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1198 cdbuffer_size = cdbuffer_size_expect;
1199 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1201 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1202 ret, block, sector);
1205 if (cdbuffer_size != cdbuffer_size_expect)
1206 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1207 cdbuffer_size_expect, sector);
1211 compr_img->current_block = block;
1214 if (dest != cdbuffer) // copy avoid HACK
1215 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1217 return CD_FRAMESIZE_RAW;
1221 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1223 return chd_img->buffer
1224 + current_buffer * chd_img->header->hunkbytes
1225 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1228 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1234 hunk = sector / chd_img->sectors_per_hunk;
1235 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1237 if (hunk == chd_img->current_hunk[0])
1238 chd_img->current_buffer = 0;
1239 else if (hunk == chd_img->current_hunk[1])
1240 chd_img->current_buffer = 1;
1243 chd_read(chd_img->chd, hunk, chd_img->buffer +
1244 chd_img->current_buffer * chd_img->header->hunkbytes);
1245 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1248 if (dest != cdbuffer) // copy avoid HACK
1249 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1251 return CD_FRAMESIZE_RAW;
1254 static int cdread_sub_chd(FILE *f, int sector)
1256 unsigned int sector_in_hunk;
1257 unsigned int buffer;
1263 hunk = sector / chd_img->sectors_per_hunk;
1264 sector_in_hunk = sector % chd_img->sectors_per_hunk;
1266 if (hunk == chd_img->current_hunk[0])
1268 else if (hunk == chd_img->current_hunk[1])
1272 buffer = chd_img->current_buffer ^ 1;
1273 chd_read(chd_img->chd, hunk, chd_img->buffer +
1274 buffer * chd_img->header->hunkbytes);
1275 chd_img->current_hunk[buffer] = hunk;
1278 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1279 return SUB_FRAMESIZE;
1283 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1287 fseek(f, base + sector * 2048, SEEK_SET);
1288 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1290 // not really necessary, fake mode 2 header
1291 memset(cdbuffer, 0, 12 * 2);
1292 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1293 cdbuffer[12 + 3] = 1;
1298 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1299 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1303 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1304 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1308 static unsigned char * CALLBACK ISOgetBuffer(void) {
1309 return cdbuffer + 12;
1312 static void PrintTracks(void) {
1315 for (i = 1; i <= numtracks; i++) {
1316 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1317 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1318 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1319 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1323 // This function is invoked by the front-end when opening an ISO
1324 // file for playback
1325 static long CALLBACK ISOopen(void) {
1326 boolean isMode1ISO = FALSE;
1327 char alt_bin_filename[MAXPATHLEN];
1328 const char *bin_filename;
1329 char image_str[1024];
1332 if (cdHandle != NULL) {
1333 return 0; // it's already open
1336 cdHandle = fopen(GetIsoFile(), "rb");
1337 if (cdHandle == NULL) {
1338 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1339 GetIsoFile(), strerror(errno));
1343 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1344 "Loaded CD Image: %s", GetIsoFile());
1346 cddaBigEndian = FALSE;
1347 subChanMixed = FALSE;
1350 cdrIsoMultidiskCount = 1;
1353 CDR_getBuffer = ISOgetBuffer;
1354 cdimg_read_func = cdread_normal;
1355 cdimg_read_sub_func = NULL;
1357 if (parsetoc(GetIsoFile()) == 0) {
1358 strcat(image_str, "[+toc]");
1360 else if (parseccd(GetIsoFile()) == 0) {
1361 strcat(image_str, "[+ccd]");
1363 else if (parsemds(GetIsoFile()) == 0) {
1364 strcat(image_str, "[+mds]");
1366 else if (parsecue(GetIsoFile()) == 0) {
1367 strcat(image_str, "[+cue]");
1369 if (handlepbp(GetIsoFile()) == 0) {
1370 strcat(image_str, "[+pbp]");
1371 CDR_getBuffer = ISOgetBuffer_compr;
1372 cdimg_read_func = cdread_compressed;
1374 else if (handlecbin(GetIsoFile()) == 0) {
1375 strcat(image_str, "[+cbin]");
1376 CDR_getBuffer = ISOgetBuffer_compr;
1377 cdimg_read_func = cdread_compressed;
1380 else if (handlechd(GetIsoFile()) == 0) {
1381 strcat(image_str, "[+chd]");
1382 CDR_getBuffer = ISOgetBuffer_chd;
1383 cdimg_read_func = cdread_chd;
1384 cdimg_read_sub_func = cdread_sub_chd;
1389 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1390 strcat(image_str, "[+sub]");
1392 if (opensbifile(GetIsoFile()) == 0) {
1393 strcat(image_str, "[+sbi]");
1396 fseeko(cdHandle, 0, SEEK_END);
1398 // maybe user selected metadata file instead of main .bin ..
1399 bin_filename = GetIsoFile();
1400 if (ftello(cdHandle) < 2352 * 0x10) {
1401 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1406 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1407 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1408 if (strlen(alt_bin_filename) >= 4) {
1409 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1410 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1412 tmpf = fopen(alt_bin_filename, "rb");
1418 bin_filename = alt_bin_filename;
1421 fseeko(cdHandle, 0, SEEK_END);
1425 // guess whether it is mode1/2048
1426 if (ftello(cdHandle) % 2048 == 0) {
1427 unsigned int modeTest = 0;
1428 fseek(cdHandle, 0, SEEK_SET);
1429 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1431 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1435 if (SWAP32(modeTest) != 0xffffff00) {
1436 strcat(image_str, "[2048]");
1440 fseek(cdHandle, 0, SEEK_SET);
1442 SysPrintf("%s.\n", image_str);
1446 if (subChanMixed && !is_chd) {
1447 cdimg_read_func = cdread_sub_mixed;
1448 cdimg_read_sub_func = cdread_sub_sub_mixed;
1450 else if (isMode1ISO) {
1451 cdimg_read_func = cdread_2048;
1452 cdimg_read_sub_func = NULL;
1455 // make sure we have another handle open for cdda
1456 if (numtracks > 1 && ti[1].handle == NULL) {
1457 ti[1].handle = fopen(bin_filename, "rb");
1463 static long CALLBACK ISOclose(void) {
1466 if (cdHandle != NULL) {
1470 if (subHandle != NULL) {
1477 if (compr_img != NULL) {
1478 free(compr_img->index_table);
1484 if (chd_img != NULL) {
1485 chd_close(chd_img->chd);
1486 free(chd_img->buffer);
1492 for (i = 1; i <= numtracks; i++) {
1493 if (ti[i].handle != NULL) {
1494 fclose(ti[i].handle);
1495 ti[i].handle = NULL;
1502 memset(cdbuffer, 0, sizeof(cdbuffer));
1503 CDR_getBuffer = ISOgetBuffer;
1508 static long CALLBACK ISOinit(void) {
1509 assert(cdHandle == NULL);
1510 assert(subHandle == NULL);
1512 return 0; // do nothing
1515 static long CALLBACK ISOshutdown(void) {
1520 // return Starting and Ending Track
1522 // byte 0 - start track
1523 // byte 1 - end track
1524 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1527 if (numtracks > 0) {
1528 buffer[1] = numtracks;
1537 // return Track Time
1542 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1545 unsigned char time[3];
1546 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1547 sec2msf(sect, (char *)time);
1548 buffer[2] = time[0];
1549 buffer[1] = time[1];
1550 buffer[0] = time[2];
1552 else if (numtracks > 0 && track <= numtracks) {
1553 buffer[2] = ti[track].start[0];
1554 buffer[1] = ti[track].start[1];
1555 buffer[0] = ti[track].start[2];
1566 // decode 'raw' subchannel data ripped by cdrdao
1567 static void DecodeRawSubData(void) {
1568 unsigned char subQData[12];
1571 memset(subQData, 0, sizeof(subQData));
1573 for (i = 0; i < 8 * 12; i++) {
1574 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1575 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1579 memcpy(&subbuffer[12], subQData, 12);
1583 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1585 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1586 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1589 if (cdHandle == NULL) {
1593 if (pregapOffset && sector >= pregapOffset)
1596 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1597 if (ret < 12*2 + 2048)
1604 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1605 // does NOT uses bcd format
1606 static long CALLBACK ISOplay(unsigned char *time) {
1612 static long CALLBACK ISOstop(void) {
1617 // gets subchannel data
1618 static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1619 if (pregapOffset && sector >= pregapOffset) {
1621 if (sector < pregapOffset) // ?
1625 if (cdimg_read_sub_func != NULL) {
1626 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1629 else if (subHandle != NULL) {
1630 if (fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1632 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1639 if (subChanRaw) DecodeRawSubData();
1643 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1646 CDR__getStatus(stat);
1650 stat->Status |= 0x80;
1653 // BIOS - boot ID (CD type)
1654 stat->Type = ti[1].type;
1657 // relative -> absolute time
1659 sec2msf(sect, (char *)stat->Time);
1664 // read CDDA sector into buffer
1665 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1666 unsigned char msf[3] = {m, s, f};
1667 unsigned int file, track, track_start = 0;
1670 cddaCurPos = msf2sec((char *)msf);
1672 // find current track index
1673 for (track = numtracks; ; track--) {
1674 track_start = msf2sec(ti[track].start);
1675 if (track_start <= cddaCurPos)
1681 // data tracks play silent
1682 if (ti[track].type != CDDA) {
1683 memset(buffer, 0, CD_FRAMESIZE_RAW);
1689 // find the file that contains this track
1690 for (file = track; file > 1; file--)
1691 if (ti[file].handle != NULL)
1695 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1696 buffer, cddaCurPos - track_start);
1697 if (ret != CD_FRAMESIZE_RAW) {
1698 memset(buffer, 0, CD_FRAMESIZE_RAW);
1702 if (cddaBigEndian) {
1706 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1707 tmp = buffer[i * 2];
1708 buffer[i * 2] = buffer[i * 2 + 1];
1709 buffer[i * 2 + 1] = tmp;
1716 void cdrIsoInit(void) {
1718 CDR_shutdown = ISOshutdown;
1720 CDR_close = ISOclose;
1721 CDR_getTN = ISOgetTN;
1722 CDR_getTD = ISOgetTD;
1723 CDR_readTrack = ISOreadTrack;
1724 CDR_getBuffer = ISOgetBuffer;
1727 CDR_getBufferSub = ISOgetBufferSub;
1728 CDR_getStatus = ISOgetStatus;
1729 CDR_readCDDA = ISOreadCDDA;
1731 CDR_getDriveLetter = CDR__getDriveLetter;
1732 CDR_configure = CDR__configure;
1733 CDR_test = CDR__test;
1734 CDR_about = CDR__about;
1735 CDR_setfilename = CDR__setfilename;
1740 int cdrIsoActive(void) {
1741 return (cdHandle != NULL);