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