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