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