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"
32 #define WIN32_LEAN_AND_MEAN
35 #define strcasecmp _stricmp
36 #define usleep(x) (Sleep((x) / 1000))
43 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
45 unsigned int cdrIsoMultidiskCount;
46 unsigned int cdrIsoMultidiskSelect;
48 static FILE *cdHandle = NULL;
49 static FILE *cddaHandle = NULL;
50 static FILE *subHandle = NULL;
52 static boolean subChanMixed = FALSE;
53 static boolean subChanRaw = FALSE;
54 static boolean subChanMissing = FALSE;
56 static boolean multifile = FALSE;
58 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
59 static unsigned char subbuffer[SUB_FRAMESIZE];
61 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
63 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
66 static HANDLE threadid;
68 static pthread_t threadid;
70 static unsigned int initial_offset = 0;
71 static boolean playing = FALSE;
72 static boolean cddaBigEndian = FALSE;
73 // cdda sectors in toc, byte offset in file
74 static unsigned int cdda_cur_sector;
75 static unsigned int cdda_first_sector;
76 static unsigned int cdda_file_offset;
77 /* Frame offset into CD image where pregap data would be found if it was there.
78 * If a game seeks there we must *not* return subchannel data since it's
79 * not in the CD image, so that cdrom code can fake subchannel data instead.
80 * XXX: there could be multiple pregaps but PSX dumps only have one? */
81 static unsigned int pregapOffset;
83 #define cddaCurPos cdda_cur_sector
85 // compressed image stuff
87 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
88 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
90 unsigned int index_len;
91 unsigned int block_shift;
92 unsigned int current_block;
93 unsigned int sector_in_blk;
96 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
98 char* CALLBACK CDR__getDriveLetter(void);
99 long CALLBACK CDR__configure(void);
100 long CALLBACK CDR__test(void);
101 void CALLBACK CDR__about(void);
102 long CALLBACK CDR__setfilename(char *filename);
103 long CALLBACK CDR__getStatus(struct CdrStat *stat);
105 static void DecodeRawSubData(void);
108 enum {DATA=1, CDDA} type;
109 char start[3]; // MSF-format
110 char length[3]; // MSF-format
111 FILE *handle; // for multi-track images CDDA
112 unsigned int start_offset; // byte offset from start of above file
115 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
117 static int numtracks = 0;
118 static struct trackinfo ti[MAXTRACKS];
120 // get a sector from a msf-array
121 static unsigned int msf2sec(char *msf) {
122 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
125 static void sec2msf(unsigned int s, char *msf) {
126 msf[0] = s / 75 / 60;
127 s = s - msf[0] * 75 * 60;
133 // divide a string of xx:yy:zz into m, s, f
134 static void tok2msf(char *time, char *msf) {
137 token = strtok(time, ":");
139 msf[0] = atoi(token);
145 token = strtok(NULL, ":");
147 msf[1] = atoi(token);
153 token = strtok(NULL, ":");
155 msf[2] = atoi(token);
163 static long GetTickCount(void) {
164 static time_t initial_time = 0;
167 gettimeofday(&now, NULL);
169 if (initial_time == 0) {
170 initial_time = now.tv_sec;
173 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
177 // this thread plays audio data
179 static void playthread(void *param)
181 static void *playthread(void *param)
184 long osleep, d, t, i, s;
186 int ret = 0, sector_offs;
192 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
193 sector_offs = cdda_cur_sector - cdda_first_sector;
194 if (sector_offs < 0) {
195 d = CD_FRAMESIZE_RAW;
196 memset(sndbuffer + s, 0, d);
199 d = cdimg_read_func(cddaHandle, cdda_file_offset,
200 sndbuffer + s, sector_offs);
201 if (d < CD_FRAMESIZE_RAW)
215 if (!cdr.Muted && playing) {
217 for (i = 0; i < s / 2; i++) {
218 tmp = sndbuffer[i * 2];
219 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
220 sndbuffer[i * 2 + 1] = tmp;
224 // can't do it yet due to readahead..
225 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
227 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
232 } while (ret == 0x7761 && playing); // rearmed_wait
235 if (ret != 0x676f) { // !rearmed_go
239 // HACK: stop feeding data while emu is paused
241 while (stop && playing)
246 now = GetTickCount();
252 else if (osleep > CDDA_FRAMETIME) {
253 osleep = CDDA_FRAMETIME;
257 usleep(osleep * 1000);
271 // stop the CDDA playback
272 static void stopCDDA() {
279 WaitForSingleObject(threadid, INFINITE);
281 pthread_join(threadid, NULL);
285 // start the CDDA playback
286 static void startCDDA(void) {
294 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
296 pthread_create(&threadid, NULL, playthread, NULL);
300 // this function tries to get the .toc file of the given .bin
301 // the necessary data is put into the ti (trackinformation)-array
302 static int parsetoc(const char *isofile) {
303 char tocname[MAXPATHLEN];
305 char linebuf[256], tmp[256], name[256];
307 char time[20], time2[20];
308 unsigned int t, sector_offs, sector_size;
309 unsigned int current_zero_gap = 0;
313 // copy name of the iso and change extension from .bin to .toc
314 strncpy(tocname, isofile, sizeof(tocname));
315 tocname[MAXPATHLEN - 1] = '\0';
316 if (strlen(tocname) >= 4) {
317 strcpy(tocname + strlen(tocname) - 4, ".toc");
323 if ((fi = fopen(tocname, "r")) == NULL) {
324 // try changing extension to .cue (to satisfy some stupid tutorials)
325 strcpy(tocname + strlen(tocname) - 4, ".cue");
326 if ((fi = fopen(tocname, "r")) == NULL) {
327 // if filename is image.toc.bin, try removing .bin (for Brasero)
328 strcpy(tocname, isofile);
330 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
331 tocname[t - 4] = '\0';
332 if ((fi = fopen(tocname, "r")) == NULL) {
340 // check if it's really a TOC named as a .cue
341 fgets(linebuf, sizeof(linebuf), fi);
342 token = strtok(linebuf, " ");
343 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
347 fseek(fi, 0, SEEK_SET);
350 memset(&ti, 0, sizeof(ti));
351 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
353 sector_size = CD_FRAMESIZE_RAW;
354 sector_offs = 2 * 75;
356 // parse the .toc file
357 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
359 strncpy(tmp, linebuf, sizeof(linebuf));
360 token = strtok(tmp, " ");
362 if (token == NULL) continue;
364 if (!strcmp(token, "TRACK")) {
365 sector_offs += current_zero_gap;
366 current_zero_gap = 0;
369 token = strtok(NULL, " ");
372 if (!strncmp(token, "MODE2_RAW", 9)) {
373 ti[numtracks].type = DATA;
374 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
376 // check if this image contains mixed subchannel data
377 token = strtok(NULL, " ");
378 if (token != NULL && !strncmp(token, "RW", 2)) {
379 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
381 if (!strncmp(token, "RW_RAW", 6))
385 else if (!strncmp(token, "AUDIO", 5)) {
386 ti[numtracks].type = CDDA;
389 else if (!strcmp(token, "DATAFILE")) {
390 if (ti[numtracks].type == CDDA) {
391 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
392 ti[numtracks].start_offset = t;
393 t = t / sector_size + sector_offs;
394 sec2msf(t, (char *)&ti[numtracks].start);
395 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
398 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
399 tok2msf((char *)&time, (char *)&ti[numtracks].length);
402 else if (!strcmp(token, "FILE")) {
403 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
404 tok2msf((char *)&time, (char *)&ti[numtracks].start);
405 t += msf2sec(ti[numtracks].start) * sector_size;
406 ti[numtracks].start_offset = t;
407 t = t / sector_size + sector_offs;
408 sec2msf(t, (char *)&ti[numtracks].start);
409 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
411 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
412 // skip unneeded optional fields
413 while (token != NULL) {
414 token = strtok(NULL, " ");
415 if (strchr(token, ':') != NULL)
420 current_zero_gap = msf2sec(tmp);
423 t = ti[numtracks - 1].start_offset;
425 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
428 else if (!strcmp(token, "START")) {
429 token = strtok(NULL, " ");
430 if (token != NULL && strchr(token, ':')) {
433 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
434 t = msf2sec(ti[numtracks].start) + t;
435 sec2msf(t, (char *)&ti[numtracks].start);
445 // this function tries to get the .cue file of the given .bin
446 // the necessary data is put into the ti (trackinformation)-array
447 static int parsecue(const char *isofile) {
448 char cuename[MAXPATHLEN];
449 char filepath[MAXPATHLEN];
455 char linebuf[256], tmpb[256], dummy[256];
456 unsigned int incue_max_len;
457 unsigned int t, file_len, mode, sector_offs;
458 unsigned int sector_size = 2352;
462 // copy name of the iso and change extension from .bin to .cue
463 strncpy(cuename, isofile, sizeof(cuename));
464 cuename[MAXPATHLEN - 1] = '\0';
465 if (strlen(cuename) >= 4) {
466 strcpy(cuename + strlen(cuename) - 4, ".cue");
472 if ((fi = fopen(cuename, "r")) == NULL) {
476 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
477 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
479 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
480 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
481 // Don't proceed further, as this is actually a .toc file rather
484 return parsetoc(isofile);
486 fseek(fi, 0, SEEK_SET);
489 // build a path for files referenced in .cue
490 strncpy(filepath, cuename, sizeof(filepath));
491 tmp = strrchr(filepath, '/');
493 tmp = strrchr(filepath, '\\');
499 filepath[sizeof(filepath) - 1] = 0;
501 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
503 memset(&ti, 0, sizeof(ti));
506 sector_offs = 2 * 75;
508 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
509 strncpy(dummy, linebuf, sizeof(linebuf));
510 token = strtok(dummy, " ");
516 if (!strcmp(token, "TRACK")) {
520 if (strstr(linebuf, "AUDIO") != NULL) {
521 ti[numtracks].type = CDDA;
524 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
525 ti[numtracks].type = DATA;
527 SysPrintf(".cue: failed to parse TRACK\n");
528 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
530 if (sector_size == 0)
533 else if (!strcmp(token, "INDEX")) {
534 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
535 SysPrintf(".cue: failed to parse INDEX\n");
536 tok2msf(time, (char *)&ti[numtracks].start);
538 t = msf2sec(ti[numtracks].start);
539 ti[numtracks].start_offset = t * sector_size;
541 sec2msf(t, ti[numtracks].start);
543 // default track length to file length
544 t = file_len - ti[numtracks].start_offset / sector_size;
545 sec2msf(t, ti[numtracks].length);
547 if (numtracks > 1 && ti[numtracks].handle == NULL) {
548 // this track uses the same file as the last,
549 // start of this track is last track's end
550 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
551 sec2msf(t, ti[numtracks - 1].length);
553 if (numtracks > 1 && pregapOffset == -1)
554 pregapOffset = ti[numtracks].start_offset / sector_size;
556 else if (!strcmp(token, "PREGAP")) {
557 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
558 tok2msf(time, dummy);
559 sector_offs += msf2sec(dummy);
561 pregapOffset = -1; // mark to fill track start_offset
563 else if (!strcmp(token, "FILE")) {
564 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
566 sscanf(linebuf, " FILE %255s", tmpb);
568 tmp = strrchr(tmpb, '\\');
570 tmp = strrchr(tmpb, '/');
575 strncpy(incue_fname, tmp, incue_max_len);
576 ti[numtracks + 1].handle = fopen(filepath, "rb");
578 // update global offset if this is not first file in this .cue
579 if (numtracks + 1 > 1) {
581 sector_offs += file_len;
585 if (ti[numtracks + 1].handle == NULL) {
586 SysPrintf(_("\ncould not open: %s\n"), filepath);
589 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
590 file_len = ftell(ti[numtracks + 1].handle) / 2352;
592 if (numtracks == 0 && strlen(isofile) >= 4 &&
593 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
595 // user selected .cue as image file, use it's data track instead
597 cdHandle = fopen(filepath, "rb");
607 // this function tries to get the .ccd file of the given .img
608 // the necessary data is put into the ti (trackinformation)-array
609 static int parseccd(const char *isofile) {
610 char ccdname[MAXPATHLEN];
617 // copy name of the iso and change extension from .img to .ccd
618 strncpy(ccdname, isofile, sizeof(ccdname));
619 ccdname[MAXPATHLEN - 1] = '\0';
620 if (strlen(ccdname) >= 4) {
621 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
627 if ((fi = fopen(ccdname, "r")) == NULL) {
631 memset(&ti, 0, sizeof(ti));
633 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
634 if (!strncmp(linebuf, "[TRACK", 6)){
637 else if (!strncmp(linebuf, "MODE=", 5)) {
638 sscanf(linebuf, "MODE=%d", &t);
639 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
641 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
642 sscanf(linebuf, "INDEX 1=%d", &t);
643 sec2msf(t + 2 * 75, ti[numtracks].start);
644 ti[numtracks].start_offset = t * 2352;
646 // If we've already seen another track, this is its end
648 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
649 sec2msf(t, ti[numtracks - 1].length);
656 // Fill out the last track's end based on size
657 if (numtracks >= 1) {
658 fseek(cdHandle, 0, SEEK_END);
659 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
660 sec2msf(t, ti[numtracks].length);
666 // this function tries to get the .mds file of the given .mdf
667 // the necessary data is put into the ti (trackinformation)-array
668 static int parsemds(const char *isofile) {
669 char mdsname[MAXPATHLEN];
671 unsigned int offset, extra_offset, l, i;
676 // copy name of the iso and change extension from .mdf to .mds
677 strncpy(mdsname, isofile, sizeof(mdsname));
678 mdsname[MAXPATHLEN - 1] = '\0';
679 if (strlen(mdsname) >= 4) {
680 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
686 if ((fi = fopen(mdsname, "rb")) == NULL) {
690 memset(&ti, 0, sizeof(ti));
692 // check if it's a valid mds file
693 fread(&i, 1, sizeof(unsigned int), fi);
695 if (i != 0x4944454D) {
696 // not an valid mds file
701 // get offset to session block
702 fseek(fi, 0x50, SEEK_SET);
703 fread(&offset, 1, sizeof(unsigned int), fi);
704 offset = SWAP32(offset);
706 // get total number of tracks
708 fseek(fi, offset, SEEK_SET);
709 fread(&s, 1, sizeof(unsigned short), fi);
713 // get offset to track blocks
714 fseek(fi, 4, SEEK_CUR);
715 fread(&offset, 1, sizeof(unsigned int), fi);
716 offset = SWAP32(offset);
720 fseek(fi, offset + 4, SEEK_SET);
721 if (fgetc(fi) < 0xA0) {
727 // check if the image contains mixed subchannel data
728 fseek(fi, offset + 1, SEEK_SET);
729 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
732 for (i = 1; i <= numtracks; i++) {
733 fseek(fi, offset, SEEK_SET);
735 // get the track type
736 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
737 fseek(fi, 8, SEEK_CUR);
739 // get the track starting point
740 ti[i].start[0] = fgetc(fi);
741 ti[i].start[1] = fgetc(fi);
742 ti[i].start[2] = fgetc(fi);
744 fread(&extra_offset, 1, sizeof(unsigned int), fi);
745 extra_offset = SWAP32(extra_offset);
747 // get track start offset (in .mdf)
748 fseek(fi, offset + 0x28, SEEK_SET);
749 fread(&l, 1, sizeof(unsigned int), fi);
751 ti[i].start_offset = l;
754 fseek(fi, extra_offset, SEEK_SET);
755 fread(&l, 1, sizeof(unsigned int), fi);
758 pregapOffset = msf2sec(ti[i].start);
760 // get the track length
761 fread(&l, 1, sizeof(unsigned int), fi);
763 sec2msf(l, ti[i].length);
772 static int handlepbp(const char *isofile) {
775 unsigned int dontcare[8];
776 unsigned int psar_offs;
789 unsigned int dontcare[6];
792 off_t psisoimg_offs, cdimg_base;
793 unsigned int t, cd_length;
794 unsigned int offsettab[8];
795 const char *ext = NULL;
798 if (strlen(isofile) >= 4)
799 ext = isofile + strlen(isofile) - 4;
800 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
803 fseeko(cdHandle, 0, SEEK_SET);
807 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
808 if (ret != sizeof(pbp_hdr)) {
809 SysPrintf("failed to read pbp\n");
813 ret = fseeko(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
815 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
819 psisoimg_offs = pbp_hdr.psar_offs;
820 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
822 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
824 ret = fseeko(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
826 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
830 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
831 SysPrintf("failed to read offsettab\n");
835 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
836 if (offsettab[i] == 0)
839 cdrIsoMultidiskCount = i;
840 if (cdrIsoMultidiskCount == 0) {
841 SysPrintf("multidisk eboot has 0 images?\n");
845 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
846 cdrIsoMultidiskSelect = 0;
848 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
850 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
852 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
856 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
860 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
861 SysPrintf("bad psar_sig: %s\n", psar_sig);
866 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
868 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
872 // first 3 entries are special
873 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
874 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
875 numtracks = btoi(toc_entry.index1[0]);
877 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
878 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
879 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
881 for (i = 1; i <= numtracks; i++) {
882 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
884 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
886 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
887 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
888 ti[i].start_offset *= 2352;
889 ti[i].start[0] = btoi(toc_entry.index1[0]);
890 ti[i].start[1] = btoi(toc_entry.index1[1]);
891 ti[i].start[2] = btoi(toc_entry.index1[2]);
894 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
895 sec2msf(t, ti[i - 1].length);
898 t = cd_length - ti[numtracks].start_offset / 2352;
899 sec2msf(t, ti[numtracks].length);
902 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
904 SysPrintf("failed to seek to ISO index\n");
908 compr_img = calloc(1, sizeof(*compr_img));
909 if (compr_img == NULL)
912 compr_img->block_shift = 4;
913 compr_img->current_block = (unsigned int)-1;
915 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
916 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
917 if (compr_img->index_table == NULL)
920 cdimg_base = psisoimg_offs + 0x100000;
921 for (i = 0; i < compr_img->index_len; i++) {
922 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
923 if (ret != sizeof(index_entry)) {
924 SysPrintf("failed to read index_entry #%d\n", i);
928 if (index_entry.size == 0)
931 compr_img->index_table[i] = cdimg_base + index_entry.offset;
933 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
938 free(compr_img->index_table);
939 compr_img->index_table = NULL;
941 if (compr_img != NULL) {
948 static int handlecbin(const char *isofile) {
952 unsigned int header_size;
953 unsigned long long total_bytes;
954 unsigned int block_size;
955 unsigned char ver; // 1
957 unsigned char rsv_06[2];
959 const char *ext = NULL;
960 unsigned int *index_table = 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 = fseeko(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 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
998 if (index_table == NULL)
1001 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
1002 if (ret != compr_img->index_len) {
1003 SysPrintf("failed to read index table\n");
1007 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
1008 if (compr_img->index_table == NULL)
1011 for (i = 0; i < compr_img->index_len + 1; i++) {
1012 index = index_table[i];
1013 plain = index & 0x80000000;
1014 index &= 0x7fffffff;
1015 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
1017 compr_img->index_table[i] |= OFF_T_MSB;
1025 if (compr_img != NULL) {
1032 // this function tries to get the .sub file of the given .img
1033 static int opensubfile(const char *isoname) {
1034 char subname[MAXPATHLEN];
1036 // copy name of the iso and change extension from .img to .sub
1037 strncpy(subname, isoname, sizeof(subname));
1038 subname[MAXPATHLEN - 1] = '\0';
1039 if (strlen(subname) >= 4) {
1040 strcpy(subname + strlen(subname) - 4, ".sub");
1046 subHandle = fopen(subname, "rb");
1047 if (subHandle == NULL) {
1054 static int opensbifile(const char *isoname) {
1055 char sbiname[MAXPATHLEN];
1058 strncpy(sbiname, isoname, sizeof(sbiname));
1059 sbiname[MAXPATHLEN - 1] = '\0';
1060 if (strlen(sbiname) >= 4) {
1061 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1067 fseek(cdHandle, 0, SEEK_END);
1068 s = ftell(cdHandle) / 2352;
1070 return LoadSBI(sbiname, s);
1073 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1075 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1076 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1079 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1083 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1084 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1085 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1087 if (subChanRaw) DecodeRawSubData();
1092 static int uncomp2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1097 if (z.zalloc == NULL) {
1098 // XXX: one-time leak here..
1104 ret = inflateInit2(&z, -15);
1107 ret = inflateReset(&z);
1112 z.avail_in = in_size;
1114 z.avail_out = *out_size;
1116 ret = inflate(&z, Z_NO_FLUSH);
1119 *out_size -= z.avail_out;
1120 return ret == 1 ? 0 : ret;
1123 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1125 unsigned long cdbuffer_size, cdbuffer_size_expect;
1132 sector += base / 2352;
1134 block = sector >> compr_img->block_shift;
1135 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1137 if (block == compr_img->current_block) {
1138 //printf("hit sect %d\n", sector);
1142 if (sector >= compr_img->index_len * 16) {
1143 SysPrintf("sector %d is past img end\n", sector);
1147 start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1148 if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1149 SysPrintf("seek error for block %d at %llx: ",
1150 block, (long long)start_byte);
1155 is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1156 size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1157 if (size > sizeof(compr_img->buff_compressed)) {
1158 SysPrintf("block %d is too large: %u\n", block, size);
1162 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1163 1, size, cdHandle) != size) {
1164 SysPrintf("read error for block %d at %x: ", block, start_byte);
1169 if (is_compressed) {
1170 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1171 cdbuffer_size = cdbuffer_size_expect;
1172 ret = uncomp2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1174 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1175 ret, block, sector);
1178 if (cdbuffer_size != cdbuffer_size_expect)
1179 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1180 cdbuffer_size_expect, sector);
1184 compr_img->current_block = block;
1187 if (dest != cdbuffer) // copy avoid HACK
1188 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1190 return CD_FRAMESIZE_RAW;
1193 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1197 fseek(f, base + sector * 2048, SEEK_SET);
1198 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1200 // not really necessary, fake mode 2 header
1201 memset(cdbuffer, 0, 12 * 2);
1202 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1203 cdbuffer[12 + 3] = 1;
1208 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1209 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1212 static unsigned char * CALLBACK ISOgetBuffer(void) {
1213 return cdbuffer + 12;
1216 static void PrintTracks(void) {
1219 for (i = 1; i <= numtracks; i++) {
1220 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1221 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1222 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1223 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1227 // This function is invoked by the front-end when opening an ISO
1228 // file for playback
1229 static long CALLBACK ISOopen(void) {
1230 boolean isMode1ISO = FALSE;
1231 char alt_bin_filename[MAXPATHLEN];
1232 const char *bin_filename;
1234 if (cdHandle != NULL) {
1235 return 0; // it's already open
1238 cdHandle = fopen(GetIsoFile(), "rb");
1239 if (cdHandle == NULL) {
1240 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1241 GetIsoFile(), strerror(errno));
1245 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1247 cddaBigEndian = FALSE;
1248 subChanMixed = FALSE;
1251 cdrIsoMultidiskCount = 1;
1254 CDR_getBuffer = ISOgetBuffer;
1255 cdimg_read_func = cdread_normal;
1257 if (parsetoc(GetIsoFile()) == 0) {
1258 SysPrintf("[+toc]");
1260 else if (parseccd(GetIsoFile()) == 0) {
1261 SysPrintf("[+ccd]");
1263 else if (parsemds(GetIsoFile()) == 0) {
1264 SysPrintf("[+mds]");
1266 else if (parsecue(GetIsoFile()) == 0) {
1267 SysPrintf("[+cue]");
1269 if (handlepbp(GetIsoFile()) == 0) {
1271 CDR_getBuffer = ISOgetBuffer_compr;
1272 cdimg_read_func = cdread_compressed;
1274 else if (handlecbin(GetIsoFile()) == 0) {
1275 SysPrintf("[cbin]");
1276 CDR_getBuffer = ISOgetBuffer_compr;
1277 cdimg_read_func = cdread_compressed;
1280 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1281 SysPrintf("[+sub]");
1283 if (opensbifile(GetIsoFile()) == 0) {
1284 SysPrintf("[+sbi]");
1287 fseeko(cdHandle, 0, SEEK_END);
1289 // maybe user selected metadata file instead of main .bin ..
1290 bin_filename = GetIsoFile();
1291 if (ftello(cdHandle) < 2352 * 0x10) {
1292 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1297 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1298 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1299 if (strlen(alt_bin_filename) >= 4) {
1300 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1301 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1303 tmpf = fopen(alt_bin_filename, "rb");
1309 bin_filename = alt_bin_filename;
1312 fseeko(cdHandle, 0, SEEK_END);
1316 // guess whether it is mode1/2048
1317 if (ftello(cdHandle) % 2048 == 0) {
1318 unsigned int modeTest = 0;
1319 fseek(cdHandle, 0, SEEK_SET);
1320 fread(&modeTest, 4, 1, cdHandle);
1321 if (SWAP32(modeTest) != 0xffffff00) {
1322 SysPrintf("[2048]");
1326 fseek(cdHandle, 0, SEEK_SET);
1333 cdimg_read_func = cdread_sub_mixed;
1334 else if (isMode1ISO)
1335 cdimg_read_func = cdread_2048;
1337 // make sure we have another handle open for cdda
1338 if (numtracks > 1 && ti[1].handle == NULL) {
1339 ti[1].handle = fopen(bin_filename, "rb");
1341 cdda_cur_sector = 0;
1342 cdda_file_offset = 0;
1347 static long CALLBACK ISOclose(void) {
1350 if (cdHandle != NULL) {
1354 if (subHandle != NULL) {
1361 if (compr_img != NULL) {
1362 free(compr_img->index_table);
1367 for (i = 1; i <= numtracks; i++) {
1368 if (ti[i].handle != NULL) {
1369 fclose(ti[i].handle);
1370 ti[i].handle = NULL;
1377 memset(cdbuffer, 0, sizeof(cdbuffer));
1378 CDR_getBuffer = ISOgetBuffer;
1383 static long CALLBACK ISOinit(void) {
1384 assert(cdHandle == NULL);
1385 assert(subHandle == NULL);
1387 return 0; // do nothing
1390 static long CALLBACK ISOshutdown(void) {
1395 // return Starting and Ending Track
1397 // byte 0 - start track
1398 // byte 1 - end track
1399 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1402 if (numtracks > 0) {
1403 buffer[1] = numtracks;
1412 // return Track Time
1417 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1420 unsigned char time[3];
1421 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1422 sec2msf(sect, (char *)time);
1423 buffer[2] = time[0];
1424 buffer[1] = time[1];
1425 buffer[0] = time[2];
1427 else if (numtracks > 0 && track <= numtracks) {
1428 buffer[2] = ti[track].start[0];
1429 buffer[1] = ti[track].start[1];
1430 buffer[0] = ti[track].start[2];
1441 // decode 'raw' subchannel data ripped by cdrdao
1442 static void DecodeRawSubData(void) {
1443 unsigned char subQData[12];
1446 memset(subQData, 0, sizeof(subQData));
1448 for (i = 0; i < 8 * 12; i++) {
1449 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1450 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1454 memcpy(&subbuffer[12], subQData, 12);
1458 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1460 static long CALLBACK ISOreadTrack(unsigned char *time) {
1461 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1464 if (cdHandle == NULL) {
1469 subChanMissing = FALSE;
1470 if (sector >= pregapOffset) {
1472 if (sector < pregapOffset)
1473 subChanMissing = TRUE;
1477 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1481 if (subHandle != NULL) {
1482 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1483 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1485 if (subChanRaw) DecodeRawSubData();
1492 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1493 // does NOT uses bcd format
1494 static long CALLBACK ISOplay(unsigned char *time) {
1501 cdda_cur_sector = msf2sec((char *)time);
1502 for (i = numtracks; i > 1; i--) {
1503 cdda_first_sector = msf2sec(ti[i].start);
1504 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1507 cdda_file_offset = ti[i].start_offset;
1509 // find the file that contains this track
1511 if (ti[i].handle != NULL)
1514 cddaHandle = ti[i].handle;
1516 if (SPU_playCDDAchannel != NULL)
1523 static long CALLBACK ISOstop(void) {
1528 // gets subchannel data
1529 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1530 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1537 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1540 CDR__getStatus(stat);
1544 stat->Status |= 0x80;
1547 // BIOS - boot ID (CD type)
1548 stat->Type = ti[1].type;
1551 // relative -> absolute time
1553 sec2msf(sect, (char *)stat->Time);
1558 // read CDDA sector into buffer
1559 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1560 unsigned char msf[3] = {m, s, f};
1561 unsigned int file, track, track_start = 0;
1564 cddaCurPos = msf2sec((char *)msf);
1566 // find current track index
1567 for (track = numtracks; ; track--) {
1568 track_start = msf2sec(ti[track].start);
1569 if (track_start <= cddaCurPos)
1575 // data tracks play silent
1576 if (ti[track].type != CDDA) {
1577 memset(buffer, 0, CD_FRAMESIZE_RAW);
1583 // find the file that contains this track
1584 for (file = track; file > 1; file--)
1585 if (ti[file].handle != NULL)
1589 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1590 buffer, cddaCurPos - track_start);
1591 if (ret != CD_FRAMESIZE_RAW) {
1592 memset(buffer, 0, CD_FRAMESIZE_RAW);
1596 if (cddaBigEndian) {
1600 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1601 tmp = buffer[i * 2];
1602 buffer[i * 2] = buffer[i * 2 + 1];
1603 buffer[i * 2 + 1] = tmp;
1610 void cdrIsoInit(void) {
1612 CDR_shutdown = ISOshutdown;
1614 CDR_close = ISOclose;
1615 CDR_getTN = ISOgetTN;
1616 CDR_getTD = ISOgetTD;
1617 CDR_readTrack = ISOreadTrack;
1618 CDR_getBuffer = ISOgetBuffer;
1621 CDR_getBufferSub = ISOgetBufferSub;
1622 CDR_getStatus = ISOgetStatus;
1623 CDR_readCDDA = ISOreadCDDA;
1625 CDR_getDriveLetter = CDR__getDriveLetter;
1626 CDR_configure = CDR__configure;
1627 CDR_test = CDR__test;
1628 CDR_about = CDR__about;
1629 CDR_setfilename = CDR__setfilename;
1634 int cdrIsoActive(void) {
1635 return (cdHandle != NULL);