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