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