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"
33 #define WIN32_LEAN_AND_MEAN
36 #define strcasecmp _stricmp
37 #define usleep(x) (Sleep((x) / 1000))
44 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
46 unsigned int cdrIsoMultidiskCount;
47 unsigned int cdrIsoMultidiskSelect;
49 static FILE *cdHandle = NULL;
50 static FILE *cddaHandle = NULL;
51 static FILE *subHandle = NULL;
53 static boolean subChanMixed = FALSE;
54 static boolean subChanRaw = FALSE;
55 static boolean subChanMissing = FALSE;
57 static boolean multifile = FALSE;
59 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
60 static unsigned char subbuffer[SUB_FRAMESIZE];
62 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
64 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
67 static HANDLE threadid;
69 static pthread_t threadid;
71 static unsigned int initial_offset = 0;
72 static boolean playing = FALSE;
73 static boolean cddaBigEndian = FALSE;
74 // cdda sectors in toc, byte offset in file
75 static unsigned int cdda_cur_sector;
76 static unsigned int cdda_first_sector;
77 static unsigned int cdda_file_offset;
78 /* Frame offset into CD image where pregap data would be found if it was there.
79 * If a game seeks there we must *not* return subchannel data since it's
80 * not in the CD image, so that cdrom code can fake subchannel data instead.
81 * XXX: there could be multiple pregaps but PSX dumps only have one? */
82 static unsigned int pregapOffset;
84 #define cddaCurPos cdda_cur_sector
86 // compressed image stuff
88 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
89 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
91 unsigned int index_len;
92 unsigned int block_shift;
93 unsigned int current_block;
94 unsigned int sector_in_blk;
98 unsigned char (*buffer)[CD_FRAMESIZE_RAW + SUB_FRAMESIZE];
100 const chd_header* header;
101 unsigned int sectors_per_hunk;
102 unsigned int current_hunk;
103 unsigned int sector_in_hunk;
106 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
108 char* CALLBACK CDR__getDriveLetter(void);
109 long CALLBACK CDR__configure(void);
110 long CALLBACK CDR__test(void);
111 void CALLBACK CDR__about(void);
112 long CALLBACK CDR__setfilename(char *filename);
113 long CALLBACK CDR__getStatus(struct CdrStat *stat);
115 static void DecodeRawSubData(void);
118 enum {DATA=1, CDDA} type;
119 char start[3]; // MSF-format
120 char length[3]; // MSF-format
121 FILE *handle; // for multi-track images CDDA
122 unsigned int start_offset; // byte offset from start of above file
125 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
127 static int numtracks = 0;
128 static struct trackinfo ti[MAXTRACKS];
130 // get a sector from a msf-array
131 static unsigned int msf2sec(char *msf) {
132 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
135 static void sec2msf(unsigned int s, char *msf) {
136 msf[0] = s / 75 / 60;
137 s = s - msf[0] * 75 * 60;
143 // divide a string of xx:yy:zz into m, s, f
144 static void tok2msf(char *time, char *msf) {
147 token = strtok(time, ":");
149 msf[0] = atoi(token);
155 token = strtok(NULL, ":");
157 msf[1] = atoi(token);
163 token = strtok(NULL, ":");
165 msf[2] = atoi(token);
173 static long GetTickCount(void) {
174 static time_t initial_time = 0;
177 gettimeofday(&now, NULL);
179 if (initial_time == 0) {
180 initial_time = now.tv_sec;
183 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
187 // this thread plays audio data
189 static void playthread(void *param)
191 static void *playthread(void *param)
194 long osleep, d, t, i, s;
196 int ret = 0, sector_offs;
202 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
203 sector_offs = cdda_cur_sector - cdda_first_sector;
204 if (sector_offs < 0) {
205 d = CD_FRAMESIZE_RAW;
206 memset(sndbuffer + s, 0, d);
209 d = cdimg_read_func(cddaHandle, cdda_file_offset,
210 sndbuffer + s, sector_offs);
211 if (d < CD_FRAMESIZE_RAW)
225 if (!cdr.Muted && playing) {
227 for (i = 0; i < s / 2; i++) {
228 tmp = sndbuffer[i * 2];
229 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
230 sndbuffer[i * 2 + 1] = tmp;
234 // can't do it yet due to readahead..
235 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
237 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
242 } while (ret == 0x7761 && playing); // rearmed_wait
245 if (ret != 0x676f) { // !rearmed_go
249 // HACK: stop feeding data while emu is paused
251 while (stop && playing)
256 now = GetTickCount();
262 else if (osleep > CDDA_FRAMETIME) {
263 osleep = CDDA_FRAMETIME;
267 usleep(osleep * 1000);
281 // stop the CDDA playback
282 static void stopCDDA() {
289 WaitForSingleObject(threadid, INFINITE);
291 pthread_join(threadid, NULL);
295 // start the CDDA playback
296 static void startCDDA(void) {
304 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
306 pthread_create(&threadid, NULL, playthread, NULL);
310 // this function tries to get the .toc file of the given .bin
311 // the necessary data is put into the ti (trackinformation)-array
312 static int parsetoc(const char *isofile) {
313 char tocname[MAXPATHLEN];
315 char linebuf[256], tmp[256], name[256];
317 char time[20], time2[20];
318 unsigned int t, sector_offs, sector_size;
319 unsigned int current_zero_gap = 0;
323 // copy name of the iso and change extension from .bin to .toc
324 strncpy(tocname, isofile, sizeof(tocname));
325 tocname[MAXPATHLEN - 1] = '\0';
326 if (strlen(tocname) >= 4) {
327 strcpy(tocname + strlen(tocname) - 4, ".toc");
333 if ((fi = fopen(tocname, "r")) == NULL) {
334 // try changing extension to .cue (to satisfy some stupid tutorials)
335 strcpy(tocname + strlen(tocname) - 4, ".cue");
336 if ((fi = fopen(tocname, "r")) == NULL) {
337 // if filename is image.toc.bin, try removing .bin (for Brasero)
338 strcpy(tocname, isofile);
340 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
341 tocname[t - 4] = '\0';
342 if ((fi = fopen(tocname, "r")) == NULL) {
350 // check if it's really a TOC named as a .cue
351 fgets(linebuf, sizeof(linebuf), fi);
352 token = strtok(linebuf, " ");
353 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
357 fseek(fi, 0, SEEK_SET);
360 memset(&ti, 0, sizeof(ti));
361 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
363 sector_size = CD_FRAMESIZE_RAW;
364 sector_offs = 2 * 75;
366 // parse the .toc file
367 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
369 strncpy(tmp, linebuf, sizeof(linebuf));
370 token = strtok(tmp, " ");
372 if (token == NULL) continue;
374 if (!strcmp(token, "TRACK")) {
375 sector_offs += current_zero_gap;
376 current_zero_gap = 0;
379 token = strtok(NULL, " ");
382 if (!strncmp(token, "MODE2_RAW", 9)) {
383 ti[numtracks].type = DATA;
384 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
386 // check if this image contains mixed subchannel data
387 token = strtok(NULL, " ");
388 if (token != NULL && !strncmp(token, "RW", 2)) {
389 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
391 if (!strncmp(token, "RW_RAW", 6))
395 else if (!strncmp(token, "AUDIO", 5)) {
396 ti[numtracks].type = CDDA;
399 else if (!strcmp(token, "DATAFILE")) {
400 if (ti[numtracks].type == CDDA) {
401 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
402 ti[numtracks].start_offset = t;
403 t = t / sector_size + sector_offs;
404 sec2msf(t, (char *)&ti[numtracks].start);
405 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
408 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
409 tok2msf((char *)&time, (char *)&ti[numtracks].length);
412 else if (!strcmp(token, "FILE")) {
413 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
414 tok2msf((char *)&time, (char *)&ti[numtracks].start);
415 t += msf2sec(ti[numtracks].start) * sector_size;
416 ti[numtracks].start_offset = t;
417 t = t / sector_size + sector_offs;
418 sec2msf(t, (char *)&ti[numtracks].start);
419 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
421 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
422 // skip unneeded optional fields
423 while (token != NULL) {
424 token = strtok(NULL, " ");
425 if (strchr(token, ':') != NULL)
430 current_zero_gap = msf2sec(tmp);
433 t = ti[numtracks - 1].start_offset;
435 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
438 else if (!strcmp(token, "START")) {
439 token = strtok(NULL, " ");
440 if (token != NULL && strchr(token, ':')) {
443 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
444 t = msf2sec(ti[numtracks].start) + t;
445 sec2msf(t, (char *)&ti[numtracks].start);
455 // this function tries to get the .cue file of the given .bin
456 // the necessary data is put into the ti (trackinformation)-array
457 static int parsecue(const char *isofile) {
458 char cuename[MAXPATHLEN];
459 char filepath[MAXPATHLEN];
465 char linebuf[256], tmpb[256], dummy[256];
466 unsigned int incue_max_len;
467 unsigned int t, file_len, mode, sector_offs;
468 unsigned int sector_size = 2352;
472 // copy name of the iso and change extension from .bin to .cue
473 strncpy(cuename, isofile, sizeof(cuename));
474 cuename[MAXPATHLEN - 1] = '\0';
475 if (strlen(cuename) >= 4) {
476 strcpy(cuename + strlen(cuename) - 4, ".cue");
482 if ((fi = fopen(cuename, "r")) == NULL) {
486 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
487 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
489 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
490 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
491 // Don't proceed further, as this is actually a .toc file rather
494 return parsetoc(isofile);
496 fseek(fi, 0, SEEK_SET);
499 // build a path for files referenced in .cue
500 strncpy(filepath, cuename, sizeof(filepath));
501 tmp = strrchr(filepath, '/');
503 tmp = strrchr(filepath, '\\');
509 filepath[sizeof(filepath) - 1] = 0;
511 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
513 memset(&ti, 0, sizeof(ti));
516 sector_offs = 2 * 75;
518 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
519 strncpy(dummy, linebuf, sizeof(linebuf));
520 token = strtok(dummy, " ");
526 if (!strcmp(token, "TRACK")) {
530 if (strstr(linebuf, "AUDIO") != NULL) {
531 ti[numtracks].type = CDDA;
534 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
535 ti[numtracks].type = DATA;
537 SysPrintf(".cue: failed to parse TRACK\n");
538 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
540 if (sector_size == 0)
543 else if (!strcmp(token, "INDEX")) {
544 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
545 SysPrintf(".cue: failed to parse INDEX\n");
546 tok2msf(time, (char *)&ti[numtracks].start);
548 t = msf2sec(ti[numtracks].start);
549 ti[numtracks].start_offset = t * sector_size;
551 sec2msf(t, ti[numtracks].start);
553 // default track length to file length
554 t = file_len - ti[numtracks].start_offset / sector_size;
555 sec2msf(t, ti[numtracks].length);
557 if (numtracks > 1 && ti[numtracks].handle == NULL) {
558 // this track uses the same file as the last,
559 // start of this track is last track's end
560 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
561 sec2msf(t, ti[numtracks - 1].length);
563 if (numtracks > 1 && pregapOffset == -1)
564 pregapOffset = ti[numtracks].start_offset / sector_size;
566 else if (!strcmp(token, "PREGAP")) {
567 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
568 tok2msf(time, dummy);
569 sector_offs += msf2sec(dummy);
571 pregapOffset = -1; // mark to fill track start_offset
573 else if (!strcmp(token, "FILE")) {
574 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
576 sscanf(linebuf, " FILE %255s", tmpb);
578 tmp = strrchr(tmpb, '\\');
580 tmp = strrchr(tmpb, '/');
585 strncpy(incue_fname, tmp, incue_max_len);
586 ti[numtracks + 1].handle = fopen(filepath, "rb");
588 // update global offset if this is not first file in this .cue
589 if (numtracks + 1 > 1) {
591 sector_offs += file_len;
595 if (ti[numtracks + 1].handle == NULL) {
596 SysPrintf(_("\ncould not open: %s\n"), filepath);
599 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
600 file_len = ftell(ti[numtracks + 1].handle) / 2352;
602 if (numtracks == 0 && strlen(isofile) >= 4 &&
603 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
605 // user selected .cue as image file, use it's data track instead
607 cdHandle = fopen(filepath, "rb");
617 // this function tries to get the .ccd file of the given .img
618 // the necessary data is put into the ti (trackinformation)-array
619 static int parseccd(const char *isofile) {
620 char ccdname[MAXPATHLEN];
627 // copy name of the iso and change extension from .img to .ccd
628 strncpy(ccdname, isofile, sizeof(ccdname));
629 ccdname[MAXPATHLEN - 1] = '\0';
630 if (strlen(ccdname) >= 4) {
631 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
637 if ((fi = fopen(ccdname, "r")) == NULL) {
641 memset(&ti, 0, sizeof(ti));
643 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
644 if (!strncmp(linebuf, "[TRACK", 6)){
647 else if (!strncmp(linebuf, "MODE=", 5)) {
648 sscanf(linebuf, "MODE=%d", &t);
649 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
651 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
652 sscanf(linebuf, "INDEX 1=%d", &t);
653 sec2msf(t + 2 * 75, ti[numtracks].start);
654 ti[numtracks].start_offset = t * 2352;
656 // If we've already seen another track, this is its end
658 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
659 sec2msf(t, ti[numtracks - 1].length);
666 // Fill out the last track's end based on size
667 if (numtracks >= 1) {
668 fseek(cdHandle, 0, SEEK_END);
669 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
670 sec2msf(t, ti[numtracks].length);
676 // this function tries to get the .mds file of the given .mdf
677 // the necessary data is put into the ti (trackinformation)-array
678 static int parsemds(const char *isofile) {
679 char mdsname[MAXPATHLEN];
681 unsigned int offset, extra_offset, l, i;
686 // copy name of the iso and change extension from .mdf to .mds
687 strncpy(mdsname, isofile, sizeof(mdsname));
688 mdsname[MAXPATHLEN - 1] = '\0';
689 if (strlen(mdsname) >= 4) {
690 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
696 if ((fi = fopen(mdsname, "rb")) == NULL) {
700 memset(&ti, 0, sizeof(ti));
702 // check if it's a valid mds file
703 fread(&i, 1, sizeof(unsigned int), fi);
705 if (i != 0x4944454D) {
706 // not an valid mds file
711 // get offset to session block
712 fseek(fi, 0x50, SEEK_SET);
713 fread(&offset, 1, sizeof(unsigned int), fi);
714 offset = SWAP32(offset);
716 // get total number of tracks
718 fseek(fi, offset, SEEK_SET);
719 fread(&s, 1, sizeof(unsigned short), fi);
723 // get offset to track blocks
724 fseek(fi, 4, SEEK_CUR);
725 fread(&offset, 1, sizeof(unsigned int), fi);
726 offset = SWAP32(offset);
730 fseek(fi, offset + 4, SEEK_SET);
731 if (fgetc(fi) < 0xA0) {
737 // check if the image contains mixed subchannel data
738 fseek(fi, offset + 1, SEEK_SET);
739 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
742 for (i = 1; i <= numtracks; i++) {
743 fseek(fi, offset, SEEK_SET);
745 // get the track type
746 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
747 fseek(fi, 8, SEEK_CUR);
749 // get the track starting point
750 ti[i].start[0] = fgetc(fi);
751 ti[i].start[1] = fgetc(fi);
752 ti[i].start[2] = fgetc(fi);
754 fread(&extra_offset, 1, sizeof(unsigned int), fi);
755 extra_offset = SWAP32(extra_offset);
757 // get track start offset (in .mdf)
758 fseek(fi, offset + 0x28, SEEK_SET);
759 fread(&l, 1, sizeof(unsigned int), fi);
761 ti[i].start_offset = l;
764 fseek(fi, extra_offset, SEEK_SET);
765 fread(&l, 1, sizeof(unsigned int), fi);
768 pregapOffset = msf2sec(ti[i].start);
770 // get the track length
771 fread(&l, 1, sizeof(unsigned int), fi);
773 sec2msf(l, ti[i].length);
782 static int handlepbp(const char *isofile) {
785 unsigned int dontcare[8];
786 unsigned int psar_offs;
799 unsigned int dontcare[6];
802 off_t psisoimg_offs, cdimg_base;
803 unsigned int t, cd_length;
804 unsigned int offsettab[8];
805 const char *ext = NULL;
808 if (strlen(isofile) >= 4)
809 ext = isofile + strlen(isofile) - 4;
810 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
813 fseeko(cdHandle, 0, SEEK_SET);
817 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
818 if (ret != sizeof(pbp_hdr)) {
819 SysPrintf("failed to read pbp\n");
823 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
825 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
829 psisoimg_offs = pbp_hdr.psar_offs;
830 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
832 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
834 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
836 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
840 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
841 SysPrintf("failed to read offsettab\n");
845 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
846 if (offsettab[i] == 0)
849 cdrIsoMultidiskCount = i;
850 if (cdrIsoMultidiskCount == 0) {
851 SysPrintf("multidisk eboot has 0 images?\n");
855 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
856 cdrIsoMultidiskSelect = 0;
858 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
860 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
862 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
866 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
870 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
871 SysPrintf("bad psar_sig: %s\n", psar_sig);
876 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
878 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
882 // first 3 entries are special
883 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
884 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
885 numtracks = btoi(toc_entry.index1[0]);
887 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
888 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
889 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
891 for (i = 1; i <= numtracks; i++) {
892 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
894 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
896 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
897 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
898 ti[i].start_offset *= 2352;
899 ti[i].start[0] = btoi(toc_entry.index1[0]);
900 ti[i].start[1] = btoi(toc_entry.index1[1]);
901 ti[i].start[2] = btoi(toc_entry.index1[2]);
904 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
905 sec2msf(t, ti[i - 1].length);
908 t = cd_length - ti[numtracks].start_offset / 2352;
909 sec2msf(t, ti[numtracks].length);
912 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
914 SysPrintf("failed to seek to ISO index\n");
918 compr_img = calloc(1, sizeof(*compr_img));
919 if (compr_img == NULL)
922 compr_img->block_shift = 4;
923 compr_img->current_block = (unsigned int)-1;
925 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
926 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
927 if (compr_img->index_table == NULL)
930 cdimg_base = psisoimg_offs + 0x100000;
931 for (i = 0; i < compr_img->index_len; i++) {
932 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
933 if (ret != sizeof(index_entry)) {
934 SysPrintf("failed to read index_entry #%d\n", i);
938 if (index_entry.size == 0)
941 compr_img->index_table[i] = cdimg_base + index_entry.offset;
943 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
948 free(compr_img->index_table);
949 compr_img->index_table = NULL;
951 if (compr_img != NULL) {
958 static int handlecbin(const char *isofile) {
962 unsigned int header_size;
963 unsigned long long total_bytes;
964 unsigned int block_size;
965 unsigned char ver; // 1
967 unsigned char rsv_06[2];
969 const char *ext = NULL;
970 unsigned int *index_table = NULL;
971 unsigned int index = 0, plain;
974 if (strlen(isofile) >= 5)
975 ext = isofile + strlen(isofile) - 5;
976 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
979 fseek(cdHandle, 0, SEEK_SET);
981 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
982 if (ret != sizeof(ciso_hdr)) {
983 SysPrintf("failed to read ciso header\n");
987 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
988 SysPrintf("bad ciso header\n");
991 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
992 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
994 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
999 compr_img = calloc(1, sizeof(*compr_img));
1000 if (compr_img == NULL)
1003 compr_img->block_shift = 0;
1004 compr_img->current_block = (unsigned int)-1;
1006 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
1007 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
1008 if (index_table == NULL)
1011 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1012 if (ret != compr_img->index_len) {
1013 SysPrintf("failed to read index table\n");
1017 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1018 if (compr_img->index_table == NULL)
1021 for (i = 0; i < compr_img->index_len + 1; i++) {
1022 index = index_table[i];
1023 plain = index & 0x80000000;
1024 index &= 0x7fffffff;
1025 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1027 compr_img->index_table[i] |= OFF_T_MSB;
1035 if (compr_img != NULL) {
1042 static int handlechd(const char *isofile) {
1043 chd_img = calloc(1, sizeof(*chd_img));
1044 if (chd_img == NULL)
1047 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
1050 chd_img->header = chd_get_header(chd_img->chd);
1052 chd_img->buffer = malloc(chd_img->header->hunkbytes);
1053 if (chd_img->buffer == NULL)
1056 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1057 chd_img->current_hunk = (unsigned int)-1;
1059 cddaBigEndian = TRUE;
1062 int frame_offset = 150;
1063 memset(ti, 0, sizeof(ti));
1078 uint32_t meta_size = 0;
1080 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1081 sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1082 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1083 sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1087 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1089 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1090 sec2msf(md.frames - md.pregap, ti[md.track].length);
1092 if (!strcmp(md.type, md.pgtype))
1093 frame_offset += md.pregap;
1095 ti[md.track].start_offset = frame_offset * CD_FRAMESIZE_RAW;
1097 frame_offset += md.frames;
1098 frame_offset += md.postgap;
1106 if (chd_img != NULL) {
1107 free(chd_img->buffer);
1114 // this function tries to get the .sub file of the given .img
1115 static int opensubfile(const char *isoname) {
1116 char subname[MAXPATHLEN];
1118 // copy name of the iso and change extension from .img to .sub
1119 strncpy(subname, isoname, sizeof(subname));
1120 subname[MAXPATHLEN - 1] = '\0';
1121 if (strlen(subname) >= 4) {
1122 strcpy(subname + strlen(subname) - 4, ".sub");
1128 subHandle = fopen(subname, "rb");
1129 if (subHandle == NULL) {
1136 static int opensbifile(const char *isoname) {
1137 char sbiname[MAXPATHLEN];
1140 strncpy(sbiname, isoname, sizeof(sbiname));
1141 sbiname[MAXPATHLEN - 1] = '\0';
1142 if (strlen(sbiname) >= 4) {
1143 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1149 fseek(cdHandle, 0, SEEK_END);
1150 s = ftell(cdHandle) / 2352;
1152 return LoadSBI(sbiname, s);
1155 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1157 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1158 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1161 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1165 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1166 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1167 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1169 if (subChanRaw) DecodeRawSubData();
1174 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1179 if (z.zalloc == NULL) {
1180 // XXX: one-time leak here..
1186 ret = inflateInit2(&z, -15);
1189 ret = inflateReset(&z);
1194 z.avail_in = in_size;
1196 z.avail_out = *out_size;
1198 ret = inflate(&z, Z_NO_FLUSH);
1201 *out_size -= z.avail_out;
1202 return ret == 1 ? 0 : ret;
1205 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1207 unsigned long cdbuffer_size, cdbuffer_size_expect;
1214 sector += base / 2352;
1216 block = sector >> compr_img->block_shift;
1217 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1219 if (block == compr_img->current_block) {
1220 //printf("hit sect %d\n", sector);
1224 if (sector >= compr_img->index_len * 16) {
1225 SysPrintf("sector %d is past img end\n", sector);
1229 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1230 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1231 SysPrintf("seek error for block %d at %llx: ",
1232 block, (long long)start_byte);
1237 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1238 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1239 if (size > sizeof(compr_img->buff_compressed)) {
1240 SysPrintf("block %d is too large: %u\n", block, size);
1244 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1245 1, size, cdHandle) != size) {
1246 SysPrintf("read error for block %d at %x: ", block, start_byte);
1251 if (is_compressed) {
1252 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1253 cdbuffer_size = cdbuffer_size_expect;
1254 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1256 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1257 ret, block, sector);
1260 if (cdbuffer_size != cdbuffer_size_expect)
1261 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1262 cdbuffer_size_expect, sector);
1266 compr_img->current_block = block;
1269 if (dest != cdbuffer) // copy avoid HACK
1270 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1272 return CD_FRAMESIZE_RAW;
1275 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1280 sector += base / CD_FRAMESIZE_RAW;
1282 hunk = sector / chd_img->sectors_per_hunk;
1283 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1285 if (hunk == chd_img->current_hunk)
1288 chd_read(chd_img->chd, hunk, chd_img->buffer);
1290 chd_img->current_hunk = hunk;
1293 if (dest != cdbuffer) // copy avoid HACK
1294 memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
1296 return CD_FRAMESIZE_RAW;
1299 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1303 fseek(f, base + sector * 2048, SEEK_SET);
1304 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1306 // not really necessary, fake mode 2 header
1307 memset(cdbuffer, 0, 12 * 2);
1308 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1309 cdbuffer[12 + 3] = 1;
1314 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1315 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1318 static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
1319 return chd_img->buffer[chd_img->sector_in_hunk] + 12;
1322 static unsigned char * CALLBACK ISOgetBuffer(void) {
1323 return cdbuffer + 12;
1326 static void PrintTracks(void) {
1329 for (i = 1; i <= numtracks; i++) {
1330 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1331 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1332 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1333 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1337 // This function is invoked by the front-end when opening an ISO
1338 // file for playback
1339 static long CALLBACK ISOopen(void) {
1340 boolean isMode1ISO = FALSE;
1341 char alt_bin_filename[MAXPATHLEN];
1342 const char *bin_filename;
1344 if (cdHandle != NULL) {
1345 return 0; // it's already open
1348 cdHandle = fopen(GetIsoFile(), "rb");
1349 if (cdHandle == NULL) {
1350 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1351 GetIsoFile(), strerror(errno));
1355 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1357 cddaBigEndian = FALSE;
1358 subChanMixed = FALSE;
1361 cdrIsoMultidiskCount = 1;
1364 CDR_getBuffer = ISOgetBuffer;
1365 cdimg_read_func = cdread_normal;
1367 if (parsetoc(GetIsoFile()) == 0) {
1368 SysPrintf("[+toc]");
1370 else if (parseccd(GetIsoFile()) == 0) {
1371 SysPrintf("[+ccd]");
1373 else if (parsemds(GetIsoFile()) == 0) {
1374 SysPrintf("[+mds]");
1376 else if (parsecue(GetIsoFile()) == 0) {
1377 SysPrintf("[+cue]");
1379 if (handlepbp(GetIsoFile()) == 0) {
1381 CDR_getBuffer = ISOgetBuffer_compr;
1382 cdimg_read_func = cdread_compressed;
1384 else if (handlecbin(GetIsoFile()) == 0) {
1385 SysPrintf("[cbin]");
1386 CDR_getBuffer = ISOgetBuffer_compr;
1387 cdimg_read_func = cdread_compressed;
1389 else if (handlechd(GetIsoFile()) == 0) {
1391 CDR_getBuffer = ISOgetBuffer_chd;
1392 cdimg_read_func = cdread_chd;
1395 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1396 SysPrintf("[+sub]");
1398 if (opensbifile(GetIsoFile()) == 0) {
1399 SysPrintf("[+sbi]");
1402 fseeko(cdHandle, 0, SEEK_END);
1404 // maybe user selected metadata file instead of main .bin ..
1405 bin_filename = GetIsoFile();
1406 if (ftello(cdHandle) < 2352 * 0x10) {
1407 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1412 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1413 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1414 if (strlen(alt_bin_filename) >= 4) {
1415 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1416 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1418 tmpf = fopen(alt_bin_filename, "rb");
1424 bin_filename = alt_bin_filename;
1427 fseeko(cdHandle, 0, SEEK_END);
1431 // guess whether it is mode1/2048
1432 if (ftello(cdHandle) % 2048 == 0) {
1433 unsigned int modeTest = 0;
1434 fseek(cdHandle, 0, SEEK_SET);
1435 fread(&modeTest, 4, 1, cdHandle);
1436 if (SWAP32(modeTest) != 0xffffff00) {
1437 SysPrintf("[2048]");
1441 fseek(cdHandle, 0, SEEK_SET);
1448 cdimg_read_func = cdread_sub_mixed;
1449 else if (isMode1ISO)
1450 cdimg_read_func = cdread_2048;
1452 // make sure we have another handle open for cdda
1453 if (numtracks > 1 && ti[1].handle == NULL) {
1454 ti[1].handle = fopen(bin_filename, "rb");
1456 cdda_cur_sector = 0;
1457 cdda_file_offset = 0;
1462 static long CALLBACK ISOclose(void) {
1465 if (cdHandle != NULL) {
1469 if (subHandle != NULL) {
1476 if (compr_img != NULL) {
1477 free(compr_img->index_table);
1482 if (chd_img != NULL) {
1483 chd_close(chd_img->chd);
1484 free(chd_img->buffer);
1489 for (i = 1; i <= numtracks; i++) {
1490 if (ti[i].handle != NULL) {
1491 fclose(ti[i].handle);
1492 ti[i].handle = NULL;
1499 memset(cdbuffer, 0, sizeof(cdbuffer));
1500 CDR_getBuffer = ISOgetBuffer;
1505 static long CALLBACK ISOinit(void) {
1506 assert(cdHandle == NULL);
1507 assert(subHandle == NULL);
1509 return 0; // do nothing
1512 static long CALLBACK ISOshutdown(void) {
1517 // return Starting and Ending Track
1519 // byte 0 - start track
1520 // byte 1 - end track
1521 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1524 if (numtracks > 0) {
1525 buffer[1] = numtracks;
1534 // return Track Time
1539 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1542 unsigned char time[3];
1543 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1544 sec2msf(sect, (char *)time);
1545 buffer[2] = time[0];
1546 buffer[1] = time[1];
1547 buffer[0] = time[2];
1549 else if (numtracks > 0 && track <= numtracks) {
1550 buffer[2] = ti[track].start[0];
1551 buffer[1] = ti[track].start[1];
1552 buffer[0] = ti[track].start[2];
1563 // decode 'raw' subchannel data ripped by cdrdao
1564 static void DecodeRawSubData(void) {
1565 unsigned char subQData[12];
1568 memset(subQData, 0, sizeof(subQData));
1570 for (i = 0; i < 8 * 12; i++) {
1571 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1572 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1576 memcpy(&subbuffer[12], subQData, 12);
1580 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1582 static long CALLBACK ISOreadTrack(unsigned char *time) {
1583 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1586 if (cdHandle == NULL) {
1591 subChanMissing = FALSE;
1592 if (sector >= pregapOffset) {
1594 if (sector < pregapOffset)
1595 subChanMissing = TRUE;
1599 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1603 if (subHandle != NULL) {
1604 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1605 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1607 if (subChanRaw) DecodeRawSubData();
1614 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1615 // does NOT uses bcd format
1616 static long CALLBACK ISOplay(unsigned char *time) {
1623 cdda_cur_sector = msf2sec((char *)time);
1624 for (i = numtracks; i > 1; i--) {
1625 cdda_first_sector = msf2sec(ti[i].start);
1626 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1629 cdda_file_offset = ti[i].start_offset;
1631 // find the file that contains this track
1633 if (ti[i].handle != NULL)
1636 cddaHandle = ti[i].handle;
1638 if (SPU_playCDDAchannel != NULL)
1645 static long CALLBACK ISOstop(void) {
1650 // gets subchannel data
1651 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1652 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1659 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1662 CDR__getStatus(stat);
1666 stat->Status |= 0x80;
1669 // BIOS - boot ID (CD type)
1670 stat->Type = ti[1].type;
1673 // relative -> absolute time
1675 sec2msf(sect, (char *)stat->Time);
1680 // read CDDA sector into buffer
1681 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1682 unsigned char msf[3] = {m, s, f};
1683 unsigned int file, track, track_start = 0;
1686 cddaCurPos = msf2sec((char *)msf);
1688 // find current track index
1689 for (track = numtracks; ; track--) {
1690 track_start = msf2sec(ti[track].start);
1691 if (track_start <= cddaCurPos)
1697 // data tracks play silent
1698 if (ti[track].type != CDDA) {
1699 memset(buffer, 0, CD_FRAMESIZE_RAW);
1705 // find the file that contains this track
1706 for (file = track; file > 1; file--)
1707 if (ti[file].handle != NULL)
1711 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1712 buffer, cddaCurPos - track_start);
1713 if (ret != CD_FRAMESIZE_RAW) {
1714 memset(buffer, 0, CD_FRAMESIZE_RAW);
1718 if (cddaBigEndian) {
1722 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1723 tmp = buffer[i * 2];
1724 buffer[i * 2] = buffer[i * 2 + 1];
1725 buffer[i * 2 + 1] = tmp;
1732 void cdrIsoInit(void) {
1734 CDR_shutdown = ISOshutdown;
1736 CDR_close = ISOclose;
1737 CDR_getTN = ISOgetTN;
1738 CDR_getTD = ISOgetTD;
1739 CDR_readTrack = ISOreadTrack;
1740 CDR_getBuffer = ISOgetBuffer;
1743 CDR_getBufferSub = ISOgetBufferSub;
1744 CDR_getStatus = ISOgetStatus;
1745 CDR_readCDDA = ISOreadCDDA;
1747 CDR_getDriveLetter = CDR__getDriveLetter;
1748 CDR_configure = CDR__configure;
1749 CDR_test = CDR__test;
1750 CDR_about = CDR__about;
1751 CDR_setfilename = CDR__setfilename;
1756 int cdrIsoActive(void) {
1757 return (cdHandle != NULL);