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