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