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