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