1 /***************************************************************************
2 * Copyright (C) 2007 PCSX-df Team *
3 * Copyright (C) 2009 Wei Mingzhi *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA. *
19 ***************************************************************************/
21 #include "psxcommon.h"
36 unsigned int cdrIsoMultidiskCount;
37 unsigned int cdrIsoMultidiskSelect;
39 static FILE *cdHandle = NULL;
40 static FILE *cddaHandle = NULL;
41 static FILE *subHandle = NULL;
43 static boolean subChanMixed = FALSE;
44 static boolean subChanRaw = FALSE;
45 static boolean subChanMissing = FALSE;
47 static unsigned char cdbuffer[DATA_SIZE];
48 static unsigned char subbuffer[SUB_FRAMESIZE];
50 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
52 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
55 static HANDLE threadid;
57 static pthread_t threadid;
59 static unsigned int initial_offset = 0;
60 static boolean playing = FALSE;
61 static boolean cddaBigEndian = FALSE;
62 static unsigned int cdda_cur_sector;
63 static unsigned int cdda_start_sector;
64 /* Frame offset into CD image where pregap data would be found if it was there.
65 * If a game seeks there we must *not* return subchannel data since it's
66 * not in the CD image, so that cdrom code can fake subchannel data instead.
67 * XXX: there could be multiple pregaps but PSX dumps only have one? */
68 static unsigned int pregapOffset;
70 // compressed image stuff
72 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
73 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
74 unsigned int *index_table;
75 unsigned int index_len;
76 unsigned int block_shift;
77 unsigned int current_block;
78 unsigned int sector_in_blk;
81 int (*cdimg_read_func)(FILE *f, void *dest, int sector, int offset);
83 char* CALLBACK CDR__getDriveLetter(void);
84 long CALLBACK CDR__configure(void);
85 long CALLBACK CDR__test(void);
86 void CALLBACK CDR__about(void);
87 long CALLBACK CDR__setfilename(char *filename);
88 long CALLBACK CDR__getStatus(struct CdrStat *stat);
90 static void DecodeRawSubData(void);
92 extern void *hCDRDriver;
95 enum {DATA, CDDA} type;
96 char start[3]; // MSF-format
97 char length[3]; // MSF-format
98 FILE *handle; // for multi-track images CDDA
99 int start_offset; // sector offset from start of above file
102 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
104 static int numtracks = 0;
105 static struct trackinfo ti[MAXTRACKS];
107 // get a sector from a msf-array
108 static unsigned int msf2sec(char *msf) {
109 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
112 static void sec2msf(unsigned int s, char *msf) {
113 msf[0] = s / 75 / 60;
114 s = s - msf[0] * 75 * 60;
120 // divide a string of xx:yy:zz into m, s, f
121 static void tok2msf(char *time, char *msf) {
124 token = strtok(time, ":");
126 msf[0] = atoi(token);
132 token = strtok(NULL, ":");
134 msf[1] = atoi(token);
140 token = strtok(NULL, ":");
142 msf[2] = atoi(token);
150 static long GetTickCount(void) {
151 static time_t initial_time = 0;
154 gettimeofday(&now, NULL);
156 if (initial_time == 0) {
157 initial_time = now.tv_sec;
160 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
164 // this thread plays audio data
166 static void playthread(void *param)
168 static void *playthread(void *param)
171 long osleep, d, t, i, s;
179 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
180 d = cdimg_read_func(cddaHandle, sndbuffer + s, cdda_cur_sector, 0);
181 if (d < CD_FRAMESIZE_RAW)
194 if (!cdr.Muted && playing) {
196 for (i = 0; i < s / 2; i++) {
197 tmp = sndbuffer[i * 2];
198 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
199 sndbuffer[i * 2 + 1] = tmp;
204 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
207 } while (ret == 0x7761 && playing); // rearmed_wait
210 if (ret != 0x676f) { // !rearmed_go
214 // HACK: stop feeding data while emu is paused
216 while (stop && playing)
219 now = GetTickCount();
225 else if (osleep > CDDA_FRAMETIME) {
226 osleep = CDDA_FRAMETIME;
230 usleep(osleep * 1000);
244 // stop the CDDA playback
245 static void stopCDDA() {
252 WaitForSingleObject(threadid, INFINITE);
254 pthread_join(threadid, NULL);
258 // start the CDDA playback
259 static void startCDDA(unsigned int sector) {
264 cdda_cur_sector = sector;
268 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
270 pthread_create(&threadid, NULL, playthread, NULL);
274 // this function tries to get the .toc file of the given .bin
275 // the necessary data is put into the ti (trackinformation)-array
276 static int parsetoc(const char *isofile) {
277 char tocname[MAXPATHLEN];
279 char linebuf[256], dummy[256], name[256];
281 char time[20], time2[20];
282 unsigned int t, sector_offs;
286 // copy name of the iso and change extension from .bin to .toc
287 strncpy(tocname, isofile, sizeof(tocname));
288 tocname[MAXPATHLEN - 1] = '\0';
289 if (strlen(tocname) >= 4) {
290 strcpy(tocname + strlen(tocname) - 4, ".toc");
296 if ((fi = fopen(tocname, "r")) == NULL) {
297 // try changing extension to .cue (to satisfy some stupid tutorials)
298 strcpy(tocname + strlen(tocname) - 4, ".cue");
299 if ((fi = fopen(tocname, "r")) == NULL) {
300 // if filename is image.toc.bin, try removing .bin (for Brasero)
301 strcpy(tocname, isofile);
303 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
304 tocname[t - 4] = '\0';
305 if ((fi = fopen(tocname, "r")) == NULL) {
315 memset(&ti, 0, sizeof(ti));
316 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
318 sector_offs = 2 * 75;
320 // parse the .toc file
321 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
323 strncpy(dummy, linebuf, sizeof(linebuf));
324 token = strtok(dummy, " ");
326 if (token == NULL) continue;
328 if (!strcmp(token, "TRACK")) {
330 token = strtok(NULL, " ");
333 if (!strncmp(token, "MODE2_RAW", 9)) {
334 ti[numtracks].type = DATA;
335 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
337 // check if this image contains mixed subchannel data
338 token = strtok(NULL, " ");
339 if (token != NULL && !strncmp(token, "RW_RAW", 6)) {
344 else if (!strncmp(token, "AUDIO", 5)) {
345 ti[numtracks].type = CDDA;
348 else if (!strcmp(token, "DATAFILE")) {
349 if (ti[numtracks].type == CDDA) {
350 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
351 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
352 ti[numtracks].start_offset = t;
354 sec2msf(t, (char *)&ti[numtracks].start);
355 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
358 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
359 tok2msf((char *)&time, (char *)&ti[numtracks].length);
362 else if (!strcmp(token, "FILE")) {
363 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
364 tok2msf((char *)&time, (char *)&ti[numtracks].start);
365 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
366 ti[numtracks].start_offset = t;
367 t += msf2sec(ti[numtracks].start) + sector_offs;
368 sec2msf(t, (char *)&ti[numtracks].start);
369 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
371 else if (!strcmp(token, "ZERO")) {
372 sscanf(linebuf, "ZERO AUDIO RW_RAW %8s", time);
373 tok2msf((char *)&time, dummy);
374 sector_offs += msf2sec(dummy);
376 t = ti[numtracks - 1].start_offset;
377 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
387 // this function tries to get the .cue file of the given .bin
388 // the necessary data is put into the ti (trackinformation)-array
389 static int parsecue(const char *isofile) {
390 char cuename[MAXPATHLEN];
391 char filepath[MAXPATHLEN];
397 char linebuf[256], tmpb[256], dummy[256];
398 unsigned int incue_max_len;
399 unsigned int t, file_len, sector_offs;
403 // copy name of the iso and change extension from .bin to .cue
404 strncpy(cuename, isofile, sizeof(cuename));
405 cuename[MAXPATHLEN - 1] = '\0';
406 if (strlen(cuename) >= 4) {
407 strcpy(cuename + strlen(cuename) - 4, ".cue");
413 if ((fi = fopen(cuename, "r")) == NULL) {
417 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
418 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
420 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
421 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
422 // Don't proceed further, as this is actually a .toc file rather
425 return parsetoc(isofile);
427 fseek(fi, 0, SEEK_SET);
430 // build a path for files referenced in .cue
431 strncpy(filepath, cuename, sizeof(filepath));
432 tmp = strrchr(filepath, '/') + 1;
434 tmp = strrchr(filepath, '\\') + 1;
438 filepath[sizeof(filepath) - 1] = 0;
440 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
442 memset(&ti, 0, sizeof(ti));
445 sector_offs = 2 * 75;
447 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
448 strncpy(dummy, linebuf, sizeof(linebuf));
449 token = strtok(dummy, " ");
455 if (!strcmp(token, "TRACK")) {
458 if (strstr(linebuf, "AUDIO") != NULL) {
459 ti[numtracks].type = CDDA;
461 else if (strstr(linebuf, "MODE1/2352") != NULL || strstr(linebuf, "MODE2/2352") != NULL) {
462 ti[numtracks].type = DATA;
465 else if (!strcmp(token, "INDEX")) {
466 sscanf(linebuf, " INDEX %02d %8s", &t, time);
467 tok2msf(time, (char *)&ti[numtracks].start);
469 t = msf2sec(ti[numtracks].start);
470 ti[numtracks].start_offset = t;
472 sec2msf(t, ti[numtracks].start);
474 // default track length to file length
475 t = file_len - ti[numtracks].start_offset;
476 sec2msf(t, ti[numtracks].length);
478 if (numtracks > 1 && ti[numtracks].handle == NULL) {
479 // this track uses the same file as the last,
480 // start of this track is last track's end
481 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
482 sec2msf(t, ti[numtracks - 1].length);
484 if (numtracks > 1 && pregapOffset == -1)
485 pregapOffset = ti[numtracks].start_offset;
487 else if (!strcmp(token, "PREGAP")) {
488 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
489 tok2msf(time, dummy);
490 sector_offs += msf2sec(dummy);
492 pregapOffset = -1; // mark to fill track start_offset
494 else if (!strcmp(token, "FILE")) {
495 sscanf(linebuf, " FILE \"%[^\"]\"", tmpb);
498 ti[numtracks + 1].handle = fopen(tmpb, "rb");
499 if (ti[numtracks + 1].handle == NULL) {
501 tmp = strrchr(tmpb, '\\');
503 tmp = strrchr(tmpb, '/');
508 strncpy(incue_fname, tmp, incue_max_len);
509 ti[numtracks + 1].handle = fopen(filepath, "rb");
512 // update global offset if this is not first file in this .cue
513 if (numtracks + 1 > 1)
514 sector_offs += file_len;
517 if (ti[numtracks + 1].handle == NULL) {
518 SysPrintf(_("\ncould not open: %s\n"), filepath);
521 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
522 file_len = ftell(ti[numtracks + 1].handle) / 2352;
524 if (numtracks == 0 && strlen(isofile) >= 4 &&
525 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
527 // user selected .cue as image file, use it's data track instead
529 cdHandle = fopen(filepath, "rb");
539 // this function tries to get the .ccd file of the given .img
540 // the necessary data is put into the ti (trackinformation)-array
541 static int parseccd(const char *isofile) {
542 char ccdname[MAXPATHLEN];
549 // copy name of the iso and change extension from .img to .ccd
550 strncpy(ccdname, isofile, sizeof(ccdname));
551 ccdname[MAXPATHLEN - 1] = '\0';
552 if (strlen(ccdname) >= 4) {
553 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
559 if ((fi = fopen(ccdname, "r")) == NULL) {
563 memset(&ti, 0, sizeof(ti));
565 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
566 if (!strncmp(linebuf, "[TRACK", 6)){
569 else if (!strncmp(linebuf, "MODE=", 5)) {
570 sscanf(linebuf, "MODE=%d", &t);
571 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
573 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
574 sscanf(linebuf, "INDEX 1=%d", &t);
575 sec2msf(t + 2 * 75, ti[numtracks].start);
576 ti[numtracks].start_offset = t;
578 // If we've already seen another track, this is its end
580 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
581 sec2msf(t, ti[numtracks - 1].length);
588 // Fill out the last track's end based on size
589 if (numtracks >= 1) {
590 fseek(cdHandle, 0, SEEK_END);
591 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
592 sec2msf(t, ti[numtracks].length);
598 // this function tries to get the .mds file of the given .mdf
599 // the necessary data is put into the ti (trackinformation)-array
600 static int parsemds(const char *isofile) {
601 char mdsname[MAXPATHLEN];
603 unsigned int offset, extra_offset, l, i;
608 // copy name of the iso and change extension from .mdf to .mds
609 strncpy(mdsname, isofile, sizeof(mdsname));
610 mdsname[MAXPATHLEN - 1] = '\0';
611 if (strlen(mdsname) >= 4) {
612 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
618 if ((fi = fopen(mdsname, "rb")) == NULL) {
622 memset(&ti, 0, sizeof(ti));
624 // check if it's a valid mds file
625 fread(&i, 1, sizeof(unsigned int), fi);
627 if (i != 0x4944454D) {
628 // not an valid mds file
633 // get offset to session block
634 fseek(fi, 0x50, SEEK_SET);
635 fread(&offset, 1, sizeof(unsigned int), fi);
636 offset = SWAP32(offset);
638 // get total number of tracks
640 fseek(fi, offset, SEEK_SET);
641 fread(&s, 1, sizeof(unsigned short), fi);
645 // get offset to track blocks
646 fseek(fi, 4, SEEK_CUR);
647 fread(&offset, 1, sizeof(unsigned int), fi);
648 offset = SWAP32(offset);
652 fseek(fi, offset + 4, SEEK_SET);
653 if (fgetc(fi) < 0xA0) {
659 // check if the image contains mixed subchannel data
660 fseek(fi, offset + 1, SEEK_SET);
661 subChanMixed = (fgetc(fi) ? TRUE : FALSE);
664 for (i = 1; i <= numtracks; i++) {
665 fseek(fi, offset, SEEK_SET);
667 // get the track type
668 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
669 fseek(fi, 8, SEEK_CUR);
671 // get the track starting point
672 ti[i].start[0] = fgetc(fi);
673 ti[i].start[1] = fgetc(fi);
674 ti[i].start[2] = fgetc(fi);
676 fread(&extra_offset, 1, sizeof(unsigned int), fi);
677 extra_offset = SWAP32(extra_offset);
679 // get track start offset (in .mdf)
680 fseek(fi, offset + 0x28, SEEK_SET);
681 fread(&l, 1, sizeof(unsigned int), fi);
683 ti[i].start_offset = l / CD_FRAMESIZE_RAW;
686 fseek(fi, extra_offset, SEEK_SET);
687 fread(&l, 1, sizeof(unsigned int), fi);
690 pregapOffset = ti[i].start_offset;
692 // get the track length
693 fread(&l, 1, sizeof(unsigned int), fi);
695 sec2msf(l, ti[i].length);
704 static int handlepbp(const char *isofile) {
707 unsigned int dontcare[8];
708 unsigned int psar_offs;
721 unsigned int dontcare[6];
724 unsigned int t, cd_length, cdimg_base;
725 unsigned int offsettab[8], psisoimg_offs;
726 const char *ext = NULL;
729 if (strlen(isofile) >= 4)
730 ext = isofile + strlen(isofile) - 4;
731 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
736 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
737 if (ret != sizeof(pbp_hdr)) {
738 fprintf(stderr, "failed to read pbp\n");
742 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
744 fprintf(stderr, "failed to seek to %x\n", pbp_hdr.psar_offs);
748 psisoimg_offs = pbp_hdr.psar_offs;
749 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
751 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
753 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
755 fprintf(stderr, "failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
759 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
760 fprintf(stderr, "failed to read offsettab\n");
764 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
765 if (offsettab[i] == 0)
768 cdrIsoMultidiskCount = i;
769 if (cdrIsoMultidiskCount == 0) {
770 fprintf(stderr, "multidisk eboot has 0 images?\n");
774 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
775 cdrIsoMultidiskSelect = 0;
777 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
779 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
781 fprintf(stderr, "failed to seek to %x\n", psisoimg_offs);
785 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
789 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
790 fprintf(stderr, "bad psar_sig: %s\n", psar_sig);
795 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
797 fprintf(stderr, "failed to seek to %x\n", psisoimg_offs + 0x800);
801 // first 3 entries are special
802 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
803 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
804 numtracks = btoi(toc_entry.index1[0]);
806 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
807 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
808 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
810 for (i = 1; i <= numtracks; i++) {
811 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
813 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
815 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
816 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
817 ti[i].start[0] = btoi(toc_entry.index1[0]);
818 ti[i].start[1] = btoi(toc_entry.index1[1]);
819 ti[i].start[2] = btoi(toc_entry.index1[2]);
822 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
823 sec2msf(t, ti[i - 1].length);
826 t = cd_length - ti[numtracks].start_offset;
827 sec2msf(t, ti[numtracks].length);
830 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
832 fprintf(stderr, "failed to seek to ISO index\n");
836 compr_img = calloc(1, sizeof(*compr_img));
837 if (compr_img == NULL)
840 compr_img->block_shift = 4;
841 compr_img->current_block = (unsigned int)-1;
843 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
844 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
845 if (compr_img->index_table == NULL)
848 cdimg_base = psisoimg_offs + 0x100000;
849 for (i = 0; i < compr_img->index_len; i++) {
850 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
851 if (ret != sizeof(index_entry)) {
852 fprintf(stderr, "failed to read index_entry #%d\n", i);
856 if (index_entry.size == 0)
859 compr_img->index_table[i] = cdimg_base + index_entry.offset;
861 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
866 free(compr_img->index_table);
867 compr_img->index_table = NULL;
869 if (compr_img != NULL) {
876 static int handlecbin(const char *isofile) {
880 unsigned int header_size;
881 unsigned long long total_bytes;
882 unsigned int block_size;
883 unsigned char ver; // 1
885 unsigned char rsv_06[2];
887 const char *ext = NULL;
888 unsigned int index = 0, plain;
891 if (strlen(isofile) >= 5)
892 ext = isofile + strlen(isofile) - 5;
893 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
896 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
897 if (ret != sizeof(ciso_hdr)) {
898 fprintf(stderr, "failed to read ciso header\n");
902 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
903 fprintf(stderr, "bad ciso header\n");
906 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
907 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
909 fprintf(stderr, "failed to seek to %x\n", ciso_hdr.header_size);
914 compr_img = calloc(1, sizeof(*compr_img));
915 if (compr_img == NULL)
918 compr_img->block_shift = 0;
919 compr_img->current_block = (unsigned int)-1;
921 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
922 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
923 if (compr_img->index_table == NULL)
926 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
927 if (ret != compr_img->index_len) {
928 fprintf(stderr, "failed to read index table\n");
932 for (i = 0; i < compr_img->index_len + 1; i++) {
933 index = compr_img->index_table[i];
934 plain = index & 0x80000000;
936 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
938 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
939 fprintf(stderr, "warning: ciso img too large, expect problems\n");
944 free(compr_img->index_table);
945 compr_img->index_table = NULL;
947 if (compr_img != NULL) {
954 // this function tries to get the .sub file of the given .img
955 static int opensubfile(const char *isoname) {
956 char subname[MAXPATHLEN];
958 // copy name of the iso and change extension from .img to .sub
959 strncpy(subname, isoname, sizeof(subname));
960 subname[MAXPATHLEN - 1] = '\0';
961 if (strlen(subname) >= 4) {
962 strcpy(subname + strlen(subname) - 4, ".sub");
968 subHandle = fopen(subname, "rb");
969 if (subHandle == NULL) {
976 static int opensbifile(const char *isoname) {
977 char sbiname[MAXPATHLEN];
980 strncpy(sbiname, isoname, sizeof(sbiname));
981 sbiname[MAXPATHLEN - 1] = '\0';
982 if (strlen(sbiname) >= 4) {
983 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
989 fseek(cdHandle, 0, SEEK_END);
990 s = ftell(cdHandle) / 2352;
992 return LoadSBI(sbiname, s);
995 static int cdread_normal(FILE *f, void *dest, int sector, int offset)
997 fseek(f, sector * CD_FRAMESIZE_RAW + offset, SEEK_SET);
998 return fread(dest, 1, CD_FRAMESIZE_RAW - offset, f);
1001 static int cdread_sub_mixed(FILE *f, void *dest, int sector, int offset)
1005 fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + offset, SEEK_SET);
1006 ret = fread(dest, 1, CD_FRAMESIZE_RAW - offset, f);
1007 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1009 if (subChanRaw) DecodeRawSubData();
1014 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1019 if (z.zalloc == NULL) {
1020 // XXX: one-time leak here..
1026 ret = inflateInit2(&z, -15);
1029 ret = inflateReset(&z);
1034 z.avail_in = in_size;
1036 z.avail_out = *out_size;
1038 ret = inflate(&z, Z_NO_FLUSH);
1041 *out_size -= z.avail_out;
1042 return ret == 1 ? 0 : ret;
1045 static int cdread_compressed(FILE *f, void *dest, int sector, int offset)
1047 unsigned long cdbuffer_size, cdbuffer_size_expect;
1048 unsigned int start_byte, size;
1052 block = sector >> compr_img->block_shift;
1053 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1055 if (block == compr_img->current_block) {
1056 //printf("hit sect %d\n", sector);
1060 if (sector >= compr_img->index_len * 16) {
1061 fprintf(stderr, "sector %d is past img end\n", sector);
1065 start_byte = compr_img->index_table[block] & 0x7fffffff;
1066 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1067 fprintf(stderr, "seek error for block %d at %x: ",
1073 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1074 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1075 if (size > sizeof(compr_img->buff_compressed)) {
1076 fprintf(stderr, "block %d is too large: %u\n", block, size);
1080 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1081 1, size, cdHandle) != size) {
1082 fprintf(stderr, "read error for block %d at %x: ", block, start_byte);
1087 if (is_compressed) {
1088 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1089 cdbuffer_size = cdbuffer_size_expect;
1090 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1092 fprintf(stderr, "uncompress failed with %d for block %d, sector %d\n",
1093 ret, block, sector);
1096 if (cdbuffer_size != cdbuffer_size_expect)
1097 fprintf(stderr, "cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1098 cdbuffer_size_expect, sector);
1102 compr_img->current_block = block;
1105 if (dest != cdbuffer) // copy avoid HACK
1106 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk] + offset,
1107 CD_FRAMESIZE_RAW - offset);
1108 return CD_FRAMESIZE_RAW - offset;
1111 static int cdread_2048(FILE *f, void *dest, int sector, int offset)
1115 fseek(f, sector * 2048, SEEK_SET);
1116 ret = fread((char *)dest + 12, 1, 2048, f);
1118 // not really necessary, fake mode 2 header
1119 memset(cdbuffer, 0, 12);
1120 sec2msf(sector + 2 * 75, (char *)cdbuffer);
1126 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1127 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1130 static unsigned char * CALLBACK ISOgetBuffer(void) {
1134 static void PrintTracks(void) {
1137 for (i = 1; i <= numtracks; i++) {
1138 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1139 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1140 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1141 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1145 // This function is invoked by the front-end when opening an ISO
1146 // file for playback
1147 static long CALLBACK ISOopen(void) {
1148 boolean isMode1ISO = FALSE;
1150 if (cdHandle != NULL) {
1151 return 0; // it's already open
1154 cdHandle = fopen(GetIsoFile(), "rb");
1155 if (cdHandle == NULL) {
1159 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1161 cddaBigEndian = FALSE;
1162 subChanMixed = FALSE;
1165 cdrIsoMultidiskCount = 1;
1167 CDR_getBuffer = ISOgetBuffer;
1168 cdimg_read_func = cdread_normal;
1170 if (parsecue(GetIsoFile()) == 0) {
1171 SysPrintf("[+cue]");
1173 else if (parsetoc(GetIsoFile()) == 0) {
1174 SysPrintf("[+toc]");
1176 else if (parseccd(GetIsoFile()) == 0) {
1177 SysPrintf("[+ccd]");
1179 else if (parsemds(GetIsoFile()) == 0) {
1180 SysPrintf("[+mds]");
1182 if (handlepbp(GetIsoFile()) == 0) {
1184 CDR_getBuffer = ISOgetBuffer_compr;
1185 cdimg_read_func = cdread_compressed;
1187 else if (handlecbin(GetIsoFile()) == 0) {
1188 SysPrintf("[cbin]");
1189 CDR_getBuffer = ISOgetBuffer_compr;
1190 cdimg_read_func = cdread_compressed;
1193 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1194 SysPrintf("[+sub]");
1196 if (opensbifile(GetIsoFile()) == 0) {
1197 SysPrintf("[+sbi]");
1200 // guess whether it is mode1/2048
1201 fseek(cdHandle, 0, SEEK_END);
1202 if (ftell(cdHandle) % 2048 == 0) {
1203 unsigned int modeTest = 0;
1204 fseek(cdHandle, 0, SEEK_SET);
1205 fread(&modeTest, 4, 1, cdHandle);
1206 if (SWAP32(modeTest) != 0xffffff00) {
1207 SysPrintf("[2048]");
1211 fseek(cdHandle, 0, SEEK_SET);
1218 cdimg_read_func = cdread_sub_mixed;
1219 else if (isMode1ISO)
1220 cdimg_read_func = cdread_2048;
1222 // make sure we have another handle open for cdda
1223 if (numtracks > 1 && ti[1].handle == NULL) {
1224 ti[1].handle = fopen(GetIsoFile(), "rb");
1226 cdda_cur_sector = cdda_start_sector = 0;
1231 static long CALLBACK ISOclose(void) {
1234 if (cdHandle != NULL) {
1238 if (subHandle != NULL) {
1245 if (compr_img != NULL) {
1246 free(compr_img->index_table);
1251 for (i = 1; i <= numtracks; i++) {
1252 if (ti[i].handle != NULL) {
1253 fclose(ti[i].handle);
1254 ti[i].handle = NULL;
1263 static long CALLBACK ISOinit(void) {
1264 assert(cdHandle == NULL);
1265 assert(subHandle == NULL);
1267 return 0; // do nothing
1270 static long CALLBACK ISOshutdown(void) {
1275 // return Starting and Ending Track
1277 // byte 0 - start track
1278 // byte 1 - end track
1279 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1282 if (numtracks > 0) {
1283 buffer[1] = numtracks;
1292 // return Track Time
1297 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1299 // CD length according pcsxr-svn (done a bit different here)
1301 unsigned char time[3];
1302 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1303 sec2msf(sect, (char *)time);
1304 buffer[2] = time[0];
1305 buffer[1] = time[1];
1306 buffer[0] = time[2];
1308 else if (numtracks > 0 && track <= numtracks) {
1309 buffer[2] = ti[track].start[0];
1310 buffer[1] = ti[track].start[1];
1311 buffer[0] = ti[track].start[2];
1322 // decode 'raw' subchannel data ripped by cdrdao
1323 static void DecodeRawSubData(void) {
1324 unsigned char subQData[12];
1327 memset(subQData, 0, sizeof(subQData));
1329 for (i = 0; i < 8 * 12; i++) {
1330 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1331 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1335 memcpy(&subbuffer[12], subQData, 12);
1339 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1341 static long CALLBACK ISOreadTrack(unsigned char *time) {
1342 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1344 if (cdHandle == NULL) {
1349 subChanMissing = FALSE;
1350 if (sector >= pregapOffset) {
1352 if (sector < pregapOffset)
1353 subChanMissing = TRUE;
1357 cdimg_read_func(cdHandle, cdbuffer, sector, 12);
1359 if (subHandle != NULL) {
1360 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1361 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1363 if (subChanRaw) DecodeRawSubData();
1370 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1371 // does NOT uses bcd format
1372 static long CALLBACK ISOplay(unsigned char *time) {
1373 unsigned int i, abs_sect;
1380 abs_sect = msf2sec((char *)time);
1381 for (i = numtracks; i > 1; i--)
1382 if (msf2sec(ti[i].start) <= abs_sect + 2 * 75)
1385 file_sect = ti[i].start_offset + (abs_sect - msf2sec(ti[i].start));
1389 // find the file that contains this track
1391 if (ti[i].handle != NULL)
1394 cdda_start_sector = abs_sect - file_sect;
1395 cddaHandle = ti[i].handle;
1397 if (pregapOffset && (unsigned int)(pregapOffset - file_sect) < 2 * 75) {
1398 // get out of the missing pregap to avoid noise
1399 file_sect = pregapOffset;
1402 if (SPU_playCDDAchannel != NULL) {
1403 startCDDA(file_sect);
1409 static long CALLBACK ISOstop(void) {
1414 // gets subchannel data
1415 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1416 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1423 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1426 CDR__getStatus(stat);
1430 stat->Status |= 0x80;
1436 sec = cdda_start_sector + cdda_cur_sector;
1437 sec2msf(sec, (char *)stat->Time);
1442 void cdrIsoInit(void) {
1444 CDR_shutdown = ISOshutdown;
1446 CDR_close = ISOclose;
1447 CDR_getTN = ISOgetTN;
1448 CDR_getTD = ISOgetTD;
1449 CDR_readTrack = ISOreadTrack;
1450 CDR_getBuffer = ISOgetBuffer;
1453 CDR_getBufferSub = ISOgetBufferSub;
1454 CDR_getStatus = ISOgetStatus;
1456 CDR_getDriveLetter = CDR__getDriveLetter;
1457 CDR_configure = CDR__configure;
1458 CDR_test = CDR__test;
1459 CDR_about = CDR__about;
1460 CDR_setfilename = CDR__setfilename;
1465 int cdrIsoActive(void) {
1466 return (cdHandle != NULL);