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)
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 unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
66 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
68 static unsigned int initial_offset = 0;
69 static boolean playing = FALSE;
70 static boolean cddaBigEndian = FALSE;
71 // cdda sectors in toc, byte offset in file
72 static unsigned int cdda_cur_sector;
73 static unsigned int cdda_first_sector;
74 static unsigned int cdda_file_offset;
75 /* Frame offset into CD image where pregap data would be found if it was there.
76 * If a game seeks there we must *not* return subchannel data since it's
77 * not in the CD image, so that cdrom code can fake subchannel data instead.
78 * XXX: there could be multiple pregaps but PSX dumps only have one? */
79 static unsigned int pregapOffset;
81 #define cddaCurPos cdda_cur_sector
83 // compressed image stuff
85 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
86 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
88 unsigned int index_len;
89 unsigned int block_shift;
90 unsigned int current_block;
91 unsigned int sector_in_blk;
96 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
98 const chd_header* header;
99 unsigned int sectors_per_hunk;
100 unsigned int current_hunk;
101 unsigned int sector_in_hunk;
104 static CHD_IMG *chd_img;
107 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
109 char* CALLBACK CDR__getDriveLetter(void);
110 long CALLBACK CDR__configure(void);
111 long CALLBACK CDR__test(void);
112 void CALLBACK CDR__about(void);
113 long CALLBACK CDR__setfilename(char *filename);
114 long CALLBACK CDR__getStatus(struct CdrStat *stat);
116 static void DecodeRawSubData(void);
119 enum {DATA=1, CDDA} type;
120 char start[3]; // MSF-format
121 char length[3]; // MSF-format
122 FILE *handle; // for multi-track images CDDA
123 unsigned int start_offset; // byte offset from start of above file
126 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
128 static int numtracks = 0;
129 static struct trackinfo ti[MAXTRACKS];
131 // get a sector from a msf-array
132 static unsigned int msf2sec(char *msf) {
133 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
136 static void sec2msf(unsigned int s, char *msf) {
137 msf[0] = s / 75 / 60;
138 s = s - msf[0] * 75 * 60;
144 // divide a string of xx:yy:zz into m, s, f
145 static void tok2msf(char *time, char *msf) {
148 token = strtok(time, ":");
150 msf[0] = atoi(token);
156 token = strtok(NULL, ":");
158 msf[1] = atoi(token);
164 token = strtok(NULL, ":");
166 msf[2] = atoi(token);
174 static long GetTickCount(void) {
175 static time_t initial_time = 0;
178 gettimeofday(&now, NULL);
180 if (initial_time == 0) {
181 initial_time = now.tv_sec;
184 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
188 // stop the CDDA playback
189 static void stopCDDA() {
193 // this function tries to get the .toc file of the given .bin
194 // the necessary data is put into the ti (trackinformation)-array
195 static int parsetoc(const char *isofile) {
196 char tocname[MAXPATHLEN];
198 char linebuf[256], tmp[256], name[256];
200 char time[20], time2[20];
201 unsigned int t, sector_offs, sector_size;
202 unsigned int current_zero_gap = 0;
206 // copy name of the iso and change extension from .bin to .toc
207 strncpy(tocname, isofile, sizeof(tocname));
208 tocname[MAXPATHLEN - 1] = '\0';
209 if (strlen(tocname) >= 4) {
210 strcpy(tocname + strlen(tocname) - 4, ".toc");
216 if ((fi = fopen(tocname, "r")) == NULL) {
217 // try changing extension to .cue (to satisfy some stupid tutorials)
218 strcpy(tocname + strlen(tocname) - 4, ".cue");
219 if ((fi = fopen(tocname, "r")) == NULL) {
220 // if filename is image.toc.bin, try removing .bin (for Brasero)
221 strcpy(tocname, isofile);
223 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
224 tocname[t - 4] = '\0';
225 if ((fi = fopen(tocname, "r")) == NULL) {
233 // check if it's really a TOC named as a .cue
234 fgets(linebuf, sizeof(linebuf), fi);
235 token = strtok(linebuf, " ");
236 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
240 fseek(fi, 0, SEEK_SET);
243 memset(&ti, 0, sizeof(ti));
244 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
246 sector_size = CD_FRAMESIZE_RAW;
247 sector_offs = 2 * 75;
249 // parse the .toc file
250 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
252 strncpy(tmp, linebuf, sizeof(linebuf));
253 token = strtok(tmp, " ");
255 if (token == NULL) continue;
257 if (!strcmp(token, "TRACK")) {
258 sector_offs += current_zero_gap;
259 current_zero_gap = 0;
262 token = strtok(NULL, " ");
265 if (!strncmp(token, "MODE2_RAW", 9)) {
266 ti[numtracks].type = DATA;
267 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
269 // check if this image contains mixed subchannel data
270 token = strtok(NULL, " ");
271 if (token != NULL && !strncmp(token, "RW", 2)) {
272 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
274 if (!strncmp(token, "RW_RAW", 6))
278 else if (!strncmp(token, "AUDIO", 5)) {
279 ti[numtracks].type = CDDA;
282 else if (!strcmp(token, "DATAFILE")) {
283 if (ti[numtracks].type == CDDA) {
284 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
285 ti[numtracks].start_offset = t;
286 t = t / sector_size + sector_offs;
287 sec2msf(t, (char *)&ti[numtracks].start);
288 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
291 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
292 tok2msf((char *)&time, (char *)&ti[numtracks].length);
295 else if (!strcmp(token, "FILE")) {
296 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
297 tok2msf((char *)&time, (char *)&ti[numtracks].start);
298 t += msf2sec(ti[numtracks].start) * sector_size;
299 ti[numtracks].start_offset = t;
300 t = t / sector_size + sector_offs;
301 sec2msf(t, (char *)&ti[numtracks].start);
302 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
304 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
305 // skip unneeded optional fields
306 while (token != NULL) {
307 token = strtok(NULL, " ");
308 if (strchr(token, ':') != NULL)
313 current_zero_gap = msf2sec(tmp);
316 t = ti[numtracks - 1].start_offset;
318 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
321 else if (!strcmp(token, "START")) {
322 token = strtok(NULL, " ");
323 if (token != NULL && strchr(token, ':')) {
326 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
327 t = msf2sec(ti[numtracks].start) + t;
328 sec2msf(t, (char *)&ti[numtracks].start);
338 // this function tries to get the .cue file of the given .bin
339 // the necessary data is put into the ti (trackinformation)-array
340 static int parsecue(const char *isofile) {
341 char cuename[MAXPATHLEN];
342 char filepath[MAXPATHLEN];
348 char linebuf[256], tmpb[256], dummy[256];
349 unsigned int incue_max_len;
350 unsigned int t, file_len, mode, sector_offs;
351 unsigned int sector_size = 2352;
355 // copy name of the iso and change extension from .bin to .cue
356 strncpy(cuename, isofile, sizeof(cuename));
357 cuename[MAXPATHLEN - 1] = '\0';
358 if (strlen(cuename) >= 4) {
359 strcpy(cuename + strlen(cuename) - 4, ".cue");
365 if ((fi = fopen(cuename, "r")) == NULL) {
369 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
370 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
372 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
373 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
374 // Don't proceed further, as this is actually a .toc file rather
377 return parsetoc(isofile);
379 fseek(fi, 0, SEEK_SET);
382 // build a path for files referenced in .cue
383 strncpy(filepath, cuename, sizeof(filepath));
384 tmp = strrchr(filepath, '/');
386 tmp = strrchr(filepath, '\\');
392 filepath[sizeof(filepath) - 1] = 0;
394 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
396 memset(&ti, 0, sizeof(ti));
399 sector_offs = 2 * 75;
401 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
402 strncpy(dummy, linebuf, sizeof(linebuf));
403 token = strtok(dummy, " ");
409 if (!strcmp(token, "TRACK")) {
413 if (strstr(linebuf, "AUDIO") != NULL) {
414 ti[numtracks].type = CDDA;
417 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
418 ti[numtracks].type = DATA;
420 SysPrintf(".cue: failed to parse TRACK\n");
421 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
423 if (sector_size == 0)
426 else if (!strcmp(token, "INDEX")) {
427 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
428 SysPrintf(".cue: failed to parse INDEX\n");
429 tok2msf(time, (char *)&ti[numtracks].start);
431 t = msf2sec(ti[numtracks].start);
432 ti[numtracks].start_offset = t * sector_size;
434 sec2msf(t, ti[numtracks].start);
436 // default track length to file length
437 t = file_len - ti[numtracks].start_offset / sector_size;
438 sec2msf(t, ti[numtracks].length);
440 if (numtracks > 1 && ti[numtracks].handle == NULL) {
441 // this track uses the same file as the last,
442 // start of this track is last track's end
443 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
444 sec2msf(t, ti[numtracks - 1].length);
446 if (numtracks > 1 && pregapOffset == -1)
447 pregapOffset = ti[numtracks].start_offset / sector_size;
449 else if (!strcmp(token, "PREGAP")) {
450 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
451 tok2msf(time, dummy);
452 sector_offs += msf2sec(dummy);
454 pregapOffset = -1; // mark to fill track start_offset
456 else if (!strcmp(token, "FILE")) {
457 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
459 sscanf(linebuf, " FILE %255s", tmpb);
462 ti[numtracks + 1].handle = fopen(tmpb, "rb");
463 if (ti[numtracks + 1].handle == NULL) {
465 tmp = strrchr(tmpb, '\\');
467 tmp = strrchr(tmpb, '/');
472 strncpy(incue_fname, tmp, incue_max_len);
473 ti[numtracks + 1].handle = fopen(filepath, "rb");
476 // update global offset if this is not first file in this .cue
477 if (numtracks + 1 > 1) {
479 sector_offs += file_len;
483 if (ti[numtracks + 1].handle == NULL) {
484 SysPrintf(_("\ncould not open: %s\n"), filepath);
487 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
488 file_len = ftell(ti[numtracks + 1].handle) / 2352;
490 if (numtracks == 0 && strlen(isofile) >= 4 &&
491 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
493 // user selected .cue as image file, use it's data track instead
495 cdHandle = fopen(filepath, "rb");
505 // this function tries to get the .ccd file of the given .img
506 // the necessary data is put into the ti (trackinformation)-array
507 static int parseccd(const char *isofile) {
508 char ccdname[MAXPATHLEN];
515 // copy name of the iso and change extension from .img to .ccd
516 strncpy(ccdname, isofile, sizeof(ccdname));
517 ccdname[MAXPATHLEN - 1] = '\0';
518 if (strlen(ccdname) >= 4) {
519 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
525 if ((fi = fopen(ccdname, "r")) == NULL) {
529 memset(&ti, 0, sizeof(ti));
531 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
532 if (!strncmp(linebuf, "[TRACK", 6)){
535 else if (!strncmp(linebuf, "MODE=", 5)) {
536 sscanf(linebuf, "MODE=%d", &t);
537 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
539 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
540 sscanf(linebuf, "INDEX 1=%d", &t);
541 sec2msf(t + 2 * 75, ti[numtracks].start);
542 ti[numtracks].start_offset = t * 2352;
544 // If we've already seen another track, this is its end
546 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
547 sec2msf(t, ti[numtracks - 1].length);
554 // Fill out the last track's end based on size
555 if (numtracks >= 1) {
556 fseek(cdHandle, 0, SEEK_END);
557 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
558 sec2msf(t, ti[numtracks].length);
564 // this function tries to get the .mds file of the given .mdf
565 // the necessary data is put into the ti (trackinformation)-array
566 static int parsemds(const char *isofile) {
567 char mdsname[MAXPATHLEN];
569 unsigned int offset, extra_offset, l, i;
574 // copy name of the iso and change extension from .mdf to .mds
575 strncpy(mdsname, isofile, sizeof(mdsname));
576 mdsname[MAXPATHLEN - 1] = '\0';
577 if (strlen(mdsname) >= 4) {
578 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
584 if ((fi = fopen(mdsname, "rb")) == NULL) {
588 memset(&ti, 0, sizeof(ti));
590 // check if it's a valid mds file
591 fread(&i, 1, sizeof(unsigned int), fi);
593 if (i != 0x4944454D) {
594 // not an valid mds file
599 // get offset to session block
600 fseek(fi, 0x50, SEEK_SET);
601 fread(&offset, 1, sizeof(unsigned int), fi);
602 offset = SWAP32(offset);
604 // get total number of tracks
606 fseek(fi, offset, SEEK_SET);
607 fread(&s, 1, sizeof(unsigned short), fi);
611 // get offset to track blocks
612 fseek(fi, 4, SEEK_CUR);
613 fread(&offset, 1, sizeof(unsigned int), fi);
614 offset = SWAP32(offset);
618 fseek(fi, offset + 4, SEEK_SET);
619 if (fgetc(fi) < 0xA0) {
625 // check if the image contains mixed subchannel data
626 fseek(fi, offset + 1, SEEK_SET);
627 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
630 for (i = 1; i <= numtracks; i++) {
631 fseek(fi, offset, SEEK_SET);
633 // get the track type
634 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
635 fseek(fi, 8, SEEK_CUR);
637 // get the track starting point
638 ti[i].start[0] = fgetc(fi);
639 ti[i].start[1] = fgetc(fi);
640 ti[i].start[2] = fgetc(fi);
642 fread(&extra_offset, 1, sizeof(unsigned int), fi);
643 extra_offset = SWAP32(extra_offset);
645 // get track start offset (in .mdf)
646 fseek(fi, offset + 0x28, SEEK_SET);
647 fread(&l, 1, sizeof(unsigned int), fi);
649 ti[i].start_offset = l;
652 fseek(fi, extra_offset, SEEK_SET);
653 fread(&l, 1, sizeof(unsigned int), fi);
656 pregapOffset = msf2sec(ti[i].start);
658 // get the track length
659 fread(&l, 1, sizeof(unsigned int), fi);
661 sec2msf(l, ti[i].length);
670 static int handlepbp(const char *isofile) {
673 unsigned int dontcare[8];
674 unsigned int psar_offs;
687 unsigned int dontcare[6];
690 off_t psisoimg_offs, cdimg_base;
691 unsigned int t, cd_length;
692 unsigned int offsettab[8];
693 const char *ext = NULL;
696 if (strlen(isofile) >= 4)
697 ext = isofile + strlen(isofile) - 4;
698 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
701 fseeko(cdHandle, 0, SEEK_SET);
705 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
706 if (ret != sizeof(pbp_hdr)) {
707 SysPrintf("failed to read pbp\n");
711 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
713 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
717 psisoimg_offs = pbp_hdr.psar_offs;
718 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
720 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
722 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
724 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
728 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
729 SysPrintf("failed to read offsettab\n");
733 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
734 if (offsettab[i] == 0)
737 cdrIsoMultidiskCount = i;
738 if (cdrIsoMultidiskCount == 0) {
739 SysPrintf("multidisk eboot has 0 images?\n");
743 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
744 cdrIsoMultidiskSelect = 0;
746 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
748 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
750 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
754 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
758 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
759 SysPrintf("bad psar_sig: %s\n", psar_sig);
764 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
766 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
770 // first 3 entries are special
771 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
772 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
773 numtracks = btoi(toc_entry.index1[0]);
775 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
776 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
777 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
779 for (i = 1; i <= numtracks; i++) {
780 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
782 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
784 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
785 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
786 ti[i].start_offset *= 2352;
787 ti[i].start[0] = btoi(toc_entry.index1[0]);
788 ti[i].start[1] = btoi(toc_entry.index1[1]);
789 ti[i].start[2] = btoi(toc_entry.index1[2]);
792 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
793 sec2msf(t, ti[i - 1].length);
796 t = cd_length - ti[numtracks].start_offset / 2352;
797 sec2msf(t, ti[numtracks].length);
800 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
802 SysPrintf("failed to seek to ISO index\n");
806 compr_img = calloc(1, sizeof(*compr_img));
807 if (compr_img == NULL)
810 compr_img->block_shift = 4;
811 compr_img->current_block = (unsigned int)-1;
813 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
814 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
815 if (compr_img->index_table == NULL)
818 cdimg_base = psisoimg_offs + 0x100000;
819 for (i = 0; i < compr_img->index_len; i++) {
820 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
821 if (ret != sizeof(index_entry)) {
822 SysPrintf("failed to read index_entry #%d\n", i);
826 if (index_entry.size == 0)
829 compr_img->index_table[i] = cdimg_base + index_entry.offset;
831 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
836 free(compr_img->index_table);
837 compr_img->index_table = NULL;
839 if (compr_img != NULL) {
846 static int handlecbin(const char *isofile) {
850 unsigned int header_size;
851 unsigned long long total_bytes;
852 unsigned int block_size;
853 unsigned char ver; // 1
855 unsigned char rsv_06[2];
857 const char *ext = NULL;
858 unsigned int *index_table = NULL;
859 unsigned int index = 0, plain;
862 if (strlen(isofile) >= 5)
863 ext = isofile + strlen(isofile) - 5;
864 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
867 fseek(cdHandle, 0, SEEK_SET);
869 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
870 if (ret != sizeof(ciso_hdr)) {
871 SysPrintf("failed to read ciso header\n");
875 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
876 SysPrintf("bad ciso header\n");
879 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
880 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
882 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
887 compr_img = calloc(1, sizeof(*compr_img));
888 if (compr_img == NULL)
891 compr_img->block_shift = 0;
892 compr_img->current_block = (unsigned int)-1;
894 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
895 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
896 if (index_table == NULL)
899 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
900 if (ret != compr_img->index_len) {
901 SysPrintf("failed to read index table\n");
905 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
906 if (compr_img->index_table == NULL)
909 for (i = 0; i < compr_img->index_len + 1; i++) {
910 index = index_table[i];
911 plain = index & 0x80000000;
913 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
915 compr_img->index_table[i] |= OFF_T_MSB;
923 if (compr_img != NULL) {
931 static int handlechd(const char *isofile) {
932 int frame_offset = 0;
935 chd_img = (CHD_IMG *)calloc(1, sizeof(*chd_img));
939 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
942 chd_img->header = chd_get_header(chd_img->chd);
944 chd_img->buffer = (unsigned char (*)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE])malloc(chd_img->header->hunkbytes);
945 if (chd_img->buffer == NULL)
948 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
949 chd_img->current_hunk = (unsigned int)-1;
951 cddaBigEndian = TRUE;
954 memset(ti, 0, sizeof(ti));
969 uint32_t meta_size = 0;
971 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
972 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
973 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
974 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
981 sec2msf(msf2sec(ti[md.track-1].length) + md.pregap, ti[md.track-1].length);
983 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
985 sec2msf(frame_offset + md.pregap, ti[md.track].start);
986 sec2msf(md.frames, ti[md.track].length);
988 ti[md.track].start_offset = file_offset;
990 frame_offset += md.pregap + md.frames + md.postgap;
991 file_offset += md.frames + md.postgap;
999 if (chd_img != NULL) {
1000 free(chd_img->buffer);
1008 // this function tries to get the .sub file of the given .img
1009 static int opensubfile(const char *isoname) {
1010 char subname[MAXPATHLEN];
1012 // copy name of the iso and change extension from .img to .sub
1013 strncpy(subname, isoname, sizeof(subname));
1014 subname[MAXPATHLEN - 1] = '\0';
1015 if (strlen(subname) >= 4) {
1016 strcpy(subname + strlen(subname) - 4, ".sub");
1022 subHandle = fopen(subname, "rb");
1023 if (subHandle == NULL) {
1030 static int opensbifile(const char *isoname) {
1031 char sbiname[MAXPATHLEN];
1034 strncpy(sbiname, isoname, sizeof(sbiname));
1035 sbiname[MAXPATHLEN - 1] = '\0';
1036 if (strlen(sbiname) >= 4) {
1037 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1043 fseek(cdHandle, 0, SEEK_END);
1044 s = ftell(cdHandle) / 2352;
1046 return LoadSBI(sbiname, s);
1049 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1051 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1052 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1055 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1059 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1060 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1061 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1063 if (subChanRaw) DecodeRawSubData();
1068 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1073 if (z.zalloc == NULL) {
1074 // XXX: one-time leak here..
1080 ret = inflateInit2(&z, -15);
1083 ret = inflateReset(&z);
1088 z.avail_in = in_size;
1090 z.avail_out = *out_size;
1092 ret = inflate(&z, Z_NO_FLUSH);
1095 *out_size -= z.avail_out;
1096 return ret == 1 ? 0 : ret;
1099 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1101 unsigned long cdbuffer_size, cdbuffer_size_expect;
1108 sector += base / 2352;
1110 block = sector >> compr_img->block_shift;
1111 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1113 if (block == compr_img->current_block) {
1114 //printf("hit sect %d\n", sector);
1118 if (sector >= compr_img->index_len * 16) {
1119 SysPrintf("sector %d is past img end\n", sector);
1123 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1124 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1125 SysPrintf("seek error for block %d at %llx: ",
1126 block, (long long)start_byte);
1131 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1132 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1133 if (size > sizeof(compr_img->buff_compressed)) {
1134 SysPrintf("block %d is too large: %u\n", block, size);
1138 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1139 1, size, cdHandle) != size) {
1140 SysPrintf("read error for block %d at %x: ", block, start_byte);
1145 if (is_compressed) {
1146 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1147 cdbuffer_size = cdbuffer_size_expect;
1148 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1150 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1151 ret, block, sector);
1154 if (cdbuffer_size != cdbuffer_size_expect)
1155 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1156 cdbuffer_size_expect, sector);
1160 compr_img->current_block = block;
1163 if (dest != cdbuffer) // copy avoid HACK
1164 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1166 return CD_FRAMESIZE_RAW;
1170 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1177 hunk = sector / chd_img->sectors_per_hunk;
1178 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1180 if (hunk != chd_img->current_hunk)
1182 chd_read(chd_img->chd, hunk, chd_img->buffer);
1183 chd_img->current_hunk = hunk;
1186 if (dest != cdbuffer) // copy avoid HACK
1187 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1189 return CD_FRAMESIZE_RAW;
1193 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1197 fseek(f, base + sector * 2048, SEEK_SET);
1198 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1200 // not really necessary, fake mode 2 header
1201 memset(cdbuffer, 0, 12 * 2);
1202 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1203 cdbuffer[12 + 3] = 1;
1208 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1209 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1213 static unsigned char *ISOgetBuffer_chd(void) {
1214 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1218 static unsigned char * CALLBACK ISOgetBuffer(void) {
1219 return cdbuffer + 12;
1222 static void PrintTracks(void) {
1225 for (i = 1; i <= numtracks; i++) {
1226 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1227 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1228 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1229 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1233 // This function is invoked by the front-end when opening an ISO
1234 // file for playback
1235 static long CALLBACK ISOopen(void) {
1236 boolean isMode1ISO = FALSE;
1237 char alt_bin_filename[MAXPATHLEN];
1238 const char *bin_filename;
1240 if (cdHandle != NULL) {
1241 return 0; // it's already open
1244 cdHandle = fopen(GetIsoFile(), "rb");
1245 if (cdHandle == NULL) {
1246 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1247 GetIsoFile(), strerror(errno));
1251 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1253 cddaBigEndian = FALSE;
1254 subChanMixed = FALSE;
1257 cdrIsoMultidiskCount = 1;
1260 CDR_getBuffer = ISOgetBuffer;
1261 cdimg_read_func = cdread_normal;
1263 if (parsetoc(GetIsoFile()) == 0) {
1264 SysPrintf("[+toc]");
1266 else if (parseccd(GetIsoFile()) == 0) {
1267 SysPrintf("[+ccd]");
1269 else if (parsemds(GetIsoFile()) == 0) {
1270 SysPrintf("[+mds]");
1272 else if (parsecue(GetIsoFile()) == 0) {
1273 SysPrintf("[+cue]");
1275 if (handlepbp(GetIsoFile()) == 0) {
1277 CDR_getBuffer = ISOgetBuffer_compr;
1278 cdimg_read_func = cdread_compressed;
1280 else if (handlecbin(GetIsoFile()) == 0) {
1281 SysPrintf("[cbin]");
1282 CDR_getBuffer = ISOgetBuffer_compr;
1283 cdimg_read_func = cdread_compressed;
1287 else if (handlechd(GetIsoFile()) == 0) {
1289 CDR_getBuffer = ISOgetBuffer_chd;
1290 cdimg_read_func = cdread_chd;
1294 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1295 SysPrintf("[+sub]");
1297 if (opensbifile(GetIsoFile()) == 0) {
1298 SysPrintf("[+sbi]");
1301 fseeko(cdHandle, 0, SEEK_END);
1303 // maybe user selected metadata file instead of main .bin ..
1304 bin_filename = GetIsoFile();
1305 if (ftello(cdHandle) < 2352 * 0x10) {
1306 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1311 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1312 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1313 if (strlen(alt_bin_filename) >= 4) {
1314 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1315 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1317 tmpf = fopen(alt_bin_filename, "rb");
1323 bin_filename = alt_bin_filename;
1326 fseeko(cdHandle, 0, SEEK_END);
1330 // guess whether it is mode1/2048
1331 if (ftello(cdHandle) % 2048 == 0) {
1332 unsigned int modeTest = 0;
1333 fseek(cdHandle, 0, SEEK_SET);
1334 fread(&modeTest, 4, 1, cdHandle);
1335 if (SWAP32(modeTest) != 0xffffff00) {
1336 SysPrintf("[2048]");
1340 fseek(cdHandle, 0, SEEK_SET);
1347 cdimg_read_func = cdread_sub_mixed;
1348 else if (isMode1ISO)
1349 cdimg_read_func = cdread_2048;
1351 // make sure we have another handle open for cdda
1352 if (numtracks > 1 && ti[1].handle == NULL) {
1353 ti[1].handle = fopen(bin_filename, "rb");
1355 cdda_cur_sector = 0;
1356 cdda_file_offset = 0;
1361 static long CALLBACK ISOclose(void) {
1364 if (cdHandle != NULL) {
1368 if (subHandle != NULL) {
1375 if (compr_img != NULL) {
1376 free(compr_img->index_table);
1382 if (chd_img != NULL) {
1383 chd_close(chd_img->chd);
1384 free(chd_img->buffer);
1390 for (i = 1; i <= numtracks; i++) {
1391 if (ti[i].handle != NULL) {
1392 fclose(ti[i].handle);
1393 ti[i].handle = NULL;
1400 memset(cdbuffer, 0, sizeof(cdbuffer));
1401 CDR_getBuffer = ISOgetBuffer;
1406 static long CALLBACK ISOinit(void) {
1407 assert(cdHandle == NULL);
1408 assert(subHandle == NULL);
1410 return 0; // do nothing
1413 static long CALLBACK ISOshutdown(void) {
1418 // return Starting and Ending Track
1420 // byte 0 - start track
1421 // byte 1 - end track
1422 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1425 if (numtracks > 0) {
1426 buffer[1] = numtracks;
1435 // return Track Time
1440 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1443 unsigned char time[3];
1444 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1445 sec2msf(sect, (char *)time);
1446 buffer[2] = time[0];
1447 buffer[1] = time[1];
1448 buffer[0] = time[2];
1450 else if (numtracks > 0 && track <= numtracks) {
1451 buffer[2] = ti[track].start[0];
1452 buffer[1] = ti[track].start[1];
1453 buffer[0] = ti[track].start[2];
1464 // decode 'raw' subchannel data ripped by cdrdao
1465 static void DecodeRawSubData(void) {
1466 unsigned char subQData[12];
1469 memset(subQData, 0, sizeof(subQData));
1471 for (i = 0; i < 8 * 12; i++) {
1472 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1473 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1477 memcpy(&subbuffer[12], subQData, 12);
1481 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1483 static boolean CALLBACK ISOreadTrack(unsigned char *time) {
1484 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1487 if (cdHandle == NULL) {
1492 subChanMissing = FALSE;
1493 if (sector >= pregapOffset) {
1495 if (sector < pregapOffset)
1496 subChanMissing = TRUE;
1500 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1504 if (subHandle != NULL) {
1505 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1506 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1508 if (subChanRaw) DecodeRawSubData();
1515 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1516 // does NOT uses bcd format
1517 static long CALLBACK ISOplay(unsigned char *time) {
1523 static long CALLBACK ISOstop(void) {
1528 // gets subchannel data
1529 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1530 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1537 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1540 CDR__getStatus(stat);
1544 stat->Status |= 0x80;
1547 // BIOS - boot ID (CD type)
1548 stat->Type = ti[1].type;
1551 // relative -> absolute time
1553 sec2msf(sect, (char *)stat->Time);
1558 // read CDDA sector into buffer
1559 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1560 unsigned char msf[3] = {m, s, f};
1561 unsigned int file, track, track_start = 0;
1564 cddaCurPos = msf2sec((char *)msf);
1566 // find current track index
1567 for (track = numtracks; ; track--) {
1568 track_start = msf2sec(ti[track].start);
1569 if (track_start <= cddaCurPos)
1575 // data tracks play silent
1576 if (ti[track].type != CDDA) {
1577 memset(buffer, 0, CD_FRAMESIZE_RAW);
1583 // find the file that contains this track
1584 for (file = track; file > 1; file--)
1585 if (ti[file].handle != NULL)
1589 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1590 buffer, cddaCurPos - track_start);
1591 if (ret != CD_FRAMESIZE_RAW) {
1592 memset(buffer, 0, CD_FRAMESIZE_RAW);
1596 if (cddaBigEndian) {
1600 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1601 tmp = buffer[i * 2];
1602 buffer[i * 2] = buffer[i * 2 + 1];
1603 buffer[i * 2 + 1] = tmp;
1610 void cdrIsoInit(void) {
1612 CDR_shutdown = ISOshutdown;
1614 CDR_close = ISOclose;
1615 CDR_getTN = ISOgetTN;
1616 CDR_getTD = ISOgetTD;
1617 CDR_readTrack = ISOreadTrack;
1618 CDR_getBuffer = ISOgetBuffer;
1621 CDR_getBufferSub = ISOgetBufferSub;
1622 CDR_getStatus = ISOgetStatus;
1623 CDR_readCDDA = ISOreadCDDA;
1625 CDR_getDriveLetter = CDR__getDriveLetter;
1626 CDR_configure = CDR__configure;
1627 CDR_test = CDR__test;
1628 CDR_about = CDR__about;
1629 CDR_setfilename = CDR__setfilename;
1634 int cdrIsoActive(void) {
1635 return (cdHandle != NULL);