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