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