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