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