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;
57 static boolean subChanMissing = FALSE;
59 static boolean multifile = FALSE;
61 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
62 static unsigned char subbuffer[SUB_FRAMESIZE];
64 static boolean playing = FALSE;
65 static boolean cddaBigEndian = FALSE;
66 /* Frame offset into CD image where pregap data would be found if it was there.
67 * If a game seeks there we must *not* return subchannel data since it's
68 * not in the CD image, so that cdrom code can fake subchannel data instead.
69 * XXX: there could be multiple pregaps but PSX dumps only have one? */
70 static unsigned int pregapOffset;
72 static unsigned int cddaCurPos;
74 // compressed image stuff
76 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
77 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
79 unsigned int index_len;
80 unsigned int block_shift;
81 unsigned int current_block;
82 unsigned int sector_in_blk;
87 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
89 const chd_header* header;
90 unsigned int sectors_per_hunk;
91 unsigned int current_hunk;
92 unsigned int sector_in_hunk;
96 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
98 char* CALLBACK CDR__getDriveLetter(void);
99 long CALLBACK CDR__configure(void);
100 long CALLBACK CDR__test(void);
101 void CALLBACK CDR__about(void);
102 long CALLBACK CDR__setfilename(char *filename);
103 long CALLBACK CDR__getStatus(struct CdrStat *stat);
105 static void DecodeRawSubData(void);
108 enum {DATA=1, CDDA} type;
109 char start[3]; // MSF-format
110 char length[3]; // MSF-format
111 FILE *handle; // for multi-track images CDDA
112 unsigned int start_offset; // byte offset from start of above file
115 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
117 static int numtracks = 0;
118 static struct trackinfo ti[MAXTRACKS];
120 // get a sector from a msf-array
121 static unsigned int msf2sec(char *msf) {
122 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
125 static void sec2msf(unsigned int s, char *msf) {
126 msf[0] = s / 75 / 60;
127 s = s - msf[0] * 75 * 60;
133 // divide a string of xx:yy:zz into m, s, f
134 static void tok2msf(char *time, char *msf) {
137 token = strtok(time, ":");
139 msf[0] = atoi(token);
145 token = strtok(NULL, ":");
147 msf[1] = atoi(token);
153 token = strtok(NULL, ":");
155 msf[2] = atoi(token);
162 // this function tries to get the .toc file of the given .bin
163 // the necessary data is put into the ti (trackinformation)-array
164 static int parsetoc(const char *isofile) {
165 char tocname[MAXPATHLEN];
167 char linebuf[256], tmp[256], name[256];
169 char time[20], time2[20];
170 unsigned int t, sector_offs, sector_size;
171 unsigned int current_zero_gap = 0;
175 // copy name of the iso and change extension from .bin to .toc
176 strncpy(tocname, isofile, sizeof(tocname));
177 tocname[MAXPATHLEN - 1] = '\0';
178 if (strlen(tocname) >= 4) {
179 strcpy(tocname + strlen(tocname) - 4, ".toc");
185 if ((fi = fopen(tocname, "r")) == NULL) {
186 // try changing extension to .cue (to satisfy some stupid tutorials)
187 strcpy(tocname + strlen(tocname) - 4, ".cue");
188 if ((fi = fopen(tocname, "r")) == NULL) {
189 // if filename is image.toc.bin, try removing .bin (for Brasero)
190 strcpy(tocname, isofile);
192 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
193 tocname[t - 4] = '\0';
194 if ((fi = fopen(tocname, "r")) == NULL) {
202 // check if it's really a TOC named as a .cue
203 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
204 token = strtok(linebuf, " ");
205 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
210 fseek(fi, 0, SEEK_SET);
213 memset(&ti, 0, sizeof(ti));
214 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
216 sector_size = CD_FRAMESIZE_RAW;
217 sector_offs = 2 * 75;
219 // parse the .toc file
220 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
222 strncpy(tmp, linebuf, sizeof(linebuf));
223 token = strtok(tmp, " ");
225 if (token == NULL) continue;
227 if (!strcmp(token, "TRACK")) {
228 sector_offs += current_zero_gap;
229 current_zero_gap = 0;
232 token = strtok(NULL, " ");
235 if (!strncmp(token, "MODE2_RAW", 9)) {
236 ti[numtracks].type = DATA;
237 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
239 // check if this image contains mixed subchannel data
240 token = strtok(NULL, " ");
241 if (token != NULL && !strncmp(token, "RW", 2)) {
242 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
244 if (!strncmp(token, "RW_RAW", 6))
248 else if (!strncmp(token, "AUDIO", 5)) {
249 ti[numtracks].type = CDDA;
252 else if (!strcmp(token, "DATAFILE")) {
253 if (ti[numtracks].type == CDDA) {
254 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
255 ti[numtracks].start_offset = t;
256 t = t / sector_size + sector_offs;
257 sec2msf(t, (char *)&ti[numtracks].start);
258 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
261 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
262 tok2msf((char *)&time, (char *)&ti[numtracks].length);
265 else if (!strcmp(token, "FILE")) {
266 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
267 tok2msf((char *)&time, (char *)&ti[numtracks].start);
268 t += msf2sec(ti[numtracks].start) * sector_size;
269 ti[numtracks].start_offset = t;
270 t = t / sector_size + sector_offs;
271 sec2msf(t, (char *)&ti[numtracks].start);
272 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
274 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
275 // skip unneeded optional fields
276 while (token != NULL) {
277 token = strtok(NULL, " ");
278 if (strchr(token, ':') != NULL)
283 current_zero_gap = msf2sec(tmp);
286 t = ti[numtracks - 1].start_offset;
288 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
291 else if (!strcmp(token, "START")) {
292 token = strtok(NULL, " ");
293 if (token != NULL && strchr(token, ':')) {
296 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
297 t = msf2sec(ti[numtracks].start) + t;
298 sec2msf(t, (char *)&ti[numtracks].start);
308 // this function tries to get the .cue file of the given .bin
309 // the necessary data is put into the ti (trackinformation)-array
310 static int parsecue(const char *isofile) {
311 char cuename[MAXPATHLEN];
312 char filepath[MAXPATHLEN];
318 char linebuf[256], tmpb[256], dummy[256];
319 unsigned int incue_max_len;
320 unsigned int t, file_len, mode, sector_offs;
321 unsigned int sector_size = 2352;
325 // copy name of the iso and change extension from .bin to .cue
326 strncpy(cuename, isofile, sizeof(cuename));
327 cuename[MAXPATHLEN - 1] = '\0';
328 if (strlen(cuename) >= 4) {
329 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
330 // and don't try to search the additional .cue file
331 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
332 strcpy(cuename + strlen(cuename) - 4, ".cue");
338 if ((fi = fopen(cuename, "r")) == NULL) {
342 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
343 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
345 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
346 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
347 // Don't proceed further, as this is actually a .toc file rather
350 return parsetoc(isofile);
352 fseek(fi, 0, SEEK_SET);
355 // build a path for files referenced in .cue
356 strncpy(filepath, cuename, sizeof(filepath));
357 tmp = strrchr(filepath, '/');
359 tmp = strrchr(filepath, '\\');
365 filepath[sizeof(filepath) - 1] = 0;
367 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
369 memset(&ti, 0, sizeof(ti));
372 sector_offs = 2 * 75;
374 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
375 strncpy(dummy, linebuf, sizeof(linebuf));
376 token = strtok(dummy, " ");
382 if (!strcmp(token, "TRACK")) {
386 if (strstr(linebuf, "AUDIO") != NULL) {
387 ti[numtracks].type = CDDA;
390 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
391 ti[numtracks].type = DATA;
393 SysPrintf(".cue: failed to parse TRACK\n");
394 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
396 if (sector_size == 0)
399 else if (!strcmp(token, "INDEX")) {
400 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
401 SysPrintf(".cue: failed to parse INDEX\n");
402 tok2msf(time, (char *)&ti[numtracks].start);
404 t = msf2sec(ti[numtracks].start);
405 ti[numtracks].start_offset = t * sector_size;
407 sec2msf(t, ti[numtracks].start);
409 // default track length to file length
410 t = file_len - ti[numtracks].start_offset / sector_size;
411 sec2msf(t, ti[numtracks].length);
413 if (numtracks > 1 && ti[numtracks].handle == NULL) {
414 // this track uses the same file as the last,
415 // start of this track is last track's end
416 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
417 sec2msf(t, ti[numtracks - 1].length);
419 if (numtracks > 1 && pregapOffset == -1)
420 pregapOffset = ti[numtracks].start_offset / sector_size;
422 else if (!strcmp(token, "PREGAP")) {
423 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
424 tok2msf(time, dummy);
425 sector_offs += msf2sec(dummy);
427 pregapOffset = -1; // mark to fill track start_offset
429 else if (!strcmp(token, "FILE")) {
430 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
432 sscanf(linebuf, " FILE %255s", tmpb);
435 ti[numtracks + 1].handle = fopen(tmpb, "rb");
436 if (ti[numtracks + 1].handle == NULL) {
438 tmp = strrchr(tmpb, '\\');
440 tmp = strrchr(tmpb, '/');
445 strncpy(incue_fname, tmp, incue_max_len);
446 ti[numtracks + 1].handle = fopen(filepath, "rb");
449 // update global offset if this is not first file in this .cue
450 if (numtracks + 1 > 1) {
452 sector_offs += file_len;
456 if (ti[numtracks + 1].handle == NULL) {
457 SysPrintf(_("\ncould not open: %s\n"), filepath);
460 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
461 file_len = ftell(ti[numtracks + 1].handle) / 2352;
463 if (numtracks == 0 && strlen(isofile) >= 4 &&
464 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
465 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
466 // user selected .cue/.cdX as image file, use it's data track instead
468 cdHandle = fopen(filepath, "rb");
475 // if there are no tracks detected, then it's not a cue file
482 // this function tries to get the .ccd file of the given .img
483 // the necessary data is put into the ti (trackinformation)-array
484 static int parseccd(const char *isofile) {
485 char ccdname[MAXPATHLEN];
492 // copy name of the iso and change extension from .img to .ccd
493 strncpy(ccdname, isofile, sizeof(ccdname));
494 ccdname[MAXPATHLEN - 1] = '\0';
495 if (strlen(ccdname) >= 4) {
496 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
502 if ((fi = fopen(ccdname, "r")) == NULL) {
506 memset(&ti, 0, sizeof(ti));
508 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
509 if (!strncmp(linebuf, "[TRACK", 6)){
512 else if (!strncmp(linebuf, "MODE=", 5)) {
513 sscanf(linebuf, "MODE=%d", &t);
514 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
516 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
517 sscanf(linebuf, "INDEX 1=%d", &t);
518 sec2msf(t + 2 * 75, ti[numtracks].start);
519 ti[numtracks].start_offset = t * 2352;
521 // If we've already seen another track, this is its end
523 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
524 sec2msf(t, ti[numtracks - 1].length);
531 // Fill out the last track's end based on size
532 if (numtracks >= 1) {
533 fseek(cdHandle, 0, SEEK_END);
534 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
535 sec2msf(t, ti[numtracks].length);
541 // this function tries to get the .mds file of the given .mdf
542 // the necessary data is put into the ti (trackinformation)-array
543 static int parsemds(const char *isofile) {
544 char mdsname[MAXPATHLEN];
546 unsigned int offset, extra_offset, l, i;
551 // copy name of the iso and change extension from .mdf to .mds
552 strncpy(mdsname, isofile, sizeof(mdsname));
553 mdsname[MAXPATHLEN - 1] = '\0';
554 if (strlen(mdsname) >= 4) {
555 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
561 if ((fi = fopen(mdsname, "rb")) == NULL) {
565 memset(&ti, 0, sizeof(ti));
567 // check if it's a valid mds file
568 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
571 if (i != 0x4944454D) {
572 // not an valid mds file
577 // get offset to session block
578 fseek(fi, 0x50, SEEK_SET);
579 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
581 offset = SWAP32(offset);
583 // get total number of tracks
585 fseek(fi, offset, SEEK_SET);
586 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
591 // get offset to track blocks
592 fseek(fi, 4, SEEK_CUR);
593 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
595 offset = SWAP32(offset);
599 fseek(fi, offset + 4, SEEK_SET);
600 if (fgetc(fi) < 0xA0) {
606 // check if the image contains mixed subchannel data
607 fseek(fi, offset + 1, SEEK_SET);
608 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
611 for (i = 1; i <= numtracks; i++) {
612 fseek(fi, offset, SEEK_SET);
614 // get the track type
615 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
616 fseek(fi, 8, SEEK_CUR);
618 // get the track starting point
619 ti[i].start[0] = fgetc(fi);
620 ti[i].start[1] = fgetc(fi);
621 ti[i].start[2] = fgetc(fi);
623 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
625 extra_offset = SWAP32(extra_offset);
627 // get track start offset (in .mdf)
628 fseek(fi, offset + 0x28, SEEK_SET);
629 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
632 ti[i].start_offset = l;
635 fseek(fi, extra_offset, SEEK_SET);
636 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
640 pregapOffset = msf2sec(ti[i].start);
642 // get the track length
643 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
646 sec2msf(l, ti[i].length);
654 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
660 static int handlepbp(const char *isofile) {
663 unsigned int dontcare[8];
664 unsigned int psar_offs;
677 unsigned int dontcare[6];
680 off_t psisoimg_offs, cdimg_base;
681 unsigned int t, cd_length;
682 unsigned int offsettab[8];
683 unsigned int psar_offs, index_entry_size, index_entry_offset;
684 const char *ext = NULL;
687 if (strlen(isofile) >= 4)
688 ext = isofile + strlen(isofile) - 4;
689 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
692 fseeko(cdHandle, 0, SEEK_SET);
696 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
697 if (ret != sizeof(pbp_hdr)) {
698 SysPrintf("failed to read pbp\n");
702 psar_offs = SWAP32(pbp_hdr.psar_offs);
704 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
706 SysPrintf("failed to seek to %x\n", psar_offs);
710 psisoimg_offs = psar_offs;
711 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
714 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
716 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
718 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
722 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
723 SysPrintf("failed to read offsettab\n");
727 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
728 if (offsettab[i] == 0)
731 cdrIsoMultidiskCount = i;
732 if (cdrIsoMultidiskCount == 0) {
733 SysPrintf("multidisk eboot has 0 images?\n");
737 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
738 cdrIsoMultidiskSelect = 0;
740 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
742 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
744 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
748 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
753 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
754 SysPrintf("bad psar_sig: %s\n", psar_sig);
759 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
761 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
765 // first 3 entries are special
766 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
767 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
769 numtracks = btoi(toc_entry.index1[0]);
771 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
773 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
774 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
776 for (i = 1; i <= numtracks; i++) {
777 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
780 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
782 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
783 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
784 ti[i].start_offset *= 2352;
785 ti[i].start[0] = btoi(toc_entry.index1[0]);
786 ti[i].start[1] = btoi(toc_entry.index1[1]);
787 ti[i].start[2] = btoi(toc_entry.index1[2]);
790 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
791 sec2msf(t, ti[i - 1].length);
794 t = cd_length - ti[numtracks].start_offset / 2352;
795 sec2msf(t, ti[numtracks].length);
798 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
800 SysPrintf("failed to seek to ISO index\n");
804 compr_img = calloc(1, sizeof(*compr_img));
805 if (compr_img == NULL)
808 compr_img->block_shift = 4;
809 compr_img->current_block = (unsigned int)-1;
811 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
812 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
813 if (compr_img->index_table == NULL)
816 cdimg_base = psisoimg_offs + 0x100000;
817 for (i = 0; i < compr_img->index_len; i++) {
818 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
819 if (ret != sizeof(index_entry)) {
820 SysPrintf("failed to read index_entry #%d\n", i);
824 index_entry_size = SWAP32(index_entry.size);
825 index_entry_offset = SWAP32(index_entry.offset);
827 if (index_entry_size == 0)
830 compr_img->index_table[i] = cdimg_base + index_entry_offset;
832 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
837 free(compr_img->index_table);
838 compr_img->index_table = NULL;
843 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
847 if (compr_img != NULL) {
854 static int handlecbin(const char *isofile) {
858 unsigned int header_size;
859 unsigned long long total_bytes;
860 unsigned int block_size;
861 unsigned char ver; // 1
863 unsigned char rsv_06[2];
865 const char *ext = NULL;
866 unsigned int *index_table = NULL;
867 unsigned int index = 0, plain;
870 if (strlen(isofile) >= 5)
871 ext = isofile + strlen(isofile) - 5;
872 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
875 fseek(cdHandle, 0, SEEK_SET);
877 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
878 if (ret != sizeof(ciso_hdr)) {
879 SysPrintf("failed to read ciso header\n");
883 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
884 SysPrintf("bad ciso header\n");
887 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
888 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
890 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
895 compr_img = calloc(1, sizeof(*compr_img));
896 if (compr_img == NULL)
899 compr_img->block_shift = 0;
900 compr_img->current_block = (unsigned int)-1;
902 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
903 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
904 if (index_table == NULL)
907 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
908 if (ret != compr_img->index_len) {
909 SysPrintf("failed to read index table\n");
913 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
914 if (compr_img->index_table == NULL)
917 for (i = 0; i < compr_img->index_len + 1; i++) {
918 index = index_table[i];
919 plain = index & 0x80000000;
921 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
923 compr_img->index_table[i] |= OFF_T_MSB;
931 if (compr_img != NULL) {
939 static int handlechd(const char *isofile) {
940 int frame_offset = 150;
943 chd_img = calloc(1, sizeof(*chd_img));
947 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
950 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
953 chd_img->header = chd_get_header(chd_img->chd);
955 chd_img->buffer = malloc(chd_img->header->hunkbytes);
956 if (chd_img->buffer == NULL)
959 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
960 chd_img->current_hunk = (unsigned int)-1;
962 cddaBigEndian = TRUE;
965 memset(ti, 0, sizeof(ti));
980 uint32_t meta_size = 0;
982 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
983 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
984 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
985 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
989 SysPrintf("chd: %s\n", meta);
992 if (!strncmp(md.subtype, "RW", 2)) {
994 if (!strcmp(md.subtype, "RW_RAW"))
999 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1001 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1002 sec2msf(md.frames, ti[md.track].length);
1004 ti[md.track].start_offset = file_offset + md.pregap;
1006 // XXX: what about postgap?
1007 frame_offset += md.frames;
1008 file_offset += md.frames;
1016 if (chd_img != NULL) {
1017 free(chd_img->buffer);
1025 // this function tries to get the .sub file of the given .img
1026 static int opensubfile(const char *isoname) {
1027 char subname[MAXPATHLEN];
1029 // copy name of the iso and change extension from .img to .sub
1030 strncpy(subname, isoname, sizeof(subname));
1031 subname[MAXPATHLEN - 1] = '\0';
1032 if (strlen(subname) >= 4) {
1033 strcpy(subname + strlen(subname) - 4, ".sub");
1039 subHandle = fopen(subname, "rb");
1040 if (subHandle == NULL) {
1047 static int opensbifile(const char *isoname) {
1048 char sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1051 strncpy(sbiname, isoname, sizeof(sbiname));
1052 sbiname[MAXPATHLEN - 1] = '\0';
1053 if (strlen(sbiname) >= 4) {
1054 if (cdrIsoMultidiskCount > 1) {
1055 sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1056 strcpy(sbiname + strlen(sbiname) - 4, disknum);
1059 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1065 fseek(cdHandle, 0, SEEK_END);
1066 s = ftell(cdHandle) / 2352;
1068 return LoadSBI(sbiname, s);
1071 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1073 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1074 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1077 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1081 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1082 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1083 if (fread(subbuffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1086 if (subChanRaw) DecodeRawSubData();
1091 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1098 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1103 if (z.zalloc == NULL) {
1104 // XXX: one-time leak here..
1110 ret = inflateInit2(&z, -15);
1113 ret = inflateReset(&z);
1118 z.avail_in = in_size;
1120 z.avail_out = *out_size;
1122 ret = inflate(&z, Z_NO_FLUSH);
1125 *out_size -= z.avail_out;
1126 return ret == 1 ? 0 : ret;
1129 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1131 unsigned long cdbuffer_size, cdbuffer_size_expect;
1138 sector += base / 2352;
1140 block = sector >> compr_img->block_shift;
1141 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1143 if (block == compr_img->current_block) {
1144 //printf("hit sect %d\n", sector);
1148 if (sector >= compr_img->index_len * 16) {
1149 SysPrintf("sector %d is past img end\n", sector);
1153 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1154 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1155 SysPrintf("seek error for block %d at %llx: ",
1156 block, (long long)start_byte);
1161 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1162 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1163 if (size > sizeof(compr_img->buff_compressed)) {
1164 SysPrintf("block %d is too large: %u\n", block, size);
1168 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1169 1, size, cdHandle) != size) {
1170 SysPrintf("read error for block %d at %x: ", block, start_byte);
1175 if (is_compressed) {
1176 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1177 cdbuffer_size = cdbuffer_size_expect;
1178 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1180 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1181 ret, block, sector);
1184 if (cdbuffer_size != cdbuffer_size_expect)
1185 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1186 cdbuffer_size_expect, sector);
1190 compr_img->current_block = block;
1193 if (dest != cdbuffer) // copy avoid HACK
1194 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1196 return CD_FRAMESIZE_RAW;
1200 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1207 hunk = sector / chd_img->sectors_per_hunk;
1208 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1210 if (hunk != chd_img->current_hunk)
1212 chd_read(chd_img->chd, hunk, chd_img->buffer);
1213 chd_img->current_hunk = hunk;
1216 if (dest != cdbuffer) // copy avoid HACK
1217 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1220 memcpy(subbuffer, chd_img->buffer[chd_img->sector_in_hunk] + CD_FRAMESIZE_RAW,
1225 return CD_FRAMESIZE_RAW;
1229 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1233 fseek(f, base + sector * 2048, SEEK_SET);
1234 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1236 // not really necessary, fake mode 2 header
1237 memset(cdbuffer, 0, 12 * 2);
1238 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1239 cdbuffer[12 + 3] = 1;
1244 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1245 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1249 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1250 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1254 static unsigned char * CALLBACK ISOgetBuffer(void) {
1255 return cdbuffer + 12;
1258 static void PrintTracks(void) {
1261 for (i = 1; i <= numtracks; i++) {
1262 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1263 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1264 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1265 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1269 // This function is invoked by the front-end when opening an ISO
1270 // file for playback
1271 static long CALLBACK ISOopen(void) {
1272 boolean isMode1ISO = FALSE;
1273 char alt_bin_filename[MAXPATHLEN];
1274 const char *bin_filename;
1275 char image_str[1024];
1278 if (cdHandle != NULL) {
1279 return 0; // it's already open
1282 cdHandle = fopen(GetIsoFile(), "rb");
1283 if (cdHandle == NULL) {
1284 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1285 GetIsoFile(), strerror(errno));
1289 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1290 "Loaded CD Image: %s", GetIsoFile());
1292 cddaBigEndian = FALSE;
1293 subChanMixed = FALSE;
1296 cdrIsoMultidiskCount = 1;
1299 CDR_getBuffer = ISOgetBuffer;
1300 cdimg_read_func = cdread_normal;
1302 if (parsetoc(GetIsoFile()) == 0) {
1303 strcat(image_str, "[+toc]");
1305 else if (parseccd(GetIsoFile()) == 0) {
1306 strcat(image_str, "[+ccd]");
1308 else if (parsemds(GetIsoFile()) == 0) {
1309 strcat(image_str, "[+mds]");
1311 else if (parsecue(GetIsoFile()) == 0) {
1312 strcat(image_str, "[+cue]");
1314 if (handlepbp(GetIsoFile()) == 0) {
1315 strcat(image_str, "[+pbp]");
1316 CDR_getBuffer = ISOgetBuffer_compr;
1317 cdimg_read_func = cdread_compressed;
1319 else if (handlecbin(GetIsoFile()) == 0) {
1320 strcat(image_str, "[+cbin]");
1321 CDR_getBuffer = ISOgetBuffer_compr;
1322 cdimg_read_func = cdread_compressed;
1325 else if (handlechd(GetIsoFile()) == 0) {
1326 strcat(image_str, "[+chd]");
1327 CDR_getBuffer = ISOgetBuffer_chd;
1328 cdimg_read_func = cdread_chd;
1333 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1334 strcat(image_str, "[+sub]");
1336 if (opensbifile(GetIsoFile()) == 0) {
1337 strcat(image_str, "[+sbi]");
1340 fseeko(cdHandle, 0, SEEK_END);
1342 // maybe user selected metadata file instead of main .bin ..
1343 bin_filename = GetIsoFile();
1344 if (ftello(cdHandle) < 2352 * 0x10) {
1345 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1350 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1351 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1352 if (strlen(alt_bin_filename) >= 4) {
1353 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1354 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1356 tmpf = fopen(alt_bin_filename, "rb");
1362 bin_filename = alt_bin_filename;
1365 fseeko(cdHandle, 0, SEEK_END);
1369 // guess whether it is mode1/2048
1370 if (ftello(cdHandle) % 2048 == 0) {
1371 unsigned int modeTest = 0;
1372 fseek(cdHandle, 0, SEEK_SET);
1373 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1375 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1379 if (SWAP32(modeTest) != 0xffffff00) {
1380 strcat(image_str, "[2048]");
1384 fseek(cdHandle, 0, SEEK_SET);
1386 SysPrintf("%s.\n", image_str);
1390 if (subChanMixed && !is_chd)
1391 cdimg_read_func = cdread_sub_mixed;
1392 else if (isMode1ISO)
1393 cdimg_read_func = cdread_2048;
1395 // make sure we have another handle open for cdda
1396 if (numtracks > 1 && ti[1].handle == NULL) {
1397 ti[1].handle = fopen(bin_filename, "rb");
1403 static long CALLBACK ISOclose(void) {
1406 if (cdHandle != NULL) {
1410 if (subHandle != NULL) {
1417 if (compr_img != NULL) {
1418 free(compr_img->index_table);
1424 if (chd_img != NULL) {
1425 chd_close(chd_img->chd);
1426 free(chd_img->buffer);
1432 for (i = 1; i <= numtracks; i++) {
1433 if (ti[i].handle != NULL) {
1434 fclose(ti[i].handle);
1435 ti[i].handle = NULL;
1442 memset(cdbuffer, 0, sizeof(cdbuffer));
1443 CDR_getBuffer = ISOgetBuffer;
1448 static long CALLBACK ISOinit(void) {
1449 assert(cdHandle == NULL);
1450 assert(subHandle == NULL);
1452 return 0; // do nothing
1455 static long CALLBACK ISOshutdown(void) {
1460 // return Starting and Ending Track
1462 // byte 0 - start track
1463 // byte 1 - end track
1464 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1467 if (numtracks > 0) {
1468 buffer[1] = numtracks;
1477 // return Track Time
1482 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1485 unsigned char time[3];
1486 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1487 sec2msf(sect, (char *)time);
1488 buffer[2] = time[0];
1489 buffer[1] = time[1];
1490 buffer[0] = time[2];
1492 else if (numtracks > 0 && track <= numtracks) {
1493 buffer[2] = ti[track].start[0];
1494 buffer[1] = ti[track].start[1];
1495 buffer[0] = ti[track].start[2];
1506 // decode 'raw' subchannel data ripped by cdrdao
1507 static void DecodeRawSubData(void) {
1508 unsigned char subQData[12];
1511 memset(subQData, 0, sizeof(subQData));
1513 for (i = 0; i < 8 * 12; i++) {
1514 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1515 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1519 memcpy(&subbuffer[12], subQData, 12);
1523 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1525 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1526 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1529 if (cdHandle == NULL) {
1534 subChanMissing = FALSE;
1535 if (sector >= pregapOffset) {
1537 if (sector < pregapOffset)
1538 subChanMissing = TRUE;
1542 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1543 if (ret < 12*2 + 2048)
1546 if (subHandle != NULL) {
1547 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1548 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1549 /* Faulty subchannel data shouldn't cause a read failure */
1552 if (subChanRaw) DecodeRawSubData();
1559 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1560 // does NOT uses bcd format
1561 static long CALLBACK ISOplay(unsigned char *time) {
1567 static long CALLBACK ISOstop(void) {
1572 // gets subchannel data
1573 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1574 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1581 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1584 CDR__getStatus(stat);
1588 stat->Status |= 0x80;
1591 // BIOS - boot ID (CD type)
1592 stat->Type = ti[1].type;
1595 // relative -> absolute time
1597 sec2msf(sect, (char *)stat->Time);
1602 // read CDDA sector into buffer
1603 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1604 unsigned char msf[3] = {m, s, f};
1605 unsigned int file, track, track_start = 0;
1608 cddaCurPos = msf2sec((char *)msf);
1610 // find current track index
1611 for (track = numtracks; ; track--) {
1612 track_start = msf2sec(ti[track].start);
1613 if (track_start <= cddaCurPos)
1619 // data tracks play silent
1620 if (ti[track].type != CDDA) {
1621 memset(buffer, 0, CD_FRAMESIZE_RAW);
1627 // find the file that contains this track
1628 for (file = track; file > 1; file--)
1629 if (ti[file].handle != NULL)
1633 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1634 buffer, cddaCurPos - track_start);
1635 if (ret != CD_FRAMESIZE_RAW) {
1636 memset(buffer, 0, CD_FRAMESIZE_RAW);
1640 if (cddaBigEndian) {
1644 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1645 tmp = buffer[i * 2];
1646 buffer[i * 2] = buffer[i * 2 + 1];
1647 buffer[i * 2 + 1] = tmp;
1654 void cdrIsoInit(void) {
1656 CDR_shutdown = ISOshutdown;
1658 CDR_close = ISOclose;
1659 CDR_getTN = ISOgetTN;
1660 CDR_getTD = ISOgetTD;
1661 CDR_readTrack = ISOreadTrack;
1662 CDR_getBuffer = ISOgetBuffer;
1665 CDR_getBufferSub = ISOgetBufferSub;
1666 CDR_getStatus = ISOgetStatus;
1667 CDR_readCDDA = ISOreadCDDA;
1669 CDR_getDriveLetter = CDR__getDriveLetter;
1670 CDR_configure = CDR__configure;
1671 CDR_test = CDR__test;
1672 CDR_about = CDR__about;
1673 CDR_setfilename = CDR__setfilename;
1678 int cdrIsoActive(void) {
1679 return (cdHandle != NULL);