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