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