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