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