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