Attempt to avod build errors for Mingw
[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 #ifdef _WIN32
29 #define WIN32_LEAN_AND_MEAN
30 #include <process.h>
31 #include <windows.h>
32 #define strcasecmp _stricmp
33 #define usleep(x) (Sleep((x) / 1000))
34 #else
35 #include <pthread.h>
36 #include <sys/time.h>
37 #include <unistd.h>
38 #endif
39 #include <errno.h>
40 #include <zlib.h>
41
42 unsigned int cdrIsoMultidiskCount;
43 unsigned int cdrIsoMultidiskSelect;
44
45 static FILE *cdHandle = NULL;
46 static FILE *cddaHandle = NULL;
47 static FILE *subHandle = NULL;
48
49 static boolean subChanMixed = FALSE;
50 static boolean subChanRaw = FALSE;
51 static boolean subChanMissing = FALSE;
52
53 static boolean multifile = FALSE;
54
55 static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
56 static unsigned char subbuffer[SUB_FRAMESIZE];
57
58 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
59
60 #define CDDA_FRAMETIME                  (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
61
62 #ifdef _WIN32
63 static HANDLE threadid;
64 #else
65 static pthread_t threadid;
66 #endif
67 static unsigned int initial_offset = 0;
68 static boolean playing = FALSE;
69 static boolean cddaBigEndian = FALSE;
70 // cdda sectors in toc, byte offset in file
71 static unsigned int cdda_cur_sector;
72 static unsigned int cdda_first_sector;
73 static unsigned int cdda_file_offset;
74 /* Frame offset into CD image where pregap data would be found if it was there.
75  * If a game seeks there we must *not* return subchannel data since it's
76  * not in the CD image, so that cdrom code can fake subchannel data instead.
77  * XXX: there could be multiple pregaps but PSX dumps only have one? */
78 static unsigned int pregapOffset;
79
80 #define cddaCurPos cdda_cur_sector
81
82 // compressed image stuff
83 static struct {
84         unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
85         unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
86         unsigned int *index_table;
87         unsigned int index_len;
88         unsigned int block_shift;
89         unsigned int current_block;
90         unsigned int sector_in_blk;
91 } *compr_img;
92
93 int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
94
95 char* CALLBACK CDR__getDriveLetter(void);
96 long CALLBACK CDR__configure(void);
97 long CALLBACK CDR__test(void);
98 void CALLBACK CDR__about(void);
99 long CALLBACK CDR__setfilename(char *filename);
100 long CALLBACK CDR__getStatus(struct CdrStat *stat);
101
102 static void DecodeRawSubData(void);
103
104 struct trackinfo {
105         enum {DATA=1, CDDA} type;
106         char start[3];          // MSF-format
107         char length[3];         // MSF-format
108         FILE *handle;           // for multi-track images CDDA
109         unsigned int start_offset; // byte offset from start of above file
110 };
111
112 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
113
114 static int numtracks = 0;
115 static struct trackinfo ti[MAXTRACKS];
116
117 // get a sector from a msf-array
118 static unsigned int msf2sec(char *msf) {
119         return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
120 }
121
122 static void sec2msf(unsigned int s, char *msf) {
123         msf[0] = s / 75 / 60;
124         s = s - msf[0] * 75 * 60;
125         msf[1] = s / 75;
126         s = s - msf[1] * 75;
127         msf[2] = s;
128 }
129
130 // divide a string of xx:yy:zz into m, s, f
131 static void tok2msf(char *time, char *msf) {
132         char *token;
133
134         token = strtok(time, ":");
135         if (token) {
136                 msf[0] = atoi(token);
137         }
138         else {
139                 msf[0] = 0;
140         }
141
142         token = strtok(NULL, ":");
143         if (token) {
144                 msf[1] = atoi(token);
145         }
146         else {
147                 msf[1] = 0;
148         }
149
150         token = strtok(NULL, ":");
151         if (token) {
152                 msf[2] = atoi(token);
153         }
154         else {
155                 msf[2] = 0;
156         }
157 }
158
159 #ifndef _WIN32
160 static long GetTickCount(void) {
161         static time_t           initial_time = 0;
162         struct timeval          now;
163
164         gettimeofday(&now, NULL);
165
166         if (initial_time == 0) {
167                 initial_time = now.tv_sec;
168         }
169
170         return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
171 }
172 #endif
173
174 // this thread plays audio data
175 #ifdef _WIN32
176 static void playthread(void *param)
177 #else
178 static void *playthread(void *param)
179 #endif
180 {
181         long osleep, d, t, i, s;
182         unsigned char   tmp;
183         int ret = 0, sector_offs;
184
185         t = GetTickCount();
186
187         while (playing) {
188                 s = 0;
189                 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
190                         sector_offs = cdda_cur_sector - cdda_first_sector;
191                         if (sector_offs < 0) {
192                                 d = CD_FRAMESIZE_RAW;
193                                 memset(sndbuffer + s, 0, d);
194                         }
195                         else {
196                                 d = cdimg_read_func(cddaHandle, cdda_file_offset,
197                                         sndbuffer + s, sector_offs);
198                                 if (d < CD_FRAMESIZE_RAW)
199                                         break;
200                         }
201
202                         s += d;
203                         cdda_cur_sector++;
204                 }
205
206                 if (s == 0) {
207                         playing = FALSE;
208                         initial_offset = 0;
209                         break;
210                 }
211
212                 if (!cdr.Muted && playing) {
213                         if (cddaBigEndian) {
214                                 for (i = 0; i < s / 2; i++) {
215                                         tmp = sndbuffer[i * 2];
216                                         sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
217                                         sndbuffer[i * 2 + 1] = tmp;
218                                 }
219                         }
220
221                         // can't do it yet due to readahead..
222                         //cdrAttenuate((short *)sndbuffer, s / 4, 1);
223                         do {
224                                 ret = SPU_playCDDAchannel((short *)sndbuffer, s);
225                                 if (ret == 0x7761)
226             {
227                                         usleep(6 * 1000);
228             }
229                         } while (ret == 0x7761 && playing); // rearmed_wait
230                 }
231
232                 if (ret != 0x676f) { // !rearmed_go
233                         // do approx sleep
234                         long now;
235
236                         // HACK: stop feeding data while emu is paused
237                         extern int stop;
238                         while (stop && playing)
239          {
240                                 usleep(10000);
241          }
242
243                         now = GetTickCount();
244                         osleep = t - now;
245                         if (osleep <= 0) {
246                                 osleep = 1;
247                                 t = now;
248                         }
249                         else if (osleep > CDDA_FRAMETIME) {
250                                 osleep = CDDA_FRAMETIME;
251                                 t = now;
252                         }
253
254                         usleep(osleep * 1000);
255                         t += CDDA_FRAMETIME;
256                 }
257
258         }
259
260 #ifdef _WIN32
261         _endthread();
262 #else
263         pthread_exit(0);
264         return NULL;
265 #endif
266 }
267
268 // stop the CDDA playback
269 static void stopCDDA() {
270         if (!playing) {
271                 return;
272         }
273
274         playing = FALSE;
275 #ifdef _WIN32
276         WaitForSingleObject(threadid, INFINITE);
277 #else
278         pthread_join(threadid, NULL);
279 #endif
280 }
281
282 // start the CDDA playback
283 static void startCDDA(void) {
284         if (playing) {
285                 stopCDDA();
286         }
287
288         playing = TRUE;
289
290 #ifdef _WIN32
291         threadid = (HANDLE)_beginthread(playthread, 0, NULL);
292 #else
293         pthread_create(&threadid, NULL, playthread, NULL);
294 #endif
295 }
296
297 // this function tries to get the .toc file of the given .bin
298 // the necessary data is put into the ti (trackinformation)-array
299 static int parsetoc(const char *isofile) {
300         char                    tocname[MAXPATHLEN];
301         FILE                    *fi;
302         char                    linebuf[256], tmp[256], name[256];
303         char                    *token;
304         char                    time[20], time2[20];
305         unsigned int    t, sector_offs, sector_size;
306         unsigned int    current_zero_gap = 0;
307
308         numtracks = 0;
309
310         // copy name of the iso and change extension from .bin to .toc
311         strncpy(tocname, isofile, sizeof(tocname));
312         tocname[MAXPATHLEN - 1] = '\0';
313         if (strlen(tocname) >= 4) {
314                 strcpy(tocname + strlen(tocname) - 4, ".toc");
315         }
316         else {
317                 return -1;
318         }
319
320         if ((fi = fopen(tocname, "r")) == NULL) {
321                 // try changing extension to .cue (to satisfy some stupid tutorials)
322                 strcpy(tocname + strlen(tocname) - 4, ".cue");
323                 if ((fi = fopen(tocname, "r")) == NULL) {
324                         // if filename is image.toc.bin, try removing .bin (for Brasero)
325                         strcpy(tocname, isofile);
326                         t = strlen(tocname);
327                         if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
328                                 tocname[t - 4] = '\0';
329                                 if ((fi = fopen(tocname, "r")) == NULL) {
330                                         return -1;
331                                 }
332                         }
333                         else {
334                                 return -1;
335                         }
336                 }
337                 // check if it's really a TOC named as a .cue
338                 fgets(linebuf, sizeof(linebuf), fi);
339                 token = strtok(linebuf, " ");
340                 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
341                         fclose(fi);
342                         return -1;
343                 }
344                 fseek(fi, 0, SEEK_SET);
345         }
346
347         memset(&ti, 0, sizeof(ti));
348         cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
349
350         sector_size = CD_FRAMESIZE_RAW;
351         sector_offs = 2 * 75;
352
353         // parse the .toc file
354         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
355                 // search for tracks
356                 strncpy(tmp, linebuf, sizeof(linebuf));
357                 token = strtok(tmp, " ");
358
359                 if (token == NULL) continue;
360
361                 if (!strcmp(token, "TRACK")) {
362                         sector_offs += current_zero_gap;
363                         current_zero_gap = 0;
364
365                         // get type of track
366                         token = strtok(NULL, " ");
367                         numtracks++;
368
369                         if (!strncmp(token, "MODE2_RAW", 9)) {
370                                 ti[numtracks].type = DATA;
371                                 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
372
373                                 // check if this image contains mixed subchannel data
374                                 token = strtok(NULL, " ");
375                                 if (token != NULL && !strncmp(token, "RW", 2)) {
376                                         sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
377                                         subChanMixed = TRUE;
378                                         if (!strncmp(token, "RW_RAW", 6))
379                                                 subChanRaw = TRUE;
380                                 }
381                         }
382                         else if (!strncmp(token, "AUDIO", 5)) {
383                                 ti[numtracks].type = CDDA;
384                         }
385                 }
386                 else if (!strcmp(token, "DATAFILE")) {
387                         if (ti[numtracks].type == CDDA) {
388                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
389                                 ti[numtracks].start_offset = t;
390                                 t = t / sector_size + sector_offs;
391                                 sec2msf(t, (char *)&ti[numtracks].start);
392                                 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
393                         }
394                         else {
395                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
396                                 tok2msf((char *)&time, (char *)&ti[numtracks].length);
397                         }
398                 }
399                 else if (!strcmp(token, "FILE")) {
400                         sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
401                         tok2msf((char *)&time, (char *)&ti[numtracks].start);
402                         t += msf2sec(ti[numtracks].start) * sector_size;
403                         ti[numtracks].start_offset = t;
404                         t = t / sector_size + sector_offs;
405                         sec2msf(t, (char *)&ti[numtracks].start);
406                         tok2msf((char *)&time2, (char *)&ti[numtracks].length);
407                 }
408                 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
409                         // skip unneeded optional fields
410                         while (token != NULL) {
411                                 token = strtok(NULL, " ");
412                                 if (strchr(token, ':') != NULL)
413                                         break;
414                         }
415                         if (token != NULL) {
416                                 tok2msf(token, tmp);
417                                 current_zero_gap = msf2sec(tmp);
418                         }
419                         if (numtracks > 1) {
420                                 t = ti[numtracks - 1].start_offset;
421                                 t /= sector_size;
422                                 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
423                         }
424                 }
425                 else if (!strcmp(token, "START")) {
426                         token = strtok(NULL, " ");
427                         if (token != NULL && strchr(token, ':')) {
428                                 tok2msf(token, tmp);
429                                 t = msf2sec(tmp);
430                                 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
431                                 t = msf2sec(ti[numtracks].start) + t;
432                                 sec2msf(t, (char *)&ti[numtracks].start);
433                         }
434                 }
435         }
436
437         fclose(fi);
438
439         return 0;
440 }
441
442 // this function tries to get the .cue file of the given .bin
443 // the necessary data is put into the ti (trackinformation)-array
444 static int parsecue(const char *isofile) {
445         char                    cuename[MAXPATHLEN];
446         char                    filepath[MAXPATHLEN];
447         char                    *incue_fname;
448         FILE                    *fi;
449         char                    *token;
450         char                    time[20];
451         char                    *tmp;
452         char                    linebuf[256], tmpb[256], dummy[256];
453         unsigned int    incue_max_len;
454         unsigned int    t, file_len, mode, sector_offs;
455         unsigned int    sector_size = 2352;
456
457         numtracks = 0;
458
459         // copy name of the iso and change extension from .bin to .cue
460         strncpy(cuename, isofile, sizeof(cuename));
461         cuename[MAXPATHLEN - 1] = '\0';
462         if (strlen(cuename) >= 4) {
463                 strcpy(cuename + strlen(cuename) - 4, ".cue");
464         }
465         else {
466                 return -1;
467         }
468
469         if ((fi = fopen(cuename, "r")) == NULL) {
470                 return -1;
471         }
472
473         // Some stupid tutorials wrongly tell users to use cdrdao to rip a
474         // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
475         // that...
476         if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
477                 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
478                         // Don't proceed further, as this is actually a .toc file rather
479                         // than a .cue file.
480                         fclose(fi);
481                         return parsetoc(isofile);
482                 }
483                 fseek(fi, 0, SEEK_SET);
484         }
485
486         // build a path for files referenced in .cue
487         strncpy(filepath, cuename, sizeof(filepath));
488         tmp = strrchr(filepath, '/');
489         if (tmp == NULL)
490                 tmp = strrchr(filepath, '\\');
491         if (tmp != NULL)
492                 tmp++;
493         else
494                 tmp = filepath;
495         *tmp = 0;
496         filepath[sizeof(filepath) - 1] = 0;
497         incue_fname = tmp;
498         incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
499
500         memset(&ti, 0, sizeof(ti));
501
502         file_len = 0;
503         sector_offs = 2 * 75;
504
505         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
506                 strncpy(dummy, linebuf, sizeof(linebuf));
507                 token = strtok(dummy, " ");
508
509                 if (token == NULL) {
510                         continue;
511                 }
512
513                 if (!strcmp(token, "TRACK")) {
514                         numtracks++;
515
516                         sector_size = 0;
517                         if (strstr(linebuf, "AUDIO") != NULL) {
518                                 ti[numtracks].type = CDDA;
519                                 sector_size = 2352;
520                         }
521                         else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, &sector_size) == 3)
522                                 ti[numtracks].type = DATA;
523                         else {
524                                 SysPrintf(".cue: failed to parse TRACK\n");
525                                 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
526                         }
527                         if (sector_size == 0)
528                                 sector_size = 2352;
529                 }
530                 else if (!strcmp(token, "INDEX")) {
531                         if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
532                                 SysPrintf(".cue: failed to parse INDEX\n");
533                         tok2msf(time, (char *)&ti[numtracks].start);
534
535                         t = msf2sec(ti[numtracks].start);
536                         ti[numtracks].start_offset = t * sector_size;
537                         t += sector_offs;
538                         sec2msf(t, ti[numtracks].start);
539
540                         // default track length to file length
541                         t = file_len - ti[numtracks].start_offset / sector_size;
542                         sec2msf(t, ti[numtracks].length);
543
544                         if (numtracks > 1 && ti[numtracks].handle == NULL) {
545                                 // this track uses the same file as the last,
546                                 // start of this track is last track's end
547                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
548                                 sec2msf(t, ti[numtracks - 1].length);
549                         }
550                         if (numtracks > 1 && pregapOffset == -1)
551                                 pregapOffset = ti[numtracks].start_offset / sector_size;
552                 }
553                 else if (!strcmp(token, "PREGAP")) {
554                         if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
555                                 tok2msf(time, dummy);
556                                 sector_offs += msf2sec(dummy);
557                         }
558                         pregapOffset = -1; // mark to fill track start_offset
559                 }
560                 else if (!strcmp(token, "FILE")) {
561                         t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
562                         if (t != 1)
563                                 sscanf(linebuf, " FILE %255s", tmpb);
564
565                         // absolute path?
566                         ti[numtracks + 1].handle = fopen(tmpb, "rb");
567                         if (ti[numtracks + 1].handle == NULL) {
568                                 // relative to .cue?
569                                 tmp = strrchr(tmpb, '\\');
570                                 if (tmp == NULL)
571                                         tmp = strrchr(tmpb, '/');
572                                 if (tmp != NULL)
573                                         tmp++;
574                                 else
575                                         tmp = tmpb;
576                                 strncpy(incue_fname, tmp, incue_max_len);
577                                 ti[numtracks + 1].handle = fopen(filepath, "rb");
578                         }
579
580                         // update global offset if this is not first file in this .cue
581                         if (numtracks + 1 > 1) {
582                                 multifile = 1;
583                                 sector_offs += file_len;
584                         }
585
586                         file_len = 0;
587                         if (ti[numtracks + 1].handle == NULL) {
588                                 SysPrintf(_("\ncould not open: %s\n"), filepath);
589                                 continue;
590                         }
591                         fseek(ti[numtracks + 1].handle, 0, SEEK_END);
592                         file_len = ftell(ti[numtracks + 1].handle) / 2352;
593
594                         if (numtracks == 0 && strlen(isofile) >= 4 &&
595                                 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
596                         {
597                                 // user selected .cue as image file, use it's data track instead
598                                 fclose(cdHandle);
599                                 cdHandle = fopen(filepath, "rb");
600                         }
601                 }
602         }
603
604         fclose(fi);
605
606         return 0;
607 }
608
609 // this function tries to get the .ccd file of the given .img
610 // the necessary data is put into the ti (trackinformation)-array
611 static int parseccd(const char *isofile) {
612         char                    ccdname[MAXPATHLEN];
613         FILE                    *fi;
614         char                    linebuf[256];
615         unsigned int    t;
616
617         numtracks = 0;
618
619         // copy name of the iso and change extension from .img to .ccd
620         strncpy(ccdname, isofile, sizeof(ccdname));
621         ccdname[MAXPATHLEN - 1] = '\0';
622         if (strlen(ccdname) >= 4) {
623                 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
624         }
625         else {
626                 return -1;
627         }
628
629         if ((fi = fopen(ccdname, "r")) == NULL) {
630                 return -1;
631         }
632
633         memset(&ti, 0, sizeof(ti));
634
635         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
636                 if (!strncmp(linebuf, "[TRACK", 6)){
637                         numtracks++;
638                 }
639                 else if (!strncmp(linebuf, "MODE=", 5)) {
640                         sscanf(linebuf, "MODE=%d", &t);
641                         ti[numtracks].type = ((t == 0) ? CDDA : DATA);
642                 }
643                 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
644                         sscanf(linebuf, "INDEX 1=%d", &t);
645                         sec2msf(t + 2 * 75, ti[numtracks].start);
646                         ti[numtracks].start_offset = t * 2352;
647
648                         // If we've already seen another track, this is its end
649                         if (numtracks > 1) {
650                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
651                                 sec2msf(t, ti[numtracks - 1].length);
652                         }
653                 }
654         }
655
656         fclose(fi);
657
658         // Fill out the last track's end based on size
659         if (numtracks >= 1) {
660                 fseek(cdHandle, 0, SEEK_END);
661                 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
662                 sec2msf(t, ti[numtracks].length);
663         }
664
665         return 0;
666 }
667
668 // this function tries to get the .mds file of the given .mdf
669 // the necessary data is put into the ti (trackinformation)-array
670 static int parsemds(const char *isofile) {
671         char                    mdsname[MAXPATHLEN];
672         FILE                    *fi;
673         unsigned int    offset, extra_offset, l, i;
674         unsigned short  s;
675
676         numtracks = 0;
677
678         // copy name of the iso and change extension from .mdf to .mds
679         strncpy(mdsname, isofile, sizeof(mdsname));
680         mdsname[MAXPATHLEN - 1] = '\0';
681         if (strlen(mdsname) >= 4) {
682                 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
683         }
684         else {
685                 return -1;
686         }
687
688         if ((fi = fopen(mdsname, "rb")) == NULL) {
689                 return -1;
690         }
691
692         memset(&ti, 0, sizeof(ti));
693
694         // check if it's a valid mds file
695         fread(&i, 1, sizeof(unsigned int), fi);
696         i = SWAP32(i);
697         if (i != 0x4944454D) {
698                 // not an valid mds file
699                 fclose(fi);
700                 return -1;
701         }
702
703         // get offset to session block
704         fseek(fi, 0x50, SEEK_SET);
705         fread(&offset, 1, sizeof(unsigned int), fi);
706         offset = SWAP32(offset);
707
708         // get total number of tracks
709         offset += 14;
710         fseek(fi, offset, SEEK_SET);
711         fread(&s, 1, sizeof(unsigned short), fi);
712         s = SWAP16(s);
713         numtracks = s;
714
715         // get offset to track blocks
716         fseek(fi, 4, SEEK_CUR);
717         fread(&offset, 1, sizeof(unsigned int), fi);
718         offset = SWAP32(offset);
719
720         // skip lead-in data
721         while (1) {
722                 fseek(fi, offset + 4, SEEK_SET);
723                 if (fgetc(fi) < 0xA0) {
724                         break;
725                 }
726                 offset += 0x50;
727         }
728
729         // check if the image contains mixed subchannel data
730         fseek(fi, offset + 1, SEEK_SET);
731         subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
732
733         // read track data
734         for (i = 1; i <= numtracks; i++) {
735                 fseek(fi, offset, SEEK_SET);
736
737                 // get the track type
738                 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
739                 fseek(fi, 8, SEEK_CUR);
740
741                 // get the track starting point
742                 ti[i].start[0] = fgetc(fi);
743                 ti[i].start[1] = fgetc(fi);
744                 ti[i].start[2] = fgetc(fi);
745
746                 fread(&extra_offset, 1, sizeof(unsigned int), fi);
747                 extra_offset = SWAP32(extra_offset);
748
749                 // get track start offset (in .mdf)
750                 fseek(fi, offset + 0x28, SEEK_SET);
751                 fread(&l, 1, sizeof(unsigned int), fi);
752                 l = SWAP32(l);
753                 ti[i].start_offset = l;
754
755                 // get pregap
756                 fseek(fi, extra_offset, SEEK_SET);
757                 fread(&l, 1, sizeof(unsigned int), fi);
758                 l = SWAP32(l);
759                 if (l != 0 && i > 1)
760                         pregapOffset = msf2sec(ti[i].start);
761
762                 // get the track length
763                 fread(&l, 1, sizeof(unsigned int), fi);
764                 l = SWAP32(l);
765                 sec2msf(l, ti[i].length);
766
767                 offset += 0x50;
768         }
769
770         fclose(fi);
771         return 0;
772 }
773
774 static int handlepbp(const char *isofile) {
775         struct {
776                 unsigned int sig;
777                 unsigned int dontcare[8];
778                 unsigned int psar_offs;
779         } pbp_hdr;
780         struct {
781                 unsigned char type;
782                 unsigned char pad0;
783                 unsigned char track;
784                 char index0[3];
785                 char pad1;
786                 char index1[3];
787         } toc_entry;
788         struct {
789                 unsigned int offset;
790                 unsigned int size;
791                 unsigned int dontcare[6];
792         } index_entry;
793         char psar_sig[11];
794         unsigned int t, cd_length, cdimg_base;
795         unsigned int offsettab[8], psisoimg_offs;
796         const char *ext = NULL;
797         int i, ret;
798
799         if (strlen(isofile) >= 4)
800                 ext = isofile + strlen(isofile) - 4;
801         if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
802                 return -1;
803
804         fseek(cdHandle, 0, SEEK_SET);
805
806         numtracks = 0;
807
808         ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
809         if (ret != sizeof(pbp_hdr)) {
810                 SysPrintf("failed to read pbp\n");
811                 goto fail_io;
812         }
813
814         ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
815         if (ret != 0) {
816                 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
817                 goto fail_io;
818         }
819
820         psisoimg_offs = pbp_hdr.psar_offs;
821         fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
822         psar_sig[10] = 0;
823         if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
824                 // multidisk image?
825                 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
826                 if (ret != 0) {
827                         SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
828                         goto fail_io;
829                 }
830
831                 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
832                         SysPrintf("failed to read offsettab\n");
833                         goto fail_io;
834                 }
835
836                 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
837                         if (offsettab[i] == 0)
838                                 break;
839                 }
840                 cdrIsoMultidiskCount = i;
841                 if (cdrIsoMultidiskCount == 0) {
842                         SysPrintf("multidisk eboot has 0 images?\n");
843                         goto fail_io;
844                 }
845
846                 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
847                         cdrIsoMultidiskSelect = 0;
848
849                 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
850
851                 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
852                 if (ret != 0) {
853                         SysPrintf("failed to seek to %x\n", psisoimg_offs);
854                         goto fail_io;
855                 }
856
857                 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
858                 psar_sig[10] = 0;
859         }
860
861         if (strcmp(psar_sig, "PSISOIMG00") != 0) {
862                 SysPrintf("bad psar_sig: %s\n", psar_sig);
863                 goto fail_io;
864         }
865
866         // seek to TOC
867         ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
868         if (ret != 0) {
869                 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
870                 goto fail_io;
871         }
872
873         // first 3 entries are special
874         fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
875         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
876         numtracks = btoi(toc_entry.index1[0]);
877
878         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
879         cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
880                 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
881
882         for (i = 1; i <= numtracks; i++) {
883                 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
884
885                 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
886
887                 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
888                         btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
889                 ti[i].start_offset *= 2352;
890                 ti[i].start[0] = btoi(toc_entry.index1[0]);
891                 ti[i].start[1] = btoi(toc_entry.index1[1]);
892                 ti[i].start[2] = btoi(toc_entry.index1[2]);
893
894                 if (i > 1) {
895                         t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
896                         sec2msf(t, ti[i - 1].length);
897                 }
898         }
899         t = cd_length - ti[numtracks].start_offset / 2352;
900         sec2msf(t, ti[numtracks].length);
901
902         // seek to ISO index
903         ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
904         if (ret != 0) {
905                 SysPrintf("failed to seek to ISO index\n");
906                 goto fail_io;
907         }
908
909         compr_img = calloc(1, sizeof(*compr_img));
910         if (compr_img == NULL)
911                 goto fail_io;
912
913         compr_img->block_shift = 4;
914         compr_img->current_block = (unsigned int)-1;
915
916         compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
917         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
918         if (compr_img->index_table == NULL)
919                 goto fail_io;
920
921         cdimg_base = psisoimg_offs + 0x100000;
922         for (i = 0; i < compr_img->index_len; i++) {
923                 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
924                 if (ret != sizeof(index_entry)) {
925                         SysPrintf("failed to read index_entry #%d\n", i);
926                         goto fail_index;
927                 }
928
929                 if (index_entry.size == 0)
930                         break;
931
932                 compr_img->index_table[i] = cdimg_base + index_entry.offset;
933         }
934         compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
935
936         return 0;
937
938 fail_index:
939         free(compr_img->index_table);
940         compr_img->index_table = NULL;
941 fail_io:
942         if (compr_img != NULL) {
943                 free(compr_img);
944                 compr_img = NULL;
945         }
946         return -1;
947 }
948
949 static int handlecbin(const char *isofile) {
950         struct
951         {
952                 char magic[4];
953                 unsigned int header_size;
954                 unsigned long long total_bytes;
955                 unsigned int block_size;
956                 unsigned char ver;              // 1
957                 unsigned char align;
958                 unsigned char rsv_06[2];
959         } ciso_hdr;
960         const char *ext = NULL;
961         unsigned int index = 0, plain;
962         int i, ret;
963
964         if (strlen(isofile) >= 5)
965                 ext = isofile + strlen(isofile) - 5;
966         if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
967                 return -1;
968
969         fseek(cdHandle, 0, SEEK_SET);
970
971         ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
972         if (ret != sizeof(ciso_hdr)) {
973                 SysPrintf("failed to read ciso header\n");
974                 return -1;
975         }
976
977         if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
978                 SysPrintf("bad ciso header\n");
979                 return -1;
980         }
981         if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
982                 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
983                 if (ret != 0) {
984                         SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
985                         return -1;
986                 }
987         }
988
989         compr_img = calloc(1, sizeof(*compr_img));
990         if (compr_img == NULL)
991                 goto fail_io;
992
993         compr_img->block_shift = 0;
994         compr_img->current_block = (unsigned int)-1;
995
996         compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
997         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
998         if (compr_img->index_table == NULL)
999                 goto fail_io;
1000
1001         ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
1002         if (ret != compr_img->index_len) {
1003                 SysPrintf("failed to read index table\n");
1004                 goto fail_index;
1005         }
1006
1007         for (i = 0; i < compr_img->index_len + 1; i++) {
1008                 index = compr_img->index_table[i];
1009                 plain = index & 0x80000000;
1010                 index &= 0x7fffffff;
1011                 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1012         }
1013         if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1014                 SysPrintf("warning: ciso img too large, expect problems\n");
1015
1016         return 0;
1017
1018 fail_index:
1019         free(compr_img->index_table);
1020         compr_img->index_table = NULL;
1021 fail_io:
1022         if (compr_img != NULL) {
1023                 free(compr_img);
1024                 compr_img = NULL;
1025         }
1026         return -1;
1027 }
1028
1029 // this function tries to get the .sub file of the given .img
1030 static int opensubfile(const char *isoname) {
1031         char            subname[MAXPATHLEN];
1032
1033         // copy name of the iso and change extension from .img to .sub
1034         strncpy(subname, isoname, sizeof(subname));
1035         subname[MAXPATHLEN - 1] = '\0';
1036         if (strlen(subname) >= 4) {
1037                 strcpy(subname + strlen(subname) - 4, ".sub");
1038         }
1039         else {
1040                 return -1;
1041         }
1042
1043         subHandle = fopen(subname, "rb");
1044         if (subHandle == NULL) {
1045                 return -1;
1046         }
1047
1048         return 0;
1049 }
1050
1051 static int opensbifile(const char *isoname) {
1052         char            sbiname[MAXPATHLEN];
1053         int             s;
1054
1055         strncpy(sbiname, isoname, sizeof(sbiname));
1056         sbiname[MAXPATHLEN - 1] = '\0';
1057         if (strlen(sbiname) >= 4) {
1058                 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1059         }
1060         else {
1061                 return -1;
1062         }
1063
1064         fseek(cdHandle, 0, SEEK_END);
1065         s = ftell(cdHandle) / 2352;
1066
1067         return LoadSBI(sbiname, s);
1068 }
1069
1070 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1071 {
1072         fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1073         return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1074 }
1075
1076 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1077 {
1078         int ret;
1079
1080         fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1081         ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1082         fread(subbuffer, 1, SUB_FRAMESIZE, f);
1083
1084         if (subChanRaw) DecodeRawSubData();
1085
1086         return ret;
1087 }
1088
1089 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1090 {
1091         static z_stream z;
1092         int ret = 0;
1093
1094         if (z.zalloc == NULL) {
1095                 // XXX: one-time leak here..
1096                 z.next_in = Z_NULL;
1097                 z.avail_in = 0;
1098                 z.zalloc = Z_NULL;
1099                 z.zfree = Z_NULL;
1100                 z.opaque = Z_NULL;
1101                 ret = inflateInit2(&z, -15);
1102         }
1103         else
1104                 ret = inflateReset(&z);
1105         if (ret != Z_OK)
1106                 return ret;
1107
1108         z.next_in = in;
1109         z.avail_in = in_size;
1110         z.next_out = out;
1111         z.avail_out = *out_size;
1112
1113         ret = inflate(&z, Z_NO_FLUSH);
1114         //inflateEnd(&z);
1115
1116         *out_size -= z.avail_out;
1117         return ret == 1 ? 0 : ret;
1118 }
1119
1120 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1121 {
1122         unsigned long cdbuffer_size, cdbuffer_size_expect;
1123         unsigned int start_byte, size;
1124         int is_compressed;
1125         int ret, block;
1126
1127         if (base)
1128                 sector += base / 2352;
1129
1130         block = sector >> compr_img->block_shift;
1131         compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1132
1133         if (block == compr_img->current_block) {
1134                 //printf("hit sect %d\n", sector);
1135                 goto finish;
1136         }
1137
1138         if (sector >= compr_img->index_len * 16) {
1139                 SysPrintf("sector %d is past img end\n", sector);
1140                 return -1;
1141         }
1142
1143         start_byte = compr_img->index_table[block] & 0x7fffffff;
1144         if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1145                 SysPrintf("seek error for block %d at %x: ",
1146                         block, start_byte);
1147                 perror(NULL);
1148                 return -1;
1149         }
1150
1151         is_compressed = !(compr_img->index_table[block] & 0x80000000);
1152         size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1153         if (size > sizeof(compr_img->buff_compressed)) {
1154                 SysPrintf("block %d is too large: %u\n", block, size);
1155                 return -1;
1156         }
1157
1158         if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1159                                 1, size, cdHandle) != size) {
1160                 SysPrintf("read error for block %d at %x: ", block, start_byte);
1161                 perror(NULL);
1162                 return -1;
1163         }
1164
1165         if (is_compressed) {
1166                 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1167                 cdbuffer_size = cdbuffer_size_expect;
1168                 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1169                 if (ret != 0) {
1170                         SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1171                                         ret, block, sector);
1172                         return -1;
1173                 }
1174                 if (cdbuffer_size != cdbuffer_size_expect)
1175                         SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1176                                         cdbuffer_size_expect, sector);
1177         }
1178
1179         // done at last!
1180         compr_img->current_block = block;
1181
1182 finish:
1183         if (dest != cdbuffer) // copy avoid HACK
1184                 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1185                         CD_FRAMESIZE_RAW);
1186         return CD_FRAMESIZE_RAW;
1187 }
1188
1189 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1190 {
1191         int ret;
1192
1193         fseek(f, base + sector * 2048, SEEK_SET);
1194         ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1195
1196         // not really necessary, fake mode 2 header
1197         memset(cdbuffer, 0, 12 * 2);
1198         sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1199         cdbuffer[12 + 3] = 1;
1200
1201         return ret;
1202 }
1203
1204 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1205         return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1206 }
1207
1208 static unsigned char * CALLBACK ISOgetBuffer(void) {
1209         return cdbuffer + 12;
1210 }
1211
1212 static void PrintTracks(void) {
1213         int i;
1214
1215         for (i = 1; i <= numtracks; i++) {
1216                 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1217                         i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1218                         ti[i].start[0], ti[i].start[1], ti[i].start[2],
1219                         ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1220         }
1221 }
1222
1223 // This function is invoked by the front-end when opening an ISO
1224 // file for playback
1225 static long CALLBACK ISOopen(void) {
1226         boolean isMode1ISO = FALSE;
1227         char alt_bin_filename[MAXPATHLEN];
1228         const char *bin_filename;
1229
1230         if (cdHandle != NULL) {
1231                 return 0; // it's already open
1232         }
1233
1234         cdHandle = fopen(GetIsoFile(), "rb");
1235         if (cdHandle == NULL) {
1236                 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1237                         GetIsoFile(), strerror(errno));
1238                 return -1;
1239         }
1240
1241         SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1242
1243         cddaBigEndian = FALSE;
1244         subChanMixed = FALSE;
1245         subChanRaw = FALSE;
1246         pregapOffset = 0;
1247         cdrIsoMultidiskCount = 1;
1248         multifile = 0;
1249
1250         CDR_getBuffer = ISOgetBuffer;
1251         cdimg_read_func = cdread_normal;
1252
1253         if (parsetoc(GetIsoFile()) == 0) {
1254                 SysPrintf("[+toc]");
1255         }
1256         else if (parseccd(GetIsoFile()) == 0) {
1257                 SysPrintf("[+ccd]");
1258         }
1259         else if (parsemds(GetIsoFile()) == 0) {
1260                 SysPrintf("[+mds]");
1261         }
1262         else if (parsecue(GetIsoFile()) == 0) {
1263                 SysPrintf("[+cue]");
1264         }
1265         if (handlepbp(GetIsoFile()) == 0) {
1266                 SysPrintf("[pbp]");
1267                 CDR_getBuffer = ISOgetBuffer_compr;
1268                 cdimg_read_func = cdread_compressed;
1269         }
1270         else if (handlecbin(GetIsoFile()) == 0) {
1271                 SysPrintf("[cbin]");
1272                 CDR_getBuffer = ISOgetBuffer_compr;
1273                 cdimg_read_func = cdread_compressed;
1274         }
1275
1276         if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1277                 SysPrintf("[+sub]");
1278         }
1279         if (opensbifile(GetIsoFile()) == 0) {
1280                 SysPrintf("[+sbi]");
1281         }
1282
1283         fseek(cdHandle, 0, SEEK_END);
1284
1285         // maybe user selected metadata file instead of main .bin ..
1286         bin_filename = GetIsoFile();
1287         if (ftell(cdHandle) < 2352 * 0x10) {
1288                 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1289                 FILE *tmpf = NULL;
1290                 size_t i;
1291                 char *p;
1292
1293                 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1294                 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1295                 if (strlen(alt_bin_filename) >= 4) {
1296                         p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1297                         for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1298                                 strcpy(p, exts[i]);
1299                                 tmpf = fopen(alt_bin_filename, "rb");
1300                                 if (tmpf != NULL)
1301                                         break;
1302                         }
1303                 }
1304                 if (tmpf != NULL) {
1305                         bin_filename = alt_bin_filename;
1306                         fclose(cdHandle);
1307                         cdHandle = tmpf;
1308                         fseek(cdHandle, 0, SEEK_END);
1309                 }
1310         }
1311
1312         // guess whether it is mode1/2048
1313         if (ftell(cdHandle) % 2048 == 0) {
1314                 unsigned int modeTest = 0;
1315                 fseek(cdHandle, 0, SEEK_SET);
1316                 fread(&modeTest, 4, 1, cdHandle);
1317                 if (SWAP32(modeTest) != 0xffffff00) {
1318                         SysPrintf("[2048]");
1319                         isMode1ISO = TRUE;
1320                 }
1321         }
1322         fseek(cdHandle, 0, SEEK_SET);
1323
1324         SysPrintf(".\n");
1325
1326         PrintTracks();
1327
1328         if (subChanMixed)
1329                 cdimg_read_func = cdread_sub_mixed;
1330         else if (isMode1ISO)
1331                 cdimg_read_func = cdread_2048;
1332
1333         // make sure we have another handle open for cdda
1334         if (numtracks > 1 && ti[1].handle == NULL) {
1335                 ti[1].handle = fopen(bin_filename, "rb");
1336         }
1337         cdda_cur_sector = 0;
1338         cdda_file_offset = 0;
1339
1340         return 0;
1341 }
1342
1343 static long CALLBACK ISOclose(void) {
1344         int i;
1345
1346         if (cdHandle != NULL) {
1347                 fclose(cdHandle);
1348                 cdHandle = NULL;
1349         }
1350         if (subHandle != NULL) {
1351                 fclose(subHandle);
1352                 subHandle = NULL;
1353         }
1354         stopCDDA();
1355         cddaHandle = NULL;
1356
1357         if (compr_img != NULL) {
1358                 free(compr_img->index_table);
1359                 free(compr_img);
1360                 compr_img = NULL;
1361         }
1362
1363         for (i = 1; i <= numtracks; i++) {
1364                 if (ti[i].handle != NULL) {
1365                         fclose(ti[i].handle);
1366                         ti[i].handle = NULL;
1367                 }
1368         }
1369         numtracks = 0;
1370         ti[1].type = 0;
1371         UnloadSBI();
1372
1373         memset(cdbuffer, 0, sizeof(cdbuffer));
1374         CDR_getBuffer = ISOgetBuffer;
1375
1376         return 0;
1377 }
1378
1379 static long CALLBACK ISOinit(void) {
1380         assert(cdHandle == NULL);
1381         assert(subHandle == NULL);
1382
1383         return 0; // do nothing
1384 }
1385
1386 static long CALLBACK ISOshutdown(void) {
1387         ISOclose();
1388         return 0;
1389 }
1390
1391 // return Starting and Ending Track
1392 // buffer:
1393 //  byte 0 - start track
1394 //  byte 1 - end track
1395 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1396         buffer[0] = 1;
1397
1398         if (numtracks > 0) {
1399                 buffer[1] = numtracks;
1400         }
1401         else {
1402                 buffer[1] = 1;
1403         }
1404
1405         return 0;
1406 }
1407
1408 // return Track Time
1409 // buffer:
1410 //  byte 0 - frame
1411 //  byte 1 - second
1412 //  byte 2 - minute
1413 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1414         if (track == 0) {
1415                 unsigned int sect;
1416                 unsigned char time[3];
1417                 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1418                 sec2msf(sect, (char *)time);
1419                 buffer[2] = time[0];
1420                 buffer[1] = time[1];
1421                 buffer[0] = time[2];
1422         }
1423         else if (numtracks > 0 && track <= numtracks) {
1424                 buffer[2] = ti[track].start[0];
1425                 buffer[1] = ti[track].start[1];
1426                 buffer[0] = ti[track].start[2];
1427         }
1428         else {
1429                 buffer[2] = 0;
1430                 buffer[1] = 2;
1431                 buffer[0] = 0;
1432         }
1433
1434         return 0;
1435 }
1436
1437 // decode 'raw' subchannel data ripped by cdrdao
1438 static void DecodeRawSubData(void) {
1439         unsigned char subQData[12];
1440         int i;
1441
1442         memset(subQData, 0, sizeof(subQData));
1443
1444         for (i = 0; i < 8 * 12; i++) {
1445                 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1446                         subQData[i >> 3] |= (1 << (7 - (i & 7)));
1447                 }
1448         }
1449
1450         memcpy(&subbuffer[12], subQData, 12);
1451 }
1452
1453 // read track
1454 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1455 // uses bcd format
1456 static long CALLBACK ISOreadTrack(unsigned char *time) {
1457         int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1458         long ret;
1459
1460         if (cdHandle == NULL) {
1461                 return -1;
1462         }
1463
1464         if (pregapOffset) {
1465                 subChanMissing = FALSE;
1466                 if (sector >= pregapOffset) {
1467                         sector -= 2 * 75;
1468                         if (sector < pregapOffset)
1469                                 subChanMissing = TRUE;
1470                 }
1471         }
1472
1473         ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1474         if (ret < 0)
1475                 return -1;
1476
1477         if (subHandle != NULL) {
1478                 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1479                 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1480
1481                 if (subChanRaw) DecodeRawSubData();
1482         }
1483
1484         return 0;
1485 }
1486
1487 // plays cdda audio
1488 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1489 // does NOT uses bcd format
1490 static long CALLBACK ISOplay(unsigned char *time) {
1491         unsigned int i;
1492
1493         if (numtracks <= 1)
1494                 return 0;
1495
1496         // find the track
1497         cdda_cur_sector = msf2sec((char *)time);
1498         for (i = numtracks; i > 1; i--) {
1499                 cdda_first_sector = msf2sec(ti[i].start);
1500                 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1501                         break;
1502         }
1503         cdda_file_offset = ti[i].start_offset;
1504
1505         // find the file that contains this track
1506         for (; i > 1; i--)
1507                 if (ti[i].handle != NULL)
1508                         break;
1509
1510         cddaHandle = ti[i].handle;
1511
1512         if (SPU_playCDDAchannel != NULL)
1513                 startCDDA();
1514
1515         return 0;
1516 }
1517
1518 // stops cdda audio
1519 static long CALLBACK ISOstop(void) {
1520         stopCDDA();
1521         return 0;
1522 }
1523
1524 // gets subchannel data
1525 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1526         if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1527                 return subbuffer;
1528         }
1529
1530         return NULL;
1531 }
1532
1533 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1534         u32 sect;
1535         
1536         CDR__getStatus(stat);
1537         
1538         if (playing) {
1539                 stat->Type = 0x02;
1540                 stat->Status |= 0x80;
1541         }
1542         else {
1543                 // BIOS - boot ID (CD type)
1544                 stat->Type = ti[1].type;
1545         }
1546         
1547         // relative -> absolute time
1548         sect = cddaCurPos;
1549         sec2msf(sect, (char *)stat->Time);
1550         
1551         return 0;
1552 }
1553
1554 // read CDDA sector into buffer
1555 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1556         unsigned char msf[3] = {m, s, f};
1557         unsigned int file, track, track_start = 0;
1558         int ret;
1559
1560         cddaCurPos = msf2sec((char *)msf);
1561
1562         // find current track index
1563         for (track = numtracks; ; track--) {
1564                 track_start = msf2sec(ti[track].start);
1565                 if (track_start <= cddaCurPos)
1566                         break;
1567                 if (track == 1)
1568                         break;
1569         }
1570
1571         // data tracks play silent
1572         if (ti[track].type != CDDA) {
1573                 memset(buffer, 0, CD_FRAMESIZE_RAW);
1574                 return 0;
1575         }
1576
1577         file = 1;
1578         if (multifile) {
1579                 // find the file that contains this track
1580                 for (file = track; file > 1; file--)
1581                         if (ti[file].handle != NULL)
1582                                 break;
1583         }
1584
1585         ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1586                 buffer, cddaCurPos - track_start);
1587         if (ret != CD_FRAMESIZE_RAW) {
1588                 memset(buffer, 0, CD_FRAMESIZE_RAW);
1589                 return -1;
1590         }
1591
1592         if (cddaBigEndian) {
1593                 int i;
1594                 unsigned char tmp;
1595
1596                 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1597                         tmp = buffer[i * 2];
1598                         buffer[i * 2] = buffer[i * 2 + 1];
1599                         buffer[i * 2 + 1] = tmp;
1600                 }
1601         }
1602
1603         return 0;
1604 }
1605
1606 void cdrIsoInit(void) {
1607         CDR_init = ISOinit;
1608         CDR_shutdown = ISOshutdown;
1609         CDR_open = ISOopen;
1610         CDR_close = ISOclose;
1611         CDR_getTN = ISOgetTN;
1612         CDR_getTD = ISOgetTD;
1613         CDR_readTrack = ISOreadTrack;
1614         CDR_getBuffer = ISOgetBuffer;
1615         CDR_play = ISOplay;
1616         CDR_stop = ISOstop;
1617         CDR_getBufferSub = ISOgetBufferSub;
1618         CDR_getStatus = ISOgetStatus;
1619         CDR_readCDDA = ISOreadCDDA;
1620
1621         CDR_getDriveLetter = CDR__getDriveLetter;
1622         CDR_configure = CDR__configure;
1623         CDR_test = CDR__test;
1624         CDR_about = CDR__about;
1625         CDR_setfilename = CDR__setfilename;
1626
1627         numtracks = 0;
1628 }
1629
1630 int cdrIsoActive(void) {
1631         return (cdHandle != NULL);
1632 }