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"
31 #define strcasecmp _stricmp
39 unsigned int cdrIsoMultidiskCount;
40 unsigned int cdrIsoMultidiskSelect;
42 static FILE *cdHandle = NULL;
43 static FILE *cddaHandle = NULL;
44 static FILE *subHandle = NULL;
46 static boolean subChanMixed = FALSE;
47 static boolean subChanRaw = FALSE;
48 static boolean subChanMissing = FALSE;
50 static boolean multifile = FALSE;
52 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
53 static unsigned char subbuffer[SUB_FRAMESIZE];
55 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
57 #define CDDA_FRAMETIME (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
60 static HANDLE threadid;
62 static pthread_t threadid;
64 static unsigned int initial_offset = 0;
65 static boolean playing = FALSE;
66 static boolean cddaBigEndian = FALSE;
67 // cdda sectors in toc, byte offset in file
68 static unsigned int cdda_cur_sector;
69 static unsigned int cdda_first_sector;
70 static unsigned int cdda_file_offset;
71 /* Frame offset into CD image where pregap data would be found if it was there.
72 * If a game seeks there we must *not* return subchannel data since it's
73 * not in the CD image, so that cdrom code can fake subchannel data instead.
74 * XXX: there could be multiple pregaps but PSX dumps only have one? */
75 static unsigned int pregapOffset;
77 #define cddaCurPos cdda_cur_sector
79 // compressed image stuff
81 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
82 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
83 unsigned int *index_table;
84 unsigned int index_len;
85 unsigned int block_shift;
86 unsigned int current_block;
87 unsigned int sector_in_blk;
90 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
92 char* CALLBACK CDR__getDriveLetter(void);
93 long CALLBACK CDR__configure(void);
94 long CALLBACK CDR__test(void);
95 void CALLBACK CDR__about(void);
96 long CALLBACK CDR__setfilename(char *filename);
97 long CALLBACK CDR__getStatus(struct CdrStat *stat);
99 static void DecodeRawSubData(void);
102 enum {DATA=1, CDDA} type;
103 char start[3]; // MSF-format
104 char length[3]; // MSF-format
105 FILE *handle; // for multi-track images CDDA
106 unsigned int start_offset; // byte offset from start of above file
109 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
111 static int numtracks = 0;
112 static struct trackinfo ti[MAXTRACKS];
114 // get a sector from a msf-array
115 static unsigned int msf2sec(char *msf) {
116 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
119 static void sec2msf(unsigned int s, char *msf) {
120 msf[0] = s / 75 / 60;
121 s = s - msf[0] * 75 * 60;
127 // divide a string of xx:yy:zz into m, s, f
128 static void tok2msf(char *time, char *msf) {
131 token = strtok(time, ":");
133 msf[0] = atoi(token);
139 token = strtok(NULL, ":");
141 msf[1] = atoi(token);
147 token = strtok(NULL, ":");
149 msf[2] = atoi(token);
157 static long GetTickCount(void) {
158 static time_t initial_time = 0;
161 gettimeofday(&now, NULL);
163 if (initial_time == 0) {
164 initial_time = now.tv_sec;
167 return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
171 // this thread plays audio data
173 static void playthread(void *param)
175 static void *playthread(void *param)
178 long osleep, d, t, i, s;
180 int ret = 0, sector_offs;
186 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
187 sector_offs = cdda_cur_sector - cdda_first_sector;
188 if (sector_offs < 0) {
189 d = CD_FRAMESIZE_RAW;
190 memset(sndbuffer + s, 0, d);
193 d = cdimg_read_func(cddaHandle, cdda_file_offset,
194 sndbuffer + s, sector_offs);
195 if (d < CD_FRAMESIZE_RAW)
209 if (!cdr.Muted && playing) {
211 for (i = 0; i < s / 2; i++) {
212 tmp = sndbuffer[i * 2];
213 sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
214 sndbuffer[i * 2 + 1] = tmp;
218 // can't do it yet due to readahead..
219 //cdrAttenuate((short *)sndbuffer, s / 4, 1);
221 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
224 } while (ret == 0x7761 && playing); // rearmed_wait
227 if (ret != 0x676f) { // !rearmed_go
231 // HACK: stop feeding data while emu is paused
233 while (stop && playing)
236 now = GetTickCount();
242 else if (osleep > CDDA_FRAMETIME) {
243 osleep = CDDA_FRAMETIME;
247 usleep(osleep * 1000);
261 // stop the CDDA playback
262 static void stopCDDA() {
269 WaitForSingleObject(threadid, INFINITE);
271 pthread_join(threadid, NULL);
275 // start the CDDA playback
276 static void startCDDA(void) {
284 threadid = (HANDLE)_beginthread(playthread, 0, NULL);
286 pthread_create(&threadid, NULL, playthread, NULL);
290 // this function tries to get the .toc file of the given .bin
291 // the necessary data is put into the ti (trackinformation)-array
292 static int parsetoc(const char *isofile) {
293 char tocname[MAXPATHLEN];
295 char linebuf[256], tmp[256], name[256];
297 char time[20], time2[20];
298 unsigned int t, sector_offs, sector_size;
299 unsigned int current_zero_gap = 0;
303 // copy name of the iso and change extension from .bin to .toc
304 strncpy(tocname, isofile, sizeof(tocname));
305 tocname[MAXPATHLEN - 1] = '\0';
306 if (strlen(tocname) >= 4) {
307 strcpy(tocname + strlen(tocname) - 4, ".toc");
313 if ((fi = fopen(tocname, "r")) == NULL) {
314 // try changing extension to .cue (to satisfy some stupid tutorials)
315 strcpy(tocname + strlen(tocname) - 4, ".cue");
316 if ((fi = fopen(tocname, "r")) == NULL) {
317 // if filename is image.toc.bin, try removing .bin (for Brasero)
318 strcpy(tocname, isofile);
320 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
321 tocname[t - 4] = '\0';
322 if ((fi = fopen(tocname, "r")) == NULL) {
332 memset(&ti, 0, sizeof(ti));
333 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
335 sector_size = CD_FRAMESIZE_RAW;
336 sector_offs = 2 * 75;
338 // parse the .toc file
339 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
341 strncpy(tmp, linebuf, sizeof(linebuf));
342 token = strtok(tmp, " ");
344 if (token == NULL) continue;
346 if (!strcmp(token, "TRACK")) {
347 sector_offs += current_zero_gap;
348 current_zero_gap = 0;
351 token = strtok(NULL, " ");
354 if (!strncmp(token, "MODE2_RAW", 9)) {
355 ti[numtracks].type = DATA;
356 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
358 // check if this image contains mixed subchannel data
359 token = strtok(NULL, " ");
360 if (token != NULL && !strncmp(token, "RW", 2)) {
361 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
363 if (!strncmp(token, "RW_RAW", 6))
367 else if (!strncmp(token, "AUDIO", 5)) {
368 ti[numtracks].type = CDDA;
371 else if (!strcmp(token, "DATAFILE")) {
372 if (ti[numtracks].type == CDDA) {
373 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
374 ti[numtracks].start_offset = t;
375 t = t / sector_size + sector_offs;
376 sec2msf(t, (char *)&ti[numtracks].start);
377 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
380 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
381 tok2msf((char *)&time, (char *)&ti[numtracks].length);
384 else if (!strcmp(token, "FILE")) {
385 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
386 tok2msf((char *)&time, (char *)&ti[numtracks].start);
387 t += msf2sec(ti[numtracks].start) * sector_size;
388 ti[numtracks].start_offset = t;
389 t = t / sector_size + sector_offs;
390 sec2msf(t, (char *)&ti[numtracks].start);
391 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
393 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
394 // skip unneeded optional fields
395 while (token != NULL) {
396 token = strtok(NULL, " ");
397 if (strchr(token, ':') != NULL)
402 current_zero_gap = msf2sec(tmp);
405 t = ti[numtracks - 1].start_offset;
407 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
410 else if (!strcmp(token, "START")) {
411 token = strtok(NULL, " ");
412 if (token != NULL && strchr(token, ':')) {
415 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
416 t = msf2sec(ti[numtracks].start) + t;
417 sec2msf(t, (char *)&ti[numtracks].start);
427 // this function tries to get the .cue file of the given .bin
428 // the necessary data is put into the ti (trackinformation)-array
429 static int parsecue(const char *isofile) {
430 char cuename[MAXPATHLEN];
431 char filepath[MAXPATHLEN];
437 char linebuf[256], tmpb[256], dummy[256];
438 unsigned int incue_max_len;
439 unsigned int t, file_len, mode, sector_offs;
440 unsigned int sector_size = 2352;
444 // copy name of the iso and change extension from .bin to .cue
445 strncpy(cuename, isofile, sizeof(cuename));
446 cuename[MAXPATHLEN - 1] = '\0';
447 if (strlen(cuename) >= 4) {
448 strcpy(cuename + strlen(cuename) - 4, ".cue");
454 if ((fi = fopen(cuename, "r")) == NULL) {
458 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
459 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
461 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
462 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
463 // Don't proceed further, as this is actually a .toc file rather
466 return parsetoc(isofile);
468 fseek(fi, 0, SEEK_SET);
471 // build a path for files referenced in .cue
472 strncpy(filepath, cuename, sizeof(filepath));
473 tmp = strrchr(filepath, '/') + 1;
475 tmp = strrchr(filepath, '\\') + 1;
479 filepath[sizeof(filepath) - 1] = 0;
481 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
483 memset(&ti, 0, sizeof(ti));
486 sector_offs = 2 * 75;
488 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
489 strncpy(dummy, linebuf, sizeof(linebuf));
490 token = strtok(dummy, " ");
496 if (!strcmp(token, "TRACK")) {
500 if (strstr(linebuf, "AUDIO") != NULL) {
501 ti[numtracks].type = CDDA;
504 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, §or_size) == 3)
505 ti[numtracks].type = DATA;
507 SysPrintf(".cue: failed to parse TRACK\n");
508 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
510 if (sector_size == 0)
513 else if (!strcmp(token, "INDEX")) {
514 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
515 SysPrintf(".cue: failed to parse INDEX\n");
516 tok2msf(time, (char *)&ti[numtracks].start);
518 t = msf2sec(ti[numtracks].start);
519 ti[numtracks].start_offset = t * sector_size;
521 sec2msf(t, ti[numtracks].start);
523 // default track length to file length
524 t = file_len - ti[numtracks].start_offset / sector_size;
525 sec2msf(t, ti[numtracks].length);
527 if (numtracks > 1 && ti[numtracks].handle == NULL) {
528 // this track uses the same file as the last,
529 // start of this track is last track's end
530 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
531 sec2msf(t, ti[numtracks - 1].length);
533 if (numtracks > 1 && pregapOffset == -1)
534 pregapOffset = ti[numtracks].start_offset / sector_size;
536 else if (!strcmp(token, "PREGAP")) {
537 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
538 tok2msf(time, dummy);
539 sector_offs += msf2sec(dummy);
541 pregapOffset = -1; // mark to fill track start_offset
543 else if (!strcmp(token, "FILE")) {
544 t = sscanf(linebuf, " FILE \"%256[^\"]\"", tmpb);
546 sscanf(linebuf, " FILE %256s", tmpb);
549 ti[numtracks + 1].handle = fopen(tmpb, "rb");
550 if (ti[numtracks + 1].handle == NULL) {
552 tmp = strrchr(tmpb, '\\');
554 tmp = strrchr(tmpb, '/');
559 strncpy(incue_fname, tmp, incue_max_len);
560 ti[numtracks + 1].handle = fopen(filepath, "rb");
563 // update global offset if this is not first file in this .cue
564 if (numtracks + 1 > 1) {
566 sector_offs += file_len;
570 if (ti[numtracks + 1].handle == NULL) {
571 SysPrintf(_("\ncould not open: %s\n"), filepath);
574 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
575 file_len = ftell(ti[numtracks + 1].handle) / 2352;
577 if (numtracks == 0 && strlen(isofile) >= 4 &&
578 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
580 // user selected .cue as image file, use it's data track instead
582 cdHandle = fopen(filepath, "rb");
592 // this function tries to get the .ccd file of the given .img
593 // the necessary data is put into the ti (trackinformation)-array
594 static int parseccd(const char *isofile) {
595 char ccdname[MAXPATHLEN];
602 // copy name of the iso and change extension from .img to .ccd
603 strncpy(ccdname, isofile, sizeof(ccdname));
604 ccdname[MAXPATHLEN - 1] = '\0';
605 if (strlen(ccdname) >= 4) {
606 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
612 if ((fi = fopen(ccdname, "r")) == NULL) {
616 memset(&ti, 0, sizeof(ti));
618 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
619 if (!strncmp(linebuf, "[TRACK", 6)){
622 else if (!strncmp(linebuf, "MODE=", 5)) {
623 sscanf(linebuf, "MODE=%d", &t);
624 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
626 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
627 sscanf(linebuf, "INDEX 1=%d", &t);
628 sec2msf(t + 2 * 75, ti[numtracks].start);
629 ti[numtracks].start_offset = t * 2352;
631 // If we've already seen another track, this is its end
633 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
634 sec2msf(t, ti[numtracks - 1].length);
641 // Fill out the last track's end based on size
642 if (numtracks >= 1) {
643 fseek(cdHandle, 0, SEEK_END);
644 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
645 sec2msf(t, ti[numtracks].length);
651 // this function tries to get the .mds file of the given .mdf
652 // the necessary data is put into the ti (trackinformation)-array
653 static int parsemds(const char *isofile) {
654 char mdsname[MAXPATHLEN];
656 unsigned int offset, extra_offset, l, i;
661 // copy name of the iso and change extension from .mdf to .mds
662 strncpy(mdsname, isofile, sizeof(mdsname));
663 mdsname[MAXPATHLEN - 1] = '\0';
664 if (strlen(mdsname) >= 4) {
665 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
671 if ((fi = fopen(mdsname, "rb")) == NULL) {
675 memset(&ti, 0, sizeof(ti));
677 // check if it's a valid mds file
678 fread(&i, 1, sizeof(unsigned int), fi);
680 if (i != 0x4944454D) {
681 // not an valid mds file
686 // get offset to session block
687 fseek(fi, 0x50, SEEK_SET);
688 fread(&offset, 1, sizeof(unsigned int), fi);
689 offset = SWAP32(offset);
691 // get total number of tracks
693 fseek(fi, offset, SEEK_SET);
694 fread(&s, 1, sizeof(unsigned short), fi);
698 // get offset to track blocks
699 fseek(fi, 4, SEEK_CUR);
700 fread(&offset, 1, sizeof(unsigned int), fi);
701 offset = SWAP32(offset);
705 fseek(fi, offset + 4, SEEK_SET);
706 if (fgetc(fi) < 0xA0) {
712 // check if the image contains mixed subchannel data
713 fseek(fi, offset + 1, SEEK_SET);
714 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
717 for (i = 1; i <= numtracks; i++) {
718 fseek(fi, offset, SEEK_SET);
720 // get the track type
721 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
722 fseek(fi, 8, SEEK_CUR);
724 // get the track starting point
725 ti[i].start[0] = fgetc(fi);
726 ti[i].start[1] = fgetc(fi);
727 ti[i].start[2] = fgetc(fi);
729 fread(&extra_offset, 1, sizeof(unsigned int), fi);
730 extra_offset = SWAP32(extra_offset);
732 // get track start offset (in .mdf)
733 fseek(fi, offset + 0x28, SEEK_SET);
734 fread(&l, 1, sizeof(unsigned int), fi);
736 ti[i].start_offset = l;
739 fseek(fi, extra_offset, SEEK_SET);
740 fread(&l, 1, sizeof(unsigned int), fi);
743 pregapOffset = msf2sec(ti[i].start);
745 // get the track length
746 fread(&l, 1, sizeof(unsigned int), fi);
748 sec2msf(l, ti[i].length);
757 static int handlepbp(const char *isofile) {
760 unsigned int dontcare[8];
761 unsigned int psar_offs;
774 unsigned int dontcare[6];
777 unsigned int t, cd_length, cdimg_base;
778 unsigned int offsettab[8], psisoimg_offs;
779 const char *ext = NULL;
782 if (strlen(isofile) >= 4)
783 ext = isofile + strlen(isofile) - 4;
784 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
789 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
790 if (ret != sizeof(pbp_hdr)) {
791 SysPrintf("failed to read pbp\n");
795 ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
797 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
801 psisoimg_offs = pbp_hdr.psar_offs;
802 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
804 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
806 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
808 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
812 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
813 SysPrintf("failed to read offsettab\n");
817 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
818 if (offsettab[i] == 0)
821 cdrIsoMultidiskCount = i;
822 if (cdrIsoMultidiskCount == 0) {
823 SysPrintf("multidisk eboot has 0 images?\n");
827 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
828 cdrIsoMultidiskSelect = 0;
830 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
832 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
834 SysPrintf("failed to seek to %x\n", psisoimg_offs);
838 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
842 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
843 SysPrintf("bad psar_sig: %s\n", psar_sig);
848 ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
850 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
854 // first 3 entries are special
855 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
856 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
857 numtracks = btoi(toc_entry.index1[0]);
859 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
860 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
861 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
863 for (i = 1; i <= numtracks; i++) {
864 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
866 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
868 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
869 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
870 ti[i].start_offset *= 2352;
871 ti[i].start[0] = btoi(toc_entry.index1[0]);
872 ti[i].start[1] = btoi(toc_entry.index1[1]);
873 ti[i].start[2] = btoi(toc_entry.index1[2]);
876 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
877 sec2msf(t, ti[i - 1].length);
880 t = cd_length - ti[numtracks].start_offset / 2352;
881 sec2msf(t, ti[numtracks].length);
884 ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
886 SysPrintf("failed to seek to ISO index\n");
890 compr_img = calloc(1, sizeof(*compr_img));
891 if (compr_img == NULL)
894 compr_img->block_shift = 4;
895 compr_img->current_block = (unsigned int)-1;
897 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
898 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
899 if (compr_img->index_table == NULL)
902 cdimg_base = psisoimg_offs + 0x100000;
903 for (i = 0; i < compr_img->index_len; i++) {
904 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
905 if (ret != sizeof(index_entry)) {
906 SysPrintf("failed to read index_entry #%d\n", i);
910 if (index_entry.size == 0)
913 compr_img->index_table[i] = cdimg_base + index_entry.offset;
915 compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
920 free(compr_img->index_table);
921 compr_img->index_table = NULL;
923 if (compr_img != NULL) {
930 static int handlecbin(const char *isofile) {
934 unsigned int header_size;
935 unsigned long long total_bytes;
936 unsigned int block_size;
937 unsigned char ver; // 1
939 unsigned char rsv_06[2];
941 const char *ext = NULL;
942 unsigned int index = 0, plain;
945 if (strlen(isofile) >= 5)
946 ext = isofile + strlen(isofile) - 5;
947 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
950 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
951 if (ret != sizeof(ciso_hdr)) {
952 SysPrintf("failed to read ciso header\n");
956 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
957 SysPrintf("bad ciso header\n");
960 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
961 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
963 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
968 compr_img = calloc(1, sizeof(*compr_img));
969 if (compr_img == NULL)
972 compr_img->block_shift = 0;
973 compr_img->current_block = (unsigned int)-1;
975 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
976 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
977 if (compr_img->index_table == NULL)
980 ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
981 if (ret != compr_img->index_len) {
982 SysPrintf("failed to read index table\n");
986 for (i = 0; i < compr_img->index_len + 1; i++) {
987 index = compr_img->index_table[i];
988 plain = index & 0x80000000;
990 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
992 if ((long long)index << ciso_hdr.align >= 0x80000000ll)
993 SysPrintf("warning: ciso img too large, expect problems\n");
998 free(compr_img->index_table);
999 compr_img->index_table = NULL;
1001 if (compr_img != NULL) {
1008 // this function tries to get the .sub file of the given .img
1009 static int opensubfile(const char *isoname) {
1010 char subname[MAXPATHLEN];
1012 // copy name of the iso and change extension from .img to .sub
1013 strncpy(subname, isoname, sizeof(subname));
1014 subname[MAXPATHLEN - 1] = '\0';
1015 if (strlen(subname) >= 4) {
1016 strcpy(subname + strlen(subname) - 4, ".sub");
1022 subHandle = fopen(subname, "rb");
1023 if (subHandle == NULL) {
1030 static int opensbifile(const char *isoname) {
1031 char sbiname[MAXPATHLEN];
1034 strncpy(sbiname, isoname, sizeof(sbiname));
1035 sbiname[MAXPATHLEN - 1] = '\0';
1036 if (strlen(sbiname) >= 4) {
1037 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1043 fseek(cdHandle, 0, SEEK_END);
1044 s = ftell(cdHandle) / 2352;
1046 return LoadSBI(sbiname, s);
1049 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1051 fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1052 return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1055 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1059 fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1060 ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1061 fread(subbuffer, 1, SUB_FRAMESIZE, f);
1063 if (subChanRaw) DecodeRawSubData();
1068 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1073 if (z.zalloc == NULL) {
1074 // XXX: one-time leak here..
1080 ret = inflateInit2(&z, -15);
1083 ret = inflateReset(&z);
1088 z.avail_in = in_size;
1090 z.avail_out = *out_size;
1092 ret = inflate(&z, Z_NO_FLUSH);
1095 *out_size -= z.avail_out;
1096 return ret == 1 ? 0 : ret;
1099 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1101 unsigned long cdbuffer_size, cdbuffer_size_expect;
1102 unsigned int start_byte, size;
1107 sector += base / 2352;
1109 block = sector >> compr_img->block_shift;
1110 compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1112 if (block == compr_img->current_block) {
1113 //printf("hit sect %d\n", sector);
1117 if (sector >= compr_img->index_len * 16) {
1118 SysPrintf("sector %d is past img end\n", sector);
1122 start_byte = compr_img->index_table[block] & 0x7fffffff;
1123 if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1124 SysPrintf("seek error for block %d at %x: ",
1130 is_compressed = !(compr_img->index_table[block] & 0x80000000);
1131 size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1132 if (size > sizeof(compr_img->buff_compressed)) {
1133 SysPrintf("block %d is too large: %u\n", block, size);
1137 if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1138 1, size, cdHandle) != size) {
1139 SysPrintf("read error for block %d at %x: ", block, start_byte);
1144 if (is_compressed) {
1145 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1146 cdbuffer_size = cdbuffer_size_expect;
1147 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1149 SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1150 ret, block, sector);
1153 if (cdbuffer_size != cdbuffer_size_expect)
1154 SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1155 cdbuffer_size_expect, sector);
1159 compr_img->current_block = block;
1162 if (dest != cdbuffer) // copy avoid HACK
1163 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1165 return CD_FRAMESIZE_RAW;
1168 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1172 fseek(f, base + sector * 2048, SEEK_SET);
1173 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1175 // not really necessary, fake mode 2 header
1176 memset(cdbuffer, 0, 12 * 2);
1177 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1178 cdbuffer[12 + 3] = 1;
1183 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1184 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1187 static unsigned char * CALLBACK ISOgetBuffer(void) {
1188 return cdbuffer + 12;
1191 static void PrintTracks(void) {
1194 for (i = 1; i <= numtracks; i++) {
1195 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1196 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1197 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1198 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1202 // This function is invoked by the front-end when opening an ISO
1203 // file for playback
1204 static long CALLBACK ISOopen(void) {
1205 boolean isMode1ISO = FALSE;
1207 if (cdHandle != NULL) {
1208 return 0; // it's already open
1211 cdHandle = fopen(GetIsoFile(), "rb");
1212 if (cdHandle == NULL) {
1216 SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1218 cddaBigEndian = FALSE;
1219 subChanMixed = FALSE;
1222 cdrIsoMultidiskCount = 1;
1225 CDR_getBuffer = ISOgetBuffer;
1226 cdimg_read_func = cdread_normal;
1228 if (parsecue(GetIsoFile()) == 0) {
1229 SysPrintf("[+cue]");
1231 else if (parsetoc(GetIsoFile()) == 0) {
1232 SysPrintf("[+toc]");
1234 else if (parseccd(GetIsoFile()) == 0) {
1235 SysPrintf("[+ccd]");
1237 else if (parsemds(GetIsoFile()) == 0) {
1238 SysPrintf("[+mds]");
1240 if (handlepbp(GetIsoFile()) == 0) {
1242 CDR_getBuffer = ISOgetBuffer_compr;
1243 cdimg_read_func = cdread_compressed;
1245 else if (handlecbin(GetIsoFile()) == 0) {
1246 SysPrintf("[cbin]");
1247 CDR_getBuffer = ISOgetBuffer_compr;
1248 cdimg_read_func = cdread_compressed;
1251 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1252 SysPrintf("[+sub]");
1254 if (opensbifile(GetIsoFile()) == 0) {
1255 SysPrintf("[+sbi]");
1258 // guess whether it is mode1/2048
1259 fseek(cdHandle, 0, SEEK_END);
1260 if (ftell(cdHandle) % 2048 == 0) {
1261 unsigned int modeTest = 0;
1262 fseek(cdHandle, 0, SEEK_SET);
1263 fread(&modeTest, 4, 1, cdHandle);
1264 if (SWAP32(modeTest) != 0xffffff00) {
1265 SysPrintf("[2048]");
1269 fseek(cdHandle, 0, SEEK_SET);
1276 cdimg_read_func = cdread_sub_mixed;
1277 else if (isMode1ISO)
1278 cdimg_read_func = cdread_2048;
1280 // make sure we have another handle open for cdda
1281 if (numtracks > 1 && ti[1].handle == NULL) {
1282 ti[1].handle = fopen(GetIsoFile(), "rb");
1284 cdda_cur_sector = 0;
1285 cdda_file_offset = 0;
1290 static long CALLBACK ISOclose(void) {
1293 if (cdHandle != NULL) {
1297 if (subHandle != NULL) {
1304 if (compr_img != NULL) {
1305 free(compr_img->index_table);
1310 for (i = 1; i <= numtracks; i++) {
1311 if (ti[i].handle != NULL) {
1312 fclose(ti[i].handle);
1313 ti[i].handle = NULL;
1322 static long CALLBACK ISOinit(void) {
1323 assert(cdHandle == NULL);
1324 assert(subHandle == NULL);
1326 return 0; // do nothing
1329 static long CALLBACK ISOshutdown(void) {
1334 // return Starting and Ending Track
1336 // byte 0 - start track
1337 // byte 1 - end track
1338 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1341 if (numtracks > 0) {
1342 buffer[1] = numtracks;
1351 // return Track Time
1356 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1359 unsigned char time[3];
1360 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1361 sec2msf(sect, (char *)time);
1362 buffer[2] = time[0];
1363 buffer[1] = time[1];
1364 buffer[0] = time[2];
1366 else if (numtracks > 0 && track <= numtracks) {
1367 buffer[2] = ti[track].start[0];
1368 buffer[1] = ti[track].start[1];
1369 buffer[0] = ti[track].start[2];
1380 // decode 'raw' subchannel data ripped by cdrdao
1381 static void DecodeRawSubData(void) {
1382 unsigned char subQData[12];
1385 memset(subQData, 0, sizeof(subQData));
1387 for (i = 0; i < 8 * 12; i++) {
1388 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1389 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1393 memcpy(&subbuffer[12], subQData, 12);
1397 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1399 static long CALLBACK ISOreadTrack(unsigned char *time) {
1400 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1402 if (cdHandle == NULL) {
1407 subChanMissing = FALSE;
1408 if (sector >= pregapOffset) {
1410 if (sector < pregapOffset)
1411 subChanMissing = TRUE;
1415 cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1417 if (subHandle != NULL) {
1418 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1419 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1421 if (subChanRaw) DecodeRawSubData();
1428 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1429 // does NOT uses bcd format
1430 static long CALLBACK ISOplay(unsigned char *time) {
1437 cdda_cur_sector = msf2sec((char *)time);
1438 for (i = numtracks; i > 1; i--) {
1439 cdda_first_sector = msf2sec(ti[i].start);
1440 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1443 cdda_file_offset = ti[i].start_offset;
1445 // find the file that contains this track
1447 if (ti[i].handle != NULL)
1450 cddaHandle = ti[i].handle;
1452 if (SPU_playCDDAchannel != NULL)
1459 static long CALLBACK ISOstop(void) {
1464 // gets subchannel data
1465 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1466 if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1473 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1476 CDR__getStatus(stat);
1480 stat->Status |= 0x80;
1483 // BIOS - boot ID (CD type)
1484 stat->Type = ti[1].type;
1487 // relative -> absolute time
1489 sec2msf(sect, (char *)stat->Time);
1494 // read CDDA sector into buffer
1495 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1496 unsigned char msf[3] = {m, s, f};
1497 unsigned int file, track, track_start = 0;
1500 cddaCurPos = msf2sec((char *)msf);
1502 // find current track index
1503 for (track = numtracks; ; track--) {
1504 track_start = msf2sec(ti[track].start);
1505 if (track_start <= cddaCurPos)
1511 // data tracks play silent
1512 if (ti[track].type != CDDA) {
1513 memset(buffer, 0, CD_FRAMESIZE_RAW);
1519 // find the file that contains this track
1520 for (file = track; file > 1; file--)
1521 if (ti[file].handle != NULL)
1525 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1526 buffer, cddaCurPos - track_start);
1527 if (ret != CD_FRAMESIZE_RAW) {
1528 memset(buffer, 0, CD_FRAMESIZE_RAW);
1532 if (cddaBigEndian) {
1536 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1537 tmp = buffer[i * 2];
1538 buffer[i * 2] = buffer[i * 2 + 1];
1539 buffer[i * 2 + 1] = tmp;
1546 void cdrIsoInit(void) {
1548 CDR_shutdown = ISOshutdown;
1550 CDR_close = ISOclose;
1551 CDR_getTN = ISOgetTN;
1552 CDR_getTD = ISOgetTD;
1553 CDR_readTrack = ISOreadTrack;
1554 CDR_getBuffer = ISOgetBuffer;
1557 CDR_getBufferSub = ISOgetBufferSub;
1558 CDR_getStatus = ISOgetStatus;
1559 CDR_readCDDA = ISOreadCDDA;
1561 CDR_getDriveLetter = CDR__getDriveLetter;
1562 CDR_configure = CDR__configure;
1563 CDR_test = CDR__test;
1564 CDR_about = CDR__about;
1565 CDR_setfilename = CDR__setfilename;
1570 int cdrIsoActive(void) {
1571 return (cdHandle != NULL);