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