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