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