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