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