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 02111-1307 USA. *
20 ***************************************************************************/
22 #include "psxcommon.h"
38 unsigned int cdrIsoMultidiskCount;
39 unsigned int cdrIsoMultidiskSelect;
41 static FILE *cdHandle = NULL;
42 static FILE *cddaHandle = NULL;
43 static FILE *subHandle = NULL;
45 static boolean subChanMixed = FALSE;
46 static boolean subChanRaw = FALSE;
47 static boolean subChanMissing = FALSE;
49 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
50 static unsigned char subbuffer[SUB_FRAMESIZE];
52 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
54 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
57 static HANDLE threadid;
59 static pthread_t threadid;
61 static unsigned int initial_offset = 0;
62 static boolean playing = FALSE;
63 static boolean cddaBigEndian = FALSE;
64 // cdda sectors in toc, byte offset in file
65 static unsigned int cdda_cur_sector;
66 static unsigned int cdda_first_sector;
67 static unsigned int cdda_file_offset;
68 /* Frame offset into CD image where pregap data would be found if it was there.
69 * If a game seeks there we must *not* return subchannel data since it's
70 * not in the CD image, so that cdrom code can fake subchannel data instead.
71 * XXX: there could be multiple pregaps but PSX dumps only have one? */
72 static unsigned int pregapOffset;
74 // compressed image stuff
76 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
77 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
78 unsigned int *index_table;
79 unsigned int index_len;
80 unsigned int block_shift;
81 unsigned int current_block;
82 unsigned int sector_in_blk;
85 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
87 char* CALLBACK CDR__getDriveLetter(void);
88 long CALLBACK CDR__configure(void);
89 long CALLBACK CDR__test(void);
90 void CALLBACK CDR__about(void);
91 long CALLBACK CDR__setfilename(char *filename);
92 long CALLBACK CDR__getStatus(struct CdrStat *stat);
94 static void DecodeRawSubData(void);
96 extern void *hCDRDriver;
99 enum {DATA, CDDA} type;
100 char start[3]; // MSF-format
101 char length[3]; // MSF-format
102 FILE *handle; // for multi-track images CDDA
103 unsigned int start_offset; // byte offset from start of above file
106 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
108 static int numtracks = 0;
109 static struct trackinfo ti[MAXTRACKS];
111 // get a sector from a msf-array
112 static unsigned int msf2sec(char *msf) {
113 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
116 static void sec2msf(unsigned int s, char *msf) {
117 msf[0] = s / 75 / 60;
118 s = s - msf[0] * 75 * 60;
124 // divide a string of xx:yy:zz into m, s, f
125 static void tok2msf(char *time, char *msf) {
128 token = strtok(time, ":");
130 msf[0] = atoi(token);
136 token = strtok(NULL, ":");
138 msf[1] = atoi(token);
144 token = strtok(NULL, ":");
146 msf[2] = atoi(token);
154 static long GetTickCount(void) {
155 static time_t initial_time = 0;
158 gettimeofday(&now, NULL);
160 if (initial_time == 0) {
161 initial_time = now.tv_sec;
164 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
168 // this thread plays audio data
170 static void playthread(void *param)
172 static void *playthread(void *param)
175 long osleep, d, t, i, s;
177 int ret = 0, sector_offs;
183 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
184 sector_offs = cdda_cur_sector - cdda_first_sector;
185 if (sector_offs < 0) {
186 d = CD_FRAMESIZE_RAW;
187 memset(sndbuffer + s, 0, d);
190 d = cdimg_read_func(cddaHandle, cdda_file_offset,
191 sndbuffer + s, sector_offs);
192 if (d < CD_FRAMESIZE_RAW)
206 if (!cdr.Muted && playing) {
208 for (i = 0; i < s / 2; i++) {
209 tmp = sndbuffer[i * 2];
210 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
211 sndbuffer[i * 2 + 1] = tmp;
215 // can't do it yet due to readahead..
216 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
218 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
221 } while (ret == 0x7761 && playing); // rearmed_wait
224 if (ret != 0x676f) { // !rearmed_go
228 // HACK: stop feeding data while emu is paused
230 while (stop && playing)
233 now = GetTickCount();
239 else if (osleep > CDDA_FRAMETIME) {
240 osleep = CDDA_FRAMETIME;
244 usleep(osleep * 1000);
258 // stop the CDDA playback
259 static void stopCDDA() {
266 WaitForSingleObject(threadid, INFINITE);
268 pthread_join(threadid, NULL);
272 // start the CDDA playback
273 static void startCDDA(void) {
281 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
283 pthread_create(&threadid, NULL, playthread, NULL);
287 // this function tries to get the .toc file of the given .bin
288 // the necessary data is put into the ti (trackinformation)-array
289 static int parsetoc(const char *isofile) {
290 char tocname[MAXPATHLEN];
292 char linebuf[256], dummy[256], name[256];
294 char time[20], time2[20];
295 unsigned int t, sector_offs;
299 // copy name of the iso and change extension from .bin to .toc
300 strncpy(tocname, isofile, sizeof(tocname));
301 tocname[MAXPATHLEN - 1] = '\0';
302 if (strlen(tocname) >= 4) {
303 strcpy(tocname + strlen(tocname) - 4, ".toc");
309 if ((fi = fopen(tocname, "r")) == NULL) {
310 // try changing extension to .cue (to satisfy some stupid tutorials)
311 strcpy(tocname + strlen(tocname) - 4, ".cue");
312 if ((fi = fopen(tocname, "r")) == NULL) {
313 // if filename is image.toc.bin, try removing .bin (for Brasero)
314 strcpy(tocname, isofile);
316 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
317 tocname[t - 4] = '\0';
318 if ((fi = fopen(tocname, "r")) == NULL) {
328 memset(&ti, 0, sizeof(ti));
329 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
331 sector_offs = 2 * 75;
333 // parse the .toc file
334 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
336 strncpy(dummy, linebuf, sizeof(linebuf));
337 token = strtok(dummy, " ");
339 if (token == NULL) continue;
341 if (!strcmp(token, "TRACK")) {
343 token = strtok(NULL, " ");
346 if (!strncmp(token, "MODE2_RAW", 9)) {
347 ti[numtracks].type = DATA;
348 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
350 // check if this image contains mixed subchannel data
351 token = strtok(NULL, " ");
352 if (token != NULL && !strncmp(token, "RW_RAW", 6)) {
357 else if (!strncmp(token, "AUDIO", 5)) {
358 ti[numtracks].type = CDDA;
361 else if (!strcmp(token, "DATAFILE")) {
362 if (ti[numtracks].type == CDDA) {
363 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
364 ti[numtracks].start_offset = t;
365 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
367 sec2msf(t, (char *)&ti[numtracks].start);
368 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
371 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
372 tok2msf((char *)&time, (char *)&ti[numtracks].length);
375 else if (!strcmp(token, "FILE")) {
376 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
377 tok2msf((char *)&time, (char *)&ti[numtracks].start);
378 ti[numtracks].start_offset = t;
379 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
380 t += msf2sec(ti[numtracks].start) + sector_offs;
381 sec2msf(t, (char *)&ti[numtracks].start);
382 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
384 else if (!strcmp(token, "ZERO")) {
385 sscanf(linebuf, "ZERO AUDIO RW_RAW %8s", time);
386 tok2msf((char *)&time, dummy);
387 sector_offs += msf2sec(dummy);
389 t = ti[numtracks - 1].start_offset;
390 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
391 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
401 // this function tries to get the .cue file of the given .bin
402 // the necessary data is put into the ti (trackinformation)-array
403 static int parsecue(const char *isofile) {
404 char cuename[MAXPATHLEN];
405 char filepath[MAXPATHLEN];
411 char linebuf[256], tmpb[256], dummy[256];
412 unsigned int incue_max_len;
413 unsigned int t, file_len, mode, sector_offs;
414 unsigned int sector_size = 2352;
418 // copy name of the iso and change extension from .bin to .cue
419 strncpy(cuename, isofile, sizeof(cuename));
420 cuename[MAXPATHLEN - 1] = '\0';
421 if (strlen(cuename) >= 4) {
422 strcpy(cuename + strlen(cuename) - 4, ".cue");
428 if ((fi = fopen(cuename, "r")) == NULL) {
432 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
433 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
435 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
436 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
437 // Don't proceed further, as this is actually a .toc file rather
440 return parsetoc(isofile);
442 fseek(fi, 0, SEEK_SET);
445 // build a path for files referenced in .cue
446 strncpy(filepath, cuename, sizeof(filepath));
447 tmp = strrchr(filepath, '/') + 1;
449 tmp = strrchr(filepath, '\\') + 1;
453 filepath[sizeof(filepath) - 1] = 0;
455 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
457 memset(&ti, 0, sizeof(ti));
460 sector_offs = 2 * 75;
462 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
463 strncpy(dummy, linebuf, sizeof(linebuf));
464 token = strtok(dummy, " ");
470 if (!strcmp(token, "TRACK")) {
474 if (strstr(linebuf, "AUDIO") != NULL) {
475 ti[numtracks].type = CDDA;
478 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
479 ti[numtracks].type = DATA;
481 SysPrintf(".cue: failed to parse TRACK\n");
482 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
484 if (sector_size == 0)
487 else if (!strcmp(token, "INDEX")) {
488 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
489 SysPrintf(".cue: failed to parse INDEX\n");
490 tok2msf(time, (char *)&ti[numtracks].start);
492 t = msf2sec(ti[numtracks].start);
493 ti[numtracks].start_offset = t * sector_size;
495 sec2msf(t, ti[numtracks].start);
497 // default track length to file length
498 t = file_len - ti[numtracks].start_offset / sector_size;
499 sec2msf(t, ti[numtracks].length);
501 if (numtracks > 1 && ti[numtracks].handle == NULL) {
502 // this track uses the same file as the last,
503 // start of this track is last track's end
504 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
505 sec2msf(t, ti[numtracks - 1].length);
507 if (numtracks > 1 && pregapOffset == -1)
508 pregapOffset = ti[numtracks].start_offset / sector_size;
510 else if (!strcmp(token, "PREGAP")) {
511 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
512 tok2msf(time, dummy);
513 sector_offs += msf2sec(dummy);
515 pregapOffset = -1; // mark to fill track start_offset
517 else if (!strcmp(token, "FILE")) {
518 t = sscanf(linebuf, " FILE \"%256[^\"]\"", tmpb);
520 sscanf(linebuf, " FILE %256s", tmpb);
523 ti[numtracks + 1].handle = fopen(tmpb, "rb");
524 if (ti[numtracks + 1].handle == NULL) {
526 tmp = strrchr(tmpb, '\\');
528 tmp = strrchr(tmpb, '/');
533 strncpy(incue_fname, tmp, incue_max_len);
534 ti[numtracks + 1].handle = fopen(filepath, "rb");
537 // update global offset if this is not first file in this .cue
538 if (numtracks + 1 > 1)
539 sector_offs += file_len;
542 if (ti[numtracks + 1].handle == NULL) {
543 SysPrintf(_("\ncould not open: %s\n"), filepath);
546 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
547 file_len = ftell(ti[numtracks + 1].handle) / 2352;
549 if (numtracks == 0 && strlen(isofile) >= 4 &&
550 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
552 // user selected .cue as image file, use it's data track instead
554 cdHandle = fopen(filepath, "rb");
564 // this function tries to get the .ccd file of the given .img
565 // the necessary data is put into the ti (trackinformation)-array
566 static int parseccd(const char *isofile) {
567 char ccdname[MAXPATHLEN];
574 // copy name of the iso and change extension from .img to .ccd
575 strncpy(ccdname, isofile, sizeof(ccdname));
576 ccdname[MAXPATHLEN - 1] = '\0';
577 if (strlen(ccdname) >= 4) {
578 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
584 if ((fi = fopen(ccdname, "r")) == NULL) {
588 memset(&ti, 0, sizeof(ti));
590 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
591 if (!strncmp(linebuf, "[TRACK", 6)){
594 else if (!strncmp(linebuf, "MODE=", 5)) {
595 sscanf(linebuf, "MODE=%d", &t);
596 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
598 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
599 sscanf(linebuf, "INDEX 1=%d", &t);
600 sec2msf(t + 2 * 75, ti[numtracks].start);
601 ti[numtracks].start_offset = t * 2352;
603 // If we've already seen another track, this is its end
605 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
606 sec2msf(t, ti[numtracks - 1].length);
613 // Fill out the last track's end based on size
614 if (numtracks >= 1) {
615 fseek(cdHandle, 0, SEEK_END);
616 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
617 sec2msf(t, ti[numtracks].length);
623 // this function tries to get the .mds file of the given .mdf
624 // the necessary data is put into the ti (trackinformation)-array
625 static int parsemds(const char *isofile) {
626 char mdsname[MAXPATHLEN];
628 unsigned int offset, extra_offset, l, i;
633 // copy name of the iso and change extension from .mdf to .mds
634 strncpy(mdsname, isofile, sizeof(mdsname));
635 mdsname[MAXPATHLEN - 1] = '\0';
636 if (strlen(mdsname) >= 4) {
637 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
643 if ((fi = fopen(mdsname, "rb")) == NULL) {
647 memset(&ti, 0, sizeof(ti));
649 // check if it's a valid mds file
650 fread(&i, 1, sizeof(unsigned int), fi);
652 if (i != 0x4944454D) {
653 // not an valid mds file
658 // get offset to session block
659 fseek(fi, 0x50, SEEK_SET);
660 fread(&offset, 1, sizeof(unsigned int), fi);
661 offset = SWAP32(offset);
663 // get total number of tracks
665 fseek(fi, offset, SEEK_SET);
666 fread(&s, 1, sizeof(unsigned short), fi);
670 // get offset to track blocks
671 fseek(fi, 4, SEEK_CUR);
672 fread(&offset, 1, sizeof(unsigned int), fi);
673 offset = SWAP32(offset);
677 fseek(fi, offset + 4, SEEK_SET);
678 if (fgetc(fi) < 0xA0) {
684 // check if the image contains mixed subchannel data
685 fseek(fi, offset + 1, SEEK_SET);
686 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
689 for (i = 1; i <= numtracks; i++) {
690 fseek(fi, offset, SEEK_SET);
692 // get the track type
693 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
694 fseek(fi, 8, SEEK_CUR);
696 // get the track starting point
697 ti[i].start[0] = fgetc(fi);
698 ti[i].start[1] = fgetc(fi);
699 ti[i].start[2] = fgetc(fi);
701 fread(&extra_offset, 1, sizeof(unsigned int), fi);
702 extra_offset = SWAP32(extra_offset);
704 // get track start offset (in .mdf)
705 fseek(fi, offset + 0x28, SEEK_SET);
706 fread(&l, 1, sizeof(unsigned int), fi);
708 ti[i].start_offset = l;
711 fseek(fi, extra_offset, SEEK_SET);
712 fread(&l, 1, sizeof(unsigned int), fi);
715 pregapOffset = msf2sec(ti[i].start);
717 // get the track length
718 fread(&l, 1, sizeof(unsigned int), fi);
720 sec2msf(l, ti[i].length);
729 static int handlepbp(const char *isofile) {
732 unsigned int dontcare[8];
733 unsigned int psar_offs;
746 unsigned int dontcare[6];
749 unsigned int t, cd_length, cdimg_base;
750 unsigned int offsettab[8], psisoimg_offs;
751 const char *ext = NULL;
754 if (strlen(isofile) >= 4)
755 ext = isofile + strlen(isofile) - 4;
756 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
761 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
762 if (ret != sizeof(pbp_hdr)) {
763 SysPrintf("failed to read pbp\n");
767 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
769 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
773 psisoimg_offs = pbp_hdr.psar_offs;
774 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
776 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
778 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
780 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
784 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
785 SysPrintf("failed to read offsettab\n");
789 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
790 if (offsettab[i] == 0)
793 cdrIsoMultidiskCount = i;
794 if (cdrIsoMultidiskCount == 0) {
795 SysPrintf("multidisk eboot has 0 images?\n");
799 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
800 cdrIsoMultidiskSelect = 0;
802 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
804 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
806 SysPrintf("failed to seek to %x\n", psisoimg_offs);
810 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
814 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
815 SysPrintf("bad psar_sig: %s\n", psar_sig);
820 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
822 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
826 // first 3 entries are special
827 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
828 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
829 numtracks = btoi(toc_entry.index1[0]);
831 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
832 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
833 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
835 for (i = 1; i <= numtracks; i++) {
836 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
838 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
840 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
841 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
842 ti[i].start_offset *= 2352;
843 ti[i].start[0] = btoi(toc_entry.index1[0]);
844 ti[i].start[1] = btoi(toc_entry.index1[1]);
845 ti[i].start[2] = btoi(toc_entry.index1[2]);
848 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
849 sec2msf(t, ti[i - 1].length);
852 t = cd_length - ti[numtracks].start_offset / 2352;
853 sec2msf(t, ti[numtracks].length);
856 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
858 SysPrintf("failed to seek to ISO index\n");
862 compr_img = calloc(1, sizeof(*compr_img));
863 if (compr_img == NULL)
866 compr_img->block_shift = 4;
867 compr_img->current_block = (unsigned int)-1;
869 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
870 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
871 if (compr_img->index_table == NULL)
874 cdimg_base = psisoimg_offs + 0x100000;
875 for (i = 0; i < compr_img->index_len; i++) {
876 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
877 if (ret != sizeof(index_entry)) {
878 SysPrintf("failed to read index_entry #%d\n", i);
882 if (index_entry.size == 0)
885 compr_img->index_table[i] = cdimg_base + index_entry.offset;
887 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
892 free(compr_img->index_table);
893 compr_img->index_table = NULL;
895 if (compr_img != NULL) {
902 static int handlecbin(const char *isofile) {
906 unsigned int header_size;
907 unsigned long long total_bytes;
908 unsigned int block_size;
909 unsigned char ver; // 1
911 unsigned char rsv_06[2];
913 const char *ext = NULL;
914 unsigned int index = 0, plain;
917 if (strlen(isofile) >= 5)
918 ext = isofile + strlen(isofile) - 5;
919 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
922 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
923 if (ret != sizeof(ciso_hdr)) {
924 SysPrintf("failed to read ciso header\n");
928 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
929 SysPrintf("bad ciso header\n");
932 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
933 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
935 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
940 compr_img = calloc(1, sizeof(*compr_img));
941 if (compr_img == NULL)
944 compr_img->block_shift = 0;
945 compr_img->current_block = (unsigned int)-1;
947 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
948 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
949 if (compr_img->index_table == NULL)
952 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
953 if (ret != compr_img->index_len) {
954 SysPrintf("failed to read index table\n");
958 for (i = 0; i < compr_img->index_len + 1; i++) {
959 index = compr_img->index_table[i];
960 plain = index & 0x80000000;
962 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
964 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
965 SysPrintf("warning: ciso img too large, expect problems\n");
970 free(compr_img->index_table);
971 compr_img->index_table = NULL;
973 if (compr_img != NULL) {
980 // this function tries to get the .sub file of the given .img
981 static int opensubfile(const char *isoname) {
982 char subname[MAXPATHLEN];
984 // copy name of the iso and change extension from .img to .sub
985 strncpy(subname, isoname, sizeof(subname));
986 subname[MAXPATHLEN - 1] = '\0';
987 if (strlen(subname) >= 4) {
988 strcpy(subname + strlen(subname) - 4, ".sub");
994 subHandle = fopen(subname, "rb");
995 if (subHandle == NULL) {
1002 static int opensbifile(const char *isoname) {
1003 char sbiname[MAXPATHLEN];
1006 strncpy(sbiname, isoname, sizeof(sbiname));
1007 sbiname[MAXPATHLEN - 1] = '\0';
1008 if (strlen(sbiname) >= 4) {
1009 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1015 fseek(cdHandle, 0, SEEK_END);
1016 s = ftell(cdHandle) / 2352;
1018 return LoadSBI(sbiname, s);
1021 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1023 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1024 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1027 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1031 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1032 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1033 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1035 if (subChanRaw) DecodeRawSubData();
1040 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1045 if (z.zalloc == NULL) {
1046 // XXX: one-time leak here..
1052 ret = inflateInit2(&z, -15);
1055 ret = inflateReset(&z);
1060 z.avail_in = in_size;
1062 z.avail_out = *out_size;
1064 ret = inflate(&z, Z_NO_FLUSH);
1067 *out_size -= z.avail_out;
1068 return ret == 1 ? 0 : ret;
1071 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1073 unsigned long cdbuffer_size, cdbuffer_size_expect;
1074 unsigned int start_byte, size;
1079 sector += base / 2352;
1081 block = sector >> compr_img->block_shift;
1082 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1084 if (block == compr_img->current_block) {
1085 //printf("hit sect %d\n", sector);
1089 if (sector >= compr_img->index_len * 16) {
1090 SysPrintf("sector %d is past img end\n", sector);
1094 start_byte = compr_img->index_table[block] & 0x7fffffff;
1095 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1096 SysPrintf("seek error for block %d at %x: ",
1102 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1103 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1104 if (size > sizeof(compr_img->buff_compressed)) {
1105 SysPrintf("block %d is too large: %u\n", block, size);
1109 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1110 1, size, cdHandle) != size) {
1111 SysPrintf("read error for block %d at %x: ", block, start_byte);
1116 if (is_compressed) {
1117 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1118 cdbuffer_size = cdbuffer_size_expect;
1119 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1121 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1122 ret, block, sector);
1125 if (cdbuffer_size != cdbuffer_size_expect)
1126 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1127 cdbuffer_size_expect, sector);
1131 compr_img->current_block = block;
1134 if (dest != cdbuffer) // copy avoid HACK
1135 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1137 return CD_FRAMESIZE_RAW;
1140 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1144 fseek(f, base + sector * 2048, SEEK_SET);
1145 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1147 // not really necessary, fake mode 2 header
1148 memset(cdbuffer, 0, 12 * 2);
1149 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1150 cdbuffer[12 + 3] = 1;
1155 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1156 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1159 static unsigned char * CALLBACK ISOgetBuffer(void) {
1160 return cdbuffer + 12;
1163 static void PrintTracks(void) {
1166 for (i = 1; i <= numtracks; i++) {
1167 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1168 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1169 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1170 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1174 // This function is invoked by the front-end when opening an ISO
1175 // file for playback
1176 static long CALLBACK ISOopen(void) {
1177 boolean isMode1ISO = FALSE;
1179 if (cdHandle != NULL) {
1180 return 0; // it's already open
1183 cdHandle = fopen(GetIsoFile(), "rb");
1184 if (cdHandle == NULL) {
1188 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1190 cddaBigEndian = FALSE;
1191 subChanMixed = FALSE;
1194 cdrIsoMultidiskCount = 1;
1196 CDR_getBuffer = ISOgetBuffer;
1197 cdimg_read_func = cdread_normal;
1199 if (parsecue(GetIsoFile()) == 0) {
1200 SysPrintf("[+cue]");
1202 else if (parsetoc(GetIsoFile()) == 0) {
1203 SysPrintf("[+toc]");
1205 else if (parseccd(GetIsoFile()) == 0) {
1206 SysPrintf("[+ccd]");
1208 else if (parsemds(GetIsoFile()) == 0) {
1209 SysPrintf("[+mds]");
1211 if (handlepbp(GetIsoFile()) == 0) {
1213 CDR_getBuffer = ISOgetBuffer_compr;
1214 cdimg_read_func = cdread_compressed;
1216 else if (handlecbin(GetIsoFile()) == 0) {
1217 SysPrintf("[cbin]");
1218 CDR_getBuffer = ISOgetBuffer_compr;
1219 cdimg_read_func = cdread_compressed;
1222 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1223 SysPrintf("[+sub]");
1225 if (opensbifile(GetIsoFile()) == 0) {
1226 SysPrintf("[+sbi]");
1229 // guess whether it is mode1/2048
1230 fseek(cdHandle, 0, SEEK_END);
1231 if (ftell(cdHandle) % 2048 == 0) {
1232 unsigned int modeTest = 0;
1233 fseek(cdHandle, 0, SEEK_SET);
1234 fread(&modeTest, 4, 1, cdHandle);
1235 if (SWAP32(modeTest) != 0xffffff00) {
1236 SysPrintf("[2048]");
1240 fseek(cdHandle, 0, SEEK_SET);
1247 cdimg_read_func = cdread_sub_mixed;
1248 else if (isMode1ISO)
1249 cdimg_read_func = cdread_2048;
1251 // make sure we have another handle open for cdda
1252 if (numtracks > 1 && ti[1].handle == NULL) {
1253 ti[1].handle = fopen(GetIsoFile(), "rb");
1255 cdda_cur_sector = 0;
1256 cdda_file_offset = 0;
1261 static long CALLBACK ISOclose(void) {
1264 if (cdHandle != NULL) {
1268 if (subHandle != NULL) {
1275 if (compr_img != NULL) {
1276 free(compr_img->index_table);
1281 for (i = 1; i <= numtracks; i++) {
1282 if (ti[i].handle != NULL) {
1283 fclose(ti[i].handle);
1284 ti[i].handle = NULL;
1293 static long CALLBACK ISOinit(void) {
1294 assert(cdHandle == NULL);
1295 assert(subHandle == NULL);
1297 return 0; // do nothing
1300 static long CALLBACK ISOshutdown(void) {
1305 // return Starting and Ending Track
1307 // byte 0 - start track
1308 // byte 1 - end track
1309 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1312 if (numtracks > 0) {
1313 buffer[1] = numtracks;
1322 // return Track Time
1327 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1329 // CD length according pcsxr-svn (done a bit different here)
1331 unsigned char time[3];
1332 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1333 sec2msf(sect, (char *)time);
1334 buffer[2] = time[0];
1335 buffer[1] = time[1];
1336 buffer[0] = time[2];
1338 else if (numtracks > 0 && track <= numtracks) {
1339 buffer[2] = ti[track].start[0];
1340 buffer[1] = ti[track].start[1];
1341 buffer[0] = ti[track].start[2];
1352 // decode 'raw' subchannel data ripped by cdrdao
1353 static void DecodeRawSubData(void) {
1354 unsigned char subQData[12];
1357 memset(subQData, 0, sizeof(subQData));
1359 for (i = 0; i < 8 * 12; i++) {
1360 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1361 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1365 memcpy(&subbuffer[12], subQData, 12);
1369 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1371 static long CALLBACK ISOreadTrack(unsigned char *time) {
1372 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1374 if (cdHandle == NULL) {
1379 subChanMissing = FALSE;
1380 if (sector >= pregapOffset) {
1382 if (sector < pregapOffset)
1383 subChanMissing = TRUE;
1387 cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1389 if (subHandle != NULL) {
1390 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1391 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1393 if (subChanRaw) DecodeRawSubData();
1400 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1401 // does NOT uses bcd format
1402 static long CALLBACK ISOplay(unsigned char *time) {
1409 cdda_cur_sector = msf2sec((char *)time);
1410 for (i = numtracks; i > 1; i--) {
1411 cdda_first_sector = msf2sec(ti[i].start);
1412 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1415 cdda_file_offset = ti[i].start_offset;
1417 // find the file that contains this track
1419 if (ti[i].handle != NULL)
1422 cddaHandle = ti[i].handle;
1424 if (SPU_playCDDAchannel != NULL)
1431 static long CALLBACK ISOstop(void) {
1436 // gets subchannel data
1437 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1438 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1445 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1448 CDR__getStatus(stat);
1452 stat->Status |= 0x80;
1458 sec = cdda_cur_sector;
1459 sec2msf(sec, (char *)stat->Time);
1464 void cdrIsoInit(void) {
1466 CDR_shutdown = ISOshutdown;
1468 CDR_close = ISOclose;
1469 CDR_getTN = ISOgetTN;
1470 CDR_getTD = ISOgetTD;
1471 CDR_readTrack = ISOreadTrack;
1472 CDR_getBuffer = ISOgetBuffer;
1475 CDR_getBufferSub = ISOgetBufferSub;
1476 CDR_getStatus = ISOgetStatus;
1478 CDR_getDriveLetter = CDR__getDriveLetter;
1479 CDR_configure = CDR__configure;
1480 CDR_test = CDR__test;
1481 CDR_about = CDR__about;
1482 CDR_setfilename = CDR__setfilename;
1487 int cdrIsoActive(void) {
1488 return (cdHandle != NULL);