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