misc: merge from pcsxr r86908
[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 \"%256[^\"]\"", tmpb);
556                         if (t != 1)
557                                 sscanf(linebuf, " FILE %256s", 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         numtracks = 0;
799
800         ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
801         if (ret != sizeof(pbp_hdr)) {
802                 SysPrintf("failed to read pbp\n");
803                 goto fail_io;
804         }
805
806         ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
807         if (ret != 0) {
808                 SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs);
809                 goto fail_io;
810         }
811
812         psisoimg_offs = pbp_hdr.psar_offs;
813         fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
814         psar_sig[10] = 0;
815         if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
816                 // multidisk image?
817                 ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x200, SEEK_SET);
818                 if (ret != 0) {
819                         SysPrintf("failed to seek to %x\n", pbp_hdr.psar_offs + 0x200);
820                         goto fail_io;
821                 }
822
823                 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
824                         SysPrintf("failed to read offsettab\n");
825                         goto fail_io;
826                 }
827
828                 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
829                         if (offsettab[i] == 0)
830                                 break;
831                 }
832                 cdrIsoMultidiskCount = i;
833                 if (cdrIsoMultidiskCount == 0) {
834                         SysPrintf("multidisk eboot has 0 images?\n");
835                         goto fail_io;
836                 }
837
838                 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
839                         cdrIsoMultidiskSelect = 0;
840
841                 psisoimg_offs += offsettab[cdrIsoMultidiskSelect];
842
843                 ret = fseek(cdHandle, psisoimg_offs, SEEK_SET);
844                 if (ret != 0) {
845                         SysPrintf("failed to seek to %x\n", psisoimg_offs);
846                         goto fail_io;
847                 }
848
849                 fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
850                 psar_sig[10] = 0;
851         }
852
853         if (strcmp(psar_sig, "PSISOIMG00") != 0) {
854                 SysPrintf("bad psar_sig: %s\n", psar_sig);
855                 goto fail_io;
856         }
857
858         // seek to TOC
859         ret = fseek(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
860         if (ret != 0) {
861                 SysPrintf("failed to seek to %x\n", psisoimg_offs + 0x800);
862                 goto fail_io;
863         }
864
865         // first 3 entries are special
866         fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
867         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
868         numtracks = btoi(toc_entry.index1[0]);
869
870         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
871         cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
872                 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
873
874         for (i = 1; i <= numtracks; i++) {
875                 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
876
877                 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
878
879                 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
880                         btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
881                 ti[i].start_offset *= 2352;
882                 ti[i].start[0] = btoi(toc_entry.index1[0]);
883                 ti[i].start[1] = btoi(toc_entry.index1[1]);
884                 ti[i].start[2] = btoi(toc_entry.index1[2]);
885
886                 if (i > 1) {
887                         t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
888                         sec2msf(t, ti[i - 1].length);
889                 }
890         }
891         t = cd_length - ti[numtracks].start_offset / 2352;
892         sec2msf(t, ti[numtracks].length);
893
894         // seek to ISO index
895         ret = fseek(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
896         if (ret != 0) {
897                 SysPrintf("failed to seek to ISO index\n");
898                 goto fail_io;
899         }
900
901         compr_img = calloc(1, sizeof(*compr_img));
902         if (compr_img == NULL)
903                 goto fail_io;
904
905         compr_img->block_shift = 4;
906         compr_img->current_block = (unsigned int)-1;
907
908         compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
909         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
910         if (compr_img->index_table == NULL)
911                 goto fail_io;
912
913         cdimg_base = psisoimg_offs + 0x100000;
914         for (i = 0; i < compr_img->index_len; i++) {
915                 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
916                 if (ret != sizeof(index_entry)) {
917                         SysPrintf("failed to read index_entry #%d\n", i);
918                         goto fail_index;
919                 }
920
921                 if (index_entry.size == 0)
922                         break;
923
924                 compr_img->index_table[i] = cdimg_base + index_entry.offset;
925         }
926         compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
927
928         return 0;
929
930 fail_index:
931         free(compr_img->index_table);
932         compr_img->index_table = NULL;
933 fail_io:
934         if (compr_img != NULL) {
935                 free(compr_img);
936                 compr_img = NULL;
937         }
938         return -1;
939 }
940
941 static int handlecbin(const char *isofile) {
942         struct
943         {
944                 char magic[4];
945                 unsigned int header_size;
946                 unsigned long long total_bytes;
947                 unsigned int block_size;
948                 unsigned char ver;              // 1
949                 unsigned char align;
950                 unsigned char rsv_06[2];
951         } ciso_hdr;
952         const char *ext = NULL;
953         unsigned int index = 0, plain;
954         int i, ret;
955
956         if (strlen(isofile) >= 5)
957                 ext = isofile + strlen(isofile) - 5;
958         if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
959                 return -1;
960
961         ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
962         if (ret != sizeof(ciso_hdr)) {
963                 SysPrintf("failed to read ciso header\n");
964                 return -1;
965         }
966
967         if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
968                 SysPrintf("bad ciso header\n");
969                 return -1;
970         }
971         if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
972                 ret = fseek(cdHandle, ciso_hdr.header_size, SEEK_SET);
973                 if (ret != 0) {
974                         SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
975                         return -1;
976                 }
977         }
978
979         compr_img = calloc(1, sizeof(*compr_img));
980         if (compr_img == NULL)
981                 goto fail_io;
982
983         compr_img->block_shift = 0;
984         compr_img->current_block = (unsigned int)-1;
985
986         compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
987         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
988         if (compr_img->index_table == NULL)
989                 goto fail_io;
990
991         ret = fread(compr_img->index_table, sizeof(compr_img->index_table[0]), compr_img->index_len, cdHandle);
992         if (ret != compr_img->index_len) {
993                 SysPrintf("failed to read index table\n");
994                 goto fail_index;
995         }
996
997         for (i = 0; i < compr_img->index_len + 1; i++) {
998                 index = compr_img->index_table[i];
999                 plain = index & 0x80000000;
1000                 index &= 0x7fffffff;
1001                 compr_img->index_table[i] = (index << ciso_hdr.align) | plain;
1002         }
1003         if ((long long)index << ciso_hdr.align >= 0x80000000ll)
1004                 SysPrintf("warning: ciso img too large, expect problems\n");
1005
1006         return 0;
1007
1008 fail_index:
1009         free(compr_img->index_table);
1010         compr_img->index_table = NULL;
1011 fail_io:
1012         if (compr_img != NULL) {
1013                 free(compr_img);
1014                 compr_img = NULL;
1015         }
1016         return -1;
1017 }
1018
1019 // this function tries to get the .sub file of the given .img
1020 static int opensubfile(const char *isoname) {
1021         char            subname[MAXPATHLEN];
1022
1023         // copy name of the iso and change extension from .img to .sub
1024         strncpy(subname, isoname, sizeof(subname));
1025         subname[MAXPATHLEN - 1] = '\0';
1026         if (strlen(subname) >= 4) {
1027                 strcpy(subname + strlen(subname) - 4, ".sub");
1028         }
1029         else {
1030                 return -1;
1031         }
1032
1033         subHandle = fopen(subname, "rb");
1034         if (subHandle == NULL) {
1035                 return -1;
1036         }
1037
1038         return 0;
1039 }
1040
1041 static int opensbifile(const char *isoname) {
1042         char            sbiname[MAXPATHLEN];
1043         int             s;
1044
1045         strncpy(sbiname, isoname, sizeof(sbiname));
1046         sbiname[MAXPATHLEN - 1] = '\0';
1047         if (strlen(sbiname) >= 4) {
1048                 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
1049         }
1050         else {
1051                 return -1;
1052         }
1053
1054         fseek(cdHandle, 0, SEEK_END);
1055         s = ftell(cdHandle) / 2352;
1056
1057         return LoadSBI(sbiname, s);
1058 }
1059
1060 static int cdread_normal(FILE *f, unsigned int base, void *dest, int sector)
1061 {
1062         fseek(f, base + sector * CD_FRAMESIZE_RAW, SEEK_SET);
1063         return fread(dest, 1, CD_FRAMESIZE_RAW, f);
1064 }
1065
1066 static int cdread_sub_mixed(FILE *f, unsigned int base, void *dest, int sector)
1067 {
1068         int ret;
1069
1070         fseek(f, base + sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE), SEEK_SET);
1071         ret = fread(dest, 1, CD_FRAMESIZE_RAW, f);
1072         fread(subbuffer, 1, SUB_FRAMESIZE, f);
1073
1074         if (subChanRaw) DecodeRawSubData();
1075
1076         return ret;
1077 }
1078
1079 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
1080 {
1081         static z_stream z;
1082         int ret = 0;
1083
1084         if (z.zalloc == NULL) {
1085                 // XXX: one-time leak here..
1086                 z.next_in = Z_NULL;
1087                 z.avail_in = 0;
1088                 z.zalloc = Z_NULL;
1089                 z.zfree = Z_NULL;
1090                 z.opaque = Z_NULL;
1091                 ret = inflateInit2(&z, -15);
1092         }
1093         else
1094                 ret = inflateReset(&z);
1095         if (ret != Z_OK)
1096                 return ret;
1097
1098         z.next_in = in;
1099         z.avail_in = in_size;
1100         z.next_out = out;
1101         z.avail_out = *out_size;
1102
1103         ret = inflate(&z, Z_NO_FLUSH);
1104         //inflateEnd(&z);
1105
1106         *out_size -= z.avail_out;
1107         return ret == 1 ? 0 : ret;
1108 }
1109
1110 static int cdread_compressed(FILE *f, unsigned int base, void *dest, int sector)
1111 {
1112         unsigned long cdbuffer_size, cdbuffer_size_expect;
1113         unsigned int start_byte, size;
1114         int is_compressed;
1115         int ret, block;
1116
1117         if (base)
1118                 sector += base / 2352;
1119
1120         block = sector >> compr_img->block_shift;
1121         compr_img->sector_in_blk = sector & ((1 << compr_img->block_shift) - 1);
1122
1123         if (block == compr_img->current_block) {
1124                 //printf("hit sect %d\n", sector);
1125                 goto finish;
1126         }
1127
1128         if (sector >= compr_img->index_len * 16) {
1129                 SysPrintf("sector %d is past img end\n", sector);
1130                 return -1;
1131         }
1132
1133         start_byte = compr_img->index_table[block] & 0x7fffffff;
1134         if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
1135                 SysPrintf("seek error for block %d at %x: ",
1136                         block, start_byte);
1137                 perror(NULL);
1138                 return -1;
1139         }
1140
1141         is_compressed = !(compr_img->index_table[block] & 0x80000000);
1142         size = (compr_img->index_table[block + 1] & 0x7fffffff) - start_byte;
1143         if (size > sizeof(compr_img->buff_compressed)) {
1144                 SysPrintf("block %d is too large: %u\n", block, size);
1145                 return -1;
1146         }
1147
1148         if (fread(is_compressed ? compr_img->buff_compressed : compr_img->buff_raw[0],
1149                                 1, size, cdHandle) != size) {
1150                 SysPrintf("read error for block %d at %x: ", block, start_byte);
1151                 perror(NULL);
1152                 return -1;
1153         }
1154
1155         if (is_compressed) {
1156                 cdbuffer_size_expect = sizeof(compr_img->buff_raw[0]) << compr_img->block_shift;
1157                 cdbuffer_size = cdbuffer_size_expect;
1158                 ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
1159                 if (ret != 0) {
1160                         SysPrintf("uncompress failed with %d for block %d, sector %d\n",
1161                                         ret, block, sector);
1162                         return -1;
1163                 }
1164                 if (cdbuffer_size != cdbuffer_size_expect)
1165                         SysPrintf("cdbuffer_size: %lu != %lu, sector %d\n", cdbuffer_size,
1166                                         cdbuffer_size_expect, sector);
1167         }
1168
1169         // done at last!
1170         compr_img->current_block = block;
1171
1172 finish:
1173         if (dest != cdbuffer) // copy avoid HACK
1174                 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk],
1175                         CD_FRAMESIZE_RAW);
1176         return CD_FRAMESIZE_RAW;
1177 }
1178
1179 static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
1180 {
1181         int ret;
1182
1183         fseek(f, base + sector * 2048, SEEK_SET);
1184         ret = fread((char *)dest + 12 * 2, 1, 2048, f);
1185
1186         // not really necessary, fake mode 2 header
1187         memset(cdbuffer, 0, 12 * 2);
1188         sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1189         cdbuffer[12 + 3] = 1;
1190
1191         return ret;
1192 }
1193
1194 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1195         return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1196 }
1197
1198 static unsigned char * CALLBACK ISOgetBuffer(void) {
1199         return cdbuffer + 12;
1200 }
1201
1202 static void PrintTracks(void) {
1203         int i;
1204
1205         for (i = 1; i <= numtracks; i++) {
1206                 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1207                         i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1208                         ti[i].start[0], ti[i].start[1], ti[i].start[2],
1209                         ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1210         }
1211 }
1212
1213 // This function is invoked by the front-end when opening an ISO
1214 // file for playback
1215 static long CALLBACK ISOopen(void) {
1216         boolean isMode1ISO = FALSE;
1217         char alt_bin_filename[MAXPATHLEN];
1218         const char *bin_filename;
1219
1220         if (cdHandle != NULL) {
1221                 return 0; // it's already open
1222         }
1223
1224         cdHandle = fopen(GetIsoFile(), "rb");
1225         if (cdHandle == NULL) {
1226                 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1227                         GetIsoFile(), strerror(errno));
1228                 return -1;
1229         }
1230
1231         SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1232
1233         cddaBigEndian = FALSE;
1234         subChanMixed = FALSE;
1235         subChanRaw = FALSE;
1236         pregapOffset = 0;
1237         cdrIsoMultidiskCount = 1;
1238         multifile = 0;
1239
1240         CDR_getBuffer = ISOgetBuffer;
1241         cdimg_read_func = cdread_normal;
1242
1243         if (parsetoc(GetIsoFile()) == 0) {
1244                 SysPrintf("[+toc]");
1245         }
1246         else if (parseccd(GetIsoFile()) == 0) {
1247                 SysPrintf("[+ccd]");
1248         }
1249         else if (parsemds(GetIsoFile()) == 0) {
1250                 SysPrintf("[+mds]");
1251         }
1252         else if (parsecue(GetIsoFile()) == 0) {
1253                 SysPrintf("[+cue]");
1254         }
1255         if (handlepbp(GetIsoFile()) == 0) {
1256                 SysPrintf("[pbp]");
1257                 CDR_getBuffer = ISOgetBuffer_compr;
1258                 cdimg_read_func = cdread_compressed;
1259         }
1260         else if (handlecbin(GetIsoFile()) == 0) {
1261                 SysPrintf("[cbin]");
1262                 CDR_getBuffer = ISOgetBuffer_compr;
1263                 cdimg_read_func = cdread_compressed;
1264         }
1265
1266         if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1267                 SysPrintf("[+sub]");
1268         }
1269         if (opensbifile(GetIsoFile()) == 0) {
1270                 SysPrintf("[+sbi]");
1271         }
1272
1273         fseek(cdHandle, 0, SEEK_END);
1274
1275         // maybe user selected metadata file instead of main .bin ..
1276         bin_filename = GetIsoFile();
1277         if (ftell(cdHandle) < 2352 * 0x10) {
1278                 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
1279                 FILE *tmpf = NULL;
1280                 size_t i;
1281                 char *p;
1282
1283                 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1284                 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1285                 if (strlen(alt_bin_filename) >= 4) {
1286                         p = alt_bin_filename + strlen(alt_bin_filename) - 4;
1287                         for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1288                                 strcpy(p, exts[i]);
1289                                 tmpf = fopen(alt_bin_filename, "rb");
1290                                 if (tmpf != NULL)
1291                                         break;
1292                         }
1293                 }
1294                 if (tmpf != NULL) {
1295                         bin_filename = alt_bin_filename;
1296                         fclose(cdHandle);
1297                         cdHandle = tmpf;
1298                         fseek(cdHandle, 0, SEEK_END);
1299                 }
1300         }
1301
1302         // guess whether it is mode1/2048
1303         if (ftell(cdHandle) % 2048 == 0) {
1304                 unsigned int modeTest = 0;
1305                 fseek(cdHandle, 0, SEEK_SET);
1306                 fread(&modeTest, 4, 1, cdHandle);
1307                 if (SWAP32(modeTest) != 0xffffff00) {
1308                         SysPrintf("[2048]");
1309                         isMode1ISO = TRUE;
1310                 }
1311         }
1312         fseek(cdHandle, 0, SEEK_SET);
1313
1314         SysPrintf(".\n");
1315
1316         PrintTracks();
1317
1318         if (subChanMixed)
1319                 cdimg_read_func = cdread_sub_mixed;
1320         else if (isMode1ISO)
1321                 cdimg_read_func = cdread_2048;
1322
1323         // make sure we have another handle open for cdda
1324         if (numtracks > 1 && ti[1].handle == NULL) {
1325                 ti[1].handle = fopen(bin_filename, "rb");
1326         }
1327         cdda_cur_sector = 0;
1328         cdda_file_offset = 0;
1329
1330         return 0;
1331 }
1332
1333 static long CALLBACK ISOclose(void) {
1334         int i;
1335
1336         if (cdHandle != NULL) {
1337                 fclose(cdHandle);
1338                 cdHandle = NULL;
1339         }
1340         if (subHandle != NULL) {
1341                 fclose(subHandle);
1342                 subHandle = NULL;
1343         }
1344         stopCDDA();
1345         cddaHandle = NULL;
1346
1347         if (compr_img != NULL) {
1348                 free(compr_img->index_table);
1349                 free(compr_img);
1350                 compr_img = NULL;
1351         }
1352
1353         for (i = 1; i <= numtracks; i++) {
1354                 if (ti[i].handle != NULL) {
1355                         fclose(ti[i].handle);
1356                         ti[i].handle = NULL;
1357                 }
1358         }
1359         numtracks = 0;
1360         ti[1].type = 0;
1361         UnloadSBI();
1362
1363         memset(cdbuffer, 0, sizeof(cdbuffer));
1364         CDR_getBuffer = ISOgetBuffer;
1365
1366         return 0;
1367 }
1368
1369 static long CALLBACK ISOinit(void) {
1370         assert(cdHandle == NULL);
1371         assert(subHandle == NULL);
1372
1373         return 0; // do nothing
1374 }
1375
1376 static long CALLBACK ISOshutdown(void) {
1377         ISOclose();
1378         return 0;
1379 }
1380
1381 // return Starting and Ending Track
1382 // buffer:
1383 //  byte 0 - start track
1384 //  byte 1 - end track
1385 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1386         buffer[0] = 1;
1387
1388         if (numtracks > 0) {
1389                 buffer[1] = numtracks;
1390         }
1391         else {
1392                 buffer[1] = 1;
1393         }
1394
1395         return 0;
1396 }
1397
1398 // return Track Time
1399 // buffer:
1400 //  byte 0 - frame
1401 //  byte 1 - second
1402 //  byte 2 - minute
1403 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1404         if (track == 0) {
1405                 unsigned int sect;
1406                 unsigned char time[3];
1407                 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1408                 sec2msf(sect, (char *)time);
1409                 buffer[2] = time[0];
1410                 buffer[1] = time[1];
1411                 buffer[0] = time[2];
1412         }
1413         else if (numtracks > 0 && track <= numtracks) {
1414                 buffer[2] = ti[track].start[0];
1415                 buffer[1] = ti[track].start[1];
1416                 buffer[0] = ti[track].start[2];
1417         }
1418         else {
1419                 buffer[2] = 0;
1420                 buffer[1] = 2;
1421                 buffer[0] = 0;
1422         }
1423
1424         return 0;
1425 }
1426
1427 // decode 'raw' subchannel data ripped by cdrdao
1428 static void DecodeRawSubData(void) {
1429         unsigned char subQData[12];
1430         int i;
1431
1432         memset(subQData, 0, sizeof(subQData));
1433
1434         for (i = 0; i < 8 * 12; i++) {
1435                 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1436                         subQData[i >> 3] |= (1 << (7 - (i & 7)));
1437                 }
1438         }
1439
1440         memcpy(&subbuffer[12], subQData, 12);
1441 }
1442
1443 // read track
1444 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1445 // uses bcd format
1446 static long CALLBACK ISOreadTrack(unsigned char *time) {
1447         int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1448         long ret;
1449
1450         if (cdHandle == NULL) {
1451                 return -1;
1452         }
1453
1454         if (pregapOffset) {
1455                 subChanMissing = FALSE;
1456                 if (sector >= pregapOffset) {
1457                         sector -= 2 * 75;
1458                         if (sector < pregapOffset)
1459                                 subChanMissing = TRUE;
1460                 }
1461         }
1462
1463         ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1464         if (ret < 0)
1465                 return -1;
1466
1467         if (subHandle != NULL) {
1468                 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1469                 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1470
1471                 if (subChanRaw) DecodeRawSubData();
1472         }
1473
1474         return 0;
1475 }
1476
1477 // plays cdda audio
1478 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1479 // does NOT uses bcd format
1480 static long CALLBACK ISOplay(unsigned char *time) {
1481         unsigned int i;
1482
1483         if (numtracks <= 1)
1484                 return 0;
1485
1486         // find the track
1487         cdda_cur_sector = msf2sec((char *)time);
1488         for (i = numtracks; i > 1; i--) {
1489                 cdda_first_sector = msf2sec(ti[i].start);
1490                 if (cdda_first_sector <= cdda_cur_sector + 2 * 75)
1491                         break;
1492         }
1493         cdda_file_offset = ti[i].start_offset;
1494
1495         // find the file that contains this track
1496         for (; i > 1; i--)
1497                 if (ti[i].handle != NULL)
1498                         break;
1499
1500         cddaHandle = ti[i].handle;
1501
1502         if (SPU_playCDDAchannel != NULL)
1503                 startCDDA();
1504
1505         return 0;
1506 }
1507
1508 // stops cdda audio
1509 static long CALLBACK ISOstop(void) {
1510         stopCDDA();
1511         return 0;
1512 }
1513
1514 // gets subchannel data
1515 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1516         if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1517                 return subbuffer;
1518         }
1519
1520         return NULL;
1521 }
1522
1523 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1524         u32 sect;
1525         
1526         CDR__getStatus(stat);
1527         
1528         if (playing) {
1529                 stat->Type = 0x02;
1530                 stat->Status |= 0x80;
1531         }
1532         else {
1533                 // BIOS - boot ID (CD type)
1534                 stat->Type = ti[1].type;
1535         }
1536         
1537         // relative -> absolute time
1538         sect = cddaCurPos;
1539         sec2msf(sect, (char *)stat->Time);
1540         
1541         return 0;
1542 }
1543
1544 // read CDDA sector into buffer
1545 long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1546         unsigned char msf[3] = {m, s, f};
1547         unsigned int file, track, track_start = 0;
1548         int ret;
1549
1550         cddaCurPos = msf2sec((char *)msf);
1551
1552         // find current track index
1553         for (track = numtracks; ; track--) {
1554                 track_start = msf2sec(ti[track].start);
1555                 if (track_start <= cddaCurPos)
1556                         break;
1557                 if (track == 1)
1558                         break;
1559         }
1560
1561         // data tracks play silent
1562         if (ti[track].type != CDDA) {
1563                 memset(buffer, 0, CD_FRAMESIZE_RAW);
1564                 return 0;
1565         }
1566
1567         file = 1;
1568         if (multifile) {
1569                 // find the file that contains this track
1570                 for (file = track; file > 1; file--)
1571                         if (ti[file].handle != NULL)
1572                                 break;
1573         }
1574
1575         ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1576                 buffer, cddaCurPos - track_start);
1577         if (ret != CD_FRAMESIZE_RAW) {
1578                 memset(buffer, 0, CD_FRAMESIZE_RAW);
1579                 return -1;
1580         }
1581
1582         if (cddaBigEndian) {
1583                 int i;
1584                 unsigned char tmp;
1585
1586                 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1587                         tmp = buffer[i * 2];
1588                         buffer[i * 2] = buffer[i * 2 + 1];
1589                         buffer[i * 2 + 1] = tmp;
1590                 }
1591         }
1592
1593         return 0;
1594 }
1595
1596 void cdrIsoInit(void) {
1597         CDR_init = ISOinit;
1598         CDR_shutdown = ISOshutdown;
1599         CDR_open = ISOopen;
1600         CDR_close = ISOclose;
1601         CDR_getTN = ISOgetTN;
1602         CDR_getTD = ISOgetTD;
1603         CDR_readTrack = ISOreadTrack;
1604         CDR_getBuffer = ISOgetBuffer;
1605         CDR_play = ISOplay;
1606         CDR_stop = ISOstop;
1607         CDR_getBufferSub = ISOgetBufferSub;
1608         CDR_getStatus = ISOgetStatus;
1609         CDR_readCDDA = ISOreadCDDA;
1610
1611         CDR_getDriveLetter = CDR__getDriveLetter;
1612         CDR_configure = CDR__configure;
1613         CDR_test = CDR__test;
1614         CDR_about = CDR__about;
1615         CDR_setfilename = CDR__setfilename;
1616
1617         numtracks = 0;
1618 }
1619
1620 int cdrIsoActive(void) {
1621         return (cdHandle != NULL);
1622 }