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
39 unsigned int cdrIsoMultidiskCount;
40 unsigned int cdrIsoMultidiskSelect;
42 static FILE *cdHandle = NULL;
43 static FILE *cddaHandle = NULL;
44 static FILE *subHandle = NULL;
46 static boolean subChanMixed = FALSE;
47 static boolean subChanRaw = FALSE;
48 static boolean subChanMissing = FALSE;
50 static boolean multifile = FALSE;
52 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
53 static unsigned char subbuffer[SUB_FRAMESIZE];
55 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
57 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
60 static HANDLE threadid;
62 static pthread_t threadid;
64 static unsigned int initial_offset = 0;
65 static boolean playing = FALSE;
66 static boolean cddaBigEndian = FALSE;
67 // cdda sectors in toc, byte offset in file
68 static unsigned int cdda_cur_sector;
69 static unsigned int cdda_first_sector;
70 static unsigned int cdda_file_offset;
71 /* Frame offset into CD image where pregap data would be found if it was there.
72 * If a game seeks there we must *not* return subchannel data since it's
73 * not in the CD image, so that cdrom code can fake subchannel data instead.
74 * XXX: there could be multiple pregaps but PSX dumps only have one? */
75 static unsigned int pregapOffset;
77 #define cddaCurPos cdda_cur_sector
79 // compressed image stuff
81 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
82 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
83 unsigned int *index_table;
84 unsigned int index_len;
85 unsigned int block_shift;
86 unsigned int current_block;
87 unsigned int sector_in_blk;
90 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
92 char* CALLBACK CDR__getDriveLetter(void);
93 long CALLBACK CDR__configure(void);
94 long CALLBACK CDR__test(void);
95 void CALLBACK CDR__about(void);
96 long CALLBACK CDR__setfilename(char *filename);
97 long CALLBACK CDR__getStatus(struct CdrStat *stat);
99 static void DecodeRawSubData(void);
102 enum {DATA=1, CDDA} type;
103 char start[3]; // MSF-format
104 char length[3]; // MSF-format
105 FILE *handle; // for multi-track images CDDA
106 unsigned int start_offset; // byte offset from start of above file
109 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
111 static int numtracks = 0;
112 static struct trackinfo ti[MAXTRACKS];
114 // get a sector from a msf-array
115 static unsigned int msf2sec(char *msf) {
116 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
119 static void sec2msf(unsigned int s, char *msf) {
120 msf[0] = s / 75 / 60;
121 s = s - msf[0] * 75 * 60;
127 // divide a string of xx:yy:zz into m, s, f
128 static void tok2msf(char *time, char *msf) {
131 token = strtok(time, ":");
133 msf[0] = atoi(token);
139 token = strtok(NULL, ":");
141 msf[1] = atoi(token);
147 token = strtok(NULL, ":");
149 msf[2] = atoi(token);
157 static long GetTickCount(void) {
158 static time_t initial_time = 0;
161 gettimeofday(&now, NULL);
163 if (initial_time == 0) {
164 initial_time = now.tv_sec;
167 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
171 // this thread plays audio data
173 static void playthread(void *param)
175 static void *playthread(void *param)
178 long osleep, d, t, i, s;
180 int ret = 0, sector_offs;
186 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
187 sector_offs = cdda_cur_sector - cdda_first_sector;
188 if (sector_offs < 0) {
189 d = CD_FRAMESIZE_RAW;
190 memset(sndbuffer + s, 0, d);
193 d = cdimg_read_func(cddaHandle, cdda_file_offset,
194 sndbuffer + s, sector_offs);
195 if (d < CD_FRAMESIZE_RAW)
209 if (!cdr.Muted && playing) {
211 for (i = 0; i < s / 2; i++) {
212 tmp = sndbuffer[i * 2];
213 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
214 sndbuffer[i * 2 + 1] = tmp;
218 // can't do it yet due to readahead..
219 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
221 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
224 } while (ret == 0x7761 && playing); // rearmed_wait
227 if (ret != 0x676f) { // !rearmed_go
231 // HACK: stop feeding data while emu is paused
233 while (stop && playing)
236 now = GetTickCount();
242 else if (osleep > CDDA_FRAMETIME) {
243 osleep = CDDA_FRAMETIME;
247 usleep(osleep * 1000);
261 // stop the CDDA playback
262 static void stopCDDA() {
269 WaitForSingleObject(threadid, INFINITE);
271 pthread_join(threadid, NULL);
275 // start the CDDA playback
276 static void startCDDA(void) {
284 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
286 pthread_create(&threadid, NULL, playthread, NULL);
290 // this function tries to get the .toc file of the given .bin
291 // the necessary data is put into the ti (trackinformation)-array
292 static int parsetoc(const char *isofile) {
293 char tocname[MAXPATHLEN];
295 char linebuf[256], tmp[256], name[256];
297 char time[20], time2[20];
298 unsigned int t, sector_offs, sector_size;
299 unsigned int current_zero_gap = 0;
303 // copy name of the iso and change extension from .bin to .toc
304 strncpy(tocname, isofile, sizeof(tocname));
305 tocname[MAXPATHLEN - 1] = '\0';
306 if (strlen(tocname) >= 4) {
307 strcpy(tocname + strlen(tocname) - 4, ".toc");
313 if ((fi = fopen(tocname, "r")) == NULL) {
314 // try changing extension to .cue (to satisfy some stupid tutorials)
315 strcpy(tocname + strlen(tocname) - 4, ".cue");
316 if ((fi = fopen(tocname, "r")) == NULL) {
317 // if filename is image.toc.bin, try removing .bin (for Brasero)
318 strcpy(tocname, isofile);
320 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
321 tocname[t - 4] = '\0';
322 if ((fi = fopen(tocname, "r")) == NULL) {
330 // check if it's really a TOC named as a .cue
331 fgets(linebuf, sizeof(linebuf), fi);
332 token = strtok(linebuf, " ");
333 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
337 fseek(fi, 0, SEEK_SET);
340 memset(&ti, 0, sizeof(ti));
341 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
343 sector_size = CD_FRAMESIZE_RAW;
344 sector_offs = 2 * 75;
346 // parse the .toc file
347 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
349 strncpy(tmp, linebuf, sizeof(linebuf));
350 token = strtok(tmp, " ");
352 if (token == NULL) continue;
354 if (!strcmp(token, "TRACK")) {
355 sector_offs += current_zero_gap;
356 current_zero_gap = 0;
359 token = strtok(NULL, " ");
362 if (!strncmp(token, "MODE2_RAW", 9)) {
363 ti[numtracks].type = DATA;
364 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
366 // check if this image contains mixed subchannel data
367 token = strtok(NULL, " ");
368 if (token != NULL && !strncmp(token, "RW", 2)) {
369 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
371 if (!strncmp(token, "RW_RAW", 6))
375 else if (!strncmp(token, "AUDIO", 5)) {
376 ti[numtracks].type = CDDA;
379 else if (!strcmp(token, "DATAFILE")) {
380 if (ti[numtracks].type == CDDA) {
381 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
382 ti[numtracks].start_offset = t;
383 t = t / sector_size + sector_offs;
384 sec2msf(t, (char *)&ti[numtracks].start);
385 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
388 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
389 tok2msf((char *)&time, (char *)&ti[numtracks].length);
392 else if (!strcmp(token, "FILE")) {
393 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
394 tok2msf((char *)&time, (char *)&ti[numtracks].start);
395 t += msf2sec(ti[numtracks].start) * sector_size;
396 ti[numtracks].start_offset = t;
397 t = t / sector_size + sector_offs;
398 sec2msf(t, (char *)&ti[numtracks].start);
399 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
401 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
402 // skip unneeded optional fields
403 while (token != NULL) {
404 token = strtok(NULL, " ");
405 if (strchr(token, ':') != NULL)
410 current_zero_gap = msf2sec(tmp);
413 t = ti[numtracks - 1].start_offset;
415 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
418 else if (!strcmp(token, "START")) {
419 token = strtok(NULL, " ");
420 if (token != NULL && strchr(token, ':')) {
423 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
424 t = msf2sec(ti[numtracks].start) + t;
425 sec2msf(t, (char *)&ti[numtracks].start);
435 // this function tries to get the .cue file of the given .bin
436 // the necessary data is put into the ti (trackinformation)-array
437 static int parsecue(const char *isofile) {
438 char cuename[MAXPATHLEN];
439 char filepath[MAXPATHLEN];
445 char linebuf[256], tmpb[256], dummy[256];
446 unsigned int incue_max_len;
447 unsigned int t, file_len, mode, sector_offs;
448 unsigned int sector_size = 2352;
452 // copy name of the iso and change extension from .bin to .cue
453 strncpy(cuename, isofile, sizeof(cuename));
454 cuename[MAXPATHLEN - 1] = '\0';
455 if (strlen(cuename) >= 4) {
456 strcpy(cuename + strlen(cuename) - 4, ".cue");
462 if ((fi = fopen(cuename, "r")) == NULL) {
466 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
467 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
469 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
470 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
471 // Don't proceed further, as this is actually a .toc file rather
474 return parsetoc(isofile);
476 fseek(fi, 0, SEEK_SET);
479 // build a path for files referenced in .cue
480 strncpy(filepath, cuename, sizeof(filepath));
481 tmp = strrchr(filepath, '/');
483 tmp = strrchr(filepath, '\\');
489 filepath[sizeof(filepath) - 1] = 0;
491 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
493 memset(&ti, 0, sizeof(ti));
496 sector_offs = 2 * 75;
498 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
499 strncpy(dummy, linebuf, sizeof(linebuf));
500 token = strtok(dummy, " ");
506 if (!strcmp(token, "TRACK")) {
510 if (strstr(linebuf, "AUDIO") != NULL) {
511 ti[numtracks].type = CDDA;
514 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
515 ti[numtracks].type = DATA;
517 SysPrintf(".cue: failed to parse TRACK\n");
518 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
520 if (sector_size == 0)
523 else if (!strcmp(token, "INDEX")) {
524 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
525 SysPrintf(".cue: failed to parse INDEX\n");
526 tok2msf(time, (char *)&ti[numtracks].start);
528 t = msf2sec(ti[numtracks].start);
529 ti[numtracks].start_offset = t * sector_size;
531 sec2msf(t, ti[numtracks].start);
533 // default track length to file length
534 t = file_len - ti[numtracks].start_offset / sector_size;
535 sec2msf(t, ti[numtracks].length);
537 if (numtracks > 1 && ti[numtracks].handle == NULL) {
538 // this track uses the same file as the last,
539 // start of this track is last track's end
540 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
541 sec2msf(t, ti[numtracks - 1].length);
543 if (numtracks > 1 && pregapOffset == -1)
544 pregapOffset = ti[numtracks].start_offset / sector_size;
546 else if (!strcmp(token, "PREGAP")) {
547 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
548 tok2msf(time, dummy);
549 sector_offs += msf2sec(dummy);
551 pregapOffset = -1; // mark to fill track start_offset
553 else if (!strcmp(token, "FILE")) {
554 t = sscanf(linebuf, " FILE \"%256[^\"]\"", tmpb);
556 sscanf(linebuf, " FILE %256s", tmpb);
559 ti[numtracks + 1].handle = fopen(tmpb, "rb");
560 if (ti[numtracks + 1].handle == NULL) {
562 tmp = strrchr(tmpb, '\\');
564 tmp = strrchr(tmpb, '/');
569 strncpy(incue_fname, tmp, incue_max_len);
570 ti[numtracks + 1].handle = fopen(filepath, "rb");
573 // update global offset if this is not first file in this .cue
574 if (numtracks + 1 > 1) {
576 sector_offs += file_len;
580 if (ti[numtracks + 1].handle == NULL) {
581 SysPrintf(_("\ncould not open: %s\n"), filepath);
584 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
585 file_len = ftell(ti[numtracks + 1].handle) / 2352;
587 if (numtracks == 0 && strlen(isofile) >= 4 &&
588 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
590 // user selected .cue as image file, use it's data track instead
592 cdHandle = fopen(filepath, "rb");
602 // this function tries to get the .ccd file of the given .img
603 // the necessary data is put into the ti (trackinformation)-array
604 static int parseccd(const char *isofile) {
605 char ccdname[MAXPATHLEN];
612 // copy name of the iso and change extension from .img to .ccd
613 strncpy(ccdname, isofile, sizeof(ccdname));
614 ccdname[MAXPATHLEN - 1] = '\0';
615 if (strlen(ccdname) >= 4) {
616 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
622 if ((fi = fopen(ccdname, "r")) == NULL) {
626 memset(&ti, 0, sizeof(ti));
628 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
629 if (!strncmp(linebuf, "[TRACK", 6)){
632 else if (!strncmp(linebuf, "MODE=", 5)) {
633 sscanf(linebuf, "MODE=%d", &t);
634 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
636 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
637 sscanf(linebuf, "INDEX 1=%d", &t);
638 sec2msf(t + 2 * 75, ti[numtracks].start);
639 ti[numtracks].start_offset = t * 2352;
641 // If we've already seen another track, this is its end
643 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
644 sec2msf(t, ti[numtracks - 1].length);
651 // Fill out the last track's end based on size
652 if (numtracks >= 1) {
653 fseek(cdHandle, 0, SEEK_END);
654 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
655 sec2msf(t, ti[numtracks].length);
661 // this function tries to get the .mds file of the given .mdf
662 // the necessary data is put into the ti (trackinformation)-array
663 static int parsemds(const char *isofile) {
664 char mdsname[MAXPATHLEN];
666 unsigned int offset, extra_offset, l, i;
671 // copy name of the iso and change extension from .mdf to .mds
672 strncpy(mdsname, isofile, sizeof(mdsname));
673 mdsname[MAXPATHLEN - 1] = '\0';
674 if (strlen(mdsname) >= 4) {
675 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
681 if ((fi = fopen(mdsname, "rb")) == NULL) {
685 memset(&ti, 0, sizeof(ti));
687 // check if it's a valid mds file
688 fread(&i, 1, sizeof(unsigned int), fi);
690 if (i != 0x4944454D) {
691 // not an valid mds file
696 // get offset to session block
697 fseek(fi, 0x50, SEEK_SET);
698 fread(&offset, 1, sizeof(unsigned int), fi);
699 offset = SWAP32(offset);
701 // get total number of tracks
703 fseek(fi, offset, SEEK_SET);
704 fread(&s, 1, sizeof(unsigned short), fi);
708 // get offset to track blocks
709 fseek(fi, 4, SEEK_CUR);
710 fread(&offset, 1, sizeof(unsigned int), fi);
711 offset = SWAP32(offset);
715 fseek(fi, offset + 4, SEEK_SET);
716 if (fgetc(fi) < 0xA0) {
722 // check if the image contains mixed subchannel data
723 fseek(fi, offset + 1, SEEK_SET);
724 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
727 for (i = 1; i <= numtracks; i++) {
728 fseek(fi, offset, SEEK_SET);
730 // get the track type
731 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
732 fseek(fi, 8, SEEK_CUR);
734 // get the track starting point
735 ti[i].start[0] = fgetc(fi);
736 ti[i].start[1] = fgetc(fi);
737 ti[i].start[2] = fgetc(fi);
739 fread(&extra_offset, 1, sizeof(unsigned int), fi);
740 extra_offset = SWAP32(extra_offset);
742 // get track start offset (in .mdf)
743 fseek(fi, offset + 0x28, SEEK_SET);
744 fread(&l, 1, sizeof(unsigned int), fi);
746 ti[i].start_offset = l;
749 fseek(fi, extra_offset, SEEK_SET);
750 fread(&l, 1, sizeof(unsigned int), fi);
753 pregapOffset = msf2sec(ti[i].start);
755 // get the track length
756 fread(&l, 1, sizeof(unsigned int), fi);
758 sec2msf(l, ti[i].length);
767 static int handlepbp(const char *isofile) {
770 unsigned int dontcare[8];
771 unsigned int psar_offs;
784 unsigned int dontcare[6];
787 unsigned int t, cd_length, cdimg_base;
788 unsigned int offsettab[8], psisoimg_offs;
789 const char *ext = NULL;
792 if (strlen(isofile) >= 4)
793 ext = isofile + strlen(isofile) - 4;
794 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
799 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
800 if (ret != sizeof(pbp_hdr)) {
801 SysPrintf("failed to read pbp\n");
805 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
807 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
811 psisoimg_offs = pbp_hdr.psar_offs;
812 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
814 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
816 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
818 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
822 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
823 SysPrintf("failed to read offsettab\n");
827 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
828 if (offsettab[i] == 0)
831 cdrIsoMultidiskCount = i;
832 if (cdrIsoMultidiskCount == 0) {
833 SysPrintf("multidisk eboot has 0 images?\n");
837 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
838 cdrIsoMultidiskSelect = 0;
840 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
842 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
844 SysPrintf("failed to seek to %x\n", psisoimg_offs);
848 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
852 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
853 SysPrintf("bad psar_sig: %s\n", psar_sig);
858 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
860 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
864 // first 3 entries are special
865 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
866 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
867 numtracks = btoi(toc_entry.index1[0]);
869 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
870 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
871 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
873 for (i = 1; i <= numtracks; i++) {
874 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
876 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
878 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
879 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
880 ti[i].start_offset *= 2352;
881 ti[i].start[0] = btoi(toc_entry.index1[0]);
882 ti[i].start[1] = btoi(toc_entry.index1[1]);
883 ti[i].start[2] = btoi(toc_entry.index1[2]);
886 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
887 sec2msf(t, ti[i - 1].length);
890 t = cd_length - ti[numtracks].start_offset / 2352;
891 sec2msf(t, ti[numtracks].length);
894 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
896 SysPrintf("failed to seek to ISO index\n");
900 compr_img = calloc(1, sizeof(*compr_img));
901 if (compr_img == NULL)
904 compr_img->block_shift = 4;
905 compr_img->current_block = (unsigned int)-1;
907 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
908 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
909 if (compr_img->index_table == NULL)
912 cdimg_base = psisoimg_offs + 0x100000;
913 for (i = 0; i < compr_img->index_len; i++) {
914 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
915 if (ret != sizeof(index_entry)) {
916 SysPrintf("failed to read index_entry #%d\n", i);
920 if (index_entry.size == 0)
923 compr_img->index_table[i] = cdimg_base + index_entry.offset;
925 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
930 free(compr_img->index_table);
931 compr_img->index_table = NULL;
933 if (compr_img != NULL) {
940 static int handlecbin(const char *isofile) {
944 unsigned int header_size;
945 unsigned long long total_bytes;
946 unsigned int block_size;
947 unsigned char ver; // 1
949 unsigned char rsv_06[2];
951 const char *ext = NULL;
952 unsigned int index = 0, plain;
955 if (strlen(isofile) >= 5)
956 ext = isofile + strlen(isofile) - 5;
957 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
960 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
961 if (ret != sizeof(ciso_hdr)) {
962 SysPrintf("failed to read ciso header\n");
966 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
967 SysPrintf("bad ciso header\n");
970 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
971 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
973 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
978 compr_img = calloc(1, sizeof(*compr_img));
979 if (compr_img == NULL)
982 compr_img->block_shift = 0;
983 compr_img->current_block = (unsigned int)-1;
985 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
986 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
987 if (compr_img->index_table == NULL)
990 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
991 if (ret != compr_img->index_len) {
992 SysPrintf("failed to read index table\n");
996 for (i = 0; i < compr_img->index_len + 1; i++) {
997 index = compr_img->index_table[i];
998 plain = index & 0x80000000;
1000 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1002 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1003 SysPrintf("warning: ciso img too large, expect problems\n");
1008 free(compr_img->index_table);
1009 compr_img->index_table = NULL;
1011 if (compr_img != NULL) {
1018 // this function tries to get the .sub file of the given .img
1019 static int opensubfile(const char *isoname) {
1020 char subname[MAXPATHLEN];
1022 // copy name of the iso and change extension from .img to .sub
1023 strncpy(subname, isoname, sizeof(subname));
1024 subname[MAXPATHLEN - 1] = '\0';
1025 if (strlen(subname) >= 4) {
1026 strcpy(subname + strlen(subname) - 4, ".sub");
1032 subHandle = fopen(subname, "rb");
1033 if (subHandle == NULL) {
1040 static int opensbifile(const char *isoname) {
1041 char sbiname[MAXPATHLEN];
1044 strncpy(sbiname, isoname, sizeof(sbiname));
1045 sbiname[MAXPATHLEN - 1] = '\0';
1046 if (strlen(sbiname) >= 4) {
1047 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1053 fseek(cdHandle, 0, SEEK_END);
1054 s = ftell(cdHandle) / 2352;
1056 return LoadSBI(sbiname, s);
1059 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1061 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1062 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1065 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1069 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1070 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1071 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1073 if (subChanRaw) DecodeRawSubData();
1078 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1083 if (z.zalloc == NULL) {
1084 // XXX: one-time leak here..
1090 ret = inflateInit2(&z, -15);
1093 ret = inflateReset(&z);
1098 z.avail_in = in_size;
1100 z.avail_out = *out_size;
1102 ret = inflate(&z, Z_NO_FLUSH);
1105 *out_size -= z.avail_out;
1106 return ret == 1 ? 0 : ret;
1109 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1111 unsigned long cdbuffer_size, cdbuffer_size_expect;
1112 unsigned int start_byte, size;
1117 sector += base / 2352;
1119 block = sector >> compr_img->block_shift;
1120 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1122 if (block == compr_img->current_block) {
1123 //printf("hit sect %d\n", sector);
1127 if (sector >= compr_img->index_len * 16) {
1128 SysPrintf("sector %d is past img end\n", sector);
1132 start_byte = compr_img->index_table[block] & 0x7fffffff;
1133 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1134 SysPrintf("seek error for block %d at %x: ",
1140 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1141 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1142 if (size > sizeof(compr_img->buff_compressed)) {
1143 SysPrintf("block %d is too large: %u\n", block, size);
1147 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1148 1, size, cdHandle) != size) {
1149 SysPrintf("read error for block %d at %x: ", block, start_byte);
1154 if (is_compressed) {
1155 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1156 cdbuffer_size = cdbuffer_size_expect;
1157 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1159 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1160 ret, block, sector);
1163 if (cdbuffer_size != cdbuffer_size_expect)
1164 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1165 cdbuffer_size_expect, sector);
1169 compr_img->current_block = block;
1172 if (dest != cdbuffer) // copy avoid HACK
1173 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1175 return CD_FRAMESIZE_RAW;
1178 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1182 fseek(f, base + sector * 2048, SEEK_SET);
1183 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1185 // not really necessary, fake mode 2 header
1186 memset(cdbuffer, 0, 12 * 2);
1187 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1188 cdbuffer[12 + 3] = 1;
1193 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1194 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1197 static unsigned char * CALLBACK ISOgetBuffer(void) {
1198 return cdbuffer + 12;
1201 static void PrintTracks(void) {
1204 for (i = 1; i <= numtracks; i++) {
1205 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1206 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1207 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1208 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1212 // This function is invoked by the front-end when opening an ISO
1213 // file for playback
1214 static long CALLBACK ISOopen(void) {
1215 boolean isMode1ISO = FALSE;
1216 char alt_bin_filename[MAXPATHLEN];
1217 const char *bin_filename;
1219 if (cdHandle != NULL) {
1220 return 0; // it's already open
1223 cdHandle = fopen(GetIsoFile(), "rb");
1224 if (cdHandle == NULL) {
1228 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1230 cddaBigEndian = FALSE;
1231 subChanMixed = FALSE;
1234 cdrIsoMultidiskCount = 1;
1237 CDR_getBuffer = ISOgetBuffer;
1238 cdimg_read_func = cdread_normal;
1240 if (parsetoc(GetIsoFile()) == 0) {
1241 SysPrintf("[+toc]");
1243 else if (parseccd(GetIsoFile()) == 0) {
1244 SysPrintf("[+ccd]");
1246 else if (parsemds(GetIsoFile()) == 0) {
1247 SysPrintf("[+mds]");
1249 else if (parsecue(GetIsoFile()) == 0) {
1250 SysPrintf("[+cue]");
1252 if (handlepbp(GetIsoFile()) == 0) {
1254 CDR_getBuffer = ISOgetBuffer_compr;
1255 cdimg_read_func = cdread_compressed;
1257 else if (handlecbin(GetIsoFile()) == 0) {
1258 SysPrintf("[cbin]");
1259 CDR_getBuffer = ISOgetBuffer_compr;
1260 cdimg_read_func = cdread_compressed;
1263 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1264 SysPrintf("[+sub]");
1266 if (opensbifile(GetIsoFile()) == 0) {
1267 SysPrintf("[+sbi]");
1270 fseek(cdHandle, 0, SEEK_END);
1272 // maybe user selected metadata file instead of main .bin ..
1273 bin_filename = GetIsoFile();
1274 if (ftell(cdHandle) < 2352 * 0x10) {
1275 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1280 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1281 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1282 if (strlen(alt_bin_filename) >= 4) {
1283 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1284 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1286 tmpf = fopen(alt_bin_filename, "rb");
1292 bin_filename = alt_bin_filename;
1295 fseek(cdHandle, 0, SEEK_END);
1299 // guess whether it is mode1/2048
1300 if (ftell(cdHandle) % 2048 == 0) {
1301 unsigned int modeTest = 0;
1302 fseek(cdHandle, 0, SEEK_SET);
1303 fread(&modeTest, 4, 1, cdHandle);
1304 if (SWAP32(modeTest) != 0xffffff00) {
1305 SysPrintf("[2048]");
1309 fseek(cdHandle, 0, SEEK_SET);
1316 cdimg_read_func = cdread_sub_mixed;
1317 else if (isMode1ISO)
1318 cdimg_read_func = cdread_2048;
1320 // make sure we have another handle open for cdda
1321 if (numtracks > 1 && ti[1].handle == NULL) {
1322 ti[1].handle = fopen(bin_filename, "rb");
1324 cdda_cur_sector = 0;
1325 cdda_file_offset = 0;
1330 static long CALLBACK ISOclose(void) {
1333 if (cdHandle != NULL) {
1337 if (subHandle != NULL) {
1344 if (compr_img != NULL) {
1345 free(compr_img->index_table);
1350 for (i = 1; i <= numtracks; i++) {
1351 if (ti[i].handle != NULL) {
1352 fclose(ti[i].handle);
1353 ti[i].handle = NULL;
1360 memset(cdbuffer, 0, sizeof(cdbuffer));
1361 CDR_getBuffer = ISOgetBuffer;
1366 static long CALLBACK ISOinit(void) {
1367 assert(cdHandle == NULL);
1368 assert(subHandle == NULL);
1370 return 0; // do nothing
1373 static long CALLBACK ISOshutdown(void) {
1378 // return Starting and Ending Track
1380 // byte 0 - start track
1381 // byte 1 - end track
1382 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1385 if (numtracks > 0) {
1386 buffer[1] = numtracks;
1395 // return Track Time
1400 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1403 unsigned char time[3];
1404 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1405 sec2msf(sect, (char *)time);
1406 buffer[2] = time[0];
1407 buffer[1] = time[1];
1408 buffer[0] = time[2];
1410 else if (numtracks > 0 && track <= numtracks) {
1411 buffer[2] = ti[track].start[0];
1412 buffer[1] = ti[track].start[1];
1413 buffer[0] = ti[track].start[2];
1424 // decode 'raw' subchannel data ripped by cdrdao
1425 static void DecodeRawSubData(void) {
1426 unsigned char subQData[12];
1429 memset(subQData, 0, sizeof(subQData));
1431 for (i = 0; i < 8 * 12; i++) {
1432 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1433 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1437 memcpy(&subbuffer[12], subQData, 12);
1441 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1443 static long CALLBACK ISOreadTrack(unsigned char *time) {
1444 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1447 if (cdHandle == NULL) {
1452 subChanMissing = FALSE;
1453 if (sector >= pregapOffset) {
1455 if (sector < pregapOffset)
1456 subChanMissing = TRUE;
1460 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1464 if (subHandle != NULL) {
1465 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1466 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1468 if (subChanRaw) DecodeRawSubData();
1475 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1476 // does NOT uses bcd format
1477 static long CALLBACK ISOplay(unsigned char *time) {
1484 cdda_cur_sector = msf2sec((char *)time);
1485 for (i = numtracks; i > 1; i--) {
1486 cdda_first_sector = msf2sec(ti[i].start);
1487 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1490 cdda_file_offset = ti[i].start_offset;
1492 // find the file that contains this track
1494 if (ti[i].handle != NULL)
1497 cddaHandle = ti[i].handle;
1499 if (SPU_playCDDAchannel != NULL)
1506 static long CALLBACK ISOstop(void) {
1511 // gets subchannel data
1512 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1513 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1520 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1523 CDR__getStatus(stat);
1527 stat->Status |= 0x80;
1530 // BIOS - boot ID (CD type)
1531 stat->Type = ti[1].type;
1534 // relative -> absolute time
1536 sec2msf(sect, (char *)stat->Time);
1541 // read CDDA sector into buffer
1542 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1543 unsigned char msf[3] = {m, s, f};
1544 unsigned int file, track, track_start = 0;
1547 cddaCurPos = msf2sec((char *)msf);
1549 // find current track index
1550 for (track = numtracks; ; track--) {
1551 track_start = msf2sec(ti[track].start);
1552 if (track_start <= cddaCurPos)
1558 // data tracks play silent
1559 if (ti[track].type != CDDA) {
1560 memset(buffer, 0, CD_FRAMESIZE_RAW);
1566 // find the file that contains this track
1567 for (file = track; file > 1; file--)
1568 if (ti[file].handle != NULL)
1572 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1573 buffer, cddaCurPos - track_start);
1574 if (ret != CD_FRAMESIZE_RAW) {
1575 memset(buffer, 0, CD_FRAMESIZE_RAW);
1579 if (cddaBigEndian) {
1583 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1584 tmp = buffer[i * 2];
1585 buffer[i * 2] = buffer[i * 2 + 1];
1586 buffer[i * 2 + 1] = tmp;
1593 void cdrIsoInit(void) {
1595 CDR_shutdown = ISOshutdown;
1597 CDR_close = ISOclose;
1598 CDR_getTN = ISOgetTN;
1599 CDR_getTD = ISOgetTD;
1600 CDR_readTrack = ISOreadTrack;
1601 CDR_getBuffer = ISOgetBuffer;
1604 CDR_getBufferSub = ISOgetBufferSub;
1605 CDR_getStatus = ISOgetStatus;
1606 CDR_readCDDA = ISOreadCDDA;
1608 CDR_getDriveLetter = CDR__getDriveLetter;
1609 CDR_configure = CDR__configure;
1610 CDR_test = CDR__test;
1611 CDR_about = CDR__about;
1612 CDR_setfilename = CDR__setfilename;
1617 int cdrIsoActive(void) {
1618 return (cdHandle != NULL);