drc: merge Ari64's patch: 05_dont_write_r0
[pcsx_rearmed.git] / libpcsxcore / cdriso.c
1 /***************************************************************************
2  *   Copyright (C) 2007 PCSX-df Team                                       *
3  *   Copyright (C) 2009 Wei Mingzhi                                        *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA.           *
19  ***************************************************************************/
20
21 #include "psxcommon.h"
22 #include "plugins.h"
23 #include "cdrom.h"
24 #include "cdriso.h"
25 #include "ppf.h"
26
27 #ifdef _WIN32
28 #include <process.h>
29 #include <windows.h>
30 #else
31 #include <pthread.h>
32 #include <sys/time.h>
33 #endif
34
35 static FILE *cdHandle = NULL;
36 static FILE *cddaHandle = NULL;
37 static FILE *subHandle = NULL;
38
39 static boolean subChanMixed = FALSE;
40 static boolean subChanRaw = FALSE;
41
42 static unsigned char cdbuffer[DATA_SIZE];
43 static unsigned char subbuffer[SUB_FRAMESIZE];
44
45 static unsigned char sndbuffer[CD_FRAMESIZE_RAW * 10];
46
47 #define CDDA_FRAMETIME                  (1000 * (sizeof(sndbuffer) / CD_FRAMESIZE_RAW) / 75)
48
49 #ifdef _WIN32
50 static HANDLE threadid;
51 #else
52 static pthread_t threadid;
53 #endif
54 static unsigned int initial_offset = 0;
55 static boolean playing = FALSE;
56 static boolean cddaBigEndian = FALSE;
57 static unsigned int cddaCurOffset = 0;
58 static unsigned int cddaStartOffset;
59
60 char* CALLBACK CDR__getDriveLetter(void);
61 long CALLBACK CDR__configure(void);
62 long CALLBACK CDR__test(void);
63 void CALLBACK CDR__about(void);
64 long CALLBACK CDR__setfilename(char *filename);
65 long CALLBACK CDR__getStatus(struct CdrStat *stat);
66
67 extern void *hCDRDriver;
68
69 struct trackinfo {
70         enum {DATA, CDDA} type;
71         char start[3];          // MSF-format
72         char length[3];         // MSF-format
73         FILE *handle;           // for multi-track images CDDA
74 };
75
76 #define MAXTRACKS 100 /* How many tracks can a CD hold? */
77
78 static int numtracks = 0;
79 static struct trackinfo ti[MAXTRACKS];
80
81 // get a sector from a msf-array
82 static unsigned int msf2sec(char *msf) {
83         return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
84 }
85
86 static void sec2msf(unsigned int s, char *msf) {
87         msf[0] = s / 75 / 60;
88         s = s - msf[0] * 75 * 60;
89         msf[1] = s / 75;
90         s = s - msf[1] * 75;
91         msf[2] = s;
92 }
93
94 // divide a string of xx:yy:zz into m, s, f
95 static void tok2msf(char *time, char *msf) {
96         char *token;
97
98         token = strtok(time, ":");
99         if (token) {
100                 msf[0] = atoi(token);
101         }
102         else {
103                 msf[0] = 0;
104         }
105
106         token = strtok(NULL, ":");
107         if (token) {
108                 msf[1] = atoi(token);
109         }
110         else {
111                 msf[1] = 0;
112         }
113
114         token = strtok(NULL, ":");
115         if (token) {
116                 msf[2] = atoi(token);
117         }
118         else {
119                 msf[2] = 0;
120         }
121 }
122
123 #ifndef _WIN32
124 static long GetTickCount(void) {
125         static time_t           initial_time = 0;
126         struct timeval          now;
127
128         gettimeofday(&now, NULL);
129
130         if (initial_time == 0) {
131                 initial_time = now.tv_sec;
132         }
133
134         return (now.tv_sec - initial_time) * 1000L + now.tv_usec / 1000L;
135 }
136 #endif
137
138 // this thread plays audio data
139 #ifdef _WIN32
140 static void playthread(void *param)
141 #else
142 static void *playthread(void *param)
143 #endif
144 {
145         long                    d, t, i, s;
146         unsigned char   tmp;
147
148         t = GetTickCount();
149
150         while (playing) {
151                 d = t - (long)GetTickCount();
152                 if (d <= 0) {
153                         d = 1;
154                 }
155                 else if (d > CDDA_FRAMETIME) {
156                         d = CDDA_FRAMETIME;
157                 }
158 #ifdef _WIN32
159                 Sleep(d);
160 #else
161                 usleep(d * 1000);
162 #endif
163                 // HACK: stop feeding data while emu is paused
164                 extern int stop;
165                 if (stop) {
166                         usleep(100000);
167                         continue;
168                 }
169
170                 t = GetTickCount() + CDDA_FRAMETIME;
171
172                 if (subChanMixed) {
173                         s = 0;
174
175                         for (i = 0; i < sizeof(sndbuffer) / CD_FRAMESIZE_RAW; i++) {
176                                 // read one sector
177                                 d = fread(sndbuffer + CD_FRAMESIZE_RAW * i, 1, CD_FRAMESIZE_RAW, cddaHandle);
178                                 if (d < CD_FRAMESIZE_RAW) {
179                                         break;
180                                 }
181
182                                 s += d;
183
184                                 // skip the subchannel data
185                                 fseek(cddaHandle, SUB_FRAMESIZE, SEEK_CUR);
186                         }
187                 }
188                 else {
189                         s = fread(sndbuffer, 1, sizeof(sndbuffer), cddaHandle);
190                 }
191
192                 if (s == 0) {
193                         playing = FALSE;
194                         initial_offset = 0;
195                         break;
196                 }
197
198                 if (!cdr.Muted && playing) {
199                         if (cddaBigEndian) {
200                                 for (i = 0; i < s / 2; i++) {
201                                         tmp = sndbuffer[i * 2];
202                                         sndbuffer[i * 2] = sndbuffer[i * 2 + 1];
203                                         sndbuffer[i * 2 + 1] = tmp;
204                                 }
205                         }
206
207                         SPU_playCDDAchannel((short *)sndbuffer, s);
208                 }
209
210                 cddaCurOffset += s;
211         }
212
213 #ifdef _WIN32
214         _endthread();
215 #else
216         pthread_exit(0);
217         return NULL;
218 #endif
219 }
220
221 // stop the CDDA playback
222 static void stopCDDA() {
223         if (!playing) {
224                 return;
225         }
226
227         playing = FALSE;
228 #ifdef _WIN32
229         WaitForSingleObject(threadid, INFINITE);
230 #else
231         pthread_join(threadid, NULL);
232 #endif
233
234         initial_offset = 0;
235 }
236
237 // start the CDDA playback
238 static void startCDDA(unsigned int offset) {
239         if (playing) {
240                 if (initial_offset == offset) {
241                         return;
242                 }
243                 stopCDDA();
244         }
245
246         initial_offset = offset;
247         cddaCurOffset = initial_offset;
248         fseek(cddaHandle, initial_offset, SEEK_SET);
249
250         playing = TRUE;
251
252 #ifdef _WIN32
253         threadid = (HANDLE)_beginthread(playthread, 0, NULL);
254 #else
255         pthread_create(&threadid, NULL, playthread, NULL);
256 #endif
257 }
258
259 // this function tries to get the .toc file of the given .bin
260 // the necessary data is put into the ti (trackinformation)-array
261 static int parsetoc(const char *isofile) {
262         char                    tocname[MAXPATHLEN];
263         FILE                    *fi;
264         char                    linebuf[256], dummy[256], name[256];
265         char                    *token;
266         char                    time[20], time2[20];
267         unsigned int    t;
268
269         numtracks = 0;
270
271         // copy name of the iso and change extension from .bin to .toc
272         strncpy(tocname, isofile, sizeof(tocname));
273         tocname[MAXPATHLEN - 1] = '\0';
274         if (strlen(tocname) >= 4) {
275                 strcpy(tocname + strlen(tocname) - 4, ".toc");
276         }
277         else {
278                 return -1;
279         }
280
281         if ((fi = fopen(tocname, "r")) == NULL) {
282                 // try changing extension to .cue (to satisfy some stupid tutorials)
283                 strcpy(tocname + strlen(tocname) - 4, ".cue");
284                 if ((fi = fopen(tocname, "r")) == NULL) {
285                         // if filename is image.toc.bin, try removing .bin (for Brasero)
286                         strcpy(tocname, isofile);
287                         t = strlen(tocname);
288                         if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
289                                 tocname[t - 4] = '\0';
290                                 if ((fi = fopen(tocname, "r")) == NULL) {
291                                         return -1;
292                                 }
293                         }
294                         else {
295                                 return -1;
296                         }
297                 }
298         }
299
300         memset(&ti, 0, sizeof(ti));
301         cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
302
303         // parse the .toc file
304         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
305                 // search for tracks
306                 strncpy(dummy, linebuf, sizeof(linebuf));
307                 token = strtok(dummy, " ");
308
309                 if (token == NULL) continue;
310
311                 if (!strcmp(token, "TRACK")) {
312                         // get type of track
313                         token = strtok(NULL, " ");
314                         numtracks++;
315
316                         if (!strncmp(token, "MODE2_RAW", 9)) {
317                                 ti[numtracks].type = DATA;
318                                 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
319
320                                 // check if this image contains mixed subchannel data
321                                 token = strtok(NULL, " ");
322                                 if (token != NULL && !strncmp(token, "RW_RAW", 6)) {
323                                         subChanMixed = TRUE;
324                                         subChanRaw = TRUE;
325                                 }
326                         }
327                         else if (!strncmp(token, "AUDIO", 5)) {
328                                 ti[numtracks].type = CDDA;
329                         }
330                 }
331                 else if (!strcmp(token, "DATAFILE")) {
332                         if (ti[numtracks].type == CDDA) {
333                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
334                                 t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
335                                 t += 2 * 75;
336                                 sec2msf(t, (char *)&ti[numtracks].start);
337                                 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
338                         }
339                         else {
340                                 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
341                                 tok2msf((char *)&time, (char *)&ti[numtracks].length);
342                         }
343                 }
344                 else if (!strcmp(token, "FILE")) {
345                         sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
346                         tok2msf((char *)&time, (char *)&ti[numtracks].start);
347                         t /= CD_FRAMESIZE_RAW + (subChanMixed ? SUB_FRAMESIZE : 0);
348                         t += msf2sec(ti[numtracks].start) + 2 * 75;
349                         sec2msf(t, (char *)&ti[numtracks].start);
350                         tok2msf((char *)&time2, (char *)&ti[numtracks].length);
351                 }
352         }
353
354         fclose(fi);
355
356         return 0;
357 }
358
359 // this function tries to get the .cue file of the given .bin
360 // the necessary data is put into the ti (trackinformation)-array
361 static int parsecue(const char *isofile) {
362         char                    cuename[MAXPATHLEN];
363         char                    filepath[MAXPATHLEN];
364         char                    *incue_fname;
365         FILE                    *fi;
366         char                    *token;
367         char                    time[20];
368         char                    *tmp;
369         char                    linebuf[256], dummy[256];
370         unsigned int    incue_max_len;
371         unsigned int    t, i, total, file_len;
372
373         numtracks = 0;
374
375         // copy name of the iso and change extension from .bin to .cue
376         strncpy(cuename, isofile, sizeof(cuename));
377         cuename[MAXPATHLEN - 1] = '\0';
378         if (strlen(cuename) >= 4) {
379                 strcpy(cuename + strlen(cuename) - 4, ".cue");
380         }
381         else {
382                 return -1;
383         }
384
385         if ((fi = fopen(cuename, "r")) == NULL) {
386                 return -1;
387         }
388
389         // Some stupid tutorials wrongly tell users to use cdrdao to rip a
390         // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
391         // that...
392         if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
393                 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
394                         // Don't proceed further, as this is actually a .toc file rather
395                         // than a .cue file.
396                         fclose(fi);
397                         return parsetoc(isofile);
398                 }
399                 fseek(fi, 0, SEEK_SET);
400         }
401
402         // build a path for files referenced in .cue
403         strncpy(filepath, cuename, sizeof(filepath));
404         tmp = strrchr(filepath, '/') + 1;
405         if (tmp == NULL)
406                 tmp = strrchr(filepath, '\\') + 1;
407         if (tmp == NULL)
408                 tmp = filepath;
409         *tmp = 0;
410         filepath[sizeof(filepath) - 1] = 0;
411         incue_fname = tmp;
412         incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
413
414         memset(&ti, 0, sizeof(ti));
415
416         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
417                 strncpy(dummy, linebuf, sizeof(linebuf));
418                 token = strtok(dummy, " ");
419
420                 if (token == NULL) {
421                         continue;
422                 }
423
424                 if (!strcmp(token, "TRACK")){
425                         numtracks++;
426
427                         if (strstr(linebuf, "AUDIO") != NULL) {
428                                 ti[numtracks].type = CDDA;
429                         }
430                         else if (strstr(linebuf, "MODE1/2352") != NULL || strstr(linebuf, "MODE2/2352") != NULL) {
431                                 ti[numtracks].type = DATA;
432                         }
433                 }
434                 else if (!strcmp(token, "INDEX")) {
435                         tmp = strstr(linebuf, "INDEX");
436                         if (tmp != NULL) {
437                                 tmp += strlen("INDEX") + 3; // 3 - space + numeric index
438                                 while (*tmp == ' ') tmp++;
439                                 if (*tmp != '\n') sscanf(tmp, "%8s", time);
440                         }
441
442                         tok2msf((char *)&time, (char *)&ti[numtracks].start);
443
444                         t = msf2sec(ti[numtracks].start) + 2 * 75;
445                         sec2msf(t, ti[numtracks].start);
446                 }
447                 else if (!strcmp(token, "FILE")) {
448                         tmp = strstr(linebuf, "FILE");
449                         if (tmp == NULL) {
450                                 continue;
451                         }
452                         tmp += 4;
453                         while (*tmp == ' ')
454                                 tmp++;
455                         if (*tmp == '"') {
456                                 token = tmp + 1;
457                                 tmp = strchr(token, '"');
458                                 if (tmp != NULL)
459                                         *tmp = 0;
460                         }
461                         else {
462                                 token = tmp;
463                                 tmp = strchr(token, ' ');
464                                 if (tmp != NULL)
465                                         *tmp = 0;
466                         }
467
468                         strncpy(incue_fname, token, incue_max_len);
469                         ti[numtracks + 1].handle = fopen(filepath, "rb");
470                         if (ti[numtracks + 1].handle == NULL) {
471                                 SysPrintf(_("could not open: %s\n"), filepath);
472                         }
473                         else if (numtracks == 0 && strlen(isofile) >= 4 &&
474                                         strcmp(isofile + strlen(isofile) - 4, ".cue") == 0) {
475                                 // user selected .cue as image file, use it's data track instead
476                                 fclose(cdHandle);
477                                 cdHandle = fopen(filepath, "rb");
478                         }
479                 }
480         }
481
482         fclose(fi);
483
484         // make corrections for multi-track .cue, fill track lengths
485         total = 2 * 75;
486         file_len = 0;
487         for (i = 1; i <= numtracks; i++) {
488                 if (ti[i].handle != NULL) {
489                         sec2msf(total, ti[i].start);
490                         fseek(ti[i].handle, 0, SEEK_END);
491                         file_len = ftell(ti[i].handle) / 2352;
492                         sec2msf(file_len, ti[i].length);
493                         total += file_len;
494                 }
495                 else {
496                         // this track uses the same file as the last,
497                         // start of this track is last track's end
498                         if (i > 1) {
499                                 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
500                                 sec2msf(t, ti[i - 1].length);
501                         }
502                         t = file_len - msf2sec(ti[i].start) + 2 * 75;
503                         sec2msf(t, ti[i].length);
504                 }
505         }
506
507         return 0;
508 }
509
510 // this function tries to get the .ccd file of the given .img
511 // the necessary data is put into the ti (trackinformation)-array
512 static int parseccd(const char *isofile) {
513         char                    ccdname[MAXPATHLEN];
514         FILE                    *fi;
515         char                    linebuf[256];
516         unsigned int    t;
517
518         numtracks = 0;
519
520         // copy name of the iso and change extension from .img to .ccd
521         strncpy(ccdname, isofile, sizeof(ccdname));
522         ccdname[MAXPATHLEN - 1] = '\0';
523         if (strlen(ccdname) >= 4) {
524                 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
525         }
526         else {
527                 return -1;
528         }
529
530         if ((fi = fopen(ccdname, "r")) == NULL) {
531                 return -1;
532         }
533
534         memset(&ti, 0, sizeof(ti));
535
536         while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
537                 if (!strncmp(linebuf, "[TRACK", 6)){
538                         numtracks++;
539                 }
540                 else if (!strncmp(linebuf, "MODE=", 5)) {
541                         sscanf(linebuf, "MODE=%d", &t);
542                         ti[numtracks].type = ((t == 0) ? CDDA : DATA);
543                 }
544                 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
545                         sscanf(linebuf, "INDEX 1=%d", &t);
546                         sec2msf(t + 2 * 75, ti[numtracks].start);
547
548                         // If we've already seen another track, this is its end
549                         if (numtracks > 1) {
550                                 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
551                                 sec2msf(t, ti[numtracks - 1].length);
552                         }
553                 }
554         }
555
556         fclose(fi);
557
558         // Fill out the last track's end based on size
559         if (numtracks >= 1) {
560                 fseek(cdHandle, 0, SEEK_END);
561                 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
562                 sec2msf(t, ti[numtracks].length);
563         }
564
565         return 0;
566 }
567
568 // this function tries to get the .mds file of the given .mdf
569 // the necessary data is put into the ti (trackinformation)-array
570 static int parsemds(const char *isofile) {
571         char                    mdsname[MAXPATHLEN];
572         FILE                    *fi;
573         unsigned int    offset, extra_offset, l, i;
574         unsigned short  s;
575
576         numtracks = 0;
577
578         // copy name of the iso and change extension from .mdf to .mds
579         strncpy(mdsname, isofile, sizeof(mdsname));
580         mdsname[MAXPATHLEN - 1] = '\0';
581         if (strlen(mdsname) >= 4) {
582                 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
583         }
584         else {
585                 return -1;
586         }
587
588         if ((fi = fopen(mdsname, "rb")) == NULL) {
589                 return -1;
590         }
591
592         memset(&ti, 0, sizeof(ti));
593
594         // check if it's a valid mds file
595         fread(&i, 1, sizeof(unsigned int), fi);
596         i = SWAP32(i);
597         if (i != 0x4944454D) {
598                 // not an valid mds file
599                 fclose(fi);
600                 return -1;
601         }
602
603         // get offset to session block
604         fseek(fi, 0x50, SEEK_SET);
605         fread(&offset, 1, sizeof(unsigned int), fi);
606         offset = SWAP32(offset);
607
608         // get total number of tracks
609         offset += 14;
610         fseek(fi, offset, SEEK_SET);
611         fread(&s, 1, sizeof(unsigned short), fi);
612         s = SWAP16(s);
613         numtracks = s;
614
615         // get offset to track blocks
616         fseek(fi, 4, SEEK_CUR);
617         fread(&offset, 1, sizeof(unsigned int), fi);
618         offset = SWAP32(offset);
619
620         // skip lead-in data
621         while (1) {
622                 fseek(fi, offset + 4, SEEK_SET);
623                 if (fgetc(fi) < 0xA0) {
624                         break;
625                 }
626                 offset += 0x50;
627         }
628
629         // check if the image contains mixed subchannel data
630         fseek(fi, offset + 1, SEEK_SET);
631         subChanMixed = (fgetc(fi) ? TRUE : FALSE);
632
633         // read track data
634         for (i = 1; i <= numtracks; i++) {
635                 fseek(fi, offset, SEEK_SET);
636
637                 // get the track type
638                 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
639                 fseek(fi, 8, SEEK_CUR);
640
641                 // get the track starting point
642                 ti[i].start[0] = fgetc(fi);
643                 ti[i].start[1] = fgetc(fi);
644                 ti[i].start[2] = fgetc(fi);
645
646                 if (i > 1) {
647                         l = msf2sec(ti[i].start);
648                         sec2msf(l - 2 * 75, ti[i].start); // ???
649                 }
650
651                 // get the track length
652                 fread(&extra_offset, 1, sizeof(unsigned int), fi);
653                 extra_offset = SWAP32(extra_offset);
654
655                 fseek(fi, extra_offset + 4, SEEK_SET);
656                 fread(&l, 1, sizeof(unsigned int), fi);
657                 l = SWAP32(l);
658                 sec2msf(l, ti[i].length);
659
660                 offset += 0x50;
661         }
662
663         fclose(fi);
664         return 0;
665 }
666
667 // this function tries to get the .sub file of the given .img
668 static int opensubfile(const char *isoname) {
669         char            subname[MAXPATHLEN];
670
671         // copy name of the iso and change extension from .img to .sub
672         strncpy(subname, isoname, sizeof(subname));
673         subname[MAXPATHLEN - 1] = '\0';
674         if (strlen(subname) >= 4) {
675                 strcpy(subname + strlen(subname) - 4, ".sub");
676         }
677         else {
678                 return -1;
679         }
680
681         subHandle = fopen(subname, "rb");
682         if (subHandle == NULL) {
683                 return -1;
684         }
685
686         return 0;
687 }
688
689 static int opensbifile(const char *isoname) {
690         char            sbiname[MAXPATHLEN];
691         int             s;
692
693         strncpy(sbiname, isoname, sizeof(sbiname));
694         sbiname[MAXPATHLEN - 1] = '\0';
695         if (strlen(sbiname) >= 4) {
696                 strcpy(sbiname + strlen(sbiname) - 4, ".sbi");
697         }
698         else {
699                 return -1;
700         }
701
702         fseek(cdHandle, 0, SEEK_END);
703         s = ftell(cdHandle) / 2352;
704
705         return LoadSBI(sbiname, s);
706 }
707
708 static void PrintTracks(void) {
709         int i;
710
711         for (i = 1; i <= numtracks; i++) {
712                 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
713                         i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
714                         ti[i].start[0], ti[i].start[1], ti[i].start[2],
715                         ti[i].length[0], ti[i].length[1], ti[i].length[2]);
716         }
717 }
718
719 // This function is invoked by the front-end when opening an ISO
720 // file for playback
721 static long CALLBACK ISOopen(void) {
722         if (cdHandle != NULL) {
723                 return 0; // it's already open
724         }
725
726         cdHandle = fopen(GetIsoFile(), "rb");
727         if (cdHandle == NULL) {
728                 return -1;
729         }
730
731         SysPrintf(_("Loaded CD Image: %s"), GetIsoFile());
732
733         cddaBigEndian = FALSE;
734         subChanMixed = FALSE;
735         subChanRaw = FALSE;
736
737         if (parsecue(GetIsoFile()) == 0) {
738                 SysPrintf("[+cue]");
739         }
740         else if (parsetoc(GetIsoFile()) == 0) {
741                 SysPrintf("[+toc]");
742         }
743         else if (parseccd(GetIsoFile()) == 0) {
744                 SysPrintf("[+ccd]");
745         }
746         else if (parsemds(GetIsoFile()) == 0) {
747                 SysPrintf("[+mds]");
748         }
749
750         if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
751                 SysPrintf("[+sub]");
752         }
753         if (opensbifile(GetIsoFile()) == 0) {
754                 SysPrintf("[+sbi]");
755         }
756
757         SysPrintf(".\n");
758
759         PrintTracks();
760
761         // make sure we have another handle open for cdda
762         if (numtracks > 1 && ti[1].handle == NULL) {
763                 ti[1].handle = fopen(GetIsoFile(), "rb");
764         }
765         cddaCurOffset = cddaStartOffset = 0;
766
767         return 0;
768 }
769
770 static long CALLBACK ISOclose(void) {
771         int i;
772
773         if (cdHandle != NULL) {
774                 fclose(cdHandle);
775                 cdHandle = NULL;
776         }
777         if (subHandle != NULL) {
778                 fclose(subHandle);
779                 subHandle = NULL;
780         }
781         stopCDDA();
782         cddaHandle = NULL;
783
784         for (i = 1; i <= numtracks; i++) {
785                 if (ti[i].handle != NULL) {
786                         fclose(ti[i].handle);
787                         ti[i].handle = NULL;
788                 }
789         }
790         numtracks = 0;
791         UnloadSBI();
792
793         return 0;
794 }
795
796 static long CALLBACK ISOinit(void) {
797         assert(cdHandle == NULL);
798         assert(subHandle == NULL);
799
800         return 0; // do nothing
801 }
802
803 static long CALLBACK ISOshutdown(void) {
804         ISOclose();
805         return 0;
806 }
807
808 // return Starting and Ending Track
809 // buffer:
810 //  byte 0 - start track
811 //  byte 1 - end track
812 static long CALLBACK ISOgetTN(unsigned char *buffer) {
813         buffer[0] = 1;
814
815         if (numtracks > 0) {
816                 buffer[1] = numtracks;
817         }
818         else {
819                 buffer[1] = 1;
820         }
821
822         return 0;
823 }
824
825 // return Track Time
826 // buffer:
827 //  byte 0 - frame
828 //  byte 1 - second
829 //  byte 2 - minute
830 static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
831         if (track == 0) {
832                 // CD length according pcsxr-svn (done a bit different here)
833                 unsigned int sect;
834                 unsigned char time[3];
835                 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
836                 sec2msf(sect, time);
837                 buffer[2] = time[0];
838                 buffer[1] = time[1];
839                 buffer[0] = time[2];
840         }
841         else if (numtracks > 0 && track <= numtracks) {
842                 buffer[2] = ti[track].start[0];
843                 buffer[1] = ti[track].start[1];
844                 buffer[0] = ti[track].start[2];
845         }
846         else {
847                 buffer[2] = 0;
848                 buffer[1] = 2;
849                 buffer[0] = 0;
850         }
851
852         return 0;
853 }
854
855 // decode 'raw' subchannel data ripped by cdrdao
856 static void DecodeRawSubData(void) {
857         unsigned char subQData[12];
858         int i;
859
860         memset(subQData, 0, sizeof(subQData));
861
862         for (i = 0; i < 8 * 12; i++) {
863                 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
864                         subQData[i >> 3] |= (1 << (7 - (i & 7)));
865                 }
866         }
867
868         memcpy(&subbuffer[12], subQData, 12);
869 }
870
871 // read track
872 // time: byte 0 - minute; byte 1 - second; byte 2 - frame
873 // uses bcd format
874 static long CALLBACK ISOreadTrack(unsigned char *time) {
875         if (cdHandle == NULL) {
876                 return -1;
877         }
878
879         if (subChanMixed) {
880                 fseek(cdHandle, MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])) * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE) + 12, SEEK_SET);
881                 fread(cdbuffer, 1, DATA_SIZE, cdHandle);
882                 fread(subbuffer, 1, SUB_FRAMESIZE, cdHandle);
883
884                 if (subChanRaw) DecodeRawSubData();
885         }
886         else {
887                 fseek(cdHandle, MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])) * CD_FRAMESIZE_RAW + 12, SEEK_SET);
888                 fread(cdbuffer, 1, DATA_SIZE, cdHandle);
889
890                 if (subHandle != NULL) {
891                         fseek(subHandle, MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])) * SUB_FRAMESIZE, SEEK_SET);
892                         fread(subbuffer, 1, SUB_FRAMESIZE, subHandle);
893
894                         if (subChanRaw) DecodeRawSubData();
895                 }
896         }
897
898         return 0;
899 }
900
901 // return readed track
902 static unsigned char * CALLBACK ISOgetBuffer(void) {
903         return cdbuffer;
904 }
905
906 // plays cdda audio
907 // sector: byte 0 - minute; byte 1 - second; byte 2 - frame
908 // does NOT uses bcd format
909 static long CALLBACK ISOplay(unsigned char *time) {
910         unsigned int i, sect;
911
912         if (numtracks <= 1)
913                 return 0;
914
915         // find the track
916         sect = msf2sec(time);
917         for (i = numtracks; i > 1; i--)
918                 if (msf2sec(ti[i].start) <= sect + 2 * 75)
919                         break;
920
921         // find the file that contains this track
922         for (; i > 1; i--)
923                 if (ti[i].handle != NULL)
924                         break;
925
926         cddaStartOffset = msf2sec(ti[i].start);
927         sect -= cddaStartOffset - 2 * 75;
928         cddaHandle = ti[i].handle;
929
930         if (SPU_playCDDAchannel != NULL) {
931                 if (subChanMixed) {
932                         startCDDA(sect * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE));
933                 }
934                 else {
935                         startCDDA(sect * CD_FRAMESIZE_RAW);
936                 }
937         }
938         return 0;
939 }
940
941 // stops cdda audio
942 static long CALLBACK ISOstop(void) {
943         stopCDDA();
944         return 0;
945 }
946
947 // gets subchannel data
948 static unsigned char* CALLBACK ISOgetBufferSub(void) {
949         if (subHandle != NULL || subChanMixed) {
950                 return subbuffer;
951         }
952
953         return NULL;
954 }
955
956 static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
957         int sec;
958
959         CDR__getStatus(stat);
960
961         if (playing) {
962                 stat->Type = 0x02;
963                 stat->Status |= 0x80;
964         }
965         else {
966                 stat->Type = 0x01;
967         }
968
969         sec = (cddaStartOffset + cddaCurOffset) / CD_FRAMESIZE_RAW;
970         sec2msf(sec, (char *)stat->Time);
971
972         return 0;
973 }
974
975 void cdrIsoInit(void) {
976         CDR_init = ISOinit;
977         CDR_shutdown = ISOshutdown;
978         CDR_open = ISOopen;
979         CDR_close = ISOclose;
980         CDR_getTN = ISOgetTN;
981         CDR_getTD = ISOgetTD;
982         CDR_readTrack = ISOreadTrack;
983         CDR_getBuffer = ISOgetBuffer;
984         CDR_play = ISOplay;
985         CDR_stop = ISOstop;
986         CDR_getBufferSub = ISOgetBufferSub;
987         CDR_getStatus = ISOgetStatus;
988
989         CDR_getDriveLetter = CDR__getDriveLetter;
990         CDR_configure = CDR__configure;
991         CDR_test = CDR__test;
992         CDR_about = CDR__about;
993         CDR_setfilename = CDR__setfilename;
994
995         numtracks = 0;
996 }
997
998 int cdrIsoActive(void) {
999         return (cdHandle != NULL);
1000 }