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