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