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