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