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))
42 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
44 unsigned int cdrIsoMultidiskCount;
45 unsigned int cdrIsoMultidiskSelect;
47 static FILE *cdHandle = NULL;
48 static FILE *cddaHandle = NULL;
49 static FILE *subHandle = NULL;
51 static boolean subChanMixed = FALSE;
52 static boolean subChanRaw = FALSE;
53 static boolean subChanMissing = FALSE;
55 static boolean multifile = FALSE;
57 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
58 static unsigned char subbuffer[SUB_FRAMESIZE];
60 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
62 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
65 static HANDLE threadid;
67 static pthread_t threadid;
69 static unsigned int initial_offset = 0;
70 static boolean playing = FALSE;
71 static boolean cddaBigEndian = FALSE;
72 // cdda sectors in toc, byte offset in file
73 static unsigned int cdda_cur_sector;
74 static unsigned int cdda_first_sector;
75 static unsigned int cdda_file_offset;
76 /* Frame offset into CD image where pregap data would be found if it was there.
77 * If a game seeks there we must *not* return subchannel data since it's
78 * not in the CD image, so that cdrom code can fake subchannel data instead.
79 * XXX: there could be multiple pregaps but PSX dumps only have one? */
80 static unsigned int pregapOffset;
82 #define cddaCurPos cdda_cur_sector
84 // compressed image stuff
86 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
87 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
89 unsigned int index_len;
90 unsigned int block_shift;
91 unsigned int current_block;
92 unsigned int sector_in_blk;
95 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
97 char* CALLBACK CDR__getDriveLetter(void);
98 long CALLBACK CDR__configure(void);
99 long CALLBACK CDR__test(void);
100 void CALLBACK CDR__about(void);
101 long CALLBACK CDR__setfilename(char *filename);
102 long CALLBACK CDR__getStatus(struct CdrStat *stat);
104 static void DecodeRawSubData(void);
107 enum {DATA=1, CDDA} type;
108 char start[3]; // MSF-format
109 char length[3]; // MSF-format
110 FILE *handle; // for multi-track images CDDA
111 unsigned int start_offset; // byte offset from start of above file
114 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
116 static int numtracks = 0;
117 static struct trackinfo ti[MAXTRACKS];
119 // get a sector from a msf-array
120 static unsigned int msf2sec(char *msf) {
121 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
124 static void sec2msf(unsigned int s, char *msf) {
125 msf[0] = s / 75 / 60;
126 s = s - msf[0] * 75 * 60;
132 // divide a string of xx:yy:zz into m, s, f
133 static void tok2msf(char *time, char *msf) {
136 token = strtok(time, ":");
138 msf[0] = atoi(token);
144 token = strtok(NULL, ":");
146 msf[1] = atoi(token);
152 token = strtok(NULL, ":");
154 msf[2] = atoi(token);
162 static long GetTickCount(void) {
163 static time_t initial_time = 0;
166 gettimeofday(&now, NULL);
168 if (initial_time == 0) {
169 initial_time = now.tv_sec;
172 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
176 // this thread plays audio data
178 static void playthread(void *param)
180 static void *playthread(void *param)
183 long osleep, d, t, i, s;
185 int ret = 0, sector_offs;
191 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
192 sector_offs = cdda_cur_sector - cdda_first_sector;
193 if (sector_offs < 0) {
194 d = CD_FRAMESIZE_RAW;
195 memset(sndbuffer + s, 0, d);
198 d = cdimg_read_func(cddaHandle, cdda_file_offset,
199 sndbuffer + s, sector_offs);
200 if (d < CD_FRAMESIZE_RAW)
214 if (!cdr.Muted && playing) {
216 for (i = 0; i < s / 2; i++) {
217 tmp = sndbuffer[i * 2];
218 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
219 sndbuffer[i * 2 + 1] = tmp;
223 // can't do it yet due to readahead..
224 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
226 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
231 } while (ret == 0x7761 && playing); // rearmed_wait
234 if (ret != 0x676f) { // !rearmed_go
238 // HACK: stop feeding data while emu is paused
240 while (stop && playing)
245 now = GetTickCount();
251 else if (osleep > CDDA_FRAMETIME) {
252 osleep = CDDA_FRAMETIME;
256 usleep(osleep * 1000);
270 // stop the CDDA playback
271 static void stopCDDA() {
278 WaitForSingleObject(threadid, INFINITE);
280 pthread_join(threadid, NULL);
284 // start the CDDA playback
285 static void startCDDA(void) {
293 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
295 pthread_create(&threadid, NULL, playthread, NULL);
299 // this function tries to get the .toc file of the given .bin
300 // the necessary data is put into the ti (trackinformation)-array
301 static int parsetoc(const char *isofile) {
302 char tocname[MAXPATHLEN];
304 char linebuf[256], tmp[256], name[256];
306 char time[20], time2[20];
307 unsigned int t, sector_offs, sector_size;
308 unsigned int current_zero_gap = 0;
312 // copy name of the iso and change extension from .bin to .toc
313 strncpy(tocname, isofile, sizeof(tocname));
314 tocname[MAXPATHLEN - 1] = '\0';
315 if (strlen(tocname) >= 4) {
316 strcpy(tocname + strlen(tocname) - 4, ".toc");
322 if ((fi = fopen(tocname, "r")) == NULL) {
323 // try changing extension to .cue (to satisfy some stupid tutorials)
324 strcpy(tocname + strlen(tocname) - 4, ".cue");
325 if ((fi = fopen(tocname, "r")) == NULL) {
326 // if filename is image.toc.bin, try removing .bin (for Brasero)
327 strcpy(tocname, isofile);
329 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
330 tocname[t - 4] = '\0';
331 if ((fi = fopen(tocname, "r")) == NULL) {
339 // check if it's really a TOC named as a .cue
340 fgets(linebuf, sizeof(linebuf), fi);
341 token = strtok(linebuf, " ");
342 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
346 fseek(fi, 0, SEEK_SET);
349 memset(&ti, 0, sizeof(ti));
350 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
352 sector_size = CD_FRAMESIZE_RAW;
353 sector_offs = 2 * 75;
355 // parse the .toc file
356 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
358 strncpy(tmp, linebuf, sizeof(linebuf));
359 token = strtok(tmp, " ");
361 if (token == NULL) continue;
363 if (!strcmp(token, "TRACK")) {
364 sector_offs += current_zero_gap;
365 current_zero_gap = 0;
368 token = strtok(NULL, " ");
371 if (!strncmp(token, "MODE2_RAW", 9)) {
372 ti[numtracks].type = DATA;
373 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
375 // check if this image contains mixed subchannel data
376 token = strtok(NULL, " ");
377 if (token != NULL && !strncmp(token, "RW", 2)) {
378 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
380 if (!strncmp(token, "RW_RAW", 6))
384 else if (!strncmp(token, "AUDIO", 5)) {
385 ti[numtracks].type = CDDA;
388 else if (!strcmp(token, "DATAFILE")) {
389 if (ti[numtracks].type == CDDA) {
390 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
391 ti[numtracks].start_offset = t;
392 t = t / sector_size + sector_offs;
393 sec2msf(t, (char *)&ti[numtracks].start);
394 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
397 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
398 tok2msf((char *)&time, (char *)&ti[numtracks].length);
401 else if (!strcmp(token, "FILE")) {
402 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
403 tok2msf((char *)&time, (char *)&ti[numtracks].start);
404 t += msf2sec(ti[numtracks].start) * sector_size;
405 ti[numtracks].start_offset = t;
406 t = t / sector_size + sector_offs;
407 sec2msf(t, (char *)&ti[numtracks].start);
408 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
410 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
411 // skip unneeded optional fields
412 while (token != NULL) {
413 token = strtok(NULL, " ");
414 if (strchr(token, ':') != NULL)
419 current_zero_gap = msf2sec(tmp);
422 t = ti[numtracks - 1].start_offset;
424 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
427 else if (!strcmp(token, "START")) {
428 token = strtok(NULL, " ");
429 if (token != NULL && strchr(token, ':')) {
432 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
433 t = msf2sec(ti[numtracks].start) + t;
434 sec2msf(t, (char *)&ti[numtracks].start);
444 // this function tries to get the .cue file of the given .bin
445 // the necessary data is put into the ti (trackinformation)-array
446 static int parsecue(const char *isofile) {
447 char cuename[MAXPATHLEN];
448 char filepath[MAXPATHLEN];
454 char linebuf[256], tmpb[256], dummy[256];
455 unsigned int incue_max_len;
456 unsigned int t, file_len, mode, sector_offs;
457 unsigned int sector_size = 2352;
461 // copy name of the iso and change extension from .bin to .cue
462 strncpy(cuename, isofile, sizeof(cuename));
463 cuename[MAXPATHLEN - 1] = '\0';
464 if (strlen(cuename) >= 4) {
465 strcpy(cuename + strlen(cuename) - 4, ".cue");
471 if ((fi = fopen(cuename, "r")) == NULL) {
475 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
476 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
478 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
479 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
480 // Don't proceed further, as this is actually a .toc file rather
483 return parsetoc(isofile);
485 fseek(fi, 0, SEEK_SET);
488 // build a path for files referenced in .cue
489 strncpy(filepath, cuename, sizeof(filepath));
490 tmp = strrchr(filepath, '/');
492 tmp = strrchr(filepath, '\\');
498 filepath[sizeof(filepath) - 1] = 0;
500 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
502 memset(&ti, 0, sizeof(ti));
505 sector_offs = 2 * 75;
507 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
508 strncpy(dummy, linebuf, sizeof(linebuf));
509 token = strtok(dummy, " ");
515 if (!strcmp(token, "TRACK")) {
519 if (strstr(linebuf, "AUDIO") != NULL) {
520 ti[numtracks].type = CDDA;
523 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
524 ti[numtracks].type = DATA;
526 SysPrintf(".cue: failed to parse TRACK\n");
527 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
529 if (sector_size == 0)
532 else if (!strcmp(token, "INDEX")) {
533 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
534 SysPrintf(".cue: failed to parse INDEX\n");
535 tok2msf(time, (char *)&ti[numtracks].start);
537 t = msf2sec(ti[numtracks].start);
538 ti[numtracks].start_offset = t * sector_size;
540 sec2msf(t, ti[numtracks].start);
542 // default track length to file length
543 t = file_len - ti[numtracks].start_offset / sector_size;
544 sec2msf(t, ti[numtracks].length);
546 if (numtracks > 1 && ti[numtracks].handle == NULL) {
547 // this track uses the same file as the last,
548 // start of this track is last track's end
549 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
550 sec2msf(t, ti[numtracks - 1].length);
552 if (numtracks > 1 && pregapOffset == -1)
553 pregapOffset = ti[numtracks].start_offset / sector_size;
555 else if (!strcmp(token, "PREGAP")) {
556 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
557 tok2msf(time, dummy);
558 sector_offs += msf2sec(dummy);
560 pregapOffset = -1; // mark to fill track start_offset
562 else if (!strcmp(token, "FILE")) {
563 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
565 sscanf(linebuf, " FILE %255s", tmpb);
568 ti[numtracks + 1].handle = fopen(tmpb, "rb");
569 if (ti[numtracks + 1].handle == NULL) {
571 tmp = strrchr(tmpb, '\\');
573 tmp = strrchr(tmpb, '/');
578 strncpy(incue_fname, tmp, incue_max_len);
579 ti[numtracks + 1].handle = fopen(filepath, "rb");
582 // update global offset if this is not first file in this .cue
583 if (numtracks + 1 > 1) {
585 sector_offs += file_len;
589 if (ti[numtracks + 1].handle == NULL) {
590 SysPrintf(_("\ncould not open: %s\n"), filepath);
593 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
594 file_len = ftell(ti[numtracks + 1].handle) / 2352;
596 if (numtracks == 0 && strlen(isofile) >= 4 &&
597 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
599 // user selected .cue as image file, use it's data track instead
601 cdHandle = fopen(filepath, "rb");
611 // this function tries to get the .ccd file of the given .img
612 // the necessary data is put into the ti (trackinformation)-array
613 static int parseccd(const char *isofile) {
614 char ccdname[MAXPATHLEN];
621 // copy name of the iso and change extension from .img to .ccd
622 strncpy(ccdname, isofile, sizeof(ccdname));
623 ccdname[MAXPATHLEN - 1] = '\0';
624 if (strlen(ccdname) >= 4) {
625 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
631 if ((fi = fopen(ccdname, "r")) == NULL) {
635 memset(&ti, 0, sizeof(ti));
637 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
638 if (!strncmp(linebuf, "[TRACK", 6)){
641 else if (!strncmp(linebuf, "MODE=", 5)) {
642 sscanf(linebuf, "MODE=%d", &t);
643 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
645 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
646 sscanf(linebuf, "INDEX 1=%d", &t);
647 sec2msf(t + 2 * 75, ti[numtracks].start);
648 ti[numtracks].start_offset = t * 2352;
650 // If we've already seen another track, this is its end
652 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
653 sec2msf(t, ti[numtracks - 1].length);
660 // Fill out the last track's end based on size
661 if (numtracks >= 1) {
662 fseek(cdHandle, 0, SEEK_END);
663 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
664 sec2msf(t, ti[numtracks].length);
670 // this function tries to get the .mds file of the given .mdf
671 // the necessary data is put into the ti (trackinformation)-array
672 static int parsemds(const char *isofile) {
673 char mdsname[MAXPATHLEN];
675 unsigned int offset, extra_offset, l, i;
680 // copy name of the iso and change extension from .mdf to .mds
681 strncpy(mdsname, isofile, sizeof(mdsname));
682 mdsname[MAXPATHLEN - 1] = '\0';
683 if (strlen(mdsname) >= 4) {
684 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
690 if ((fi = fopen(mdsname, "rb")) == NULL) {
694 memset(&ti, 0, sizeof(ti));
696 // check if it's a valid mds file
697 fread(&i, 1, sizeof(unsigned int), fi);
699 if (i != 0x4944454D) {
700 // not an valid mds file
705 // get offset to session block
706 fseek(fi, 0x50, SEEK_SET);
707 fread(&offset, 1, sizeof(unsigned int), fi);
708 offset = SWAP32(offset);
710 // get total number of tracks
712 fseek(fi, offset, SEEK_SET);
713 fread(&s, 1, sizeof(unsigned short), fi);
717 // get offset to track blocks
718 fseek(fi, 4, SEEK_CUR);
719 fread(&offset, 1, sizeof(unsigned int), fi);
720 offset = SWAP32(offset);
724 fseek(fi, offset + 4, SEEK_SET);
725 if (fgetc(fi) < 0xA0) {
731 // check if the image contains mixed subchannel data
732 fseek(fi, offset + 1, SEEK_SET);
733 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
736 for (i = 1; i <= numtracks; i++) {
737 fseek(fi, offset, SEEK_SET);
739 // get the track type
740 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
741 fseek(fi, 8, SEEK_CUR);
743 // get the track starting point
744 ti[i].start[0] = fgetc(fi);
745 ti[i].start[1] = fgetc(fi);
746 ti[i].start[2] = fgetc(fi);
748 fread(&extra_offset, 1, sizeof(unsigned int), fi);
749 extra_offset = SWAP32(extra_offset);
751 // get track start offset (in .mdf)
752 fseek(fi, offset + 0x28, SEEK_SET);
753 fread(&l, 1, sizeof(unsigned int), fi);
755 ti[i].start_offset = l;
758 fseek(fi, extra_offset, SEEK_SET);
759 fread(&l, 1, sizeof(unsigned int), fi);
762 pregapOffset = msf2sec(ti[i].start);
764 // get the track length
765 fread(&l, 1, sizeof(unsigned int), fi);
767 sec2msf(l, ti[i].length);
776 static int handlepbp(const char *isofile) {
779 unsigned int dontcare[8];
780 unsigned int psar_offs;
793 unsigned int dontcare[6];
796 off_t psisoimg_offs, cdimg_base;
797 unsigned int t, cd_length;
798 unsigned int offsettab[8];
799 const char *ext = NULL;
802 if (strlen(isofile) >= 4)
803 ext = isofile + strlen(isofile) - 4;
804 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
807 fseeko(cdHandle, 0, SEEK_SET);
811 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
812 if (ret != sizeof(pbp_hdr)) {
813 SysPrintf("failed to read pbp\n");
817 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
819 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
823 psisoimg_offs = pbp_hdr.psar_offs;
824 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
826 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
828 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
830 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
834 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
835 SysPrintf("failed to read offsettab\n");
839 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
840 if (offsettab[i] == 0)
843 cdrIsoMultidiskCount = i;
844 if (cdrIsoMultidiskCount == 0) {
845 SysPrintf("multidisk eboot has 0 images?\n");
849 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
850 cdrIsoMultidiskSelect = 0;
852 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
854 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
856 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
860 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
864 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
865 SysPrintf("bad psar_sig: %s\n", psar_sig);
870 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
872 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
876 // first 3 entries are special
877 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
878 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
879 numtracks = btoi(toc_entry.index1[0]);
881 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
882 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
883 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
885 for (i = 1; i <= numtracks; i++) {
886 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
888 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
890 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
891 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
892 ti[i].start_offset *= 2352;
893 ti[i].start[0] = btoi(toc_entry.index1[0]);
894 ti[i].start[1] = btoi(toc_entry.index1[1]);
895 ti[i].start[2] = btoi(toc_entry.index1[2]);
898 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
899 sec2msf(t, ti[i - 1].length);
902 t = cd_length - ti[numtracks].start_offset / 2352;
903 sec2msf(t, ti[numtracks].length);
906 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
908 SysPrintf("failed to seek to ISO index\n");
912 compr_img = calloc(1, sizeof(*compr_img));
913 if (compr_img == NULL)
916 compr_img->block_shift = 4;
917 compr_img->current_block = (unsigned int)-1;
919 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
920 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
921 if (compr_img->index_table == NULL)
924 cdimg_base = psisoimg_offs + 0x100000;
925 for (i = 0; i < compr_img->index_len; i++) {
926 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
927 if (ret != sizeof(index_entry)) {
928 SysPrintf("failed to read index_entry #%d\n", i);
932 if (index_entry.size == 0)
935 compr_img->index_table[i] = cdimg_base + index_entry.offset;
937 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
942 free(compr_img->index_table);
943 compr_img->index_table = NULL;
945 if (compr_img != NULL) {
952 static int handlecbin(const char *isofile) {
956 unsigned int header_size;
957 unsigned long long total_bytes;
958 unsigned int block_size;
959 unsigned char ver; // 1
961 unsigned char rsv_06[2];
963 const char *ext = NULL;
964 unsigned int *index_table = NULL;
965 unsigned int index = 0, plain;
968 if (strlen(isofile) >= 5)
969 ext = isofile + strlen(isofile) - 5;
970 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
973 fseek(cdHandle, 0, SEEK_SET);
975 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
976 if (ret != sizeof(ciso_hdr)) {
977 SysPrintf("failed to read ciso header\n");
981 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
982 SysPrintf("bad ciso header\n");
985 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
986 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
988 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
993 compr_img = calloc(1, sizeof(*compr_img));
994 if (compr_img == NULL)
997 compr_img->block_shift = 0;
998 compr_img->current_block = (unsigned int)-1;
1000 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
1001 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
1002 if (index_table == NULL)
1005 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1006 if (ret != compr_img->index_len) {
1007 SysPrintf("failed to read index table\n");
1011 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1012 if (compr_img->index_table == NULL)
1015 for (i = 0; i < compr_img->index_len + 1; i++) {
1016 index = index_table[i];
1017 plain = index & 0x80000000;
1018 index &= 0x7fffffff;
1019 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1021 compr_img->index_table[i] |= OFF_T_MSB;
1029 if (compr_img != NULL) {
1036 // this function tries to get the .sub file of the given .img
1037 static int opensubfile(const char *isoname) {
1038 char subname[MAXPATHLEN];
1040 // copy name of the iso and change extension from .img to .sub
1041 strncpy(subname, isoname, sizeof(subname));
1042 subname[MAXPATHLEN - 1] = '\0';
1043 if (strlen(subname) >= 4) {
1044 strcpy(subname + strlen(subname) - 4, ".sub");
1050 subHandle = fopen(subname, "rb");
1051 if (subHandle == NULL) {
1058 static int opensbifile(const char *isoname) {
1059 char sbiname[MAXPATHLEN];
1062 strncpy(sbiname, isoname, sizeof(sbiname));
1063 sbiname[MAXPATHLEN - 1] = '\0';
1064 if (strlen(sbiname) >= 4) {
1065 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1071 fseek(cdHandle, 0, SEEK_END);
1072 s = ftell(cdHandle) / 2352;
1074 return LoadSBI(sbiname, s);
1077 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1079 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1080 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1083 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1087 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1088 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1089 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1091 if (subChanRaw) DecodeRawSubData();
1096 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1101 if (z.zalloc == NULL) {
1102 // XXX: one-time leak here..
1108 ret = inflateInit2(&z, -15);
1111 ret = inflateReset(&z);
1116 z.avail_in = in_size;
1118 z.avail_out = *out_size;
1120 ret = inflate(&z, Z_NO_FLUSH);
1123 *out_size -= z.avail_out;
1124 return ret == 1 ? 0 : ret;
1127 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1129 unsigned long cdbuffer_size, cdbuffer_size_expect;
1136 sector += base / 2352;
1138 block = sector >> compr_img->block_shift;
1139 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1141 if (block == compr_img->current_block) {
1142 //printf("hit sect %d\n", sector);
1146 if (sector >= compr_img->index_len * 16) {
1147 SysPrintf("sector %d is past img end\n", sector);
1151 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1152 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1153 SysPrintf("seek error for block %d at %llx: ",
1154 block, (long long)start_byte);
1159 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1160 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1161 if (size > sizeof(compr_img->buff_compressed)) {
1162 SysPrintf("block %d is too large: %u\n", block, size);
1166 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1167 1, size, cdHandle) != size) {
1168 SysPrintf("read error for block %d at %x: ", block, start_byte);
1173 if (is_compressed) {
1174 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1175 cdbuffer_size = cdbuffer_size_expect;
1176 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1178 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1179 ret, block, sector);
1182 if (cdbuffer_size != cdbuffer_size_expect)
1183 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1184 cdbuffer_size_expect, sector);
1188 compr_img->current_block = block;
1191 if (dest != cdbuffer) // copy avoid HACK
1192 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1194 return CD_FRAMESIZE_RAW;
1197 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1201 fseek(f, base + sector * 2048, SEEK_SET);
1202 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1204 // not really necessary, fake mode 2 header
1205 memset(cdbuffer, 0, 12 * 2);
1206 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1207 cdbuffer[12 + 3] = 1;
1212 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1213 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1216 static unsigned char * CALLBACK ISOgetBuffer(void) {
1217 return cdbuffer + 12;
1220 static void PrintTracks(void) {
1223 for (i = 1; i <= numtracks; i++) {
1224 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1225 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1226 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1227 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1231 // This function is invoked by the front-end when opening an ISO
1232 // file for playback
1233 static long CALLBACK ISOopen(void) {
1234 boolean isMode1ISO = FALSE;
1235 char alt_bin_filename[MAXPATHLEN];
1236 const char *bin_filename;
1238 if (cdHandle != NULL) {
1239 return 0; // it's already open
1242 cdHandle = fopen(GetIsoFile(), "rb");
1243 if (cdHandle == NULL) {
1244 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1245 GetIsoFile(), strerror(errno));
1249 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1251 cddaBigEndian = FALSE;
1252 subChanMixed = FALSE;
1255 cdrIsoMultidiskCount = 1;
1258 CDR_getBuffer = ISOgetBuffer;
1259 cdimg_read_func = cdread_normal;
1261 if (parsetoc(GetIsoFile()) == 0) {
1262 SysPrintf("[+toc]");
1264 else if (parseccd(GetIsoFile()) == 0) {
1265 SysPrintf("[+ccd]");
1267 else if (parsemds(GetIsoFile()) == 0) {
1268 SysPrintf("[+mds]");
1270 else if (parsecue(GetIsoFile()) == 0) {
1271 SysPrintf("[+cue]");
1273 if (handlepbp(GetIsoFile()) == 0) {
1275 CDR_getBuffer = ISOgetBuffer_compr;
1276 cdimg_read_func = cdread_compressed;
1278 else if (handlecbin(GetIsoFile()) == 0) {
1279 SysPrintf("[cbin]");
1280 CDR_getBuffer = ISOgetBuffer_compr;
1281 cdimg_read_func = cdread_compressed;
1284 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1285 SysPrintf("[+sub]");
1287 if (opensbifile(GetIsoFile()) == 0) {
1288 SysPrintf("[+sbi]");
1291 fseeko(cdHandle, 0, SEEK_END);
1293 // maybe user selected metadata file instead of main .bin ..
1294 bin_filename = GetIsoFile();
1295 if (ftello(cdHandle) < 2352 * 0x10) {
1296 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1301 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1302 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1303 if (strlen(alt_bin_filename) >= 4) {
1304 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1305 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1307 tmpf = fopen(alt_bin_filename, "rb");
1313 bin_filename = alt_bin_filename;
1316 fseeko(cdHandle, 0, SEEK_END);
1320 // guess whether it is mode1/2048
1321 if (ftello(cdHandle) % 2048 == 0) {
1322 unsigned int modeTest = 0;
1323 fseek(cdHandle, 0, SEEK_SET);
1324 fread(&modeTest, 4, 1, cdHandle);
1325 if (SWAP32(modeTest) != 0xffffff00) {
1326 SysPrintf("[2048]");
1330 fseek(cdHandle, 0, SEEK_SET);
1337 cdimg_read_func = cdread_sub_mixed;
1338 else if (isMode1ISO)
1339 cdimg_read_func = cdread_2048;
1341 // make sure we have another handle open for cdda
1342 if (numtracks > 1 && ti[1].handle == NULL) {
1343 ti[1].handle = fopen(bin_filename, "rb");
1345 cdda_cur_sector = 0;
1346 cdda_file_offset = 0;
1351 static long CALLBACK ISOclose(void) {
1354 if (cdHandle != NULL) {
1358 if (subHandle != NULL) {
1365 if (compr_img != NULL) {
1366 free(compr_img->index_table);
1371 for (i = 1; i <= numtracks; i++) {
1372 if (ti[i].handle != NULL) {
1373 fclose(ti[i].handle);
1374 ti[i].handle = NULL;
1381 memset(cdbuffer, 0, sizeof(cdbuffer));
1382 CDR_getBuffer = ISOgetBuffer;
1387 static long CALLBACK ISOinit(void) {
1388 assert(cdHandle == NULL);
1389 assert(subHandle == NULL);
1391 return 0; // do nothing
1394 static long CALLBACK ISOshutdown(void) {
1399 // return Starting and Ending Track
1401 // byte 0 - start track
1402 // byte 1 - end track
1403 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1406 if (numtracks > 0) {
1407 buffer[1] = numtracks;
1416 // return Track Time
1421 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1424 unsigned char time[3];
1425 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1426 sec2msf(sect, (char *)time);
1427 buffer[2] = time[0];
1428 buffer[1] = time[1];
1429 buffer[0] = time[2];
1431 else if (numtracks > 0 && track <= numtracks) {
1432 buffer[2] = ti[track].start[0];
1433 buffer[1] = ti[track].start[1];
1434 buffer[0] = ti[track].start[2];
1445 // decode 'raw' subchannel data ripped by cdrdao
1446 static void DecodeRawSubData(void) {
1447 unsigned char subQData[12];
1450 memset(subQData, 0, sizeof(subQData));
1452 for (i = 0; i < 8 * 12; i++) {
1453 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1454 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1458 memcpy(&subbuffer[12], subQData, 12);
1462 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1464 static long CALLBACK ISOreadTrack(unsigned char *time) {
1465 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1468 if (cdHandle == NULL) {
1473 subChanMissing = FALSE;
1474 if (sector >= pregapOffset) {
1476 if (sector < pregapOffset)
1477 subChanMissing = TRUE;
1481 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1485 if (subHandle != NULL) {
1486 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1487 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1489 if (subChanRaw) DecodeRawSubData();
1496 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1497 // does NOT uses bcd format
1498 static long CALLBACK ISOplay(unsigned char *time) {
1505 cdda_cur_sector = msf2sec((char *)time);
1506 for (i = numtracks; i > 1; i--) {
1507 cdda_first_sector = msf2sec(ti[i].start);
1508 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1511 cdda_file_offset = ti[i].start_offset;
1513 // find the file that contains this track
1515 if (ti[i].handle != NULL)
1518 cddaHandle = ti[i].handle;
1520 if (SPU_playCDDAchannel != NULL)
1527 static long CALLBACK ISOstop(void) {
1532 // gets subchannel data
1533 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1534 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1541 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1544 CDR__getStatus(stat);
1548 stat->Status |= 0x80;
1551 // BIOS - boot ID (CD type)
1552 stat->Type = ti[1].type;
1555 // relative -> absolute time
1557 sec2msf(sect, (char *)stat->Time);
1562 // read CDDA sector into buffer
1563 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1564 unsigned char msf[3] = {m, s, f};
1565 unsigned int file, track, track_start = 0;
1568 cddaCurPos = msf2sec((char *)msf);
1570 // find current track index
1571 for (track = numtracks; ; track--) {
1572 track_start = msf2sec(ti[track].start);
1573 if (track_start <= cddaCurPos)
1579 // data tracks play silent
1580 if (ti[track].type != CDDA) {
1581 memset(buffer, 0, CD_FRAMESIZE_RAW);
1587 // find the file that contains this track
1588 for (file = track; file > 1; file--)
1589 if (ti[file].handle != NULL)
1593 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1594 buffer, cddaCurPos - track_start);
1595 if (ret != CD_FRAMESIZE_RAW) {
1596 memset(buffer, 0, CD_FRAMESIZE_RAW);
1600 if (cddaBigEndian) {
1604 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1605 tmp = buffer[i * 2];
1606 buffer[i * 2] = buffer[i * 2 + 1];
1607 buffer[i * 2 + 1] = tmp;
1614 void cdrIsoInit(void) {
1616 CDR_shutdown = ISOshutdown;
1618 CDR_close = ISOclose;
1619 CDR_getTN = ISOgetTN;
1620 CDR_getTD = ISOgetTD;
1621 CDR_readTrack = ISOreadTrack;
1622 CDR_getBuffer = ISOgetBuffer;
1625 CDR_getBufferSub = ISOgetBufferSub;
1626 CDR_getStatus = ISOgetStatus;
1627 CDR_readCDDA = ISOreadCDDA;
1629 CDR_getDriveLetter = CDR__getDriveLetter;
1630 CDR_configure = CDR__configure;
1631 CDR_test = CDR__test;
1632 CDR_about = CDR__about;
1633 CDR_setfilename = CDR__setfilename;
1638 int cdrIsoActive(void) {
1639 return (cdHandle != NULL);