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"
31 #define strcasecmp _stricmp
40 unsigned int cdrIsoMultidiskCount;
41 unsigned int cdrIsoMultidiskSelect;
43 static FILE *cdHandle = NULL;
44 static FILE *cddaHandle = NULL;
45 static FILE *subHandle = NULL;
47 static boolean subChanMixed = FALSE;
48 static boolean subChanRaw = FALSE;
49 static boolean subChanMissing = FALSE;
51 static boolean multifile = FALSE;
53 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
54 static unsigned char subbuffer[SUB_FRAMESIZE];
56 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
58 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
61 static HANDLE threadid;
63 static pthread_t threadid;
65 static unsigned int initial_offset = 0;
66 static boolean playing = FALSE;
67 static boolean cddaBigEndian = FALSE;
68 // cdda sectors in toc, byte offset in file
69 static unsigned int cdda_cur_sector;
70 static unsigned int cdda_first_sector;
71 static unsigned int cdda_file_offset;
72 /* Frame offset into CD image where pregap data would be found if it was there.
73 * If a game seeks there we must *not* return subchannel data since it's
74 * not in the CD image, so that cdrom code can fake subchannel data instead.
75 * XXX: there could be multiple pregaps but PSX dumps only have one? */
76 static unsigned int pregapOffset;
78 #define cddaCurPos cdda_cur_sector
80 // compressed image stuff
82 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
83 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
84 unsigned int *index_table;
85 unsigned int index_len;
86 unsigned int block_shift;
87 unsigned int current_block;
88 unsigned int sector_in_blk;
91 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
93 char* CALLBACK CDR__getDriveLetter(void);
94 long CALLBACK CDR__configure(void);
95 long CALLBACK CDR__test(void);
96 void CALLBACK CDR__about(void);
97 long CALLBACK CDR__setfilename(char *filename);
98 long CALLBACK CDR__getStatus(struct CdrStat *stat);
100 static void DecodeRawSubData(void);
103 enum {DATA=1, CDDA} type;
104 char start[3]; // MSF-format
105 char length[3]; // MSF-format
106 FILE *handle; // for multi-track images CDDA
107 unsigned int start_offset; // byte offset from start of above file
110 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
112 static int numtracks = 0;
113 static struct trackinfo ti[MAXTRACKS];
115 // get a sector from a msf-array
116 static unsigned int msf2sec(char *msf) {
117 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
120 static void sec2msf(unsigned int s, char *msf) {
121 msf[0] = s / 75 / 60;
122 s = s - msf[0] * 75 * 60;
128 // divide a string of xx:yy:zz into m, s, f
129 static void tok2msf(char *time, char *msf) {
132 token = strtok(time, ":");
134 msf[0] = atoi(token);
140 token = strtok(NULL, ":");
142 msf[1] = atoi(token);
148 token = strtok(NULL, ":");
150 msf[2] = atoi(token);
158 static long GetTickCount(void) {
159 static time_t initial_time = 0;
162 gettimeofday(&now, NULL);
164 if (initial_time == 0) {
165 initial_time = now.tv_sec;
168 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
172 // this thread plays audio data
174 static void playthread(void *param)
176 static void *playthread(void *param)
179 long osleep, d, t, i, s;
181 int ret = 0, sector_offs;
187 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
188 sector_offs = cdda_cur_sector - cdda_first_sector;
189 if (sector_offs < 0) {
190 d = CD_FRAMESIZE_RAW;
191 memset(sndbuffer + s, 0, d);
194 d = cdimg_read_func(cddaHandle, cdda_file_offset,
195 sndbuffer + s, sector_offs);
196 if (d < CD_FRAMESIZE_RAW)
210 if (!cdr.Muted && playing) {
212 for (i = 0; i < s / 2; i++) {
213 tmp = sndbuffer[i * 2];
214 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
215 sndbuffer[i * 2 + 1] = tmp;
219 // can't do it yet due to readahead..
220 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
222 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
225 } while (ret == 0x7761 && playing); // rearmed_wait
228 if (ret != 0x676f) { // !rearmed_go
232 // HACK: stop feeding data while emu is paused
234 while (stop && playing)
237 now = GetTickCount();
243 else if (osleep > CDDA_FRAMETIME) {
244 osleep = CDDA_FRAMETIME;
248 usleep(osleep * 1000);
262 // stop the CDDA playback
263 static void stopCDDA() {
270 WaitForSingleObject(threadid, INFINITE);
272 pthread_join(threadid, NULL);
276 // start the CDDA playback
277 static void startCDDA(void) {
285 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
287 pthread_create(&threadid, NULL, playthread, NULL);
291 // this function tries to get the .toc file of the given .bin
292 // the necessary data is put into the ti (trackinformation)-array
293 static int parsetoc(const char *isofile) {
294 char tocname[MAXPATHLEN];
296 char linebuf[256], tmp[256], name[256];
298 char time[20], time2[20];
299 unsigned int t, sector_offs, sector_size;
300 unsigned int current_zero_gap = 0;
304 // copy name of the iso and change extension from .bin to .toc
305 strncpy(tocname, isofile, sizeof(tocname));
306 tocname[MAXPATHLEN - 1] = '\0';
307 if (strlen(tocname) >= 4) {
308 strcpy(tocname + strlen(tocname) - 4, ".toc");
314 if ((fi = fopen(tocname, "r")) == NULL) {
315 // try changing extension to .cue (to satisfy some stupid tutorials)
316 strcpy(tocname + strlen(tocname) - 4, ".cue");
317 if ((fi = fopen(tocname, "r")) == NULL) {
318 // if filename is image.toc.bin, try removing .bin (for Brasero)
319 strcpy(tocname, isofile);
321 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
322 tocname[t - 4] = '\0';
323 if ((fi = fopen(tocname, "r")) == NULL) {
331 // check if it's really a TOC named as a .cue
332 fgets(linebuf, sizeof(linebuf), fi);
333 token = strtok(linebuf, " ");
334 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
338 fseek(fi, 0, SEEK_SET);
341 memset(&ti, 0, sizeof(ti));
342 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
344 sector_size = CD_FRAMESIZE_RAW;
345 sector_offs = 2 * 75;
347 // parse the .toc file
348 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
350 strncpy(tmp, linebuf, sizeof(linebuf));
351 token = strtok(tmp, " ");
353 if (token == NULL) continue;
355 if (!strcmp(token, "TRACK")) {
356 sector_offs += current_zero_gap;
357 current_zero_gap = 0;
360 token = strtok(NULL, " ");
363 if (!strncmp(token, "MODE2_RAW", 9)) {
364 ti[numtracks].type = DATA;
365 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
367 // check if this image contains mixed subchannel data
368 token = strtok(NULL, " ");
369 if (token != NULL && !strncmp(token, "RW", 2)) {
370 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
372 if (!strncmp(token, "RW_RAW", 6))
376 else if (!strncmp(token, "AUDIO", 5)) {
377 ti[numtracks].type = CDDA;
380 else if (!strcmp(token, "DATAFILE")) {
381 if (ti[numtracks].type == CDDA) {
382 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
383 ti[numtracks].start_offset = t;
384 t = t / sector_size + sector_offs;
385 sec2msf(t, (char *)&ti[numtracks].start);
386 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
389 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
390 tok2msf((char *)&time, (char *)&ti[numtracks].length);
393 else if (!strcmp(token, "FILE")) {
394 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
395 tok2msf((char *)&time, (char *)&ti[numtracks].start);
396 t += msf2sec(ti[numtracks].start) * sector_size;
397 ti[numtracks].start_offset = t;
398 t = t / sector_size + sector_offs;
399 sec2msf(t, (char *)&ti[numtracks].start);
400 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
402 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
403 // skip unneeded optional fields
404 while (token != NULL) {
405 token = strtok(NULL, " ");
406 if (strchr(token, ':') != NULL)
411 current_zero_gap = msf2sec(tmp);
414 t = ti[numtracks - 1].start_offset;
416 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
419 else if (!strcmp(token, "START")) {
420 token = strtok(NULL, " ");
421 if (token != NULL && strchr(token, ':')) {
424 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
425 t = msf2sec(ti[numtracks].start) + t;
426 sec2msf(t, (char *)&ti[numtracks].start);
436 // this function tries to get the .cue file of the given .bin
437 // the necessary data is put into the ti (trackinformation)-array
438 static int parsecue(const char *isofile) {
439 char cuename[MAXPATHLEN];
440 char filepath[MAXPATHLEN];
446 char linebuf[256], tmpb[256], dummy[256];
447 unsigned int incue_max_len;
448 unsigned int t, file_len, mode, sector_offs;
449 unsigned int sector_size = 2352;
453 // copy name of the iso and change extension from .bin to .cue
454 strncpy(cuename, isofile, sizeof(cuename));
455 cuename[MAXPATHLEN - 1] = '\0';
456 if (strlen(cuename) >= 4) {
457 strcpy(cuename + strlen(cuename) - 4, ".cue");
463 if ((fi = fopen(cuename, "r")) == NULL) {
467 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
468 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
470 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
471 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
472 // Don't proceed further, as this is actually a .toc file rather
475 return parsetoc(isofile);
477 fseek(fi, 0, SEEK_SET);
480 // build a path for files referenced in .cue
481 strncpy(filepath, cuename, sizeof(filepath));
482 tmp = strrchr(filepath, '/');
484 tmp = strrchr(filepath, '\\');
490 filepath[sizeof(filepath) - 1] = 0;
492 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
494 memset(&ti, 0, sizeof(ti));
497 sector_offs = 2 * 75;
499 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
500 strncpy(dummy, linebuf, sizeof(linebuf));
501 token = strtok(dummy, " ");
507 if (!strcmp(token, "TRACK")) {
511 if (strstr(linebuf, "AUDIO") != NULL) {
512 ti[numtracks].type = CDDA;
515 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
516 ti[numtracks].type = DATA;
518 SysPrintf(".cue: failed to parse TRACK\n");
519 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
521 if (sector_size == 0)
524 else if (!strcmp(token, "INDEX")) {
525 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
526 SysPrintf(".cue: failed to parse INDEX\n");
527 tok2msf(time, (char *)&ti[numtracks].start);
529 t = msf2sec(ti[numtracks].start);
530 ti[numtracks].start_offset = t * sector_size;
532 sec2msf(t, ti[numtracks].start);
534 // default track length to file length
535 t = file_len - ti[numtracks].start_offset / sector_size;
536 sec2msf(t, ti[numtracks].length);
538 if (numtracks > 1 && ti[numtracks].handle == NULL) {
539 // this track uses the same file as the last,
540 // start of this track is last track's end
541 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
542 sec2msf(t, ti[numtracks - 1].length);
544 if (numtracks > 1 && pregapOffset == -1)
545 pregapOffset = ti[numtracks].start_offset / sector_size;
547 else if (!strcmp(token, "PREGAP")) {
548 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
549 tok2msf(time, dummy);
550 sector_offs += msf2sec(dummy);
552 pregapOffset = -1; // mark to fill track start_offset
554 else if (!strcmp(token, "FILE")) {
555 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
557 sscanf(linebuf, " FILE %255s", tmpb);
560 ti[numtracks + 1].handle = fopen(tmpb, "rb");
561 if (ti[numtracks + 1].handle == NULL) {
563 tmp = strrchr(tmpb, '\\');
565 tmp = strrchr(tmpb, '/');
570 strncpy(incue_fname, tmp, incue_max_len);
571 ti[numtracks + 1].handle = fopen(filepath, "rb");
574 // update global offset if this is not first file in this .cue
575 if (numtracks + 1 > 1) {
577 sector_offs += file_len;
581 if (ti[numtracks + 1].handle == NULL) {
582 SysPrintf(_("\ncould not open: %s\n"), filepath);
585 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
586 file_len = ftell(ti[numtracks + 1].handle) / 2352;
588 if (numtracks == 0 && strlen(isofile) >= 4 &&
589 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
591 // user selected .cue as image file, use it's data track instead
593 cdHandle = fopen(filepath, "rb");
603 // this function tries to get the .ccd file of the given .img
604 // the necessary data is put into the ti (trackinformation)-array
605 static int parseccd(const char *isofile) {
606 char ccdname[MAXPATHLEN];
613 // copy name of the iso and change extension from .img to .ccd
614 strncpy(ccdname, isofile, sizeof(ccdname));
615 ccdname[MAXPATHLEN - 1] = '\0';
616 if (strlen(ccdname) >= 4) {
617 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
623 if ((fi = fopen(ccdname, "r")) == NULL) {
627 memset(&ti, 0, sizeof(ti));
629 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
630 if (!strncmp(linebuf, "[TRACK", 6)){
633 else if (!strncmp(linebuf, "MODE=", 5)) {
634 sscanf(linebuf, "MODE=%d", &t);
635 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
637 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
638 sscanf(linebuf, "INDEX 1=%d", &t);
639 sec2msf(t + 2 * 75, ti[numtracks].start);
640 ti[numtracks].start_offset = t * 2352;
642 // If we've already seen another track, this is its end
644 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
645 sec2msf(t, ti[numtracks - 1].length);
652 // Fill out the last track's end based on size
653 if (numtracks >= 1) {
654 fseek(cdHandle, 0, SEEK_END);
655 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
656 sec2msf(t, ti[numtracks].length);
662 // this function tries to get the .mds file of the given .mdf
663 // the necessary data is put into the ti (trackinformation)-array
664 static int parsemds(const char *isofile) {
665 char mdsname[MAXPATHLEN];
667 unsigned int offset, extra_offset, l, i;
672 // copy name of the iso and change extension from .mdf to .mds
673 strncpy(mdsname, isofile, sizeof(mdsname));
674 mdsname[MAXPATHLEN - 1] = '\0';
675 if (strlen(mdsname) >= 4) {
676 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
682 if ((fi = fopen(mdsname, "rb")) == NULL) {
686 memset(&ti, 0, sizeof(ti));
688 // check if it's a valid mds file
689 fread(&i, 1, sizeof(unsigned int), fi);
691 if (i != 0x4944454D) {
692 // not an valid mds file
697 // get offset to session block
698 fseek(fi, 0x50, SEEK_SET);
699 fread(&offset, 1, sizeof(unsigned int), fi);
700 offset = SWAP32(offset);
702 // get total number of tracks
704 fseek(fi, offset, SEEK_SET);
705 fread(&s, 1, sizeof(unsigned short), fi);
709 // get offset to track blocks
710 fseek(fi, 4, SEEK_CUR);
711 fread(&offset, 1, sizeof(unsigned int), fi);
712 offset = SWAP32(offset);
716 fseek(fi, offset + 4, SEEK_SET);
717 if (fgetc(fi) < 0xA0) {
723 // check if the image contains mixed subchannel data
724 fseek(fi, offset + 1, SEEK_SET);
725 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
728 for (i = 1; i <= numtracks; i++) {
729 fseek(fi, offset, SEEK_SET);
731 // get the track type
732 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
733 fseek(fi, 8, SEEK_CUR);
735 // get the track starting point
736 ti[i].start[0] = fgetc(fi);
737 ti[i].start[1] = fgetc(fi);
738 ti[i].start[2] = fgetc(fi);
740 fread(&extra_offset, 1, sizeof(unsigned int), fi);
741 extra_offset = SWAP32(extra_offset);
743 // get track start offset (in .mdf)
744 fseek(fi, offset + 0x28, SEEK_SET);
745 fread(&l, 1, sizeof(unsigned int), fi);
747 ti[i].start_offset = l;
750 fseek(fi, extra_offset, SEEK_SET);
751 fread(&l, 1, sizeof(unsigned int), fi);
754 pregapOffset = msf2sec(ti[i].start);
756 // get the track length
757 fread(&l, 1, sizeof(unsigned int), fi);
759 sec2msf(l, ti[i].length);
768 static int handlepbp(const char *isofile) {
771 unsigned int dontcare[8];
772 unsigned int psar_offs;
785 unsigned int dontcare[6];
788 unsigned int t, cd_length, cdimg_base;
789 unsigned int offsettab[8], psisoimg_offs;
790 const char *ext = NULL;
793 if (strlen(isofile) >= 4)
794 ext = isofile + strlen(isofile) - 4;
795 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
798 fseek(cdHandle, 0, SEEK_SET);
802 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
803 if (ret != sizeof(pbp_hdr)) {
804 SysPrintf("failed to read pbp\n");
808 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
810 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
814 psisoimg_offs = pbp_hdr.psar_offs;
815 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
817 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
819 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
821 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
825 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
826 SysPrintf("failed to read offsettab\n");
830 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
831 if (offsettab[i] == 0)
834 cdrIsoMultidiskCount = i;
835 if (cdrIsoMultidiskCount == 0) {
836 SysPrintf("multidisk eboot has 0 images?\n");
840 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
841 cdrIsoMultidiskSelect = 0;
843 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
845 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
847 SysPrintf("failed to seek to %x\n", psisoimg_offs);
851 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
855 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
856 SysPrintf("bad psar_sig: %s\n", psar_sig);
861 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
863 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
867 // first 3 entries are special
868 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
869 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
870 numtracks = btoi(toc_entry.index1[0]);
872 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
873 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
874 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
876 for (i = 1; i <= numtracks; i++) {
877 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
879 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
881 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
882 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
883 ti[i].start_offset *= 2352;
884 ti[i].start[0] = btoi(toc_entry.index1[0]);
885 ti[i].start[1] = btoi(toc_entry.index1[1]);
886 ti[i].start[2] = btoi(toc_entry.index1[2]);
889 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
890 sec2msf(t, ti[i - 1].length);
893 t = cd_length - ti[numtracks].start_offset / 2352;
894 sec2msf(t, ti[numtracks].length);
897 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
899 SysPrintf("failed to seek to ISO index\n");
903 compr_img = calloc(1, sizeof(*compr_img));
904 if (compr_img == NULL)
907 compr_img->block_shift = 4;
908 compr_img->current_block = (unsigned int)-1;
910 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
911 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
912 if (compr_img->index_table == NULL)
915 cdimg_base = psisoimg_offs + 0x100000;
916 for (i = 0; i < compr_img->index_len; i++) {
917 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
918 if (ret != sizeof(index_entry)) {
919 SysPrintf("failed to read index_entry #%d\n", i);
923 if (index_entry.size == 0)
926 compr_img->index_table[i] = cdimg_base + index_entry.offset;
928 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
933 free(compr_img->index_table);
934 compr_img->index_table = NULL;
936 if (compr_img != NULL) {
943 static int handlecbin(const char *isofile) {
947 unsigned int header_size;
948 unsigned long long total_bytes;
949 unsigned int block_size;
950 unsigned char ver; // 1
952 unsigned char rsv_06[2];
954 const char *ext = NULL;
955 unsigned int index = 0, plain;
958 if (strlen(isofile) >= 5)
959 ext = isofile + strlen(isofile) - 5;
960 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
963 fseek(cdHandle, 0, SEEK_SET);
965 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
966 if (ret != sizeof(ciso_hdr)) {
967 SysPrintf("failed to read ciso header\n");
971 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
972 SysPrintf("bad ciso header\n");
975 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
976 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
978 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
983 compr_img = calloc(1, sizeof(*compr_img));
984 if (compr_img == NULL)
987 compr_img->block_shift = 0;
988 compr_img->current_block = (unsigned int)-1;
990 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
991 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
992 if (compr_img->index_table == NULL)
995 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
996 if (ret != compr_img->index_len) {
997 SysPrintf("failed to read index table\n");
1001 for (i = 0; i < compr_img->index_len + 1; i++) {
1002 index = compr_img->index_table[i];
1003 plain = index & 0x80000000;
1004 index &= 0x7fffffff;
1005 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1007 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1008 SysPrintf("warning: ciso img too large, expect problems\n");
1013 free(compr_img->index_table);
1014 compr_img->index_table = NULL;
1016 if (compr_img != NULL) {
1023 // this function tries to get the .sub file of the given .img
1024 static int opensubfile(const char *isoname) {
1025 char subname[MAXPATHLEN];
1027 // copy name of the iso and change extension from .img to .sub
1028 strncpy(subname, isoname, sizeof(subname));
1029 subname[MAXPATHLEN - 1] = '\0';
1030 if (strlen(subname) >= 4) {
1031 strcpy(subname + strlen(subname) - 4, ".sub");
1037 subHandle = fopen(subname, "rb");
1038 if (subHandle == NULL) {
1045 static int opensbifile(const char *isoname) {
1046 char sbiname[MAXPATHLEN];
1049 strncpy(sbiname, isoname, sizeof(sbiname));
1050 sbiname[MAXPATHLEN - 1] = '\0';
1051 if (strlen(sbiname) >= 4) {
1052 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1058 fseek(cdHandle, 0, SEEK_END);
1059 s = ftell(cdHandle) / 2352;
1061 return LoadSBI(sbiname, s);
1064 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1066 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1067 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1070 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1074 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1075 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1076 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1078 if (subChanRaw) DecodeRawSubData();
1083 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1088 if (z.zalloc == NULL) {
1089 // XXX: one-time leak here..
1095 ret = inflateInit2(&z, -15);
1098 ret = inflateReset(&z);
1103 z.avail_in = in_size;
1105 z.avail_out = *out_size;
1107 ret = inflate(&z, Z_NO_FLUSH);
1110 *out_size -= z.avail_out;
1111 return ret == 1 ? 0 : ret;
1114 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1116 unsigned long cdbuffer_size, cdbuffer_size_expect;
1117 unsigned int start_byte, size;
1122 sector += base / 2352;
1124 block = sector >> compr_img->block_shift;
1125 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1127 if (block == compr_img->current_block) {
1128 //printf("hit sect %d\n", sector);
1132 if (sector >= compr_img->index_len * 16) {
1133 SysPrintf("sector %d is past img end\n", sector);
1137 start_byte = compr_img->index_table[block] & 0x7fffffff;
1138 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1139 SysPrintf("seek error for block %d at %x: ",
1145 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1146 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1147 if (size > sizeof(compr_img->buff_compressed)) {
1148 SysPrintf("block %d is too large: %u\n", block, size);
1152 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1153 1, size, cdHandle) != size) {
1154 SysPrintf("read error for block %d at %x: ", block, start_byte);
1159 if (is_compressed) {
1160 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1161 cdbuffer_size = cdbuffer_size_expect;
1162 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1164 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1165 ret, block, sector);
1168 if (cdbuffer_size != cdbuffer_size_expect)
1169 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1170 cdbuffer_size_expect, sector);
1174 compr_img->current_block = block;
1177 if (dest != cdbuffer) // copy avoid HACK
1178 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1180 return CD_FRAMESIZE_RAW;
1183 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1187 fseek(f, base + sector * 2048, SEEK_SET);
1188 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1190 // not really necessary, fake mode 2 header
1191 memset(cdbuffer, 0, 12 * 2);
1192 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1193 cdbuffer[12 + 3] = 1;
1198 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1199 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1202 static unsigned char * CALLBACK ISOgetBuffer(void) {
1203 return cdbuffer + 12;
1206 static void PrintTracks(void) {
1209 for (i = 1; i <= numtracks; i++) {
1210 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1211 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1212 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1213 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1217 // This function is invoked by the front-end when opening an ISO
1218 // file for playback
1219 static long CALLBACK ISOopen(void) {
1220 boolean isMode1ISO = FALSE;
1221 char alt_bin_filename[MAXPATHLEN];
1222 const char *bin_filename;
1224 if (cdHandle != NULL) {
1225 return 0; // it's already open
1228 cdHandle = fopen(GetIsoFile(), "rb");
1229 if (cdHandle == NULL) {
1230 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1231 GetIsoFile(), strerror(errno));
1235 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1237 cddaBigEndian = FALSE;
1238 subChanMixed = FALSE;
1241 cdrIsoMultidiskCount = 1;
1244 CDR_getBuffer = ISOgetBuffer;
1245 cdimg_read_func = cdread_normal;
1247 if (parsetoc(GetIsoFile()) == 0) {
1248 SysPrintf("[+toc]");
1250 else if (parseccd(GetIsoFile()) == 0) {
1251 SysPrintf("[+ccd]");
1253 else if (parsemds(GetIsoFile()) == 0) {
1254 SysPrintf("[+mds]");
1256 else if (parsecue(GetIsoFile()) == 0) {
1257 SysPrintf("[+cue]");
1259 if (handlepbp(GetIsoFile()) == 0) {
1261 CDR_getBuffer = ISOgetBuffer_compr;
1262 cdimg_read_func = cdread_compressed;
1264 else if (handlecbin(GetIsoFile()) == 0) {
1265 SysPrintf("[cbin]");
1266 CDR_getBuffer = ISOgetBuffer_compr;
1267 cdimg_read_func = cdread_compressed;
1270 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1271 SysPrintf("[+sub]");
1273 if (opensbifile(GetIsoFile()) == 0) {
1274 SysPrintf("[+sbi]");
1277 fseek(cdHandle, 0, SEEK_END);
1279 // maybe user selected metadata file instead of main .bin ..
1280 bin_filename = GetIsoFile();
1281 if (ftell(cdHandle) < 2352 * 0x10) {
1282 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1287 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1288 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1289 if (strlen(alt_bin_filename) >= 4) {
1290 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1291 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1293 tmpf = fopen(alt_bin_filename, "rb");
1299 bin_filename = alt_bin_filename;
1302 fseek(cdHandle, 0, SEEK_END);
1306 // guess whether it is mode1/2048
1307 if (ftell(cdHandle) % 2048 == 0) {
1308 unsigned int modeTest = 0;
1309 fseek(cdHandle, 0, SEEK_SET);
1310 fread(&modeTest, 4, 1, cdHandle);
1311 if (SWAP32(modeTest) != 0xffffff00) {
1312 SysPrintf("[2048]");
1316 fseek(cdHandle, 0, SEEK_SET);
1323 cdimg_read_func = cdread_sub_mixed;
1324 else if (isMode1ISO)
1325 cdimg_read_func = cdread_2048;
1327 // make sure we have another handle open for cdda
1328 if (numtracks > 1 && ti[1].handle == NULL) {
1329 ti[1].handle = fopen(bin_filename, "rb");
1331 cdda_cur_sector = 0;
1332 cdda_file_offset = 0;
1337 static long CALLBACK ISOclose(void) {
1340 if (cdHandle != NULL) {
1344 if (subHandle != NULL) {
1351 if (compr_img != NULL) {
1352 free(compr_img->index_table);
1357 for (i = 1; i <= numtracks; i++) {
1358 if (ti[i].handle != NULL) {
1359 fclose(ti[i].handle);
1360 ti[i].handle = NULL;
1367 memset(cdbuffer, 0, sizeof(cdbuffer));
1368 CDR_getBuffer = ISOgetBuffer;
1373 static long CALLBACK ISOinit(void) {
1374 assert(cdHandle == NULL);
1375 assert(subHandle == NULL);
1377 return 0; // do nothing
1380 static long CALLBACK ISOshutdown(void) {
1385 // return Starting and Ending Track
1387 // byte 0 - start track
1388 // byte 1 - end track
1389 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1392 if (numtracks > 0) {
1393 buffer[1] = numtracks;
1402 // return Track Time
1407 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1410 unsigned char time[3];
1411 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1412 sec2msf(sect, (char *)time);
1413 buffer[2] = time[0];
1414 buffer[1] = time[1];
1415 buffer[0] = time[2];
1417 else if (numtracks > 0 && track <= numtracks) {
1418 buffer[2] = ti[track].start[0];
1419 buffer[1] = ti[track].start[1];
1420 buffer[0] = ti[track].start[2];
1431 // decode 'raw' subchannel data ripped by cdrdao
1432 static void DecodeRawSubData(void) {
1433 unsigned char subQData[12];
1436 memset(subQData, 0, sizeof(subQData));
1438 for (i = 0; i < 8 * 12; i++) {
1439 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1440 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1444 memcpy(&subbuffer[12], subQData, 12);
1448 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1450 static long CALLBACK ISOreadTrack(unsigned char *time) {
1451 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1454 if (cdHandle == NULL) {
1459 subChanMissing = FALSE;
1460 if (sector >= pregapOffset) {
1462 if (sector < pregapOffset)
1463 subChanMissing = TRUE;
1467 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1471 if (subHandle != NULL) {
1472 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1473 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1475 if (subChanRaw) DecodeRawSubData();
1482 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1483 // does NOT uses bcd format
1484 static long CALLBACK ISOplay(unsigned char *time) {
1491 cdda_cur_sector = msf2sec((char *)time);
1492 for (i = numtracks; i > 1; i--) {
1493 cdda_first_sector = msf2sec(ti[i].start);
1494 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1497 cdda_file_offset = ti[i].start_offset;
1499 // find the file that contains this track
1501 if (ti[i].handle != NULL)
1504 cddaHandle = ti[i].handle;
1506 if (SPU_playCDDAchannel != NULL)
1513 static long CALLBACK ISOstop(void) {
1518 // gets subchannel data
1519 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1520 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1527 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1530 CDR__getStatus(stat);
1534 stat->Status |= 0x80;
1537 // BIOS - boot ID (CD type)
1538 stat->Type = ti[1].type;
1541 // relative -> absolute time
1543 sec2msf(sect, (char *)stat->Time);
1548 // read CDDA sector into buffer
1549 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1550 unsigned char msf[3] = {m, s, f};
1551 unsigned int file, track, track_start = 0;
1554 cddaCurPos = msf2sec((char *)msf);
1556 // find current track index
1557 for (track = numtracks; ; track--) {
1558 track_start = msf2sec(ti[track].start);
1559 if (track_start <= cddaCurPos)
1565 // data tracks play silent
1566 if (ti[track].type != CDDA) {
1567 memset(buffer, 0, CD_FRAMESIZE_RAW);
1573 // find the file that contains this track
1574 for (file = track; file > 1; file--)
1575 if (ti[file].handle != NULL)
1579 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1580 buffer, cddaCurPos - track_start);
1581 if (ret != CD_FRAMESIZE_RAW) {
1582 memset(buffer, 0, CD_FRAMESIZE_RAW);
1586 if (cddaBigEndian) {
1590 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1591 tmp = buffer[i * 2];
1592 buffer[i * 2] = buffer[i * 2 + 1];
1593 buffer[i * 2 + 1] = tmp;
1600 void cdrIsoInit(void) {
1602 CDR_shutdown = ISOshutdown;
1604 CDR_close = ISOclose;
1605 CDR_getTN = ISOgetTN;
1606 CDR_getTD = ISOgetTD;
1607 CDR_readTrack = ISOreadTrack;
1608 CDR_getBuffer = ISOgetBuffer;
1611 CDR_getBufferSub = ISOgetBufferSub;
1612 CDR_getStatus = ISOgetStatus;
1613 CDR_readCDDA = ISOreadCDDA;
1615 CDR_getDriveLetter = CDR__getDriveLetter;
1616 CDR_configure = CDR__configure;
1617 CDR_test = CDR__test;
1618 CDR_about = CDR__about;
1619 CDR_setfilename = CDR__setfilename;
1624 int cdrIsoActive(void) {
1625 return (cdHandle != NULL);