1 /***************************************************************************
2 * Copyright (C) 2007 PCSX-df Team *
3 * Copyright (C) 2009 Wei Mingzhi *
4 * Copyright (C) 2012 notaz *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
20 ***************************************************************************/
22 #include "psxcommon.h"
29 #define WIN32_LEAN_AND_MEAN
32 #define strcasecmp _stricmp
33 #define usleep(x) (Sleep((x) / 1000))
42 unsigned int cdrIsoMultidiskCount;
43 unsigned int cdrIsoMultidiskSelect;
45 static FILE *cdHandle = NULL;
46 static FILE *cddaHandle = NULL;
47 static FILE *subHandle = NULL;
49 static boolean subChanMixed = FALSE;
50 static boolean subChanRaw = FALSE;
51 static boolean subChanMissing = FALSE;
53 static boolean multifile = FALSE;
55 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
56 static unsigned char subbuffer[SUB_FRAMESIZE];
58 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
60 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
63 static HANDLE threadid;
65 static pthread_t threadid;
67 static unsigned int initial_offset = 0;
68 static boolean playing = FALSE;
69 static boolean cddaBigEndian = FALSE;
70 // cdda sectors in toc, byte offset in file
71 static unsigned int cdda_cur_sector;
72 static unsigned int cdda_first_sector;
73 static unsigned int cdda_file_offset;
74 /* Frame offset into CD image where pregap data would be found if it was there.
75 * If a game seeks there we must *not* return subchannel data since it's
76 * not in the CD image, so that cdrom code can fake subchannel data instead.
77 * XXX: there could be multiple pregaps but PSX dumps only have one? */
78 static unsigned int pregapOffset;
80 #define cddaCurPos cdda_cur_sector
82 // compressed image stuff
84 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
85 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
86 unsigned int *index_table;
87 unsigned int index_len;
88 unsigned int block_shift;
89 unsigned int current_block;
90 unsigned int sector_in_blk;
93 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
95 char* CALLBACK CDR__getDriveLetter(void);
96 long CALLBACK CDR__configure(void);
97 long CALLBACK CDR__test(void);
98 void CALLBACK CDR__about(void);
99 long CALLBACK CDR__setfilename(char *filename);
100 long CALLBACK CDR__getStatus(struct CdrStat *stat);
102 static void DecodeRawSubData(void);
105 enum {DATA=1, CDDA} type;
106 char start[3]; // MSF-format
107 char length[3]; // MSF-format
108 FILE *handle; // for multi-track images CDDA
109 unsigned int start_offset; // byte offset from start of above file
112 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
114 static int numtracks = 0;
115 static struct trackinfo ti[MAXTRACKS];
117 // get a sector from a msf-array
118 static unsigned int msf2sec(char *msf) {
119 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
122 static void sec2msf(unsigned int s, char *msf) {
123 msf[0] = s / 75 / 60;
124 s = s - msf[0] * 75 * 60;
130 // divide a string of xx:yy:zz into m, s, f
131 static void tok2msf(char *time, char *msf) {
134 token = strtok(time, ":");
136 msf[0] = atoi(token);
142 token = strtok(NULL, ":");
144 msf[1] = atoi(token);
150 token = strtok(NULL, ":");
152 msf[2] = atoi(token);
160 static long GetTickCount(void) {
161 static time_t initial_time = 0;
164 gettimeofday(&now, NULL);
166 if (initial_time == 0) {
167 initial_time = now.tv_sec;
170 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
174 // this thread plays audio data
176 static void playthread(void *param)
178 static void *playthread(void *param)
181 long osleep, d, t, i, s;
183 int ret = 0, sector_offs;
189 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
190 sector_offs = cdda_cur_sector - cdda_first_sector;
191 if (sector_offs < 0) {
192 d = CD_FRAMESIZE_RAW;
193 memset(sndbuffer + s, 0, d);
196 d = cdimg_read_func(cddaHandle, cdda_file_offset,
197 sndbuffer + s, sector_offs);
198 if (d < CD_FRAMESIZE_RAW)
212 if (!cdr.Muted && playing) {
214 for (i = 0; i < s / 2; i++) {
215 tmp = sndbuffer[i * 2];
216 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
217 sndbuffer[i * 2 + 1] = tmp;
221 // can't do it yet due to readahead..
222 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
224 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
229 } while (ret == 0x7761 && playing); // rearmed_wait
232 if (ret != 0x676f) { // !rearmed_go
236 // HACK: stop feeding data while emu is paused
238 while (stop && playing)
243 now = GetTickCount();
249 else if (osleep > CDDA_FRAMETIME) {
250 osleep = CDDA_FRAMETIME;
254 usleep(osleep * 1000);
268 // stop the CDDA playback
269 static void stopCDDA() {
276 WaitForSingleObject(threadid, INFINITE);
278 pthread_join(threadid, NULL);
282 // start the CDDA playback
283 static void startCDDA(void) {
291 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
293 pthread_create(&threadid, NULL, playthread, NULL);
297 // this function tries to get the .toc file of the given .bin
298 // the necessary data is put into the ti (trackinformation)-array
299 static int parsetoc(const char *isofile) {
300 char tocname[MAXPATHLEN];
302 char linebuf[256], tmp[256], name[256];
304 char time[20], time2[20];
305 unsigned int t, sector_offs, sector_size;
306 unsigned int current_zero_gap = 0;
310 // copy name of the iso and change extension from .bin to .toc
311 strncpy(tocname, isofile, sizeof(tocname));
312 tocname[MAXPATHLEN - 1] = '\0';
313 if (strlen(tocname) >= 4) {
314 strcpy(tocname + strlen(tocname) - 4, ".toc");
320 if ((fi = fopen(tocname, "r")) == NULL) {
321 // try changing extension to .cue (to satisfy some stupid tutorials)
322 strcpy(tocname + strlen(tocname) - 4, ".cue");
323 if ((fi = fopen(tocname, "r")) == NULL) {
324 // if filename is image.toc.bin, try removing .bin (for Brasero)
325 strcpy(tocname, isofile);
327 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
328 tocname[t - 4] = '\0';
329 if ((fi = fopen(tocname, "r")) == NULL) {
337 // check if it's really a TOC named as a .cue
338 fgets(linebuf, sizeof(linebuf), fi);
339 token = strtok(linebuf, " ");
340 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
344 fseek(fi, 0, SEEK_SET);
347 memset(&ti, 0, sizeof(ti));
348 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
350 sector_size = CD_FRAMESIZE_RAW;
351 sector_offs = 2 * 75;
353 // parse the .toc file
354 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
356 strncpy(tmp, linebuf, sizeof(linebuf));
357 token = strtok(tmp, " ");
359 if (token == NULL) continue;
361 if (!strcmp(token, "TRACK")) {
362 sector_offs += current_zero_gap;
363 current_zero_gap = 0;
366 token = strtok(NULL, " ");
369 if (!strncmp(token, "MODE2_RAW", 9)) {
370 ti[numtracks].type = DATA;
371 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
373 // check if this image contains mixed subchannel data
374 token = strtok(NULL, " ");
375 if (token != NULL && !strncmp(token, "RW", 2)) {
376 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
378 if (!strncmp(token, "RW_RAW", 6))
382 else if (!strncmp(token, "AUDIO", 5)) {
383 ti[numtracks].type = CDDA;
386 else if (!strcmp(token, "DATAFILE")) {
387 if (ti[numtracks].type == CDDA) {
388 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
389 ti[numtracks].start_offset = t;
390 t = t / sector_size + sector_offs;
391 sec2msf(t, (char *)&ti[numtracks].start);
392 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
395 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
396 tok2msf((char *)&time, (char *)&ti[numtracks].length);
399 else if (!strcmp(token, "FILE")) {
400 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
401 tok2msf((char *)&time, (char *)&ti[numtracks].start);
402 t += msf2sec(ti[numtracks].start) * sector_size;
403 ti[numtracks].start_offset = t;
404 t = t / sector_size + sector_offs;
405 sec2msf(t, (char *)&ti[numtracks].start);
406 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
408 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
409 // skip unneeded optional fields
410 while (token != NULL) {
411 token = strtok(NULL, " ");
412 if (strchr(token, ':') != NULL)
417 current_zero_gap = msf2sec(tmp);
420 t = ti[numtracks - 1].start_offset;
422 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
425 else if (!strcmp(token, "START")) {
426 token = strtok(NULL, " ");
427 if (token != NULL && strchr(token, ':')) {
430 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
431 t = msf2sec(ti[numtracks].start) + t;
432 sec2msf(t, (char *)&ti[numtracks].start);
442 // this function tries to get the .cue file of the given .bin
443 // the necessary data is put into the ti (trackinformation)-array
444 static int parsecue(const char *isofile) {
445 char cuename[MAXPATHLEN];
446 char filepath[MAXPATHLEN];
452 char linebuf[256], tmpb[256], dummy[256];
453 unsigned int incue_max_len;
454 unsigned int t, file_len, mode, sector_offs;
455 unsigned int sector_size = 2352;
459 // copy name of the iso and change extension from .bin to .cue
460 strncpy(cuename, isofile, sizeof(cuename));
461 cuename[MAXPATHLEN - 1] = '\0';
462 if (strlen(cuename) >= 4) {
463 strcpy(cuename + strlen(cuename) - 4, ".cue");
469 if ((fi = fopen(cuename, "r")) == NULL) {
473 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
474 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
476 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
477 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
478 // Don't proceed further, as this is actually a .toc file rather
481 return parsetoc(isofile);
483 fseek(fi, 0, SEEK_SET);
486 // build a path for files referenced in .cue
487 strncpy(filepath, cuename, sizeof(filepath));
488 tmp = strrchr(filepath, '/');
490 tmp = strrchr(filepath, '\\');
496 filepath[sizeof(filepath) - 1] = 0;
498 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
500 memset(&ti, 0, sizeof(ti));
503 sector_offs = 2 * 75;
505 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
506 strncpy(dummy, linebuf, sizeof(linebuf));
507 token = strtok(dummy, " ");
513 if (!strcmp(token, "TRACK")) {
517 if (strstr(linebuf, "AUDIO") != NULL) {
518 ti[numtracks].type = CDDA;
521 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
522 ti[numtracks].type = DATA;
524 SysPrintf(".cue: failed to parse TRACK\n");
525 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
527 if (sector_size == 0)
530 else if (!strcmp(token, "INDEX")) {
531 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
532 SysPrintf(".cue: failed to parse INDEX\n");
533 tok2msf(time, (char *)&ti[numtracks].start);
535 t = msf2sec(ti[numtracks].start);
536 ti[numtracks].start_offset = t * sector_size;
538 sec2msf(t, ti[numtracks].start);
540 // default track length to file length
541 t = file_len - ti[numtracks].start_offset / sector_size;
542 sec2msf(t, ti[numtracks].length);
544 if (numtracks > 1 && ti[numtracks].handle == NULL) {
545 // this track uses the same file as the last,
546 // start of this track is last track's end
547 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
548 sec2msf(t, ti[numtracks - 1].length);
550 if (numtracks > 1 && pregapOffset == -1)
551 pregapOffset = ti[numtracks].start_offset / sector_size;
553 else if (!strcmp(token, "PREGAP")) {
554 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
555 tok2msf(time, dummy);
556 sector_offs += msf2sec(dummy);
558 pregapOffset = -1; // mark to fill track start_offset
560 else if (!strcmp(token, "FILE")) {
561 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
563 sscanf(linebuf, " FILE %255s", tmpb);
566 ti[numtracks + 1].handle = fopen(tmpb, "rb");
567 if (ti[numtracks + 1].handle == NULL) {
569 tmp = strrchr(tmpb, '\\');
571 tmp = strrchr(tmpb, '/');
576 strncpy(incue_fname, tmp, incue_max_len);
577 ti[numtracks + 1].handle = fopen(filepath, "rb");
580 // update global offset if this is not first file in this .cue
581 if (numtracks + 1 > 1) {
583 sector_offs += file_len;
587 if (ti[numtracks + 1].handle == NULL) {
588 SysPrintf(_("\ncould not open: %s\n"), filepath);
591 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
592 file_len = ftell(ti[numtracks + 1].handle) / 2352;
594 if (numtracks == 0 && strlen(isofile) >= 4 &&
595 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
597 // user selected .cue as image file, use it's data track instead
599 cdHandle = fopen(filepath, "rb");
609 // this function tries to get the .ccd file of the given .img
610 // the necessary data is put into the ti (trackinformation)-array
611 static int parseccd(const char *isofile) {
612 char ccdname[MAXPATHLEN];
619 // copy name of the iso and change extension from .img to .ccd
620 strncpy(ccdname, isofile, sizeof(ccdname));
621 ccdname[MAXPATHLEN - 1] = '\0';
622 if (strlen(ccdname) >= 4) {
623 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
629 if ((fi = fopen(ccdname, "r")) == NULL) {
633 memset(&ti, 0, sizeof(ti));
635 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
636 if (!strncmp(linebuf, "[TRACK", 6)){
639 else if (!strncmp(linebuf, "MODE=", 5)) {
640 sscanf(linebuf, "MODE=%d", &t);
641 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
643 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
644 sscanf(linebuf, "INDEX 1=%d", &t);
645 sec2msf(t + 2 * 75, ti[numtracks].start);
646 ti[numtracks].start_offset = t * 2352;
648 // If we've already seen another track, this is its end
650 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
651 sec2msf(t, ti[numtracks - 1].length);
658 // Fill out the last track's end based on size
659 if (numtracks >= 1) {
660 fseek(cdHandle, 0, SEEK_END);
661 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
662 sec2msf(t, ti[numtracks].length);
668 // this function tries to get the .mds file of the given .mdf
669 // the necessary data is put into the ti (trackinformation)-array
670 static int parsemds(const char *isofile) {
671 char mdsname[MAXPATHLEN];
673 unsigned int offset, extra_offset, l, i;
678 // copy name of the iso and change extension from .mdf to .mds
679 strncpy(mdsname, isofile, sizeof(mdsname));
680 mdsname[MAXPATHLEN - 1] = '\0';
681 if (strlen(mdsname) >= 4) {
682 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
688 if ((fi = fopen(mdsname, "rb")) == NULL) {
692 memset(&ti, 0, sizeof(ti));
694 // check if it's a valid mds file
695 fread(&i, 1, sizeof(unsigned int), fi);
697 if (i != 0x4944454D) {
698 // not an valid mds file
703 // get offset to session block
704 fseek(fi, 0x50, SEEK_SET);
705 fread(&offset, 1, sizeof(unsigned int), fi);
706 offset = SWAP32(offset);
708 // get total number of tracks
710 fseek(fi, offset, SEEK_SET);
711 fread(&s, 1, sizeof(unsigned short), fi);
715 // get offset to track blocks
716 fseek(fi, 4, SEEK_CUR);
717 fread(&offset, 1, sizeof(unsigned int), fi);
718 offset = SWAP32(offset);
722 fseek(fi, offset + 4, SEEK_SET);
723 if (fgetc(fi) < 0xA0) {
729 // check if the image contains mixed subchannel data
730 fseek(fi, offset + 1, SEEK_SET);
731 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
734 for (i = 1; i <= numtracks; i++) {
735 fseek(fi, offset, SEEK_SET);
737 // get the track type
738 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
739 fseek(fi, 8, SEEK_CUR);
741 // get the track starting point
742 ti[i].start[0] = fgetc(fi);
743 ti[i].start[1] = fgetc(fi);
744 ti[i].start[2] = fgetc(fi);
746 fread(&extra_offset, 1, sizeof(unsigned int), fi);
747 extra_offset = SWAP32(extra_offset);
749 // get track start offset (in .mdf)
750 fseek(fi, offset + 0x28, SEEK_SET);
751 fread(&l, 1, sizeof(unsigned int), fi);
753 ti[i].start_offset = l;
756 fseek(fi, extra_offset, SEEK_SET);
757 fread(&l, 1, sizeof(unsigned int), fi);
760 pregapOffset = msf2sec(ti[i].start);
762 // get the track length
763 fread(&l, 1, sizeof(unsigned int), fi);
765 sec2msf(l, ti[i].length);
774 static int handlepbp(const char *isofile) {
777 unsigned int dontcare[8];
778 unsigned int psar_offs;
791 unsigned int dontcare[6];
794 unsigned int t, cd_length, cdimg_base;
795 unsigned int offsettab[8], psisoimg_offs;
796 const char *ext = NULL;
799 if (strlen(isofile) >= 4)
800 ext = isofile + strlen(isofile) - 4;
801 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
804 fseek(cdHandle, 0, SEEK_SET);
808 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
809 if (ret != sizeof(pbp_hdr)) {
810 SysPrintf("failed to read pbp\n");
814 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
816 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
820 psisoimg_offs = pbp_hdr.psar_offs;
821 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
823 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
825 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
827 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
831 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
832 SysPrintf("failed to read offsettab\n");
836 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
837 if (offsettab[i] == 0)
840 cdrIsoMultidiskCount = i;
841 if (cdrIsoMultidiskCount == 0) {
842 SysPrintf("multidisk eboot has 0 images?\n");
846 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
847 cdrIsoMultidiskSelect = 0;
849 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
851 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
853 SysPrintf("failed to seek to %x\n", psisoimg_offs);
857 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
861 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
862 SysPrintf("bad psar_sig: %s\n", psar_sig);
867 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
869 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
873 // first 3 entries are special
874 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
875 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
876 numtracks = btoi(toc_entry.index1[0]);
878 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
879 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
880 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
882 for (i = 1; i <= numtracks; i++) {
883 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
885 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
887 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
888 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
889 ti[i].start_offset *= 2352;
890 ti[i].start[0] = btoi(toc_entry.index1[0]);
891 ti[i].start[1] = btoi(toc_entry.index1[1]);
892 ti[i].start[2] = btoi(toc_entry.index1[2]);
895 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
896 sec2msf(t, ti[i - 1].length);
899 t = cd_length - ti[numtracks].start_offset / 2352;
900 sec2msf(t, ti[numtracks].length);
903 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
905 SysPrintf("failed to seek to ISO index\n");
909 compr_img = calloc(1, sizeof(*compr_img));
910 if (compr_img == NULL)
913 compr_img->block_shift = 4;
914 compr_img->current_block = (unsigned int)-1;
916 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
917 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
918 if (compr_img->index_table == NULL)
921 cdimg_base = psisoimg_offs + 0x100000;
922 for (i = 0; i < compr_img->index_len; i++) {
923 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
924 if (ret != sizeof(index_entry)) {
925 SysPrintf("failed to read index_entry #%d\n", i);
929 if (index_entry.size == 0)
932 compr_img->index_table[i] = cdimg_base + index_entry.offset;
934 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
939 free(compr_img->index_table);
940 compr_img->index_table = NULL;
942 if (compr_img != NULL) {
949 static int handlecbin(const char *isofile) {
953 unsigned int header_size;
954 unsigned long long total_bytes;
955 unsigned int block_size;
956 unsigned char ver; // 1
958 unsigned char rsv_06[2];
960 const char *ext = NULL;
961 unsigned int index = 0, plain;
964 if (strlen(isofile) >= 5)
965 ext = isofile + strlen(isofile) - 5;
966 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
969 fseek(cdHandle, 0, SEEK_SET);
971 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
972 if (ret != sizeof(ciso_hdr)) {
973 SysPrintf("failed to read ciso header\n");
977 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
978 SysPrintf("bad ciso header\n");
981 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
982 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
984 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
989 compr_img = calloc(1, sizeof(*compr_img));
990 if (compr_img == NULL)
993 compr_img->block_shift = 0;
994 compr_img->current_block = (unsigned int)-1;
996 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
997 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
998 if (compr_img->index_table == NULL)
1001 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
1002 if (ret != compr_img->index_len) {
1003 SysPrintf("failed to read index table\n");
1007 for (i = 0; i < compr_img->index_len + 1; i++) {
1008 index = compr_img->index_table[i];
1009 plain = index & 0x80000000;
1010 index &= 0x7fffffff;
1011 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1013 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1014 SysPrintf("warning: ciso img too large, expect problems\n");
1019 free(compr_img->index_table);
1020 compr_img->index_table = NULL;
1022 if (compr_img != NULL) {
1029 // this function tries to get the .sub file of the given .img
1030 static int opensubfile(const char *isoname) {
1031 char subname[MAXPATHLEN];
1033 // copy name of the iso and change extension from .img to .sub
1034 strncpy(subname, isoname, sizeof(subname));
1035 subname[MAXPATHLEN - 1] = '\0';
1036 if (strlen(subname) >= 4) {
1037 strcpy(subname + strlen(subname) - 4, ".sub");
1043 subHandle = fopen(subname, "rb");
1044 if (subHandle == NULL) {
1051 static int opensbifile(const char *isoname) {
1052 char sbiname[MAXPATHLEN];
1055 strncpy(sbiname, isoname, sizeof(sbiname));
1056 sbiname[MAXPATHLEN - 1] = '\0';
1057 if (strlen(sbiname) >= 4) {
1058 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1064 fseek(cdHandle, 0, SEEK_END);
1065 s = ftell(cdHandle) / 2352;
1067 return LoadSBI(sbiname, s);
1070 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1072 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1073 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1076 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1080 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1081 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1082 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1084 if (subChanRaw) DecodeRawSubData();
1089 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1094 if (z.zalloc == NULL) {
1095 // XXX: one-time leak here..
1101 ret = inflateInit2(&z, -15);
1104 ret = inflateReset(&z);
1109 z.avail_in = in_size;
1111 z.avail_out = *out_size;
1113 ret = inflate(&z, Z_NO_FLUSH);
1116 *out_size -= z.avail_out;
1117 return ret == 1 ? 0 : ret;
1120 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1122 unsigned long cdbuffer_size, cdbuffer_size_expect;
1123 unsigned int start_byte, size;
1128 sector += base / 2352;
1130 block = sector >> compr_img->block_shift;
1131 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1133 if (block == compr_img->current_block) {
1134 //printf("hit sect %d\n", sector);
1138 if (sector >= compr_img->index_len * 16) {
1139 SysPrintf("sector %d is past img end\n", sector);
1143 start_byte = compr_img->index_table[block] & 0x7fffffff;
1144 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1145 SysPrintf("seek error for block %d at %x: ",
1151 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1152 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1153 if (size > sizeof(compr_img->buff_compressed)) {
1154 SysPrintf("block %d is too large: %u\n", block, size);
1158 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1159 1, size, cdHandle) != size) {
1160 SysPrintf("read error for block %d at %x: ", block, start_byte);
1165 if (is_compressed) {
1166 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1167 cdbuffer_size = cdbuffer_size_expect;
1168 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1170 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1171 ret, block, sector);
1174 if (cdbuffer_size != cdbuffer_size_expect)
1175 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1176 cdbuffer_size_expect, sector);
1180 compr_img->current_block = block;
1183 if (dest != cdbuffer) // copy avoid HACK
1184 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1186 return CD_FRAMESIZE_RAW;
1189 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1193 fseek(f, base + sector * 2048, SEEK_SET);
1194 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1196 // not really necessary, fake mode 2 header
1197 memset(cdbuffer, 0, 12 * 2);
1198 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1199 cdbuffer[12 + 3] = 1;
1204 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1205 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1208 static unsigned char * CALLBACK ISOgetBuffer(void) {
1209 return cdbuffer + 12;
1212 static void PrintTracks(void) {
1215 for (i = 1; i <= numtracks; i++) {
1216 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1217 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1218 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1219 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1223 // This function is invoked by the front-end when opening an ISO
1224 // file for playback
1225 static long CALLBACK ISOopen(void) {
1226 boolean isMode1ISO = FALSE;
1227 char alt_bin_filename[MAXPATHLEN];
1228 const char *bin_filename;
1230 if (cdHandle != NULL) {
1231 return 0; // it's already open
1234 cdHandle = fopen(GetIsoFile(), "rb");
1235 if (cdHandle == NULL) {
1236 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1237 GetIsoFile(), strerror(errno));
1241 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1243 cddaBigEndian = FALSE;
1244 subChanMixed = FALSE;
1247 cdrIsoMultidiskCount = 1;
1250 CDR_getBuffer = ISOgetBuffer;
1251 cdimg_read_func = cdread_normal;
1253 if (parsetoc(GetIsoFile()) == 0) {
1254 SysPrintf("[+toc]");
1256 else if (parseccd(GetIsoFile()) == 0) {
1257 SysPrintf("[+ccd]");
1259 else if (parsemds(GetIsoFile()) == 0) {
1260 SysPrintf("[+mds]");
1262 else if (parsecue(GetIsoFile()) == 0) {
1263 SysPrintf("[+cue]");
1265 if (handlepbp(GetIsoFile()) == 0) {
1267 CDR_getBuffer = ISOgetBuffer_compr;
1268 cdimg_read_func = cdread_compressed;
1270 else if (handlecbin(GetIsoFile()) == 0) {
1271 SysPrintf("[cbin]");
1272 CDR_getBuffer = ISOgetBuffer_compr;
1273 cdimg_read_func = cdread_compressed;
1276 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1277 SysPrintf("[+sub]");
1279 if (opensbifile(GetIsoFile()) == 0) {
1280 SysPrintf("[+sbi]");
1283 fseek(cdHandle, 0, SEEK_END);
1285 // maybe user selected metadata file instead of main .bin ..
1286 bin_filename = GetIsoFile();
1287 if (ftell(cdHandle) < 2352 * 0x10) {
1288 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1293 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1294 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1295 if (strlen(alt_bin_filename) >= 4) {
1296 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1297 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1299 tmpf = fopen(alt_bin_filename, "rb");
1305 bin_filename = alt_bin_filename;
1308 fseek(cdHandle, 0, SEEK_END);
1312 // guess whether it is mode1/2048
1313 if (ftell(cdHandle) % 2048 == 0) {
1314 unsigned int modeTest = 0;
1315 fseek(cdHandle, 0, SEEK_SET);
1316 fread(&modeTest, 4, 1, cdHandle);
1317 if (SWAP32(modeTest) != 0xffffff00) {
1318 SysPrintf("[2048]");
1322 fseek(cdHandle, 0, SEEK_SET);
1329 cdimg_read_func = cdread_sub_mixed;
1330 else if (isMode1ISO)
1331 cdimg_read_func = cdread_2048;
1333 // make sure we have another handle open for cdda
1334 if (numtracks > 1 && ti[1].handle == NULL) {
1335 ti[1].handle = fopen(bin_filename, "rb");
1337 cdda_cur_sector = 0;
1338 cdda_file_offset = 0;
1343 static long CALLBACK ISOclose(void) {
1346 if (cdHandle != NULL) {
1350 if (subHandle != NULL) {
1357 if (compr_img != NULL) {
1358 free(compr_img->index_table);
1363 for (i = 1; i <= numtracks; i++) {
1364 if (ti[i].handle != NULL) {
1365 fclose(ti[i].handle);
1366 ti[i].handle = NULL;
1373 memset(cdbuffer, 0, sizeof(cdbuffer));
1374 CDR_getBuffer = ISOgetBuffer;
1379 static long CALLBACK ISOinit(void) {
1380 assert(cdHandle == NULL);
1381 assert(subHandle == NULL);
1383 return 0; // do nothing
1386 static long CALLBACK ISOshutdown(void) {
1391 // return Starting and Ending Track
1393 // byte 0 - start track
1394 // byte 1 - end track
1395 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1398 if (numtracks > 0) {
1399 buffer[1] = numtracks;
1408 // return Track Time
1413 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1416 unsigned char time[3];
1417 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1418 sec2msf(sect, (char *)time);
1419 buffer[2] = time[0];
1420 buffer[1] = time[1];
1421 buffer[0] = time[2];
1423 else if (numtracks > 0 && track <= numtracks) {
1424 buffer[2] = ti[track].start[0];
1425 buffer[1] = ti[track].start[1];
1426 buffer[0] = ti[track].start[2];
1437 // decode 'raw' subchannel data ripped by cdrdao
1438 static void DecodeRawSubData(void) {
1439 unsigned char subQData[12];
1442 memset(subQData, 0, sizeof(subQData));
1444 for (i = 0; i < 8 * 12; i++) {
1445 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1446 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1450 memcpy(&subbuffer[12], subQData, 12);
1454 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1456 static long CALLBACK ISOreadTrack(unsigned char *time) {
1457 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1460 if (cdHandle == NULL) {
1465 subChanMissing = FALSE;
1466 if (sector >= pregapOffset) {
1468 if (sector < pregapOffset)
1469 subChanMissing = TRUE;
1473 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1477 if (subHandle != NULL) {
1478 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1479 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1481 if (subChanRaw) DecodeRawSubData();
1488 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1489 // does NOT uses bcd format
1490 static long CALLBACK ISOplay(unsigned char *time) {
1497 cdda_cur_sector = msf2sec((char *)time);
1498 for (i = numtracks; i > 1; i--) {
1499 cdda_first_sector = msf2sec(ti[i].start);
1500 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1503 cdda_file_offset = ti[i].start_offset;
1505 // find the file that contains this track
1507 if (ti[i].handle != NULL)
1510 cddaHandle = ti[i].handle;
1512 if (SPU_playCDDAchannel != NULL)
1519 static long CALLBACK ISOstop(void) {
1524 // gets subchannel data
1525 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1526 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1533 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1536 CDR__getStatus(stat);
1540 stat->Status |= 0x80;
1543 // BIOS - boot ID (CD type)
1544 stat->Type = ti[1].type;
1547 // relative -> absolute time
1549 sec2msf(sect, (char *)stat->Time);
1554 // read CDDA sector into buffer
1555 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1556 unsigned char msf[3] = {m, s, f};
1557 unsigned int file, track, track_start = 0;
1560 cddaCurPos = msf2sec((char *)msf);
1562 // find current track index
1563 for (track = numtracks; ; track--) {
1564 track_start = msf2sec(ti[track].start);
1565 if (track_start <= cddaCurPos)
1571 // data tracks play silent
1572 if (ti[track].type != CDDA) {
1573 memset(buffer, 0, CD_FRAMESIZE_RAW);
1579 // find the file that contains this track
1580 for (file = track; file > 1; file--)
1581 if (ti[file].handle != NULL)
1585 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1586 buffer, cddaCurPos - track_start);
1587 if (ret != CD_FRAMESIZE_RAW) {
1588 memset(buffer, 0, CD_FRAMESIZE_RAW);
1592 if (cddaBigEndian) {
1596 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1597 tmp = buffer[i * 2];
1598 buffer[i * 2] = buffer[i * 2 + 1];
1599 buffer[i * 2 + 1] = tmp;
1606 void cdrIsoInit(void) {
1608 CDR_shutdown = ISOshutdown;
1610 CDR_close = ISOclose;
1611 CDR_getTN = ISOgetTN;
1612 CDR_getTD = ISOgetTD;
1613 CDR_readTrack = ISOreadTrack;
1614 CDR_getBuffer = ISOgetBuffer;
1617 CDR_getBufferSub = ISOgetBufferSub;
1618 CDR_getStatus = ISOgetStatus;
1619 CDR_readCDDA = ISOreadCDDA;
1621 CDR_getDriveLetter = CDR__getDriveLetter;
1622 CDR_configure = CDR__configure;
1623 CDR_test = CDR__test;
1624 CDR_about = CDR__about;
1625 CDR_setfilename = CDR__setfilename;
1630 int cdrIsoActive(void) {
1631 return (cdHandle != NULL);