drc: fix SP mirror hack
[pcsx_rearmed.git] / libpcsxcore / cdriso.c
1 /***************************************************************************
2  *   Copyright (C) 2007 PCSX-df Team                                       *
3  *   Copyright (C) 2009 Wei Mingzhi                                        *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA.           *
19  ***************************************************************************/
20
21 #include "psxcommon.h"
22 #include "plugins.h"
23 #include "cdrom.h"
24 #include "cdriso.h"
25 #include "ppf.h"
26
27 #ifdef _WIN32
28 #include <process.h>
29 #include <windows.h>
30 #else
31 #include <pthread.h>
32 #include <sys/time.h>
33 #endif
34 #include <zlib.h>
35
36 static FILE *cdHandle = NULL;
37 static FILE *cddaHandle = NULL;
38 static FILE *subHandle = NULL;
39
40 static boolean subChanMixed = FALSE;
41 static boolean subChanRaw = FALSE;
42 static boolean subChanMissing = FALSE;
43
44 static unsigned char cdbuffer[DATA_SIZE];
45 static unsigned char subbuffer[SUB_FRAMESIZE];
46
47 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
48
49 #define CDDA_FRAMETIME                  (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
50
51 #ifdef _WIN32
52 static HANDLE threadid;
53 #else
54 static pthread_t threadid;
55 #endif
56 static unsigned int initial_offset = 0;
57 static boolean playing = FALSE;
58 static boolean cddaBigEndian = FALSE;
59 static unsigned int cdda_cur_sector;
60 static unsigned int cdda_start_sector;
61 /* Frame offset into CD image where pregap data would be found if it was there.
62  * If a game seeks there we must *not* return subchannel data since it's
63  * not in the CD image, so that cdrom code can fake subchannel data instead.
64  * XXX: there could be multiple pregaps but PSX dumps only have one? */
65 static unsigned int pregapOffset;
66
67 // compressed image stuff
68 static struct {
69         unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
70         unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
71         unsigned int *index_table;
72         unsigned int index_len;
73         unsigned int current_block;
74         unsigned int sector_in_blk;
75 } *compr_img;
76
77 int (*cdimg_read_func)(FILE *f, void *dest, int sector, int offset);
78
79 char* CALLBACK CDR__getDriveLetter(void);
80 long CALLBACK CDR__configure(void);
81 long CALLBACK CDR__test(void);
82 void CALLBACK CDR__about(void);
83 long CALLBACK CDR__setfilename(char *filename);
84 long CALLBACK CDR__getStatus(struct CdrStat *stat);
85
86 static void DecodeRawSubData(void);
87
88 extern void *hCDRDriver;
89
90 struct trackinfo {
91         enum {DATA, CDDA} type;
92         char start[3];          // MSF-format
93         char length[3];         // MSF-format
94         FILE *handle;           // for multi-track images CDDA
95         int start_offset;       // sector offset from start of above file
96 };
97
98 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
99
100 static int numtracks = 0;
101 static struct trackinfo ti[MAXTRACKS];
102
103 // get a sector from a msf-array
104 static unsigned int msf2sec(char *msf) {
105         return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
106 }
107
108 static void sec2msf(unsigned int s, char *msf) {
109         msf[0] = s / 75 / 60;
110         s = s - msf[0] * 75 * 60;
111         msf[1] = s / 75;
112         s = s - msf[1] * 75;
113         msf[2] = s;
114 }
115
116 // divide a string of xx:yy:zz into m, s, f
117 static void tok2msf(char *time, char *msf) {
118         char *token;
119
120         token = strtok(time, ":");
121         if (token) {
122                 msf[0] = atoi(token);
123         }
124         else {
125                 msf[0] = 0;
126         }
127
128         token = strtok(NULL, ":");
129         if (token) {
130                 msf[1] = atoi(token);
131         }
132         else {
133                 msf[1] = 0;
134         }
135
136         token = strtok(NULL, ":");
137         if (token) {
138                 msf[2] = atoi(token);
139         }
140         else {
141                 msf[2] = 0;
142         }
143 }
144
145 #ifndef _WIN32
146 static long GetTickCount(void) {
147         static time_t           initial_time = 0;
148         struct timeval          now;
149
150         gettimeofday(&now, NULL);
151
152         if (initial_time == 0) {
153                 initial_time = now.tv_sec;
154         }
155
156         return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
157 }
158 #endif
159
160 // this thread plays audio data
161 #ifdef _WIN32
162 static void playthread(void *param)
163 #else
164 static void *playthread(void *param)
165 #endif
166 {
167         long                    d, t, i, s;
168         unsigned char   tmp;
169
170         t = GetTickCount();
171
172         while (playing) {
173                 d = t - (long)GetTickCount();
174                 if (d <= 0) {
175                         d = 1;
176                 }
177                 else if (d > CDDA_FRAMETIME) {
178                         d = CDDA_FRAMETIME;
179                 }
180 #ifdef _WIN32
181                 Sleep(d);
182 #else
183                 usleep(d * 1000);
184 #endif
185                 // HACK: stop feeding data while emu is paused
186                 extern int stop;
187                 if (stop) {
188                         usleep(100000);
189                         continue;
190                 }
191
192                 t = GetTickCount() + CDDA_FRAMETIME;
193
194                 s = 0;
195                 for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
196                         d = cdimg_read_func(cddaHandle, sndbuffer + s, cdda_cur_sector, 0);
197                         if (d < CD_FRAMESIZE_RAW)
198                                 break;
199
200                         s += d;
201                         cdda_cur_sector++;
202                 }
203
204                 if (subHandle != NULL) {
205                         fseek(subHandle, cdda_cur_sector * SUB_FRAMESIZE, SEEK_SET);
206                         fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
207
208                         if (subChanRaw) DecodeRawSubData();
209                 }
210
211                 if (s == 0) {
212                         playing = FALSE;
213                         initial_offset = 0;
214                         break;
215                 }
216
217                 if (!cdr.Muted && playing) {
218                         if (cddaBigEndian) {
219                                 for (i = 0; i < s / 2; i++) {
220                                         tmp = sndbuffer[i * 2];
221                                         sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
222                                         sndbuffer[i * 2 + 1] = tmp;
223                                 }
224                         }
225
226                         SPU_playCDDAchannel((short *)sndbuffer, s);
227                 }
228         }
229
230 #ifdef _WIN32
231         _endthread();
232 #else
233         pthread_exit(0);
234         return NULL;
235 #endif
236 }
237
238 // stop the CDDA playback
239 static void stopCDDA() {
240         if (!playing) {
241                 return;
242         }
243
244         playing = FALSE;
245 #ifdef _WIN32
246         WaitForSingleObject(threadid, INFINITE);
247 #else
248         pthread_join(threadid, NULL);
249 #endif
250 }
251
252 // start the CDDA playback
253 static void startCDDA(unsigned int sector) {
254         if (playing) {
255                 stopCDDA();
256         }
257
258         cdda_cur_sector = sector;
259         playing = TRUE;
260
261 #ifdef _WIN32
262         threadid = (HANDLE)_beginthread(playthread, 0, NULL);
263 #else
264         pthread_create(&threadid, NULL, playthread, NULL);
265 #endif
266 }
267
268 // this function tries to get the .toc file of the given .bin
269 // the necessary data is put into the ti (trackinformation)-array
270 static int parsetoc(const char *isofile) {
271         char                    tocname[MAXPATHLEN];
272         FILE                    *fi;
273         char                    linebuf[256], dummy[256], name[256];
274         char                    *token;
275         char                    time[20], time2[20];
276         unsigned int    t, sector_offs;
277
278         numtracks = 0;
279
280         // copy name of the iso and change extension from .bin to .toc
281         strncpy(tocname, isofile, sizeof(tocname));
282         tocname[MAXPATHLEN - 1] = '\0';
283         if (strlen(tocname) >= 4) {
284                 strcpy(tocname + strlen(tocname) - 4, ".toc");
285         }
286         else {
287                 return -1;
288         }
289
290         if ((fi = fopen(tocname, "r")) == NULL) {
291                 // try changing extension to .cue (to satisfy some stupid tutorials)
292                 strcpy(tocname + strlen(tocname) - 4, ".cue");
293                 if ((fi = fopen(tocname, "r")) == NULL) {
294                         // if filename is image.toc.bin, try removing .bin (for Brasero)
295                         strcpy(tocname, isofile);
296                         t = strlen(tocname);
297                         if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
298                                 tocname[t - 4] = '\0';
299                                 if ((fi = fopen(tocname, "r")) == NULL) {
300                                         return -1;
301                                 }
302                         }
303                         else {
304                                 return -1;
305                         }
306                 }
307         }
308
309         memset(&ti, 0, sizeof(ti));
310         cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
311
312         sector_offs = 2 * 75;
313
314         // parse the .toc file
315         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
316                 // search for tracks
317                 strncpy(dummy, linebuf, sizeof(linebuf));
318                 token = strtok(dummy, " ");
319
320                 if (token == NULL) continue;
321
322                 if (!strcmp(token, "TRACK")) {
323                         // get type of track
324                         token = strtok(NULL, " ");
325                         numtracks++;
326
327                         if (!strncmp(token, "MODE2_RAW", 9)) {
328                                 ti[numtracks].type = DATA;
329                                 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
330
331                                 // check if this image contains mixed subchannel data
332                                 token = strtok(NULL, " ");
333                                 if (token != NULL && !strncmp(token, "RW_RAW", 6)) {
334                                         subChanMixed = TRUE;
335                                         subChanRaw = TRUE;
336                                 }
337                         }
338                         else if (!strncmp(token, "AUDIO", 5)) {
339                                 ti[numtracks].type = CDDA;
340                         }
341                 }
342                 else if (!strcmp(token, "DATAFILE")) {
343                         if (ti[numtracks].type == CDDA) {
344                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
345                                 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
346                                 ti[numtracks].start_offset = t;
347                                 t += sector_offs;
348                                 sec2msf(t, (char *)&ti[numtracks].start);
349                                 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
350                         }
351                         else {
352                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
353                                 tok2msf((char *)&time, (char *)&ti[numtracks].length);
354                         }
355                 }
356                 else if (!strcmp(token, "FILE")) {
357                         sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
358                         tok2msf((char *)&time, (char *)&ti[numtracks].start);
359                         t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
360                         ti[numtracks].start_offset = t;
361                         t += msf2sec(ti[numtracks].start) + sector_offs;
362                         sec2msf(t, (char *)&ti[numtracks].start);
363                         tok2msf((char *)&time2, (char *)&ti[numtracks].length);
364                 }
365                 else if (!strcmp(token, "ZERO")) {
366                         sscanf(linebuf, "ZERO AUDIO RW_RAW %8s", time);
367                         tok2msf((char *)&time, dummy);
368                         sector_offs += msf2sec(dummy);
369                         if (numtracks > 1) {
370                                 t = ti[numtracks - 1].start_offset;
371                                 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
372                         }
373                 }
374         }
375
376         fclose(fi);
377
378         return 0;
379 }
380
381 // this function tries to get the .cue file of the given .bin
382 // the necessary data is put into the ti (trackinformation)-array
383 static int parsecue(const char *isofile) {
384         char                    cuename[MAXPATHLEN];
385         char                    filepath[MAXPATHLEN];
386         char                    *incue_fname;
387         FILE                    *fi;
388         char                    *token;
389         char                    time[20];
390         char                    *tmp;
391         char                    linebuf[256], tmpb[256], dummy[256];
392         unsigned int    incue_max_len;
393         unsigned int    t, file_len, sector_offs;
394
395         numtracks = 0;
396
397         // copy name of the iso and change extension from .bin to .cue
398         strncpy(cuename, isofile, sizeof(cuename));
399         cuename[MAXPATHLEN - 1] = '\0';
400         if (strlen(cuename) >= 4) {
401                 strcpy(cuename + strlen(cuename) - 4, ".cue");
402         }
403         else {
404                 return -1;
405         }
406
407         if ((fi = fopen(cuename, "r")) == NULL) {
408                 return -1;
409         }
410
411         // Some stupid tutorials wrongly tell users to use cdrdao to rip a
412         // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
413         // that...
414         if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
415                 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
416                         // Don't proceed further, as this is actually a .toc file rather
417                         // than a .cue file.
418                         fclose(fi);
419                         return parsetoc(isofile);
420                 }
421                 fseek(fi, 0, SEEK_SET);
422         }
423
424         // build a path for files referenced in .cue
425         strncpy(filepath, cuename, sizeof(filepath));
426         tmp = strrchr(filepath, '/') + 1;
427         if (tmp == NULL)
428                 tmp = strrchr(filepath, '\\') + 1;
429         if (tmp == NULL)
430                 tmp = filepath;
431         *tmp = 0;
432         filepath[sizeof(filepath) - 1] = 0;
433         incue_fname = tmp;
434         incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
435
436         memset(&ti, 0, sizeof(ti));
437
438         file_len = 0;
439         sector_offs = 2 * 75;
440
441         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
442                 strncpy(dummy, linebuf, sizeof(linebuf));
443                 token = strtok(dummy, " ");
444
445                 if (token == NULL) {
446                         continue;
447                 }
448
449                 if (!strcmp(token, "TRACK")) {
450                         numtracks++;
451
452                         if (strstr(linebuf, "AUDIO") != NULL) {
453                                 ti[numtracks].type = CDDA;
454                         }
455                         else if (strstr(linebuf, "MODE1/2352") != NULL || strstr(linebuf, "MODE2/2352") != NULL) {
456                                 ti[numtracks].type = DATA;
457                         }
458                 }
459                 else if (!strcmp(token, "INDEX")) {
460                         sscanf(linebuf, " INDEX %02d %8s", &t, time);
461                         tok2msf(time, (char *)&ti[numtracks].start);
462
463                         t = msf2sec(ti[numtracks].start);
464                         ti[numtracks].start_offset = t;
465                         t += sector_offs;
466                         sec2msf(t, ti[numtracks].start);
467
468                         // default track length to file length
469                         t = file_len - ti[numtracks].start_offset;
470                         sec2msf(t, ti[numtracks].length);
471
472                         if (numtracks > 1 && ti[numtracks].handle == NULL) {
473                                 // this track uses the same file as the last,
474                                 // start of this track is last track's end
475                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
476                                 sec2msf(t, ti[numtracks - 1].length);
477                         }
478                         if (numtracks > 1 && pregapOffset == -1)
479                                 pregapOffset = ti[numtracks].start_offset;
480                 }
481                 else if (!strcmp(token, "PREGAP")) {
482                         if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
483                                 tok2msf(time, dummy);
484                                 sector_offs += msf2sec(dummy);
485                         }
486                         pregapOffset = -1; // mark to fill track start_offset
487                 }
488                 else if (!strcmp(token, "FILE")) {
489                         sscanf(linebuf, " FILE \"%[^\"]\"", tmpb);
490
491                         // absolute path?
492                         ti[numtracks + 1].handle = fopen(tmpb, "rb");
493                         if (ti[numtracks + 1].handle == NULL) {
494                                 // relative to .cue?
495                                 tmp = strrchr(tmpb, '\\');
496                                 if (tmp == NULL)
497                                         tmp = strrchr(tmpb, '/');
498                                 if (tmp != NULL)
499                                         tmp++;
500                                 else
501                                         tmp = tmpb;
502                                 strncpy(incue_fname, tmp, incue_max_len);
503                                 ti[numtracks + 1].handle = fopen(filepath, "rb");
504                         }
505
506                         // update global offset if this is not first file in this .cue
507                         if (numtracks + 1 > 1)
508                                 sector_offs += file_len;
509
510                         file_len = 0;
511                         if (ti[numtracks + 1].handle == NULL) {
512                                 SysPrintf(_("\ncould not open: %s\n"), filepath);
513                                 continue;
514                         }
515                         fseek(ti[numtracks + 1].handle, 0, SEEK_END);
516                         file_len = ftell(ti[numtracks + 1].handle) / 2352;
517
518                         if (numtracks == 0 && strlen(isofile) >= 4 &&
519                                 strcmp(isofile + strlen(isofile) - 4, ".cue") == 0)
520                         {
521                                 // user selected .cue as image file, use it's data track instead
522                                 fclose(cdHandle);
523                                 cdHandle = fopen(filepath, "rb");
524                         }
525                 }
526         }
527
528         fclose(fi);
529
530         return 0;
531 }
532
533 // this function tries to get the .ccd file of the given .img
534 // the necessary data is put into the ti (trackinformation)-array
535 static int parseccd(const char *isofile) {
536         char                    ccdname[MAXPATHLEN];
537         FILE                    *fi;
538         char                    linebuf[256];
539         unsigned int    t;
540
541         numtracks = 0;
542
543         // copy name of the iso and change extension from .img to .ccd
544         strncpy(ccdname, isofile, sizeof(ccdname));
545         ccdname[MAXPATHLEN - 1] = '\0';
546         if (strlen(ccdname) >= 4) {
547                 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
548         }
549         else {
550                 return -1;
551         }
552
553         if ((fi = fopen(ccdname, "r")) == NULL) {
554                 return -1;
555         }
556
557         memset(&ti, 0, sizeof(ti));
558
559         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
560                 if (!strncmp(linebuf, "[TRACK", 6)){
561                         numtracks++;
562                 }
563                 else if (!strncmp(linebuf, "MODE=", 5)) {
564                         sscanf(linebuf, "MODE=%d", &t);
565                         ti[numtracks].type = ((t == 0) ? CDDA : DATA);
566                 }
567                 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
568                         sscanf(linebuf, "INDEX 1=%d", &t);
569                         sec2msf(t + 2 * 75, ti[numtracks].start);
570                         ti[numtracks].start_offset = t;
571
572                         // If we've already seen another track, this is its end
573                         if (numtracks > 1) {
574                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
575                                 sec2msf(t, ti[numtracks - 1].length);
576                         }
577                 }
578         }
579
580         fclose(fi);
581
582         // Fill out the last track's end based on size
583         if (numtracks >= 1) {
584                 fseek(cdHandle, 0, SEEK_END);
585                 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
586                 sec2msf(t, ti[numtracks].length);
587         }
588
589         return 0;
590 }
591
592 // this function tries to get the .mds file of the given .mdf
593 // the necessary data is put into the ti (trackinformation)-array
594 static int parsemds(const char *isofile) {
595         char                    mdsname[MAXPATHLEN];
596         FILE                    *fi;
597         unsigned int    offset, extra_offset, l, i;
598         unsigned short  s;
599
600         numtracks = 0;
601
602         // copy name of the iso and change extension from .mdf to .mds
603         strncpy(mdsname, isofile, sizeof(mdsname));
604         mdsname[MAXPATHLEN - 1] = '\0';
605         if (strlen(mdsname) >= 4) {
606                 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
607         }
608         else {
609                 return -1;
610         }
611
612         if ((fi = fopen(mdsname, "rb")) == NULL) {
613                 return -1;
614         }
615
616         memset(&ti, 0, sizeof(ti));
617
618         // check if it's a valid mds file
619         fread(&i, 1, sizeof(unsigned int), fi);
620         i = SWAP32(i);
621         if (i != 0x4944454D) {
622                 // not an valid mds file
623                 fclose(fi);
624                 return -1;
625         }
626
627         // get offset to session block
628         fseek(fi, 0x50, SEEK_SET);
629         fread(&offset, 1, sizeof(unsigned int), fi);
630         offset = SWAP32(offset);
631
632         // get total number of tracks
633         offset += 14;
634         fseek(fi, offset, SEEK_SET);
635         fread(&s, 1, sizeof(unsigned short), fi);
636         s = SWAP16(s);
637         numtracks = s;
638
639         // get offset to track blocks
640         fseek(fi, 4, SEEK_CUR);
641         fread(&offset, 1, sizeof(unsigned int), fi);
642         offset = SWAP32(offset);
643
644         // skip lead-in data
645         while (1) {
646                 fseek(fi, offset + 4, SEEK_SET);
647                 if (fgetc(fi) < 0xA0) {
648                         break;
649                 }
650                 offset += 0x50;
651         }
652
653         // check if the image contains mixed subchannel data
654         fseek(fi, offset + 1, SEEK_SET);
655         subChanMixed = (fgetc(fi) ? TRUE : FALSE);
656
657         // read track data
658         for (i = 1; i <= numtracks; i++) {
659                 fseek(fi, offset, SEEK_SET);
660
661                 // get the track type
662                 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
663                 fseek(fi, 8, SEEK_CUR);
664
665                 // get the track starting point
666                 ti[i].start[0] = fgetc(fi);
667                 ti[i].start[1] = fgetc(fi);
668                 ti[i].start[2] = fgetc(fi);
669
670                 fread(&extra_offset, 1, sizeof(unsigned int), fi);
671                 extra_offset = SWAP32(extra_offset);
672
673                 // get track start offset (in .mdf)
674                 fseek(fi, offset + 0x28, SEEK_SET);
675                 fread(&l, 1, sizeof(unsigned int), fi);
676                 l = SWAP32(l);
677                 ti[i].start_offset = l / CD_FRAMESIZE_RAW;
678
679                 // get pregap
680                 fseek(fi, extra_offset, SEEK_SET);
681                 fread(&l, 1, sizeof(unsigned int), fi);
682                 l = SWAP32(l);
683                 if (l != 0 && i > 1)
684                         pregapOffset = ti[i].start_offset;
685
686                 // get the track length
687                 fread(&l, 1, sizeof(unsigned int), fi);
688                 l = SWAP32(l);
689                 sec2msf(l, ti[i].length);
690
691                 offset += 0x50;
692         }
693
694         fclose(fi);
695         return 0;
696 }
697
698 static int parsepbp(const char *isofile) {
699         struct {
700                 unsigned int sig;
701                 unsigned int dontcare[8];
702                 unsigned int psar_offs;
703         } pbp_hdr;
704         struct {
705                 unsigned char type;
706                 unsigned char pad0;
707                 unsigned char track;
708                 char index0[3];
709                 char pad1;
710                 char index1[3];
711         } toc_entry;
712         struct {
713                 unsigned int offset;
714                 unsigned int size;
715                 unsigned int dontcare[6];
716         } index_entry;
717         char psar_sig[9];
718         unsigned int t, cd_length, cdimg_base;
719         const char *ext = NULL;
720         int i, ret;
721
722         if (strlen(isofile) >= 4)
723                 ext = isofile + strlen(isofile) - 4;
724         if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
725                 return -1;
726
727         numtracks = 0;
728
729         ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
730         if (ret != sizeof(pbp_hdr)) {
731                 fprintf(stderr, "failed to read pbp\n");
732                 goto fail_io;
733         }
734
735         ret = fseek(cdHandle, pbp_hdr.psar_offs, SEEK_SET);
736         if (ret != 0) {
737                 fprintf(stderr, "failed to seek to %x\n", pbp_hdr.psar_offs);
738                 goto fail_io;
739         }
740
741         fread(psar_sig, 1, sizeof(psar_sig), cdHandle);
742         psar_sig[8] = 0;
743         if (strcmp(psar_sig, "PSISOIMG") != 0) {
744                 fprintf(stderr, "bad psar_sig: %s\n", psar_sig);
745                 goto fail_io;
746         }
747
748         // seek to TOC
749         ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x800, SEEK_SET);
750         if (ret != 0) {
751                 fprintf(stderr, "failed to seek to %x\n", pbp_hdr.psar_offs);
752                 goto fail_io;
753         }
754
755         // first 3 entries are special
756         fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
757         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
758         numtracks = btoi(toc_entry.index1[0]);
759
760         fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
761         cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
762                 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
763
764         for (i = 1; i <= numtracks; i++) {
765                 fread(&toc_entry, 1, sizeof(toc_entry), cdHandle);
766
767                 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
768
769                 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
770                         btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
771                 ti[i].start[0] = btoi(toc_entry.index1[0]);
772                 ti[i].start[1] = btoi(toc_entry.index1[1]);
773                 ti[i].start[2] = btoi(toc_entry.index1[2]);
774
775                 if (i > 1) {
776                         t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
777                         sec2msf(t, ti[i - 1].length);
778                 }
779         }
780         t = cd_length - ti[numtracks].start_offset;
781         sec2msf(t, ti[numtracks].length);
782
783         // seek to ISO index
784         ret = fseek(cdHandle, pbp_hdr.psar_offs + 0x4000, SEEK_SET);
785         if (ret != 0) {
786                 fprintf(stderr, "failed to seek to ISO index\n");
787                 goto fail_io;
788         }
789
790         compr_img = calloc(1, sizeof(*compr_img));
791         if (compr_img == NULL)
792                 goto fail_io;
793
794         compr_img->current_block = (unsigned int)-1;
795
796         compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
797         compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
798         if (compr_img->index_table == NULL)
799                 goto fail_io;
800
801         cdimg_base = pbp_hdr.psar_offs + 0x100000;
802         for (i = 0; i < compr_img->index_len; i++) {
803                 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
804                 if (ret != sizeof(index_entry)) {
805                         fprintf(stderr, "failed to read index_entry #%d\n", i);
806                         goto fail_index;
807                 }
808
809                 if (index_entry.size == 0)
810                         break;
811
812                 compr_img->index_table[i] = cdimg_base + index_entry.offset;
813         }
814         compr_img->index_table[i] = cdimg_base + index_entry.offset + index_entry.size;
815
816         return 0;
817
818 fail_index:
819         free(compr_img->index_table);
820         compr_img->index_table = NULL;
821 fail_io:
822         return -1;
823 }
824
825 // this function tries to get the .sub file of the given .img
826 static int opensubfile(const char *isoname) {
827         char            subname[MAXPATHLEN];
828
829         // copy name of the iso and change extension from .img to .sub
830         strncpy(subname, isoname, sizeof(subname));
831         subname[MAXPATHLEN - 1] = '\0';
832         if (strlen(subname) >= 4) {
833                 strcpy(subname + strlen(subname) - 4, ".sub");
834         }
835         else {
836                 return -1;
837         }
838
839         subHandle = fopen(subname, "rb");
840         if (subHandle == NULL) {
841                 return -1;
842         }
843
844         return 0;
845 }
846
847 static int opensbifile(const char *isoname) {
848         char            sbiname[MAXPATHLEN];
849         int             s;
850
851         strncpy(sbiname, isoname, sizeof(sbiname));
852         sbiname[MAXPATHLEN - 1] = '\0';
853         if (strlen(sbiname) >= 4) {
854                 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
855         }
856         else {
857                 return -1;
858         }
859
860         fseek(cdHandle, 0, SEEK_END);
861         s = ftell(cdHandle) / 2352;
862
863         return LoadSBI(sbiname, s);
864 }
865
866 static int cdread_normal(FILE *f, void *dest, int sector, int offset)
867 {
868         fseek(f, sector * CD_FRAMESIZE_RAW + offset, SEEK_SET);
869         return fread(dest, 1, CD_FRAMESIZE_RAW - offset, f);
870 }
871
872 static int cdread_sub_mixed(FILE *f, void *dest, int sector, int offset)
873 {
874         int ret;
875
876         fseek(f, sector * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + offset, SEEK_SET);
877         ret = fread(dest, 1, CD_FRAMESIZE_RAW - offset, f);
878         fread(subbuffer, 1, SUB_FRAMESIZE, f);
879
880         if (subChanRaw) DecodeRawSubData();
881
882         return ret;
883 }
884
885 static int uncompress2(void *out, unsigned long *out_size, void *in, unsigned long in_size)
886 {
887         static z_stream z;
888         int ret = 0;
889
890         if (z.zalloc == NULL) {
891                 // XXX: one-time leak here..
892                 z.next_in = Z_NULL;
893                 z.avail_in = 0;
894                 z.zalloc = Z_NULL;
895                 z.zfree = Z_NULL;
896                 z.opaque = Z_NULL;
897                 ret = inflateInit2(&z, -15);
898         }
899         else
900                 ret = inflateReset(&z);
901         if (ret != Z_OK)
902                 return ret;
903
904         z.next_in = in;
905         z.avail_in = in_size;
906         z.next_out = out;
907         z.avail_out = *out_size;
908
909         ret = inflate(&z, Z_NO_FLUSH);
910         //inflateEnd(&z);
911
912         *out_size -= z.avail_out;
913         return ret == 1 ? 0 : ret;
914 }
915
916 static int cdread_compressed(FILE *f, void *dest, int sector, int offset)
917 {
918         unsigned int start_byte, size;
919         unsigned long cdbuffer_size;
920         int ret, block;
921
922         block = sector >> 4;
923         compr_img->sector_in_blk = sector & 15;
924
925         if (block == compr_img->current_block) {
926                 //printf("hit sect %d\n", sector);
927                 goto finish;
928         }
929
930         if (sector >= compr_img->index_len * 16) {
931                 fprintf(stderr, "sector %d is past img end\n", sector);
932                 return -1;
933         }
934
935         start_byte = compr_img->index_table[block];
936         if (fseek(cdHandle, start_byte, SEEK_SET) != 0) {
937                 fprintf(stderr, "seek error for block %d at %x: ",
938                         block, start_byte);
939                 perror(NULL);
940                 return -1;
941         }
942
943         size = compr_img->index_table[block + 1] - start_byte;
944         if (size > sizeof(compr_img->buff_compressed)) {
945                 fprintf(stderr, "block %d is too large: %u\n", block, size);
946                 return -1;
947         }
948
949         if (fread(compr_img->buff_compressed, 1, size, cdHandle) != size) {
950                 fprintf(stderr, "read error for block %d at %x: ", block, start_byte);
951                 perror(NULL);
952                 return -1;
953         }
954
955         cdbuffer_size = sizeof(compr_img->buff_raw[0]) * 16;
956         ret = uncompress2(compr_img->buff_raw[0], &cdbuffer_size, compr_img->buff_compressed, size);
957         if (ret != 0) {
958                 fprintf(stderr, "uncompress failed with %d for block %d, sector %d\n",
959                         ret, block, sector);
960                 return -1;
961         }
962         if (cdbuffer_size != sizeof(compr_img->buff_raw[0]) * 16)
963                 fprintf(stderr, "cdbuffer_size: %lu != %d, sector %d\n", cdbuffer_size,
964                         sizeof(compr_img->buff_raw[0]) * 16, sector);
965
966         // done at last!
967         compr_img->current_block = block;
968
969 finish:
970         if (dest != cdbuffer) // copy avoid HACK
971                 memcpy(dest, compr_img->buff_raw[compr_img->sector_in_blk] + offset,
972                         CD_FRAMESIZE_RAW - offset);
973         return CD_FRAMESIZE_RAW - offset;
974 }
975
976 static int cdread_2048(FILE *f, void *dest, int sector, int offset)
977 {
978         int ret;
979
980         fseek(f, sector * 2048, SEEK_SET);
981         ret = fread((char *)dest + 12, 1, 2048, f);
982
983         // not really necessary, fake mode 2 header
984         memset(cdbuffer, 0, 12);
985         sec2msf(sector + 2 * 75, (char *)cdbuffer);
986         cdbuffer[3] = 1;
987
988         return ret;
989 }
990
991 static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
992         return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
993 }
994
995 static unsigned char * CALLBACK ISOgetBuffer(void) {
996         return cdbuffer;
997 }
998
999 static void PrintTracks(void) {
1000         int i;
1001
1002         for (i = 1; i <= numtracks; i++) {
1003                 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1004                         i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1005                         ti[i].start[0], ti[i].start[1], ti[i].start[2],
1006                         ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1007         }
1008 }
1009
1010 // This function is invoked by the front-end when opening an ISO
1011 // file for playback
1012 static long CALLBACK ISOopen(void) {
1013         boolean isMode1ISO = FALSE;
1014
1015         if (cdHandle != NULL) {
1016                 return 0; // it's already open
1017         }
1018
1019         cdHandle = fopen(GetIsoFile(), "rb");
1020         if (cdHandle == NULL) {
1021                 return -1;
1022         }
1023
1024         SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
1025
1026         cddaBigEndian = FALSE;
1027         subChanMixed = FALSE;
1028         subChanRaw = FALSE;
1029         pregapOffset = 0;
1030
1031         CDR_getBuffer = ISOgetBuffer;
1032         cdimg_read_func = cdread_normal;
1033
1034         if (parsecue(GetIsoFile()) == 0) {
1035                 SysPrintf("[+cue]");
1036         }
1037         else if (parsetoc(GetIsoFile()) == 0) {
1038                 SysPrintf("[+toc]");
1039         }
1040         else if (parseccd(GetIsoFile()) == 0) {
1041                 SysPrintf("[+ccd]");
1042         }
1043         else if (parsemds(GetIsoFile()) == 0) {
1044                 SysPrintf("[+mds]");
1045         }
1046         else if (parsepbp(GetIsoFile()) == 0) {
1047                 SysPrintf("[pbp]");
1048                 CDR_getBuffer = ISOgetBuffer_compr;
1049                 cdimg_read_func = cdread_compressed;
1050         }
1051
1052         if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
1053                 SysPrintf("[+sub]");
1054         }
1055         if (opensbifile(GetIsoFile()) == 0) {
1056                 SysPrintf("[+sbi]");
1057         }
1058
1059         // guess whether it is mode1/2048
1060         fseek(cdHandle, 0, SEEK_END);
1061         if (ftell(cdHandle) % 2048 == 0) {
1062                 unsigned int modeTest = 0;
1063                 fseek(cdHandle, 0, SEEK_SET);
1064                 fread(&modeTest, 4, 1, cdHandle);
1065                 if (SWAP32(modeTest) != 0xffffff00) {
1066                         SysPrintf("[2048]");
1067                         isMode1ISO = TRUE;
1068                 }
1069         }
1070         fseek(cdHandle, 0, SEEK_SET);
1071
1072         SysPrintf(".\n");
1073
1074         PrintTracks();
1075
1076         if (subChanMixed)
1077                 cdimg_read_func = cdread_sub_mixed;
1078         else if (isMode1ISO)
1079                 cdimg_read_func = cdread_2048;
1080
1081         // make sure we have another handle open for cdda
1082         if (numtracks > 1 && ti[1].handle == NULL) {
1083                 ti[1].handle = fopen(GetIsoFile(), "rb");
1084         }
1085         cdda_cur_sector = cdda_start_sector = 0;
1086
1087         return 0;
1088 }
1089
1090 static long CALLBACK ISOclose(void) {
1091         int i;
1092
1093         if (cdHandle != NULL) {
1094                 fclose(cdHandle);
1095                 cdHandle = NULL;
1096         }
1097         if (subHandle != NULL) {
1098                 fclose(subHandle);
1099                 subHandle = NULL;
1100         }
1101         stopCDDA();
1102         cddaHandle = NULL;
1103
1104         if (compr_img != NULL) {
1105                 free(compr_img->index_table);
1106                 free(compr_img);
1107                 compr_img = NULL;
1108         }
1109
1110         for (i = 1; i <= numtracks; i++) {
1111                 if (ti[i].handle != NULL) {
1112                         fclose(ti[i].handle);
1113                         ti[i].handle = NULL;
1114                 }
1115         }
1116         numtracks = 0;
1117         UnloadSBI();
1118
1119         return 0;
1120 }
1121
1122 static long CALLBACK ISOinit(void) {
1123         assert(cdHandle == NULL);
1124         assert(subHandle == NULL);
1125
1126         return 0; // do nothing
1127 }
1128
1129 static long CALLBACK ISOshutdown(void) {
1130         ISOclose();
1131         return 0;
1132 }
1133
1134 // return Starting and Ending Track
1135 // buffer:
1136 //  byte 0 - start track
1137 //  byte 1 - end track
1138 static long CALLBACK ISOgetTN(unsigned char *buffer) {
1139         buffer[0] = 1;
1140
1141         if (numtracks > 0) {
1142                 buffer[1] = numtracks;
1143         }
1144         else {
1145                 buffer[1] = 1;
1146         }
1147
1148         return 0;
1149 }
1150
1151 // return Track Time
1152 // buffer:
1153 //  byte 0 - frame
1154 //  byte 1 - second
1155 //  byte 2 - minute
1156 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
1157         if (track == 0) {
1158                 // CD length according pcsxr-svn (done a bit different here)
1159                 unsigned int sect;
1160                 unsigned char time[3];
1161                 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
1162                 sec2msf(sect, (char *)time);
1163                 buffer[2] = time[0];
1164                 buffer[1] = time[1];
1165                 buffer[0] = time[2];
1166         }
1167         else if (numtracks > 0 && track <= numtracks) {
1168                 buffer[2] = ti[track].start[0];
1169                 buffer[1] = ti[track].start[1];
1170                 buffer[0] = ti[track].start[2];
1171         }
1172         else {
1173                 buffer[2] = 0;
1174                 buffer[1] = 2;
1175                 buffer[0] = 0;
1176         }
1177
1178         return 0;
1179 }
1180
1181 // decode 'raw' subchannel data ripped by cdrdao
1182 static void DecodeRawSubData(void) {
1183         unsigned char subQData[12];
1184         int i;
1185
1186         memset(subQData, 0, sizeof(subQData));
1187
1188         for (i = 0; i < 8 * 12; i++) {
1189                 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1190                         subQData[i >> 3] |= (1 << (7 - (i & 7)));
1191                 }
1192         }
1193
1194         memcpy(&subbuffer[12], subQData, 12);
1195 }
1196
1197 // read track
1198 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
1199 // uses bcd format
1200 static long CALLBACK ISOreadTrack(unsigned char *time) {
1201         int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
1202
1203         if (cdHandle == NULL) {
1204                 return -1;
1205         }
1206
1207         if (pregapOffset) {
1208                 subChanMissing = FALSE;
1209                 if (sector >= pregapOffset) {
1210                         sector -= 2 * 75;
1211                         if (sector < pregapOffset)
1212                                 subChanMissing = TRUE;
1213                 }
1214         }
1215
1216         cdimg_read_func(cdHandle, cdbuffer, sector, 12);
1217
1218         if (subHandle != NULL) {
1219                 fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET);
1220                 fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
1221
1222                 if (subChanRaw) DecodeRawSubData();
1223         }
1224
1225         return 0;
1226 }
1227
1228 // plays cdda audio
1229 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1230 // does NOT uses bcd format
1231 static long CALLBACK ISOplay(unsigned char *time) {
1232         unsigned int i, abs_sect;
1233         int file_sect;
1234
1235         if (numtracks <= 1)
1236                 return 0;
1237
1238         // find the track
1239         abs_sect = msf2sec((char *)time);
1240         for (i = numtracks; i > 1; i--)
1241                 if (msf2sec(ti[i].start) <= abs_sect + 2 * 75)
1242                         break;
1243
1244         file_sect = ti[i].start_offset + (abs_sect - msf2sec(ti[i].start));
1245         if (file_sect < 0)
1246                 file_sect = 0;
1247
1248         // find the file that contains this track
1249         for (; i > 1; i--)
1250                 if (ti[i].handle != NULL)
1251                         break;
1252
1253         cdda_start_sector = abs_sect - file_sect;
1254         cddaHandle = ti[i].handle;
1255
1256         if (pregapOffset && (unsigned int)(pregapOffset - file_sect) < 2 * 75) {
1257                 // get out of the missing pregap to avoid noise
1258                 file_sect = pregapOffset;
1259         }
1260
1261         if (SPU_playCDDAchannel != NULL) {
1262                 startCDDA(file_sect);
1263         }
1264         return 0;
1265 }
1266
1267 // stops cdda audio
1268 static long CALLBACK ISOstop(void) {
1269         stopCDDA();
1270         return 0;
1271 }
1272
1273 // gets subchannel data
1274 static unsigned char* CALLBACK ISOgetBufferSub(void) {
1275         if ((subHandle != NULL || subChanMixed) && !subChanMissing) {
1276                 return subbuffer;
1277         }
1278
1279         return NULL;
1280 }
1281
1282 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
1283         int sec;
1284
1285         CDR__getStatus(stat);
1286
1287         if (playing) {
1288                 stat->Type = 0x02;
1289                 stat->Status |= 0x80;
1290         }
1291         else {
1292                 stat->Type = 0x01;
1293         }
1294
1295         sec = cdda_start_sector + cdda_cur_sector;
1296         sec2msf(sec, (char *)stat->Time);
1297
1298         return 0;
1299 }
1300
1301 void cdrIsoInit(void) {
1302         CDR_init = ISOinit;
1303         CDR_shutdown = ISOshutdown;
1304         CDR_open = ISOopen;
1305         CDR_close = ISOclose;
1306         CDR_getTN = ISOgetTN;
1307         CDR_getTD = ISOgetTD;
1308         CDR_readTrack = ISOreadTrack;
1309         CDR_getBuffer = ISOgetBuffer;
1310         CDR_play = ISOplay;
1311         CDR_stop = ISOstop;
1312         CDR_getBufferSub = ISOgetBufferSub;
1313         CDR_getStatus = ISOgetStatus;
1314
1315         CDR_getDriveLetter = CDR__getDriveLetter;
1316         CDR_configure = CDR__configure;
1317         CDR_test = CDR__test;
1318         CDR_about = CDR__about;
1319         CDR_setfilename = CDR__setfilename;
1320
1321         numtracks = 0;
1322 }
1323
1324 int cdrIsoActive(void) {
1325         return (cdHandle != NULL);
1326 }