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