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