4c4bff6f4086db1c15ce3a6be07857f2505b249b
[pcsx_rearmed.git] / libpcsxcore / cdriso.c
1 /***************************************************************************
2  *   Copyright (C) 2007 PCSX-df Team                                       *
3  *   Copyright (C) 2009 Wei Mingzhi                                        *
4  *   Copyright (C) 2012 notaz                                              *
5  *                                                                         *
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.                                   *
10  *                                                                         *
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.                          *
15  *                                                                         *
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  ***************************************************************************/
21
22 #include "psxcommon.h"
23 #include "cdrom.h"
24 #include "cdriso.h"
25 #include "ppf.h"
26
27 #include <errno.h>
28 #include <zlib.h>
29 #ifdef HAVE_CHD
30 #include <libchdr/chd.h>
31 #endif
32
33 #ifdef _WIN32
34 #define strcasecmp _stricmp
35 #else
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #endif
40
41 #ifdef USE_LIBRETRO_VFS
42 #include <streams/file_stream_transforms.h>
43 #undef fseeko
44 #undef ftello
45 #undef rewind
46 #define ftello rftell
47 #define fseeko rfseek
48 #define rewind(f_) rfseek(f_, 0, SEEK_SET)
49 #endif
50
51 #define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
52
53 unsigned int cdrIsoMultidiskCount;
54 unsigned int cdrIsoMultidiskSelect;
55
56 static FILE *cdHandle = NULL;
57 static FILE *subHandle = NULL;
58
59 static boolean subChanMixed = FALSE;
60 static boolean subChanRaw = FALSE;
61
62 static boolean multifile = FALSE;
63
64 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
65
66 static boolean cddaBigEndian = FALSE;
67 /* Frame offset into CD image where pregap data would be found if it was there.
68  * If a game seeks there we must *not* return subchannel data since it's
69  * not in the CD image, so that cdrom code can fake subchannel data instead.
70  * XXX: there could be multiple pregaps but PSX dumps only have one? */
71 static unsigned int pregapOffset;
72
73 // compressed image stuff
74 static struct {
75         unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
76         unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
77         off_t *index_table;
78         unsigned int index_len;
79         unsigned int block_shift;
80         unsigned int current_block;
81         unsigned int sector_in_blk;
82 } *compr_img;
83
84 #ifdef HAVE_CHD
85 static struct {
86         unsigned char *buffer;
87         chd_file* chd;
88         const chd_header* header;
89         unsigned int sectors_per_hunk;
90         unsigned int current_hunk[2];
91         unsigned int current_buffer;
92         unsigned int sector_in_hunk;
93 } *chd_img;
94 #else
95 #define chd_img 0
96 #endif
97
98 static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
99 static int (*cdimg_read_sub_func)(FILE *f, int sector, void *dest);
100
101 static void DecodeRawSubData(unsigned char *subbuffer);
102
103 struct trackinfo {
104         enum {DATA=1, CDDA} type;
105         char start[3];          // MSF-format
106         char length[3];         // MSF-format
107         FILE *handle;           // for multi-track images CDDA
108         unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
109 };
110
111 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
112
113 static int numtracks = 0;
114 static struct trackinfo ti[MAXTRACKS];
115
116 // get a sector from a msf-array
117 static unsigned int msf2sec(const void *msf_) {
118         const unsigned char *msf = msf_;
119         return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
120 }
121
122 static void sec2msf(unsigned int s, void *msf_) {
123         unsigned char *msf = msf_;
124         msf[0] = s / 75 / 60;
125         s = s - msf[0] * 75 * 60;
126         msf[1] = s / 75;
127         s = s - msf[1] * 75;
128         msf[2] = s;
129 }
130
131 // divide a string of xx:yy:zz into m, s, f
132 static void tok2msf(char *time, char *msf) {
133         char *token;
134
135         token = strtok(time, ":");
136         if (token) {
137                 msf[0] = atoi(token);
138         }
139         else {
140                 msf[0] = 0;
141         }
142
143         token = strtok(NULL, ":");
144         if (token) {
145                 msf[1] = atoi(token);
146         }
147         else {
148                 msf[1] = 0;
149         }
150
151         token = strtok(NULL, ":");
152         if (token) {
153                 msf[2] = atoi(token);
154         }
155         else {
156                 msf[2] = 0;
157         }
158 }
159
160 static off_t get_size(FILE *f)
161 {
162         off_t old, size;
163 #if !defined(USE_LIBRETRO_VFS)
164         struct stat st;
165         if (fstat(fileno(f), &st) == 0)
166                 return st.st_size;
167 #endif
168         old = ftello(f);
169         fseeko(f, 0, SEEK_END);
170         size = ftello(f);
171         fseeko(f, old, SEEK_SET);
172         return size;
173 }
174
175 // Some c libs like newlib default buffering to just 1k which is less than
176 // cd sector size which is bad for performance.
177 // Note that NULL setvbuf() is implemented differently by different libs
178 // (newlib mallocs a buffer of given size and glibc ignores size and uses it's own).
179 static void set_static_stdio_buffer(FILE *f)
180 {
181 #if !defined(fopen) // no stdio redirect
182         static char buf[16 * 1024];
183         if (f) {
184                 int r;
185                 errno = 0;
186                 r = setvbuf(f, buf, _IOFBF, sizeof(buf));
187                 if (r)
188                         SysPrintf("cdriso: setvbuf %d %d\n", r, errno);
189         }
190 #endif
191 }
192
193 // this function tries to get the .toc file of the given .bin
194 // the necessary data is put into the ti (trackinformation)-array
195 static int parsetoc(const char *isofile) {
196         char                    tocname[MAXPATHLEN];
197         FILE                    *fi;
198         char                    linebuf[256], tmp[256], name[256];
199         char                    *token;
200         char                    time[20], time2[20];
201         unsigned int    t, sector_offs, sector_size;
202         unsigned int    current_zero_gap = 0;
203
204         numtracks = 0;
205
206         // copy name of the iso and change extension from .bin to .toc
207         strncpy(tocname, isofile, sizeof(tocname));
208         tocname[MAXPATHLEN - 1] = '\0';
209         if (strlen(tocname) >= 4) {
210                 strcpy(tocname + strlen(tocname) - 4, ".toc");
211         }
212         else {
213                 return -1;
214         }
215
216         if ((fi = fopen(tocname, "r")) == NULL) {
217                 // try changing extension to .cue (to satisfy some stupid tutorials)
218                 strcpy(tocname + strlen(tocname) - 4, ".cue");
219                 if ((fi = fopen(tocname, "r")) == NULL) {
220                         // if filename is image.toc.bin, try removing .bin (for Brasero)
221                         strcpy(tocname, isofile);
222                         t = strlen(tocname);
223                         if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
224                                 tocname[t - 4] = '\0';
225                                 if ((fi = fopen(tocname, "r")) == NULL) {
226                                         return -1;
227                                 }
228                         }
229                         else {
230                                 return -1;
231                         }
232                 }
233                 // check if it's really a TOC named as a .cue
234                 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
235                 token = strtok(linebuf, " ");
236                 if (token && strncmp(token, "CD", 2) != 0) {
237                        // && strcmp(token, "CATALOG") != 0) - valid for a real .cue
238                         fclose(fi);
239                         return -1;
240                 }
241                 }
242                 fseek(fi, 0, SEEK_SET);
243         }
244
245         memset(&ti, 0, sizeof(ti));
246         cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
247
248         sector_size = CD_FRAMESIZE_RAW;
249         sector_offs = 2 * 75;
250
251         // parse the .toc file
252         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
253                 // search for tracks
254                 strncpy(tmp, linebuf, sizeof(linebuf));
255                 token = strtok(tmp, " ");
256
257                 if (token == NULL) continue;
258
259                 if (!strcmp(token, "TRACK")) {
260                         sector_offs += current_zero_gap;
261                         current_zero_gap = 0;
262
263                         // get type of track
264                         token = strtok(NULL, " ");
265                         numtracks++;
266
267                         if (!strncmp(token, "MODE2_RAW", 9)) {
268                                 ti[numtracks].type = DATA;
269                                 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
270
271                                 // check if this image contains mixed subchannel data
272                                 token = strtok(NULL, " ");
273                                 if (token != NULL && !strncmp(token, "RW", 2)) {
274                                         sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
275                                         subChanMixed = TRUE;
276                                         if (!strncmp(token, "RW_RAW", 6))
277                                                 subChanRaw = TRUE;
278                                 }
279                         }
280                         else if (!strncmp(token, "AUDIO", 5)) {
281                                 ti[numtracks].type = CDDA;
282                         }
283                 }
284                 else if (!strcmp(token, "DATAFILE")) {
285                         if (ti[numtracks].type == CDDA) {
286                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
287                                 ti[numtracks].start_offset = t;
288                                 t = t / sector_size + sector_offs;
289                                 sec2msf(t, (char *)&ti[numtracks].start);
290                                 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
291                         }
292                         else {
293                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
294                                 tok2msf((char *)&time, (char *)&ti[numtracks].length);
295                         }
296                 }
297                 else if (!strcmp(token, "FILE")) {
298                         sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
299                         tok2msf((char *)&time, (char *)&ti[numtracks].start);
300                         t += msf2sec(ti[numtracks].start) * sector_size;
301                         ti[numtracks].start_offset = t;
302                         t = t / sector_size + sector_offs;
303                         sec2msf(t, (char *)&ti[numtracks].start);
304                         tok2msf((char *)&time2, (char *)&ti[numtracks].length);
305                 }
306                 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
307                         // skip unneeded optional fields
308                         while (token != NULL) {
309                                 token = strtok(NULL, " ");
310                                 if (strchr(token, ':') != NULL)
311                                         break;
312                         }
313                         if (token != NULL) {
314                                 tok2msf(token, tmp);
315                                 current_zero_gap = msf2sec(tmp);
316                         }
317                         if (numtracks > 1) {
318                                 t = ti[numtracks - 1].start_offset;
319                                 t /= sector_size;
320                                 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
321                         }
322                 }
323                 else if (!strcmp(token, "START")) {
324                         token = strtok(NULL, " ");
325                         if (token != NULL && strchr(token, ':')) {
326                                 tok2msf(token, tmp);
327                                 t = msf2sec(tmp);
328                                 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
329                                 t = msf2sec(ti[numtracks].start) + t;
330                                 sec2msf(t, (char *)&ti[numtracks].start);
331                         }
332                 }
333         }
334
335         fclose(fi);
336
337         return 0;
338 }
339
340 // this function tries to get the .cue file of the given .bin
341 // the necessary data is put into the ti (trackinformation)-array
342 static int parsecue(const char *isofile) {
343         char                    cuename[MAXPATHLEN];
344         char                    filepath[MAXPATHLEN];
345         char                    *incue_fname;
346         FILE                    *fi;
347         FILE                    *ftmp = NULL;
348         char                    *token;
349         char                    time[20];
350         char                    *tmp;
351         char                    linebuf[256], tmpb[256], dummy[256];
352         unsigned int    incue_max_len;
353         unsigned int    t, file_len, mode, sector_offs;
354         unsigned int    sector_size = 2352;
355
356         numtracks = 0;
357
358         // copy name of the iso and change extension from .bin to .cue
359         strncpy(cuename, isofile, sizeof(cuename));
360         cuename[MAXPATHLEN - 1] = '\0';
361         if (strlen(cuename) < 4)
362                 return -1;
363         if (strcasecmp(cuename + strlen(cuename) - 4, ".cue") == 0) {
364                 // it's already open as cdHandle
365                 fi = cdHandle;
366         }
367         else {
368                 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
369                 //  and don't try to search the additional .cue file
370                 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
371                         strcpy(cuename + strlen(cuename) - 4, ".cue");
372
373                 if ((ftmp = fopen(cuename, "r")) == NULL)
374                         return -1;
375                 fi = ftmp;
376         }
377
378         // Some stupid tutorials wrongly tell users to use cdrdao to rip a
379         // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
380         // that...
381         if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
382                 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
383                         // Don't proceed further, as this is actually a .toc file rather
384                         // than a .cue file.
385                         if (ftmp)
386                                 fclose(ftmp);
387                         return parsetoc(isofile);
388                 }
389                 rewind(fi);
390         }
391
392         // build a path for files referenced in .cue
393         strncpy(filepath, cuename, sizeof(filepath));
394         tmp = strrchr(filepath, '/');
395         if (tmp == NULL)
396                 tmp = strrchr(filepath, '\\');
397         if (tmp != NULL)
398                 tmp++;
399         else
400                 tmp = filepath;
401         *tmp = 0;
402         filepath[sizeof(filepath) - 1] = 0;
403         incue_fname = tmp;
404         incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
405
406         memset(&ti, 0, sizeof(ti));
407
408         file_len = 0;
409         sector_offs = 2 * 75;
410
411         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
412                 strncpy(dummy, linebuf, sizeof(linebuf));
413                 token = strtok(dummy, " ");
414
415                 if (token == NULL) {
416                         continue;
417                 }
418
419                 if (!strcmp(token, "TRACK")) {
420                         numtracks++;
421
422                         sector_size = 0;
423                         if (strstr(linebuf, "AUDIO") != NULL) {
424                                 ti[numtracks].type = CDDA;
425                                 sector_size = 2352;
426                         }
427                         else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, &sector_size) == 3)
428                                 ti[numtracks].type = DATA;
429                         else {
430                                 SysPrintf(".cue: failed to parse TRACK\n");
431                                 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
432                         }
433                         if (sector_size == 0)
434                                 sector_size = 2352;
435                 }
436                 else if (!strcmp(token, "INDEX")) {
437                         if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
438                                 SysPrintf(".cue: failed to parse INDEX\n");
439                         tok2msf(time, (char *)&ti[numtracks].start);
440
441                         t = msf2sec(ti[numtracks].start);
442                         ti[numtracks].start_offset = t * sector_size;
443                         t += sector_offs;
444                         sec2msf(t, ti[numtracks].start);
445
446                         // default track length to file length
447                         t = file_len - ti[numtracks].start_offset / sector_size;
448                         sec2msf(t, ti[numtracks].length);
449
450                         if (numtracks > 1 && ti[numtracks].handle == NULL) {
451                                 // this track uses the same file as the last,
452                                 // start of this track is last track's end
453                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
454                                 sec2msf(t, ti[numtracks - 1].length);
455                         }
456                         if (numtracks > 1 && pregapOffset == -1)
457                                 pregapOffset = ti[numtracks].start_offset / sector_size;
458                 }
459                 else if (!strcmp(token, "PREGAP")) {
460                         if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
461                                 tok2msf(time, dummy);
462                                 sector_offs += msf2sec(dummy);
463                         }
464                         pregapOffset = -1; // mark to fill track start_offset
465                 }
466                 else if (!strcmp(token, "FILE")) {
467                         t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
468                         if (t != 1)
469                                 sscanf(linebuf, " FILE %255s", tmpb);
470
471                         // absolute path?
472                         ti[numtracks + 1].handle = fopen(tmpb, "rb");
473                         if (ti[numtracks + 1].handle == NULL) {
474                                 // relative to .cue?
475                                 tmp = strrchr(tmpb, '\\');
476                                 if (tmp == NULL)
477                                         tmp = strrchr(tmpb, '/');
478                                 if (tmp != NULL)
479                                         tmp++;
480                                 else
481                                         tmp = tmpb;
482                                 strncpy(incue_fname, tmp, incue_max_len);
483                                 ti[numtracks + 1].handle = fopen(filepath, "rb");
484                         }
485
486                         // update global offset if this is not first file in this .cue
487                         if (numtracks + 1 > 1) {
488                                 multifile = 1;
489                                 sector_offs += file_len;
490                         }
491
492                         file_len = 0;
493                         if (ti[numtracks + 1].handle == NULL) {
494                                 SysPrintf(_("\ncould not open: %s\n"), filepath);
495                                 continue;
496                         }
497                         file_len = get_size(ti[numtracks + 1].handle) / 2352;
498                 }
499         }
500
501         if (ftmp)
502                 fclose(ftmp);
503
504         // if there are no tracks detected, then it's not a cue file
505         if (!numtracks)
506                 return -1;
507
508         // the data track handle is always in cdHandle
509         if (ti[1].handle) {
510                 fclose(cdHandle);
511                 cdHandle = ti[1].handle;
512                 ti[1].handle = NULL;
513                 set_static_stdio_buffer(cdHandle);
514         }
515         return 0;
516 }
517
518 // this function tries to get the .ccd file of the given .img
519 // the necessary data is put into the ti (trackinformation)-array
520 static int parseccd(const char *isofile) {
521         char                    ccdname[MAXPATHLEN];
522         FILE                    *fi;
523         char                    linebuf[256];
524         unsigned int    t;
525
526         numtracks = 0;
527
528         // copy name of the iso and change extension from .img to .ccd
529         strncpy(ccdname, isofile, sizeof(ccdname));
530         ccdname[MAXPATHLEN - 1] = '\0';
531         if (strlen(ccdname) >= 4) {
532                 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
533         }
534         else {
535                 return -1;
536         }
537
538         if ((fi = fopen(ccdname, "r")) == NULL) {
539                 return -1;
540         }
541
542         memset(&ti, 0, sizeof(ti));
543
544         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
545                 if (!strncmp(linebuf, "[TRACK", 6)){
546                         numtracks++;
547                 }
548                 else if (!strncmp(linebuf, "MODE=", 5)) {
549                         sscanf(linebuf, "MODE=%d", &t);
550                         ti[numtracks].type = ((t == 0) ? CDDA : DATA);
551                 }
552                 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
553                         sscanf(linebuf, "INDEX 1=%d", &t);
554                         sec2msf(t + 2 * 75, ti[numtracks].start);
555                         ti[numtracks].start_offset = t * 2352;
556
557                         // If we've already seen another track, this is its end
558                         if (numtracks > 1) {
559                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
560                                 sec2msf(t, ti[numtracks - 1].length);
561                         }
562                 }
563         }
564
565         fclose(fi);
566
567         // Fill out the last track's end based on size
568         if (numtracks >= 1) {
569                 t = get_size(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
570                 sec2msf(t, ti[numtracks].length);
571         }
572
573         return 0;
574 }
575
576 // this function tries to get the .mds file of the given .mdf
577 // the necessary data is put into the ti (trackinformation)-array
578 static int parsemds(const char *isofile) {
579         char                    mdsname[MAXPATHLEN];
580         FILE                    *fi;
581         unsigned int    offset, extra_offset, l, i;
582         unsigned short  s;
583
584         numtracks = 0;
585
586         // copy name of the iso and change extension from .mdf to .mds
587         strncpy(mdsname, isofile, sizeof(mdsname));
588         mdsname[MAXPATHLEN - 1] = '\0';
589         if (strlen(mdsname) >= 4) {
590                 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
591         }
592         else {
593                 return -1;
594         }
595
596         if ((fi = fopen(mdsname, "rb")) == NULL) {
597                 return -1;
598         }
599
600         memset(&ti, 0, sizeof(ti));
601
602         // check if it's a valid mds file
603         if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
604                 goto fail_io;
605         i = SWAP32(i);
606         if (i != 0x4944454D) {
607                 // not an valid mds file
608                 fclose(fi);
609                 return -1;
610         }
611
612         // get offset to session block
613         fseek(fi, 0x50, SEEK_SET);
614         if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
615                 goto fail_io;
616         offset = SWAP32(offset);
617
618         // get total number of tracks
619         offset += 14;
620         fseek(fi, offset, SEEK_SET);
621         if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
622                 goto fail_io;
623         s = SWAP16(s);
624         numtracks = s;
625
626         // get offset to track blocks
627         fseek(fi, 4, SEEK_CUR);
628         if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
629                 goto fail_io;
630         offset = SWAP32(offset);
631
632         // skip lead-in data
633         while (1) {
634                 fseek(fi, offset + 4, SEEK_SET);
635                 if (fgetc(fi) < 0xA0) {
636                         break;
637                 }
638                 offset += 0x50;
639         }
640
641         // check if the image contains mixed subchannel data
642         fseek(fi, offset + 1, SEEK_SET);
643         subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
644
645         // read track data
646         for (i = 1; i <= numtracks; i++) {
647                 fseek(fi, offset, SEEK_SET);
648
649                 // get the track type
650                 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
651                 fseek(fi, 8, SEEK_CUR);
652
653                 // get the track starting point
654                 ti[i].start[0] = fgetc(fi);
655                 ti[i].start[1] = fgetc(fi);
656                 ti[i].start[2] = fgetc(fi);
657
658                 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
659                         goto fail_io;
660                 extra_offset = SWAP32(extra_offset);
661
662                 // get track start offset (in .mdf)
663                 fseek(fi, offset + 0x28, SEEK_SET);
664                 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
665                         goto fail_io;
666                 l = SWAP32(l);
667                 ti[i].start_offset = l;
668
669                 // get pregap
670                 fseek(fi, extra_offset, SEEK_SET);
671                 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
672                         goto fail_io;
673                 l = SWAP32(l);
674                 if (l != 0 && i > 1)
675                         pregapOffset = msf2sec(ti[i].start);
676
677                 // get the track length
678                 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
679                         goto fail_io;
680                 l = SWAP32(l);
681                 sec2msf(l, ti[i].length);
682
683                 offset += 0x50;
684         }
685         fclose(fi);
686         return 0;
687 fail_io:
688 #ifndef NDEBUG
689         SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
690 #endif
691         fclose(fi);
692         return -1;
693 }
694
695 static int handlepbp(const char *isofile) {
696         struct {
697                 unsigned int sig;
698                 unsigned int dontcare[8];
699                 unsigned int psar_offs;
700         } pbp_hdr;
701         struct {
702                 unsigned char type;
703                 unsigned char pad0;
704                 unsigned char track;
705                 char index0[3];
706                 char pad1;
707                 char index1[3];
708         } toc_entry;
709         struct {
710                 unsigned int offset;
711                 unsigned int size;
712                 unsigned int dontcare[6];
713         } index_entry;
714         char psar_sig[11];
715         off_t psisoimg_offs, cdimg_base;
716         unsigned int t, cd_length;
717         unsigned int offsettab[8];
718         unsigned int psar_offs, index_entry_size, index_entry_offset;
719         const char *ext = NULL;
720         int i, ret;
721
722         if (strlen(isofile) >= 4)
723                 ext = isofile + strlen(isofile) - 4;
724         if (ext == NULL || strcasecmp(ext, ".pbp") != 0)
725                 return -1;
726
727         numtracks = 0;
728
729         ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
730         if (ret != sizeof(pbp_hdr)) {
731                 SysPrintf("failed to read pbp\n");
732                 goto fail_io;
733         }
734
735         psar_offs = SWAP32(pbp_hdr.psar_offs);
736
737         ret = fseeko(cdHandle, psar_offs, SEEK_SET);
738         if (ret != 0) {
739                 SysPrintf("failed to seek to %x\n", psar_offs);
740                 goto fail_io;
741         }
742
743         psisoimg_offs = psar_offs;
744         if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
745                 goto fail_io;
746         psar_sig[10] = 0;
747         if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
748                 // multidisk image?
749                 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
750                 if (ret != 0) {
751                         SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
752                         goto fail_io;
753                 }
754
755                 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
756                         SysPrintf("failed to read offsettab\n");
757                         goto fail_io;
758                 }
759
760                 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
761                         if (offsettab[i] == 0)
762                                 break;
763                 }
764                 cdrIsoMultidiskCount = i;
765                 if (cdrIsoMultidiskCount == 0) {
766                         SysPrintf("multidisk eboot has 0 images?\n");
767                         goto fail_io;
768                 }
769
770                 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
771                         cdrIsoMultidiskSelect = 0;
772
773                 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
774
775                 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
776                 if (ret != 0) {
777                         SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
778                         goto fail_io;
779                 }
780
781                 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
782                         goto fail_io;
783                 psar_sig[10] = 0;
784         }
785
786         if (strcmp(psar_sig, "PSISOIMG00") != 0) {
787                 SysPrintf("bad psar_sig: %s\n", psar_sig);
788                 goto fail_io;
789         }
790
791         // seek to TOC
792         ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
793         if (ret != 0) {
794                 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
795                 goto fail_io;
796         }
797
798         // first 3 entries are special
799         fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
800         if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
801                 goto fail_io;
802         numtracks = btoi(toc_entry.index1[0]);
803
804         if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
805                 goto fail_io;
806         cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
807                 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
808
809         for (i = 1; i <= numtracks; i++) {
810                 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
811                         goto fail_io;
812
813                 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
814
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_offset *= 2352;
818                 ti[i].start[0] = btoi(toc_entry.index1[0]);
819                 ti[i].start[1] = btoi(toc_entry.index1[1]);
820                 ti[i].start[2] = btoi(toc_entry.index1[2]);
821
822                 if (i > 1) {
823                         t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
824                         sec2msf(t, ti[i - 1].length);
825                 }
826         }
827         t = cd_length - ti[numtracks].start_offset / 2352;
828         sec2msf(t, ti[numtracks].length);
829
830         // seek to ISO index
831         ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
832         if (ret != 0) {
833                 SysPrintf("failed to seek to ISO index\n");
834                 goto fail_io;
835         }
836
837         compr_img = calloc(1, sizeof(*compr_img));
838         if (compr_img == NULL)
839                 goto fail_io;
840
841         compr_img->block_shift = 4;
842         compr_img->current_block = (unsigned int)-1;
843
844         compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
845         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
846         if (compr_img->index_table == NULL)
847                 goto fail_io;
848
849         cdimg_base = psisoimg_offs + 0x100000;
850         for (i = 0; i < compr_img->index_len; i++) {
851                 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
852                 if (ret != sizeof(index_entry)) {
853                         SysPrintf("failed to read index_entry #%d\n", i);
854                         goto fail_index;
855                 }
856
857                 index_entry_size = SWAP32(index_entry.size);
858                 index_entry_offset = SWAP32(index_entry.offset);
859
860                 if (index_entry_size == 0)
861                         break;
862
863                 compr_img->index_table[i] = cdimg_base + index_entry_offset;
864         }
865         compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
866
867         return 0;
868
869 fail_index:
870         free(compr_img->index_table);
871         compr_img->index_table = NULL;
872         goto done;
873
874 fail_io:
875         SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
876         rewind(cdHandle);
877
878 done:
879         if (compr_img != NULL) {
880                 free(compr_img);
881                 compr_img = NULL;
882         }
883         return -1;
884 }
885
886 static int handlecbin(const char *isofile) {
887         struct
888         {
889                 char magic[4];
890                 unsigned int header_size;
891                 unsigned long long total_bytes;
892                 unsigned int block_size;
893                 unsigned char ver;              // 1
894                 unsigned char align;
895                 unsigned char rsv_06[2];
896         } ciso_hdr;
897         const char *ext = NULL;
898         unsigned int *index_table = NULL;
899         unsigned int index = 0, plain;
900         int i, ret;
901
902         if (strlen(isofile) >= 5)
903                 ext = isofile + strlen(isofile) - 5;
904         if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
905                 return -1;
906
907         ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
908         if (ret != sizeof(ciso_hdr)) {
909                 SysPrintf("failed to read ciso header\n");
910                 goto fail_io;
911         }
912
913         if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
914                 SysPrintf("bad ciso header\n");
915                 goto fail_io;
916         }
917         if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
918                 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
919                 if (ret != 0) {
920                         SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
921                         goto fail_io;
922                 }
923         }
924
925         compr_img = calloc(1, sizeof(*compr_img));
926         if (compr_img == NULL)
927                 goto fail_io;
928
929         compr_img->block_shift = 0;
930         compr_img->current_block = (unsigned int)-1;
931
932         compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
933         index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
934         if (index_table == NULL)
935                 goto fail_io;
936
937         ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
938         if (ret != compr_img->index_len) {
939                 SysPrintf("failed to read index table\n");
940                 goto fail_index;
941         }
942
943         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
944         if (compr_img->index_table == NULL)
945                 goto fail_index;
946
947         for (i = 0; i < compr_img->index_len + 1; i++) {
948                 index = index_table[i];
949                 plain = index & 0x80000000;
950                 index &= 0x7fffffff;
951                 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
952                 if (plain)
953                         compr_img->index_table[i] |= OFF_T_MSB;
954         }
955
956         return 0;
957
958 fail_index:
959         free(index_table);
960 fail_io:
961         if (compr_img != NULL) {
962                 free(compr_img);
963                 compr_img = NULL;
964         }
965         rewind(cdHandle);
966         return -1;
967 }
968
969 #ifdef HAVE_CHD
970 static int handlechd(const char *isofile) {
971         int frame_offset = 150;
972         int file_offset = 0;
973         int is_chd_ext = 0;
974         chd_error err;
975
976         if (strlen(isofile) >= 3) {
977                 const char *ext = isofile + strlen(isofile) - 3;
978                 is_chd_ext = !strcasecmp(ext, "chd");
979         }
980         chd_img = calloc(1, sizeof(*chd_img));
981         if (chd_img == NULL)
982                 goto fail_io;
983
984         err = chd_open_file(cdHandle, CHD_OPEN_READ, NULL, &chd_img->chd);
985         if (err != CHDERR_NONE) {
986                 if (is_chd_ext)
987                         SysPrintf("chd_open: %d\n", err);
988                 goto fail_io;
989         }
990
991         if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
992                 goto fail_io;
993
994         chd_img->header = chd_get_header(chd_img->chd);
995
996         chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
997         if (chd_img->buffer == NULL)
998                 goto fail_io;
999
1000         chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1001         chd_img->current_hunk[0] = (unsigned int)-1;
1002         chd_img->current_hunk[1] = (unsigned int)-1;
1003
1004         cddaBigEndian = TRUE;
1005
1006         numtracks = 0;
1007         memset(ti, 0, sizeof(ti));
1008
1009         while (1)
1010         {
1011                 struct {
1012                         char type[64];
1013                         char subtype[32];
1014                         char pgtype[32];
1015                         char pgsub[32];
1016                         uint32_t track;
1017                         uint32_t frames;
1018                         uint32_t pregap;
1019                         uint32_t postgap;
1020                 } md = {};
1021                 char meta[256];
1022                 uint32_t meta_size = 0;
1023
1024                 if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA2_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1025                         sscanf(meta, CDROM_TRACK_METADATA2_FORMAT, &md.track, md.type, md.subtype, &md.frames, &md.pregap, md.pgtype, md.pgsub, &md.postgap);
1026                 else if (chd_get_metadata(chd_img->chd, CDROM_TRACK_METADATA_TAG, numtracks, meta, sizeof(meta), &meta_size, NULL, NULL) == CHDERR_NONE)
1027                         sscanf(meta, CDROM_TRACK_METADATA_FORMAT, &md.track, md.type, md.subtype, &md.frames);
1028                 else
1029                         break;
1030
1031                 SysPrintf("chd: %s\n", meta);
1032
1033                 if (md.track == 1) {
1034                         if (!strncmp(md.subtype, "RW", 2)) {
1035                                 subChanMixed = TRUE;
1036                                 if (!strcmp(md.subtype, "RW_RAW"))
1037                                         subChanRaw = TRUE;
1038                         }
1039                 }
1040
1041                 ti[md.track].type = !strncmp(md.type, "AUDIO", 5) ? CDDA : DATA;
1042
1043                 sec2msf(frame_offset + md.pregap, ti[md.track].start);
1044                 sec2msf(md.frames, ti[md.track].length);
1045
1046                 ti[md.track].start_offset = file_offset + md.pregap;
1047
1048                 // XXX: what about postgap?
1049                 frame_offset += md.frames;
1050                 file_offset += md.frames;
1051                 numtracks++;
1052         }
1053
1054         if (numtracks)
1055                 return 0;
1056
1057 fail_io:
1058         if (chd_img != NULL) {
1059                 free(chd_img->buffer);
1060                 free(chd_img);
1061                 chd_img = NULL;
1062         }
1063         return -1;
1064 }
1065 #endif
1066
1067 // this function tries to get the .sub file of the given .img
1068 static int opensubfile(const char *isoname) {
1069         char            subname[MAXPATHLEN];
1070
1071         // copy name of the iso and change extension from .img to .sub
1072         strncpy(subname, isoname, sizeof(subname));
1073         subname[MAXPATHLEN - 1] = '\0';
1074         if (strlen(subname) >= 4) {
1075                 strcpy(subname + strlen(subname) - 4, ".sub");
1076         }
1077         else {
1078                 return -1;
1079         }
1080
1081         subHandle = fopen(subname, "rb");
1082         if (subHandle == NULL)
1083                 return -1;
1084
1085         return 0;
1086 }
1087
1088 static int opensbifile(const char *isoname) {
1089         char            sbiname[MAXPATHLEN], disknum[MAXPATHLEN] = "0";
1090         int             s;
1091
1092         strncpy(sbiname, isoname, sizeof(sbiname));
1093         sbiname[MAXPATHLEN - 1] = '\0';
1094         if (strlen(sbiname) >= 4) {
1095                 if (cdrIsoMultidiskCount > 1) {
1096                         sprintf(disknum, "_%i.sbi", cdrIsoMultidiskSelect + 1);
1097                         strcpy(sbiname + strlen(sbiname) - 4, disknum);
1098                 }
1099                 else
1100                         strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1101         }
1102         else {
1103                 return -1;
1104         }
1105
1106         s = msf2sec(ti[1].length);
1107
1108         return LoadSBI(sbiname, s);
1109 }
1110
1111 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1112 {
1113         int ret;
1114         if (!f)
1115                 return -1;
1116         if (!dest)
1117                 dest = cdbuffer;
1118         if (fseeko(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET))
1119                 goto fail_io;
1120         ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1121         if (ret <= 0)
1122                 goto fail_io;
1123         return ret;
1124
1125 fail_io:
1126         // often happens in cdda gaps of a split cue/bin, so not logged
1127         //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1128         return -1;
1129 }
1130
1131 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1132 {
1133         int ret;
1134
1135         if (!f)
1136                 return -1;
1137         if (!dest)
1138                 dest = cdbuffer;
1139         if (fseeko(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET))
1140                 goto fail_io;
1141         ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1142         if (ret <= 0)
1143                 goto fail_io;
1144         return ret;
1145
1146 fail_io:
1147         //SysPrintf("File IO error %d, base %u, sector %u\n", errno, base, sector);
1148         return -1;
1149 }
1150
1151 static int cdread_sub_sub_mixed(FILE *f, int sector, void *buffer)
1152 {
1153         if (!f)
1154                 return -1;
1155         if (fseeko(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + CD_FRAMESIZE_RAW, SEEK_SET))
1156                 goto fail_io;
1157         if (fread(buffer, 1, SUB_FRAMESIZE, f) != SUB_FRAMESIZE)
1158                 goto fail_io;
1159
1160         return 0;
1161
1162 fail_io:
1163         SysPrintf("subchannel: file IO error %d, sector %u\n", errno, sector);
1164         return -1;
1165 }
1166
1167 static int uncompress2_pcsx(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1168 {
1169         static z_stream z;
1170         int ret = 0;
1171
1172         if (z.zalloc == NULL) {
1173                 // XXX: one-time leak here..
1174                 z.next_in = Z_NULL;
1175                 z.avail_in = 0;
1176                 z.zalloc = Z_NULL;
1177                 z.zfree = Z_NULL;
1178                 z.opaque = Z_NULL;
1179                 ret = inflateInit2(&z, -15);
1180         }
1181         else
1182                 ret = inflateReset(&z);
1183         if (ret != Z_OK)
1184                 return ret;
1185
1186         z.next_in = in;
1187         z.avail_in = in_size;
1188         z.next_out = out;
1189         z.avail_out = *out_size;
1190
1191         ret = inflate(&z, Z_NO_FLUSH);
1192         //inflateEnd(&z);
1193
1194         *out_size -= z.avail_out;
1195         return ret == 1 ? 0 : ret;
1196 }
1197
1198 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1199 {
1200         unsigned long cdbuffer_size, cdbuffer_size_expect;
1201         unsigned int size;
1202         int is_compressed;
1203         off_t start_byte;
1204         int ret, block;
1205
1206         if (!cdHandle)
1207                 return -1;
1208         if (base)
1209                 sector += base / 2352;
1210
1211         block = sector >> compr_img->block_shift;
1212         compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1213
1214         if (block == compr_img->current_block) {
1215                 //printf("hit sect %d\n", sector);
1216                 goto finish;
1217         }
1218
1219         if (sector >= compr_img->index_len * 16) {
1220                 SysPrintf("sector %d is past img end\n", sector);
1221                 return -1;
1222         }
1223
1224         start_byte = compr_img->index_table[block] & ~OFF_T_MSB;
1225         if (fseeko(cdHandle, start_byte, SEEK_SET) != 0) {
1226                 SysPrintf("seek error for block %d at %llx: ",
1227                         block, (long long)start_byte);
1228                 perror(NULL);
1229                 return -1;
1230         }
1231
1232         is_compressed = !(compr_img->index_table[block] & OFF_T_MSB);
1233         size = (compr_img->index_table[block + 1] & ~OFF_T_MSB) - start_byte;
1234         if (size > sizeof(compr_img->buff_compressed)) {
1235                 SysPrintf("block %d is too large: %u\n", block, size);
1236                 return -1;
1237         }
1238
1239         if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1240                                 1, size, cdHandle) != size) {
1241                 SysPrintf("read error for block %d at %lx: ", block, (long)start_byte);
1242                 perror(NULL);
1243                 return -1;
1244         }
1245
1246         if (is_compressed) {
1247                 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1248                 cdbuffer_size = cdbuffer_size_expect;
1249                 ret = uncompress2_pcsx(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1250                 if (ret != 0) {
1251                         SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1252                                         ret, block, sector);
1253                         return -1;
1254                 }
1255                 if (cdbuffer_size != cdbuffer_size_expect)
1256                         SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1257                                         cdbuffer_size_expect, sector);
1258         }
1259
1260         // done at last!
1261         compr_img->current_block = block;
1262
1263 finish:
1264         if (dest != NULL)
1265                 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1266                         CD_FRAMESIZE_RAW);
1267         return CD_FRAMESIZE_RAW;
1268 }
1269
1270 #ifdef HAVE_CHD
1271 static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1272 {
1273         return chd_img->buffer
1274                 + current_buffer * chd_img->header->hunkbytes
1275                 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1276 }
1277
1278 static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1279 {
1280         int hunk;
1281
1282         sector += base;
1283
1284         hunk = sector / chd_img->sectors_per_hunk;
1285         chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1286
1287         if (hunk == chd_img->current_hunk[0])
1288                 chd_img->current_buffer = 0;
1289         else if (hunk == chd_img->current_hunk[1])
1290                 chd_img->current_buffer = 1;
1291         else
1292         {
1293                 chd_read(chd_img->chd, hunk, chd_img->buffer +
1294                         chd_img->current_buffer * chd_img->header->hunkbytes);
1295                 chd_img->current_hunk[chd_img->current_buffer] = hunk;
1296         }
1297
1298         if (dest != NULL)
1299                 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
1300                         CD_FRAMESIZE_RAW);
1301         return CD_FRAMESIZE_RAW;
1302 }
1303
1304 static int cdread_sub_chd(FILE *f, int sector, void *buffer_ptr)
1305 {
1306         unsigned int sector_in_hunk;
1307         unsigned int buffer;
1308         int hunk;
1309
1310         if (!subChanMixed)
1311                 return -1;
1312
1313         hunk = sector / chd_img->sectors_per_hunk;
1314         sector_in_hunk = sector % chd_img->sectors_per_hunk;
1315
1316         if (hunk == chd_img->current_hunk[0])
1317                 buffer = 0;
1318         else if (hunk == chd_img->current_hunk[1])
1319                 buffer = 1;
1320         else
1321         {
1322                 buffer = chd_img->current_buffer ^ 1;
1323                 chd_read(chd_img->chd, hunk, chd_img->buffer +
1324                         buffer * chd_img->header->hunkbytes);
1325                 chd_img->current_hunk[buffer] = hunk;
1326         }
1327
1328         memcpy(buffer_ptr, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
1329         return 0;
1330 }
1331 #endif
1332
1333 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1334 {
1335         unsigned char *dst = dest ? dest : cdbuffer;
1336         int ret;
1337
1338         if (!f)
1339                 return -1;
1340
1341         fseeko(f, base + sector * 2048, SEEK_SET);
1342         ret = fread(dst + 12 * 2, 1, 2048, f);
1343
1344         // not really necessary, fake mode 2 header
1345         memset(dst, 0, 12 * 2);
1346         sec2msf(sector + 2 * 75, dst + 12);
1347         dst[12 + 0] = itob(dst[12 + 0]);
1348         dst[12 + 1] = itob(dst[12 + 1]);
1349         dst[12 + 2] = itob(dst[12 + 2]);
1350         dst[12 + 3] = 1;
1351
1352         return 12*2 + ret;
1353 }
1354
1355 static void * ISOgetBuffer_normal(void) {
1356        return cdbuffer + 12;
1357 }
1358
1359 static void * ISOgetBuffer_compr(void) {
1360        return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1361 }
1362
1363 #ifdef HAVE_CHD
1364 static void * ISOgetBuffer_chd(void) {
1365        return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
1366 }
1367 #endif
1368
1369 void * (*ISOgetBuffer)(void) = ISOgetBuffer_normal;
1370
1371 static void PrintTracks(void) {
1372         int i;
1373
1374         for (i = 1; i <= numtracks; i++) {
1375                 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1376                         i, (ti[i].type == DATA ? "DATA" :
1377                             (ti[i].type == CDDA ? "AUDIO" : "UNKNOWN")),
1378                         ti[i].start[0], ti[i].start[1], ti[i].start[2],
1379                         ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1380         }
1381 }
1382
1383 // This function is invoked by the front-end when opening an ISO
1384 // file for playback
1385 int ISOopen(const char *fname)
1386 {
1387         boolean isMode1ISO = FALSE;
1388         char alt_bin_filename[MAXPATHLEN];
1389         const char *bin_filename;
1390         char image_str[1024];
1391         off_t size_main;
1392
1393         if (cdHandle || chd_img) {
1394                 return 0; // it's already open
1395         }
1396
1397         cdHandle = fopen(fname, "rb");
1398         if (cdHandle == NULL) {
1399                 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1400                         fname, strerror(errno));
1401                 return -1;
1402         }
1403         set_static_stdio_buffer(cdHandle);
1404         size_main = get_size(cdHandle);
1405
1406         snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1407                 "Loaded CD Image: %s", fname);
1408
1409         cddaBigEndian = FALSE;
1410         subChanMixed = FALSE;
1411         subChanRaw = FALSE;
1412         pregapOffset = 0;
1413         cdrIsoMultidiskCount = 1;
1414         multifile = 0;
1415
1416         ISOgetBuffer = ISOgetBuffer_normal;
1417         cdimg_read_func = cdread_normal;
1418         cdimg_read_sub_func = NULL;
1419
1420         if (parsetoc(fname) == 0) {
1421                 strcat(image_str, "[+toc]");
1422         }
1423         else if (parseccd(fname) == 0) {
1424                 strcat(image_str, "[+ccd]");
1425         }
1426         else if (parsemds(fname) == 0) {
1427                 strcat(image_str, "[+mds]");
1428         }
1429         else if (parsecue(fname) == 0) {
1430                 strcat(image_str, "[+cue]");
1431         }
1432         if (handlepbp(fname) == 0) {
1433                 strcat(image_str, "[+pbp]");
1434                 ISOgetBuffer = ISOgetBuffer_compr;
1435                 cdimg_read_func = cdread_compressed;
1436         }
1437         else if (handlecbin(fname) == 0) {
1438                 strcat(image_str, "[+cbin]");
1439                 ISOgetBuffer = ISOgetBuffer_compr;
1440                 cdimg_read_func = cdread_compressed;
1441         }
1442 #ifdef HAVE_CHD
1443         else if (handlechd(fname) == 0) {
1444                 strcat(image_str, "[+chd]");
1445                 ISOgetBuffer = ISOgetBuffer_chd;
1446                 cdimg_read_func = cdread_chd;
1447                 cdimg_read_sub_func = cdread_sub_chd;
1448         }
1449 #endif
1450
1451         if (!subChanMixed && opensubfile(fname) == 0) {
1452                 strcat(image_str, "[+sub]");
1453         }
1454         if (opensbifile(fname) == 0) {
1455                 strcat(image_str, "[+sbi]");
1456         }
1457
1458         // maybe user selected metadata file instead of main .bin ..
1459         bin_filename = fname;
1460         if (cdHandle && size_main < 2352 * 0x10) {
1461                 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1462                 FILE *tmpf = NULL;
1463                 size_t i;
1464                 char *p;
1465
1466                 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1467                 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1468                 if (strlen(alt_bin_filename) >= 4) {
1469                         p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1470                         for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1471                                 strcpy(p, exts[i]);
1472                                 tmpf = fopen(alt_bin_filename, "rb");
1473                                 if (tmpf != NULL)
1474                                         break;
1475                         }
1476                 }
1477                 if (tmpf != NULL) {
1478                         bin_filename = alt_bin_filename;
1479                         fclose(cdHandle);
1480                         cdHandle = tmpf;
1481                         set_static_stdio_buffer(cdHandle);
1482                         size_main = get_size(cdHandle);
1483                 }
1484         }
1485
1486         // guess whether it is mode1/2048
1487         if (cdHandle && cdimg_read_func == cdread_normal && size_main % 2048 == 0) {
1488                 unsigned int modeTest = 0;
1489                 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
1490                         SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
1491                 }
1492                 if (SWAP32(modeTest) != 0xffffff00) {
1493                         strcat(image_str, "[2048]");
1494                         isMode1ISO = TRUE;
1495                 }
1496         }
1497
1498         SysPrintf("%s (%lld bytes).\n", image_str, (long long)size_main);
1499
1500         PrintTracks();
1501
1502         if (subChanMixed && cdimg_read_func == cdread_normal) {
1503                 cdimg_read_func = cdread_sub_mixed;
1504                 cdimg_read_sub_func = cdread_sub_sub_mixed;
1505         }
1506         else if (isMode1ISO) {
1507                 cdimg_read_func = cdread_2048;
1508                 cdimg_read_sub_func = NULL;
1509         }
1510
1511         return 0;
1512 }
1513
1514 int ISOclose(void)
1515 {
1516         int i;
1517
1518         if (cdHandle != NULL) {
1519                 fclose(cdHandle);
1520                 cdHandle = NULL;
1521         }
1522         if (subHandle != NULL) {
1523                 fclose(subHandle);
1524                 subHandle = NULL;
1525         }
1526
1527         if (compr_img != NULL) {
1528                 free(compr_img->index_table);
1529                 free(compr_img);
1530                 compr_img = NULL;
1531         }
1532
1533 #ifdef HAVE_CHD
1534         if (chd_img != NULL) {
1535                 chd_close(chd_img->chd);
1536                 free(chd_img->buffer);
1537                 free(chd_img);
1538                 chd_img = NULL;
1539         }
1540 #endif
1541
1542         for (i = 1; i <= numtracks; i++) {
1543                 if (ti[i].handle != NULL) {
1544                         fclose(ti[i].handle);
1545                         ti[i].handle = NULL;
1546                 }
1547         }
1548         numtracks = 0;
1549         ti[1].type = 0;
1550         UnloadSBI();
1551
1552         memset(cdbuffer, 0, sizeof(cdbuffer));
1553         ISOgetBuffer = ISOgetBuffer_normal;
1554
1555         return 0;
1556 }
1557
1558 int ISOinit(void)
1559 {
1560         assert(cdHandle == NULL);
1561         assert(subHandle == NULL);
1562         numtracks = 0;
1563
1564         return 0; // do nothing
1565 }
1566
1567 int ISOshutdown(void)
1568 {
1569         return ISOclose();
1570 }
1571
1572 // return Starting and Ending Track
1573 // buffer:
1574 //  byte 0 - start track
1575 //  byte 1 - end track
1576 int ISOgetTN(unsigned char *buffer)
1577 {
1578         buffer[0] = 1;
1579
1580         if (numtracks > 0) {
1581                 buffer[1] = numtracks;
1582         }
1583         else {
1584                 buffer[1] = 1;
1585         }
1586
1587         return 0;
1588 }
1589
1590 // return Track Time
1591 // buffer:
1592 //  byte 0 - minute
1593 //  byte 1 - second
1594 //  byte 2 - frame
1595 int ISOgetTD(int track, unsigned char *buffer)
1596 {
1597         if (track == 0) {
1598                 unsigned int sect;
1599                 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1600                 sec2msf(sect, buffer);
1601         }
1602         else if (numtracks > 0 && track <= numtracks) {
1603                 memcpy(buffer, ti[track].start, 3);
1604         }
1605         else {
1606                 buffer[2] = 0;
1607                 buffer[1] = 2;
1608                 buffer[0] = 0;
1609         }
1610
1611         return 0;
1612 }
1613
1614 // decode 'raw' subchannel data ripped by cdrdao
1615 static void DecodeRawSubData(unsigned char *subbuffer) {
1616         unsigned char subQData[12];
1617         int i;
1618
1619         memset(subQData, 0, sizeof(subQData));
1620
1621         for (i = 0; i < 8 * 12; i++) {
1622                 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1623                         subQData[i >> 3] |= (1 << (7 - (i & 7)));
1624                 }
1625         }
1626
1627         memcpy(&subbuffer[12], subQData, 12);
1628 }
1629
1630 // read track
1631 // time: byte 0 - minute; byte 1 - second; byte 2 - frame (non-bcd)
1632 // buf: if NULL, data is kept in internal buffer accessible by ISOgetBuffer()
1633 int ISOreadTrack(const unsigned char *time, void *buf)
1634 {
1635         int sector = msf2sec(time);
1636         long ret;
1637
1638         if (!cdHandle && !chd_img)
1639                 return -1;
1640
1641         if (numtracks > 1 && sector >= msf2sec(ti[2].start))
1642                 return ISOreadCDDA(time, buf);
1643
1644         sector -= 2 * 75;
1645         if (pregapOffset && sector >= pregapOffset)
1646                 sector -= 2 * 75;
1647
1648         ret = cdimg_read_func(cdHandle, 0, buf, sector);
1649         if (ret < 12*2 + 2048) {
1650                 if (buf && multifile && sector >= msf2sec(ti[1].length)) {
1651                         // assume a gap not backed by a file
1652                         memset(buf, 0, CD_FRAMESIZE_RAW);
1653                         return 0;
1654                 }
1655                 return -1;
1656         }
1657
1658         return 0;
1659 }
1660
1661 // read subchannel data
1662 int ISOreadSub(const unsigned char *time, void *buffer)
1663 {
1664         int ret, sector = MSF2SECT(time[0], time[1], time[2]);
1665
1666         if (pregapOffset && sector >= pregapOffset) {
1667                 sector -= 2 * 75;
1668                 if (sector < pregapOffset) // ?
1669                         return -1;
1670         }
1671
1672         if (cdimg_read_sub_func != NULL) {
1673                 if ((ret = cdimg_read_sub_func(cdHandle, sector, buffer)))
1674                         return ret;
1675         }
1676         else if (subHandle != NULL) {
1677                 if (fseeko(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1678                         return -1;
1679                 if (fread(buffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1680                         return -1;
1681         }
1682         else {
1683                 return -1;
1684         }
1685
1686         if (subChanRaw)
1687                 DecodeRawSubData(buffer);
1688         return 0;
1689 }
1690
1691 int ISOgetStatus(struct CdrStat *stat)
1692 {
1693         CDR__getStatus(stat);
1694         
1695         // BIOS - boot ID (CD type)
1696         stat->Type = ti[1].type;
1697         
1698         return 0;
1699 }
1700
1701 // read CDDA sector into buffer
1702 int ISOreadCDDA(const unsigned char *time, void *buffer)
1703 {
1704         unsigned int track, track_start = 0;
1705         FILE *handle = cdHandle;
1706         unsigned int cddaCurPos;
1707         int ret, ret_clear = -1;
1708
1709         cddaCurPos = msf2sec(time);
1710
1711         // find current track index
1712         for (track = numtracks; ; track--) {
1713                 track_start = msf2sec(ti[track].start);
1714                 if (track_start <= cddaCurPos)
1715                         break;
1716                 if (track == 1)
1717                         break;
1718         }
1719
1720         // data tracks play silent
1721         if (ti[track].type != CDDA) {
1722                 ret_clear = 0;
1723                 goto clear_return;
1724         }
1725
1726         if (multifile) {
1727                 // find the file that contains this track
1728                 unsigned int file;
1729                 for (file = track; file > 1; file--) {
1730                         if (ti[file].handle != NULL) {
1731                                 handle = ti[file].handle;
1732                                 break;
1733                         }
1734                 }
1735         }
1736         if (!handle && !chd_img)
1737                 goto clear_return;
1738
1739         ret = cdimg_read_func(handle, ti[track].start_offset,
1740                 buffer, cddaCurPos - track_start);
1741         if (ret != CD_FRAMESIZE_RAW) {
1742                 if (multifile && cddaCurPos - track_start >= msf2sec(ti[track].length))
1743                         ret_clear = 0; // gap
1744                 goto clear_return;
1745         }
1746
1747         if (cddaBigEndian && buffer) {
1748                 unsigned char tmp, *buf = buffer;
1749                 int i;
1750
1751                 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1752                         tmp = buf[i * 2];
1753                         buf[i * 2] = buf[i * 2 + 1];
1754                         buf[i * 2 + 1] = tmp;
1755                 }
1756         }
1757
1758         return 0;
1759
1760 clear_return:
1761         if (buffer)
1762                 memset(buffer, 0, CD_FRAMESIZE_RAW);
1763         return ret_clear;
1764 }