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