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