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 \"%256[^\"]\"", tmpb);
557 sscanf(linebuf, " FILE %256s", 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))
800 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
801 if (ret != sizeof(pbp_hdr)) {
802 SysPrintf("failed to read pbp\n");
806 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
808 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
812 psisoimg_offs = pbp_hdr.psar_offs;
813 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
815 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
817 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
819 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
823 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
824 SysPrintf("failed to read offsettab\n");
828 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
829 if (offsettab[i] == 0)
832 cdrIsoMultidiskCount = i;
833 if (cdrIsoMultidiskCount == 0) {
834 SysPrintf("multidisk eboot has 0 images?\n");
838 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
839 cdrIsoMultidiskSelect = 0;
841 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
843 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
845 SysPrintf("failed to seek to %x\n", psisoimg_offs);
849 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
853 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
854 SysPrintf("bad psar_sig: %s\n", psar_sig);
859 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
861 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
865 // first 3 entries are special
866 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
867 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
868 numtracks = btoi(toc_entry.index1[0]);
870 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
871 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
872 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
874 for (i = 1; i <= numtracks; i++) {
875 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
877 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
879 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
880 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
881 ti[i].start_offset *= 2352;
882 ti[i].start[0] = btoi(toc_entry.index1[0]);
883 ti[i].start[1] = btoi(toc_entry.index1[1]);
884 ti[i].start[2] = btoi(toc_entry.index1[2]);
887 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
888 sec2msf(t, ti[i - 1].length);
891 t = cd_length - ti[numtracks].start_offset / 2352;
892 sec2msf(t, ti[numtracks].length);
895 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
897 SysPrintf("failed to seek to ISO index\n");
901 compr_img = calloc(1, sizeof(*compr_img));
902 if (compr_img == NULL)
905 compr_img->block_shift = 4;
906 compr_img->current_block = (unsigned int)-1;
908 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
909 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
910 if (compr_img->index_table == NULL)
913 cdimg_base = psisoimg_offs + 0x100000;
914 for (i = 0; i < compr_img->index_len; i++) {
915 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
916 if (ret != sizeof(index_entry)) {
917 SysPrintf("failed to read index_entry #%d\n", i);
921 if (index_entry.size == 0)
924 compr_img->index_table[i] = cdimg_base + index_entry.offset;
926 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
931 free(compr_img->index_table);
932 compr_img->index_table = NULL;
934 if (compr_img != NULL) {
941 static int handlecbin(const char *isofile) {
945 unsigned int header_size;
946 unsigned long long total_bytes;
947 unsigned int block_size;
948 unsigned char ver; // 1
950 unsigned char rsv_06[2];
952 const char *ext = NULL;
953 unsigned int index = 0, plain;
956 if (strlen(isofile) >= 5)
957 ext = isofile + strlen(isofile) - 5;
958 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
961 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
962 if (ret != sizeof(ciso_hdr)) {
963 SysPrintf("failed to read ciso header\n");
967 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
968 SysPrintf("bad ciso header\n");
971 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
972 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
974 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
979 compr_img = calloc(1, sizeof(*compr_img));
980 if (compr_img == NULL)
983 compr_img->block_shift = 0;
984 compr_img->current_block = (unsigned int)-1;
986 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
987 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
988 if (compr_img->index_table == NULL)
991 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
992 if (ret != compr_img->index_len) {
993 SysPrintf("failed to read index table\n");
997 for (i = 0; i < compr_img->index_len + 1; i++) {
998 index = compr_img->index_table[i];
999 plain = index & 0x80000000;
1000 index &= 0x7fffffff;
1001 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1003 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1004 SysPrintf("warning: ciso img too large, expect problems\n");
1009 free(compr_img->index_table);
1010 compr_img->index_table = NULL;
1012 if (compr_img != NULL) {
1019 // this function tries to get the .sub file of the given .img
1020 static int opensubfile(const char *isoname) {
1021 char subname[MAXPATHLEN];
1023 // copy name of the iso and change extension from .img to .sub
1024 strncpy(subname, isoname, sizeof(subname));
1025 subname[MAXPATHLEN - 1] = '\0';
1026 if (strlen(subname) >= 4) {
1027 strcpy(subname + strlen(subname) - 4, ".sub");
1033 subHandle = fopen(subname, "rb");
1034 if (subHandle == NULL) {
1041 static int opensbifile(const char *isoname) {
1042 char sbiname[MAXPATHLEN];
1045 strncpy(sbiname, isoname, sizeof(sbiname));
1046 sbiname[MAXPATHLEN - 1] = '\0';
1047 if (strlen(sbiname) >= 4) {
1048 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1054 fseek(cdHandle, 0, SEEK_END);
1055 s = ftell(cdHandle) / 2352;
1057 return LoadSBI(sbiname, s);
1060 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1062 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1063 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1066 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1070 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1071 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1072 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1074 if (subChanRaw) DecodeRawSubData();
1079 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1084 if (z.zalloc == NULL) {
1085 // XXX: one-time leak here..
1091 ret = inflateInit2(&z, -15);
1094 ret = inflateReset(&z);
1099 z.avail_in = in_size;
1101 z.avail_out = *out_size;
1103 ret = inflate(&z, Z_NO_FLUSH);
1106 *out_size -= z.avail_out;
1107 return ret == 1 ? 0 : ret;
1110 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1112 unsigned long cdbuffer_size, cdbuffer_size_expect;
1113 unsigned int start_byte, size;
1118 sector += base / 2352;
1120 block = sector >> compr_img->block_shift;
1121 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1123 if (block == compr_img->current_block) {
1124 //printf("hit sect %d\n", sector);
1128 if (sector >= compr_img->index_len * 16) {
1129 SysPrintf("sector %d is past img end\n", sector);
1133 start_byte = compr_img->index_table[block] & 0x7fffffff;
1134 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1135 SysPrintf("seek error for block %d at %x: ",
1141 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1142 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1143 if (size > sizeof(compr_img->buff_compressed)) {
1144 SysPrintf("block %d is too large: %u\n", block, size);
1148 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1149 1, size, cdHandle) != size) {
1150 SysPrintf("read error for block %d at %x: ", block, start_byte);
1155 if (is_compressed) {
1156 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1157 cdbuffer_size = cdbuffer_size_expect;
1158 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1160 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1161 ret, block, sector);
1164 if (cdbuffer_size != cdbuffer_size_expect)
1165 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1166 cdbuffer_size_expect, sector);
1170 compr_img->current_block = block;
1173 if (dest != cdbuffer) // copy avoid HACK
1174 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1176 return CD_FRAMESIZE_RAW;
1179 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1183 fseek(f, base + sector * 2048, SEEK_SET);
1184 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1186 // not really necessary, fake mode 2 header
1187 memset(cdbuffer, 0, 12 * 2);
1188 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1189 cdbuffer[12 + 3] = 1;
1194 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1195 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1198 static unsigned char * CALLBACK ISOgetBuffer(void) {
1199 return cdbuffer + 12;
1202 static void PrintTracks(void) {
1205 for (i = 1; i <= numtracks; i++) {
1206 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1207 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1208 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1209 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1213 // This function is invoked by the front-end when opening an ISO
1214 // file for playback
1215 static long CALLBACK ISOopen(void) {
1216 boolean isMode1ISO = FALSE;
1217 char alt_bin_filename[MAXPATHLEN];
1218 const char *bin_filename;
1220 if (cdHandle != NULL) {
1221 return 0; // it's already open
1224 cdHandle = fopen(GetIsoFile(), "rb");
1225 if (cdHandle == NULL) {
1226 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1227 GetIsoFile(), strerror(errno));
1231 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1233 cddaBigEndian = FALSE;
1234 subChanMixed = FALSE;
1237 cdrIsoMultidiskCount = 1;
1240 CDR_getBuffer = ISOgetBuffer;
1241 cdimg_read_func = cdread_normal;
1243 if (parsetoc(GetIsoFile()) == 0) {
1244 SysPrintf("[+toc]");
1246 else if (parseccd(GetIsoFile()) == 0) {
1247 SysPrintf("[+ccd]");
1249 else if (parsemds(GetIsoFile()) == 0) {
1250 SysPrintf("[+mds]");
1252 else if (parsecue(GetIsoFile()) == 0) {
1253 SysPrintf("[+cue]");
1255 if (handlepbp(GetIsoFile()) == 0) {
1257 CDR_getBuffer = ISOgetBuffer_compr;
1258 cdimg_read_func = cdread_compressed;
1260 else if (handlecbin(GetIsoFile()) == 0) {
1261 SysPrintf("[cbin]");
1262 CDR_getBuffer = ISOgetBuffer_compr;
1263 cdimg_read_func = cdread_compressed;
1266 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1267 SysPrintf("[+sub]");
1269 if (opensbifile(GetIsoFile()) == 0) {
1270 SysPrintf("[+sbi]");
1273 fseek(cdHandle, 0, SEEK_END);
1275 // maybe user selected metadata file instead of main .bin ..
1276 bin_filename = GetIsoFile();
1277 if (ftell(cdHandle) < 2352 * 0x10) {
1278 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1283 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1284 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1285 if (strlen(alt_bin_filename) >= 4) {
1286 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1287 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1289 tmpf = fopen(alt_bin_filename, "rb");
1295 bin_filename = alt_bin_filename;
1298 fseek(cdHandle, 0, SEEK_END);
1302 // guess whether it is mode1/2048
1303 if (ftell(cdHandle) % 2048 == 0) {
1304 unsigned int modeTest = 0;
1305 fseek(cdHandle, 0, SEEK_SET);
1306 fread(&modeTest, 4, 1, cdHandle);
1307 if (SWAP32(modeTest) != 0xffffff00) {
1308 SysPrintf("[2048]");
1312 fseek(cdHandle, 0, SEEK_SET);
1319 cdimg_read_func = cdread_sub_mixed;
1320 else if (isMode1ISO)
1321 cdimg_read_func = cdread_2048;
1323 // make sure we have another handle open for cdda
1324 if (numtracks > 1 && ti[1].handle == NULL) {
1325 ti[1].handle = fopen(bin_filename, "rb");
1327 cdda_cur_sector = 0;
1328 cdda_file_offset = 0;
1333 static long CALLBACK ISOclose(void) {
1336 if (cdHandle != NULL) {
1340 if (subHandle != NULL) {
1347 if (compr_img != NULL) {
1348 free(compr_img->index_table);
1353 for (i = 1; i <= numtracks; i++) {
1354 if (ti[i].handle != NULL) {
1355 fclose(ti[i].handle);
1356 ti[i].handle = NULL;
1363 memset(cdbuffer, 0, sizeof(cdbuffer));
1364 CDR_getBuffer = ISOgetBuffer;
1369 static long CALLBACK ISOinit(void) {
1370 assert(cdHandle == NULL);
1371 assert(subHandle == NULL);
1373 return 0; // do nothing
1376 static long CALLBACK ISOshutdown(void) {
1381 // return Starting and Ending Track
1383 // byte 0 - start track
1384 // byte 1 - end track
1385 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1388 if (numtracks > 0) {
1389 buffer[1] = numtracks;
1398 // return Track Time
1403 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1406 unsigned char time[3];
1407 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1408 sec2msf(sect, (char *)time);
1409 buffer[2] = time[0];
1410 buffer[1] = time[1];
1411 buffer[0] = time[2];
1413 else if (numtracks > 0 && track <= numtracks) {
1414 buffer[2] = ti[track].start[0];
1415 buffer[1] = ti[track].start[1];
1416 buffer[0] = ti[track].start[2];
1427 // decode 'raw' subchannel data ripped by cdrdao
1428 static void DecodeRawSubData(void) {
1429 unsigned char subQData[12];
1432 memset(subQData, 0, sizeof(subQData));
1434 for (i = 0; i < 8 * 12; i++) {
1435 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1436 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1440 memcpy(&subbuffer[12], subQData, 12);
1444 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1446 static long CALLBACK ISOreadTrack(unsigned char *time) {
1447 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1450 if (cdHandle == NULL) {
1455 subChanMissing = FALSE;
1456 if (sector >= pregapOffset) {
1458 if (sector < pregapOffset)
1459 subChanMissing = TRUE;
1463 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1467 if (subHandle != NULL) {
1468 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1469 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1471 if (subChanRaw) DecodeRawSubData();
1478 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1479 // does NOT uses bcd format
1480 static long CALLBACK ISOplay(unsigned char *time) {
1487 cdda_cur_sector = msf2sec((char *)time);
1488 for (i = numtracks; i > 1; i--) {
1489 cdda_first_sector = msf2sec(ti[i].start);
1490 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1493 cdda_file_offset = ti[i].start_offset;
1495 // find the file that contains this track
1497 if (ti[i].handle != NULL)
1500 cddaHandle = ti[i].handle;
1502 if (SPU_playCDDAchannel != NULL)
1509 static long CALLBACK ISOstop(void) {
1514 // gets subchannel data
1515 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1516 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1523 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1526 CDR__getStatus(stat);
1530 stat->Status |= 0x80;
1533 // BIOS - boot ID (CD type)
1534 stat->Type = ti[1].type;
1537 // relative -> absolute time
1539 sec2msf(sect, (char *)stat->Time);
1544 // read CDDA sector into buffer
1545 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1546 unsigned char msf[3] = {m, s, f};
1547 unsigned int file, track, track_start = 0;
1550 cddaCurPos = msf2sec((char *)msf);
1552 // find current track index
1553 for (track = numtracks; ; track--) {
1554 track_start = msf2sec(ti[track].start);
1555 if (track_start <= cddaCurPos)
1561 // data tracks play silent
1562 if (ti[track].type != CDDA) {
1563 memset(buffer, 0, CD_FRAMESIZE_RAW);
1569 // find the file that contains this track
1570 for (file = track; file > 1; file--)
1571 if (ti[file].handle != NULL)
1575 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1576 buffer, cddaCurPos - track_start);
1577 if (ret != CD_FRAMESIZE_RAW) {
1578 memset(buffer, 0, CD_FRAMESIZE_RAW);
1582 if (cddaBigEndian) {
1586 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1587 tmp = buffer[i * 2];
1588 buffer[i * 2] = buffer[i * 2 + 1];
1589 buffer[i * 2 + 1] = tmp;
1596 void cdrIsoInit(void) {
1598 CDR_shutdown = ISOshutdown;
1600 CDR_close = ISOclose;
1601 CDR_getTN = ISOgetTN;
1602 CDR_getTD = ISOgetTD;
1603 CDR_readTrack = ISOreadTrack;
1604 CDR_getBuffer = ISOgetBuffer;
1607 CDR_getBufferSub = ISOgetBufferSub;
1608 CDR_getStatus = ISOgetStatus;
1609 CDR_readCDDA = ISOreadCDDA;
1611 CDR_getDriveLetter = CDR__getDriveLetter;
1612 CDR_configure = CDR__configure;
1613 CDR_test = CDR__test;
1614 CDR_about = CDR__about;
1615 CDR_setfilename = CDR__setfilename;
1620 int cdrIsoActive(void) {
1621 return (cdHandle != NULL);