more makefile updates
[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
94f0c7c5 39#elif P_HAVE_PTHREAD
ef79bbde
P
40#include <pthread.h>
41#include <sys/time.h>
349f7d81 42#include <unistd.h>
ef79bbde
P
43#endif
44
9f47c8ed 45// to enable the USE_READ_THREAD code, fix:
46// - https://github.com/notaz/pcsx_rearmed/issues/257
47// - ISOgetBufferSub to not race with async code
94f0c7c5 48#define USE_READ_THREAD 0 //P_HAVE_PTHREAD
9f47c8ed 49
226a5691 50#ifdef USE_LIBRETRO_VFS
51#include <streams/file_stream_transforms.h>
52#undef fseeko
53#undef ftello
54#define ftello rftell
55#define fseeko rfseek
56#endif
9361a5aa 57
cc376814 58#define OFF_T_MSB ((off_t)1 << (sizeof(off_t) * 8 - 1))
59
0c2871a7 60unsigned int cdrIsoMultidiskCount;
61unsigned int cdrIsoMultidiskSelect;
62
ef79bbde
P
63static FILE *cdHandle = NULL;
64static FILE *cddaHandle = NULL;
65static FILE *subHandle = NULL;
66
67static boolean subChanMixed = FALSE;
68static boolean subChanRaw = FALSE;
69
deebc67f 70static boolean multifile = FALSE;
71
81abe4d5 72static unsigned char cdbuffer[CD_FRAMESIZE_RAW];
ef79bbde
P
73static unsigned char subbuffer[SUB_FRAMESIZE];
74
38b8102c 75static boolean playing = FALSE;
ef79bbde 76static boolean cddaBigEndian = FALSE;
8aa91443 77/* Frame offset into CD image where pregap data would be found if it was there.
78 * If a game seeks there we must *not* return subchannel data since it's
79 * not in the CD image, so that cdrom code can fake subchannel data instead.
80 * XXX: there could be multiple pregaps but PSX dumps only have one? */
81static unsigned int pregapOffset;
ef79bbde 82
5b568098 83static unsigned int cddaCurPos;
deebc67f 84
9a92bffb 85// compressed image stuff
86static struct {
87 unsigned char buff_raw[16][CD_FRAMESIZE_RAW];
88 unsigned char buff_compressed[CD_FRAMESIZE_RAW * 16 + 100];
cc376814 89 off_t *index_table;
9a92bffb 90 unsigned int index_len;
0877957a 91 unsigned int block_shift;
9a92bffb 92 unsigned int current_block;
93 unsigned int sector_in_blk;
94} *compr_img;
95
b0ec2e6d 96#ifdef HAVE_CHD
ce188d4d 97static struct {
aeb82099 98 unsigned char *buffer;
ce188d4d 99 chd_file* chd;
100 const chd_header* header;
101 unsigned int sectors_per_hunk;
aeb82099 102 unsigned int current_hunk[2];
103 unsigned int current_buffer;
ce188d4d 104 unsigned int sector_in_hunk;
105} *chd_img;
b0ec2e6d 106#endif
ce188d4d 107
0eacae49 108static int (*cdimg_read_func)(FILE *f, unsigned int base, void *dest, int sector);
109static int (*cdimg_read_sub_func)(FILE *f, int sector);
9a92bffb 110
ef79bbde
P
111char* CALLBACK CDR__getDriveLetter(void);
112long CALLBACK CDR__configure(void);
113long CALLBACK CDR__test(void);
114void CALLBACK CDR__about(void);
115long CALLBACK CDR__setfilename(char *filename);
116long CALLBACK CDR__getStatus(struct CdrStat *stat);
117
19c03d80 118static void DecodeRawSubData(void);
119
ef79bbde 120struct trackinfo {
deebc67f 121 enum {DATA=1, CDDA} type;
ef79bbde
P
122 char start[3]; // MSF-format
123 char length[3]; // MSF-format
38b8102c 124 FILE *handle; // for multi-track images CDDA
f02c57ea 125 unsigned int start_offset; // byte offset from start of above file (chd: sector offset)
ef79bbde
P
126};
127
128#define MAXTRACKS 100 /* How many tracks can a CD hold? */
129
130static int numtracks = 0;
131static struct trackinfo ti[MAXTRACKS];
132
133// get a sector from a msf-array
134static unsigned int msf2sec(char *msf) {
135 return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
136}
137
138static void sec2msf(unsigned int s, char *msf) {
139 msf[0] = s / 75 / 60;
140 s = s - msf[0] * 75 * 60;
141 msf[1] = s / 75;
142 s = s - msf[1] * 75;
143 msf[2] = s;
144}
145
146// divide a string of xx:yy:zz into m, s, f
147static void tok2msf(char *time, char *msf) {
148 char *token;
149
150 token = strtok(time, ":");
151 if (token) {
152 msf[0] = atoi(token);
153 }
154 else {
155 msf[0] = 0;
156 }
157
158 token = strtok(NULL, ":");
159 if (token) {
160 msf[1] = atoi(token);
161 }
162 else {
163 msf[1] = 0;
164 }
165
166 token = strtok(NULL, ":");
167 if (token) {
168 msf[2] = atoi(token);
169 }
170 else {
171 msf[2] = 0;
172 }
173}
174
ef79bbde
P
175// this function tries to get the .toc file of the given .bin
176// the necessary data is put into the ti (trackinformation)-array
177static int parsetoc(const char *isofile) {
178 char tocname[MAXPATHLEN];
179 FILE *fi;
e999be41 180 char linebuf[256], tmp[256], name[256];
ef79bbde
P
181 char *token;
182 char time[20], time2[20];
e999be41 183 unsigned int t, sector_offs, sector_size;
184 unsigned int current_zero_gap = 0;
ef79bbde
P
185
186 numtracks = 0;
187
188 // copy name of the iso and change extension from .bin to .toc
189 strncpy(tocname, isofile, sizeof(tocname));
190 tocname[MAXPATHLEN - 1] = '\0';
191 if (strlen(tocname) >= 4) {
192 strcpy(tocname + strlen(tocname) - 4, ".toc");
193 }
194 else {
195 return -1;
196 }
197
226a5691 198 if ((fi = fopen(tocname, "r")) == NULL) {
ef79bbde
P
199 // try changing extension to .cue (to satisfy some stupid tutorials)
200 strcpy(tocname + strlen(tocname) - 4, ".cue");
226a5691 201 if ((fi = fopen(tocname, "r")) == NULL) {
ef79bbde
P
202 // if filename is image.toc.bin, try removing .bin (for Brasero)
203 strcpy(tocname, isofile);
204 t = strlen(tocname);
205 if (t >= 8 && strcmp(tocname + t - 8, ".toc.bin") == 0) {
206 tocname[t - 4] = '\0';
226a5691 207 if ((fi = fopen(tocname, "r")) == NULL) {
ef79bbde
P
208 return -1;
209 }
210 }
211 else {
212 return -1;
213 }
214 }
92f43ab0 215 // check if it's really a TOC named as a .cue
9361a5aa
EC
216 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
217 token = strtok(linebuf, " ");
218 if (token && strncmp(token, "CD", 2) != 0 && strcmp(token, "CATALOG") != 0) {
219 fclose(fi);
220 return -1;
221 }
92f43ab0 222 }
223 fseek(fi, 0, SEEK_SET);
ef79bbde
P
224 }
225
226 memset(&ti, 0, sizeof(ti));
227 cddaBigEndian = TRUE; // cdrdao uses big-endian for CD Audio
228
e999be41 229 sector_size = CD_FRAMESIZE_RAW;
19c03d80 230 sector_offs = 2 * 75;
231
ef79bbde
P
232 // parse the .toc file
233 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
234 // search for tracks
e999be41 235 strncpy(tmp, linebuf, sizeof(linebuf));
236 token = strtok(tmp, " ");
ef79bbde
P
237
238 if (token == NULL) continue;
239
240 if (!strcmp(token, "TRACK")) {
e999be41 241 sector_offs += current_zero_gap;
242 current_zero_gap = 0;
243
ef79bbde
P
244 // get type of track
245 token = strtok(NULL, " ");
246 numtracks++;
247
248 if (!strncmp(token, "MODE2_RAW", 9)) {
249 ti[numtracks].type = DATA;
250 sec2msf(2 * 75, ti[numtracks].start); // assume data track on 0:2:0
251
252 // check if this image contains mixed subchannel data
253 token = strtok(NULL, " ");
e999be41 254 if (token != NULL && !strncmp(token, "RW", 2)) {
255 sector_size = CD_FRAMESIZE_RAW + SUB_FRAMESIZE;
ef79bbde 256 subChanMixed = TRUE;
e999be41 257 if (!strncmp(token, "RW_RAW", 6))
258 subChanRaw = TRUE;
ef79bbde
P
259 }
260 }
261 else if (!strncmp(token, "AUDIO", 5)) {
262 ti[numtracks].type = CDDA;
263 }
264 }
265 else if (!strcmp(token, "DATAFILE")) {
266 if (ti[numtracks].type == CDDA) {
267 sscanf(linebuf, "DATAFILE \"%[^\"]\" #%d %8s", name, &t, time2);
19c03d80 268 ti[numtracks].start_offset = t;
e999be41 269 t = t / sector_size + sector_offs;
ef79bbde
P
270 sec2msf(t, (char *)&ti[numtracks].start);
271 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
272 }
273 else {
274 sscanf(linebuf, "DATAFILE \"%[^\"]\" %8s", name, time);
275 tok2msf((char *)&time, (char *)&ti[numtracks].length);
276 }
277 }
278 else if (!strcmp(token, "FILE")) {
279 sscanf(linebuf, "FILE \"%[^\"]\" #%d %8s %8s", name, &t, time, time2);
280 tok2msf((char *)&time, (char *)&ti[numtracks].start);
e999be41 281 t += msf2sec(ti[numtracks].start) * sector_size;
19c03d80 282 ti[numtracks].start_offset = t;
e999be41 283 t = t / sector_size + sector_offs;
ef79bbde
P
284 sec2msf(t, (char *)&ti[numtracks].start);
285 tok2msf((char *)&time2, (char *)&ti[numtracks].length);
286 }
e999be41 287 else if (!strcmp(token, "ZERO") || !strcmp(token, "SILENCE")) {
288 // skip unneeded optional fields
289 while (token != NULL) {
290 token = strtok(NULL, " ");
291 if (strchr(token, ':') != NULL)
292 break;
293 }
294 if (token != NULL) {
295 tok2msf(token, tmp);
296 current_zero_gap = msf2sec(tmp);
297 }
8aa91443 298 if (numtracks > 1) {
299 t = ti[numtracks - 1].start_offset;
e999be41 300 t /= sector_size;
8aa91443 301 pregapOffset = t + msf2sec(ti[numtracks - 1].length);
302 }
19c03d80 303 }
e999be41 304 else if (!strcmp(token, "START")) {
305 token = strtok(NULL, " ");
306 if (token != NULL && strchr(token, ':')) {
307 tok2msf(token, tmp);
308 t = msf2sec(tmp);
309 ti[numtracks].start_offset += (t - current_zero_gap) * sector_size;
310 t = msf2sec(ti[numtracks].start) + t;
311 sec2msf(t, (char *)&ti[numtracks].start);
312 }
313 }
ef79bbde
P
314 }
315
316 fclose(fi);
317
318 return 0;
319}
320
321// this function tries to get the .cue file of the given .bin
322// the necessary data is put into the ti (trackinformation)-array
323static int parsecue(const char *isofile) {
324 char cuename[MAXPATHLEN];
38b8102c 325 char filepath[MAXPATHLEN];
326 char *incue_fname;
ef79bbde
P
327 FILE *fi;
328 char *token;
329 char time[20];
330 char *tmp;
19c03d80 331 char linebuf[256], tmpb[256], dummy[256];
38b8102c 332 unsigned int incue_max_len;
77160d47 333 unsigned int t, file_len, mode, sector_offs;
334 unsigned int sector_size = 2352;
ef79bbde
P
335
336 numtracks = 0;
337
338 // copy name of the iso and change extension from .bin to .cue
339 strncpy(cuename, isofile, sizeof(cuename));
340 cuename[MAXPATHLEN - 1] = '\0';
341 if (strlen(cuename) >= 4) {
2cc221eb 342 // If 'isofile' is a '.cd<X>' file, use it as a .cue file
343 // and don't try to search the additional .cue file
344 if (strncasecmp(cuename + strlen(cuename) - 4, ".cd", 3) != 0 )
345 strcpy(cuename + strlen(cuename) - 4, ".cue");
ef79bbde
P
346 }
347 else {
348 return -1;
349 }
350
226a5691 351 if ((fi = fopen(cuename, "r")) == NULL) {
ef79bbde
P
352 return -1;
353 }
354
355 // Some stupid tutorials wrongly tell users to use cdrdao to rip a
356 // "bin/cue" image, which is in fact a "bin/toc" image. So let's check
357 // that...
358 if (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
359 if (!strncmp(linebuf, "CD_ROM_XA", 9)) {
360 // Don't proceed further, as this is actually a .toc file rather
361 // than a .cue file.
362 fclose(fi);
363 return parsetoc(isofile);
364 }
365 fseek(fi, 0, SEEK_SET);
366 }
367
38b8102c 368 // build a path for files referenced in .cue
369 strncpy(filepath, cuename, sizeof(filepath));
22bbabf6 370 tmp = strrchr(filepath, '/');
38b8102c 371 if (tmp == NULL)
22bbabf6 372 tmp = strrchr(filepath, '\\');
373 if (tmp != NULL)
374 tmp++;
375 else
38b8102c 376 tmp = filepath;
377 *tmp = 0;
378 filepath[sizeof(filepath) - 1] = 0;
379 incue_fname = tmp;
380 incue_max_len = sizeof(filepath) - (tmp - filepath) - 1;
381
ef79bbde
P
382 memset(&ti, 0, sizeof(ti));
383
19c03d80 384 file_len = 0;
385 sector_offs = 2 * 75;
386
ef79bbde
P
387 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
388 strncpy(dummy, linebuf, sizeof(linebuf));
389 token = strtok(dummy, " ");
390
391 if (token == NULL) {
392 continue;
393 }
394
19c03d80 395 if (!strcmp(token, "TRACK")) {
ef79bbde
P
396 numtracks++;
397
77160d47 398 sector_size = 0;
ef79bbde
P
399 if (strstr(linebuf, "AUDIO") != NULL) {
400 ti[numtracks].type = CDDA;
77160d47 401 sector_size = 2352;
ef79bbde 402 }
77160d47 403 else if (sscanf(linebuf, " TRACK %u MODE%u/%u", &t, &mode, &sector_size) == 3)
ef79bbde 404 ti[numtracks].type = DATA;
77160d47 405 else {
406 SysPrintf(".cue: failed to parse TRACK\n");
407 ti[numtracks].type = numtracks == 1 ? DATA : CDDA;
ef79bbde 408 }
77160d47 409 if (sector_size == 0)
410 sector_size = 2352;
ef79bbde
P
411 }
412 else if (!strcmp(token, "INDEX")) {
77160d47 413 if (sscanf(linebuf, " INDEX %02d %8s", &t, time) != 2)
414 SysPrintf(".cue: failed to parse INDEX\n");
19c03d80 415 tok2msf(time, (char *)&ti[numtracks].start);
ef79bbde 416
19c03d80 417 t = msf2sec(ti[numtracks].start);
77160d47 418 ti[numtracks].start_offset = t * sector_size;
19c03d80 419 t += sector_offs;
ef79bbde 420 sec2msf(t, ti[numtracks].start);
19c03d80 421
422 // default track length to file length
77160d47 423 t = file_len - ti[numtracks].start_offset / sector_size;
19c03d80 424 sec2msf(t, ti[numtracks].length);
425
426 if (numtracks > 1 && ti[numtracks].handle == NULL) {
427 // this track uses the same file as the last,
428 // start of this track is last track's end
429 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
430 sec2msf(t, ti[numtracks - 1].length);
38b8102c 431 }
8aa91443 432 if (numtracks > 1 && pregapOffset == -1)
77160d47 433 pregapOffset = ti[numtracks].start_offset / sector_size;
19c03d80 434 }
435 else if (!strcmp(token, "PREGAP")) {
436 if (sscanf(linebuf, " PREGAP %8s", time) == 1) {
437 tok2msf(time, dummy);
438 sector_offs += msf2sec(dummy);
38b8102c 439 }
8aa91443 440 pregapOffset = -1; // mark to fill track start_offset
19c03d80 441 }
442 else if (!strcmp(token, "FILE")) {
9a9bcd78 443 t = sscanf(linebuf, " FILE \"%255[^\"]\"", tmpb);
385c023b 444 if (t != 1)
9a9bcd78 445 sscanf(linebuf, " FILE %255s", tmpb);
19c03d80 446
6f4557bf 447 tmp = strrchr(tmpb, '\\');
448 if (tmp == NULL)
449 tmp = strrchr(tmpb, '/');
450 if (tmp != NULL)
451 tmp++;
452 else
453 tmp = tmpb;
454 strncpy(incue_fname, tmp, incue_max_len);
226a5691 455 ti[numtracks + 1].handle = fopen(filepath, "rb");
ef79bbde 456
19c03d80 457 // update global offset if this is not first file in this .cue
deebc67f 458 if (numtracks + 1 > 1) {
459 multifile = 1;
19c03d80 460 sector_offs += file_len;
deebc67f 461 }
19c03d80 462
463 file_len = 0;
38b8102c 464 if (ti[numtracks + 1].handle == NULL) {
19c03d80 465 SysPrintf(_("\ncould not open: %s\n"), filepath);
466 continue;
38b8102c 467 }
19c03d80 468 fseek(ti[numtracks + 1].handle, 0, SEEK_END);
469 file_len = ftell(ti[numtracks + 1].handle) / 2352;
470
471 if (numtracks == 0 && strlen(isofile) >= 4 &&
2cc221eb 472 (strcmp(isofile + strlen(isofile) - 4, ".cue") == 0 ||
473 strncasecmp(isofile + strlen(isofile) - 4, ".cd", 3) == 0)) {
474 // user selected .cue/.cdX as image file, use it's data track instead
38b8102c 475 fclose(cdHandle);
226a5691 476 cdHandle = fopen(filepath, "rb");
ef79bbde
P
477 }
478 }
479 }
480
481 fclose(fi);
482
2cc221eb 483 // if there are no tracks detected, then it's not a cue file
484 if (!numtracks)
485 return -1;
486
ef79bbde
P
487 return 0;
488}
489
490// this function tries to get the .ccd file of the given .img
491// the necessary data is put into the ti (trackinformation)-array
492static int parseccd(const char *isofile) {
493 char ccdname[MAXPATHLEN];
494 FILE *fi;
495 char linebuf[256];
496 unsigned int t;
497
498 numtracks = 0;
499
500 // copy name of the iso and change extension from .img to .ccd
501 strncpy(ccdname, isofile, sizeof(ccdname));
502 ccdname[MAXPATHLEN - 1] = '\0';
503 if (strlen(ccdname) >= 4) {
504 strcpy(ccdname + strlen(ccdname) - 4, ".ccd");
505 }
506 else {
507 return -1;
508 }
509
226a5691 510 if ((fi = fopen(ccdname, "r")) == NULL) {
ef79bbde
P
511 return -1;
512 }
513
514 memset(&ti, 0, sizeof(ti));
515
516 while (fgets(linebuf, sizeof(linebuf), fi) != NULL) {
517 if (!strncmp(linebuf, "[TRACK", 6)){
518 numtracks++;
519 }
520 else if (!strncmp(linebuf, "MODE=", 5)) {
521 sscanf(linebuf, "MODE=%d", &t);
522 ti[numtracks].type = ((t == 0) ? CDDA : DATA);
523 }
524 else if (!strncmp(linebuf, "INDEX 1=", 8)) {
525 sscanf(linebuf, "INDEX 1=%d", &t);
526 sec2msf(t + 2 * 75, ti[numtracks].start);
77160d47 527 ti[numtracks].start_offset = t * 2352;
ef79bbde
P
528
529 // If we've already seen another track, this is its end
530 if (numtracks > 1) {
531 t = msf2sec(ti[numtracks].start) - msf2sec(ti[numtracks - 1].start);
532 sec2msf(t, ti[numtracks - 1].length);
533 }
534 }
535 }
536
537 fclose(fi);
538
539 // Fill out the last track's end based on size
540 if (numtracks >= 1) {
541 fseek(cdHandle, 0, SEEK_END);
542 t = ftell(cdHandle) / 2352 - msf2sec(ti[numtracks].start) + 2 * 75;
543 sec2msf(t, ti[numtracks].length);
544 }
545
546 return 0;
547}
548
549// this function tries to get the .mds file of the given .mdf
550// the necessary data is put into the ti (trackinformation)-array
551static int parsemds(const char *isofile) {
552 char mdsname[MAXPATHLEN];
553 FILE *fi;
554 unsigned int offset, extra_offset, l, i;
555 unsigned short s;
556
557 numtracks = 0;
558
559 // copy name of the iso and change extension from .mdf to .mds
560 strncpy(mdsname, isofile, sizeof(mdsname));
561 mdsname[MAXPATHLEN - 1] = '\0';
562 if (strlen(mdsname) >= 4) {
563 strcpy(mdsname + strlen(mdsname) - 4, ".mds");
564 }
565 else {
566 return -1;
567 }
568
226a5691 569 if ((fi = fopen(mdsname, "rb")) == NULL) {
ef79bbde
P
570 return -1;
571 }
572
573 memset(&ti, 0, sizeof(ti));
574
575 // check if it's a valid mds file
9361a5aa
EC
576 if (fread(&i, 1, sizeof(i), fi) != sizeof(i))
577 goto fail_io;
ef79bbde
P
578 i = SWAP32(i);
579 if (i != 0x4944454D) {
580 // not an valid mds file
581 fclose(fi);
582 return -1;
583 }
584
585 // get offset to session block
586 fseek(fi, 0x50, SEEK_SET);
9361a5aa
EC
587 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
588 goto fail_io;
ef79bbde
P
589 offset = SWAP32(offset);
590
591 // get total number of tracks
592 offset += 14;
593 fseek(fi, offset, SEEK_SET);
9361a5aa
EC
594 if (fread(&s, 1, sizeof(s), fi) != sizeof(s))
595 goto fail_io;
ef79bbde
P
596 s = SWAP16(s);
597 numtracks = s;
598
599 // get offset to track blocks
600 fseek(fi, 4, SEEK_CUR);
9361a5aa
EC
601 if (fread(&offset, 1, sizeof(offset), fi) != sizeof(offset))
602 goto fail_io;
ef79bbde
P
603 offset = SWAP32(offset);
604
605 // skip lead-in data
606 while (1) {
607 fseek(fi, offset + 4, SEEK_SET);
608 if (fgetc(fi) < 0xA0) {
609 break;
610 }
611 offset += 0x50;
612 }
613
614 // check if the image contains mixed subchannel data
615 fseek(fi, offset + 1, SEEK_SET);
77160d47 616 subChanMixed = subChanRaw = (fgetc(fi) ? TRUE : FALSE);
ef79bbde
P
617
618 // read track data
619 for (i = 1; i <= numtracks; i++) {
620 fseek(fi, offset, SEEK_SET);
621
622 // get the track type
623 ti[i].type = ((fgetc(fi) == 0xA9) ? CDDA : DATA);
624 fseek(fi, 8, SEEK_CUR);
625
626 // get the track starting point
627 ti[i].start[0] = fgetc(fi);
628 ti[i].start[1] = fgetc(fi);
629 ti[i].start[2] = fgetc(fi);
630
9361a5aa
EC
631 if (fread(&extra_offset, 1, sizeof(extra_offset), fi) != sizeof(extra_offset))
632 goto fail_io;
ef79bbde
P
633 extra_offset = SWAP32(extra_offset);
634
19c03d80 635 // get track start offset (in .mdf)
636 fseek(fi, offset + 0x28, SEEK_SET);
9361a5aa
EC
637 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
638 goto fail_io;
19c03d80 639 l = SWAP32(l);
77160d47 640 ti[i].start_offset = l;
19c03d80 641
8aa91443 642 // get pregap
643 fseek(fi, extra_offset, SEEK_SET);
9361a5aa
EC
644 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
645 goto fail_io;
8aa91443 646 l = SWAP32(l);
647 if (l != 0 && i > 1)
77160d47 648 pregapOffset = msf2sec(ti[i].start);
8aa91443 649
650 // get the track length
9361a5aa
EC
651 if (fread(&l, 1, sizeof(l), fi) != sizeof(l))
652 goto fail_io;
8aa91443 653 l = SWAP32(l);
654 sec2msf(l, ti[i].length);
655
ef79bbde
P
656 offset += 0x50;
657 }
ef79bbde
P
658 fclose(fi);
659 return 0;
9361a5aa
EC
660fail_io:
661#ifndef NDEBUG
662 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
663#endif
664 fclose(fi);
665 return -1;
ef79bbde
P
666}
667
0877957a 668static int handlepbp(const char *isofile) {
9a92bffb 669 struct {
670 unsigned int sig;
671 unsigned int dontcare[8];
672 unsigned int psar_offs;
673 } pbp_hdr;
674 struct {
675 unsigned char type;
676 unsigned char pad0;
677 unsigned char track;
678 char index0[3];
679 char pad1;
680 char index1[3];
681 } toc_entry;
682 struct {
683 unsigned int offset;
684 unsigned int size;
685 unsigned int dontcare[6];
686 } index_entry;
0c2871a7 687 char psar_sig[11];
cc376814 688 off_t psisoimg_offs, cdimg_base;
689 unsigned int t, cd_length;
690 unsigned int offsettab[8];
58cb1438 691 unsigned int psar_offs, index_entry_size, index_entry_offset;
9a92bffb 692 const char *ext = NULL;
693 int i, ret;
694
695 if (strlen(isofile) >= 4)
696 ext = isofile + strlen(isofile) - 4;
697 if (ext == NULL || (strcmp(ext, ".pbp") != 0 && strcmp(ext, ".PBP") != 0))
698 return -1;
699
cc376814 700 fseeko(cdHandle, 0, SEEK_SET);
9726a4af 701
9a92bffb 702 numtracks = 0;
703
704 ret = fread(&pbp_hdr, 1, sizeof(pbp_hdr), cdHandle);
705 if (ret != sizeof(pbp_hdr)) {
f29fbd53 706 SysPrintf("failed to read pbp\n");
9a92bffb 707 goto fail_io;
708 }
709
58cb1438
PC
710 psar_offs = SWAP32(pbp_hdr.psar_offs);
711
712 ret = fseeko(cdHandle, psar_offs, SEEK_SET);
9a92bffb 713 if (ret != 0) {
58cb1438 714 SysPrintf("failed to seek to %x\n", psar_offs);
9a92bffb 715 goto fail_io;
716 }
717
58cb1438 718 psisoimg_offs = psar_offs;
9361a5aa
EC
719 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
720 goto fail_io;
0c2871a7 721 psar_sig[10] = 0;
722 if (strcmp(psar_sig, "PSTITLEIMG") == 0) {
723 // multidisk image?
58cb1438 724 ret = fseeko(cdHandle, psar_offs + 0x200, SEEK_SET);
0c2871a7 725 if (ret != 0) {
58cb1438 726 SysPrintf("failed to seek to %x\n", psar_offs + 0x200);
0c2871a7 727 goto fail_io;
728 }
729
730 if (fread(&offsettab, 1, sizeof(offsettab), cdHandle) != sizeof(offsettab)) {
f29fbd53 731 SysPrintf("failed to read offsettab\n");
0c2871a7 732 goto fail_io;
733 }
734
735 for (i = 0; i < sizeof(offsettab) / sizeof(offsettab[0]); i++) {
736 if (offsettab[i] == 0)
737 break;
738 }
739 cdrIsoMultidiskCount = i;
740 if (cdrIsoMultidiskCount == 0) {
f29fbd53 741 SysPrintf("multidisk eboot has 0 images?\n");
0c2871a7 742 goto fail_io;
743 }
744
745 if (cdrIsoMultidiskSelect >= cdrIsoMultidiskCount)
746 cdrIsoMultidiskSelect = 0;
747
58cb1438 748 psisoimg_offs += SWAP32(offsettab[cdrIsoMultidiskSelect]);
0c2871a7 749
cc376814 750 ret = fseeko(cdHandle, psisoimg_offs, SEEK_SET);
0c2871a7 751 if (ret != 0) {
cc376814 752 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs);
0c2871a7 753 goto fail_io;
754 }
755
9361a5aa
EC
756 if (fread(psar_sig, 1, sizeof(psar_sig), cdHandle) != sizeof(psar_sig))
757 goto fail_io;
0c2871a7 758 psar_sig[10] = 0;
759 }
760
761 if (strcmp(psar_sig, "PSISOIMG00") != 0) {
f29fbd53 762 SysPrintf("bad psar_sig: %s\n", psar_sig);
9a92bffb 763 goto fail_io;
764 }
765
766 // seek to TOC
cc376814 767 ret = fseeko(cdHandle, psisoimg_offs + 0x800, SEEK_SET);
9a92bffb 768 if (ret != 0) {
cc376814 769 SysPrintf("failed to seek to %llx\n", (long long)psisoimg_offs + 0x800);
9a92bffb 770 goto fail_io;
771 }
772
773 // first 3 entries are special
774 fseek(cdHandle, sizeof(toc_entry), SEEK_CUR);
9361a5aa
EC
775 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
776 goto fail_io;
9a92bffb 777 numtracks = btoi(toc_entry.index1[0]);
778
9361a5aa
EC
779 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
780 goto fail_io;
9a92bffb 781 cd_length = btoi(toc_entry.index1[0]) * 60 * 75 +
782 btoi(toc_entry.index1[1]) * 75 + btoi(toc_entry.index1[2]);
783
784 for (i = 1; i <= numtracks; i++) {
9361a5aa
EC
785 if (fread(&toc_entry, 1, sizeof(toc_entry), cdHandle) != sizeof(toc_entry))
786 goto fail_io;
9a92bffb 787
788 ti[i].type = (toc_entry.type == 1) ? CDDA : DATA;
789
790 ti[i].start_offset = btoi(toc_entry.index0[0]) * 60 * 75 +
791 btoi(toc_entry.index0[1]) * 75 + btoi(toc_entry.index0[2]);
77160d47 792 ti[i].start_offset *= 2352;
9a92bffb 793 ti[i].start[0] = btoi(toc_entry.index1[0]);
794 ti[i].start[1] = btoi(toc_entry.index1[1]);
795 ti[i].start[2] = btoi(toc_entry.index1[2]);
796
797 if (i > 1) {
798 t = msf2sec(ti[i].start) - msf2sec(ti[i - 1].start);
799 sec2msf(t, ti[i - 1].length);
800 }
801 }
77160d47 802 t = cd_length - ti[numtracks].start_offset / 2352;
9a92bffb 803 sec2msf(t, ti[numtracks].length);
804
805 // seek to ISO index
cc376814 806 ret = fseeko(cdHandle, psisoimg_offs + 0x4000, SEEK_SET);
9a92bffb 807 if (ret != 0) {
f29fbd53 808 SysPrintf("failed to seek to ISO index\n");
9a92bffb 809 goto fail_io;
810 }
811
812 compr_img = calloc(1, sizeof(*compr_img));
813 if (compr_img == NULL)
814 goto fail_io;
815
0877957a 816 compr_img->block_shift = 4;
9a92bffb 817 compr_img->current_block = (unsigned int)-1;
818
819 compr_img->index_len = (0x100000 - 0x4000) / sizeof(index_entry);
820 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
821 if (compr_img->index_table == NULL)
822 goto fail_io;
823
0c2871a7 824 cdimg_base = psisoimg_offs + 0x100000;
9a92bffb 825 for (i = 0; i < compr_img->index_len; i++) {
826 ret = fread(&index_entry, 1, sizeof(index_entry), cdHandle);
827 if (ret != sizeof(index_entry)) {
f29fbd53 828 SysPrintf("failed to read index_entry #%d\n", i);
9a92bffb 829 goto fail_index;
830 }
831
58cb1438
PC
832 index_entry_size = SWAP32(index_entry.size);
833 index_entry_offset = SWAP32(index_entry.offset);
834
835 if (index_entry_size == 0)
9a92bffb 836 break;
837
58cb1438 838 compr_img->index_table[i] = cdimg_base + index_entry_offset;
9a92bffb 839 }
58cb1438 840 compr_img->index_table[i] = cdimg_base + index_entry_offset + index_entry_size;
9a92bffb 841
842 return 0;
843
844fail_index:
845 free(compr_img->index_table);
846 compr_img->index_table = NULL;
9361a5aa
EC
847 goto done;
848
9a92bffb 849fail_io:
9361a5aa
EC
850#ifndef NDEBUG
851 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
852#endif
853
854done:
0877957a 855 if (compr_img != NULL) {
856 free(compr_img);
857 compr_img = NULL;
858 }
859 return -1;
860}
861
862static int handlecbin(const char *isofile) {
863 struct
864 {
865 char magic[4];
866 unsigned int header_size;
867 unsigned long long total_bytes;
868 unsigned int block_size;
869 unsigned char ver; // 1
870 unsigned char align;
871 unsigned char rsv_06[2];
872 } ciso_hdr;
873 const char *ext = NULL;
cc376814 874 unsigned int *index_table = NULL;
0c2871a7 875 unsigned int index = 0, plain;
0877957a 876 int i, ret;
877
878 if (strlen(isofile) >= 5)
879 ext = isofile + strlen(isofile) - 5;
880 if (ext == NULL || (strcasecmp(ext + 1, ".cbn") != 0 && strcasecmp(ext, ".cbin") != 0))
881 return -1;
882
9726a4af 883 fseek(cdHandle, 0, SEEK_SET);
884
0877957a 885 ret = fread(&ciso_hdr, 1, sizeof(ciso_hdr), cdHandle);
886 if (ret != sizeof(ciso_hdr)) {
f29fbd53 887 SysPrintf("failed to read ciso header\n");
0877957a 888 return -1;
889 }
890
891 if (strncmp(ciso_hdr.magic, "CISO", 4) != 0 || ciso_hdr.total_bytes <= 0 || ciso_hdr.block_size <= 0) {
f29fbd53 892 SysPrintf("bad ciso header\n");
0877957a 893 return -1;
894 }
895 if (ciso_hdr.header_size != 0 && ciso_hdr.header_size != sizeof(ciso_hdr)) {
cc376814 896 ret = fseeko(cdHandle, ciso_hdr.header_size, SEEK_SET);
0877957a 897 if (ret != 0) {
f29fbd53 898 SysPrintf("failed to seek to %x\n", ciso_hdr.header_size);
0877957a 899 return -1;
900 }
901 }
902
903 compr_img = calloc(1, sizeof(*compr_img));
904 if (compr_img == NULL)
905 goto fail_io;
906
907 compr_img->block_shift = 0;
908 compr_img->current_block = (unsigned int)-1;
909
910 compr_img->index_len = ciso_hdr.total_bytes / ciso_hdr.block_size;
cc376814 911 index_table = malloc((compr_img->index_len + 1) * sizeof(index_table[0]));
912 if (index_table == NULL)
0877957a 913 goto fail_io;
914
cc376814 915 ret = fread(index_table, sizeof(index_table[0]), compr_img->index_len, cdHandle);
0877957a 916 if (ret != compr_img->index_len) {
f29fbd53 917 SysPrintf("failed to read index table\n");
0877957a 918 goto fail_index;
919 }
920
cc376814 921 compr_img->index_table = malloc((compr_img->index_len + 1) * sizeof(compr_img->index_table[0]));
922 if (compr_img->index_table == NULL)
923 goto fail_index;
924
0877957a 925 for (i = 0; i < compr_img->index_len + 1; i++) {
cc376814 926 index = index_table[i];
0877957a 927 plain = index & 0x80000000;
928 index &= 0x7fffffff;
cc376814 929 compr_img->index_table[i] = (off_t)index << ciso_hdr.align;
930 if (plain)
931 compr_img->index_table[i] |= OFF_T_MSB;
0877957a 932 }
0877957a 933
934 return 0;
935
936fail_index:
cc376814 937 free(index_table);
0877957a 938fail_io:
939 if (compr_img != NULL) {
940 free(compr_img);
941 compr_img = NULL;
942 }
9a92bffb 943 return -1;
944}
945
b0ec2e6d 946#ifdef HAVE_CHD
ce188d4d 947static int handlechd(const char *isofile) {
6658ddcf 948 int frame_offset = 150;
949 int file_offset = 0;
950
ce188d4d 951 chd_img = calloc(1, sizeof(*chd_img));
952 if (chd_img == NULL)
953 goto fail_io;
954
955 if(chd_open(isofile, CHD_OPEN_READ, NULL, &chd_img->chd) != CHDERR_NONE)
1d2757f4 956 goto fail_io;
957
958 if (Config.CHD_Precache && (chd_precache(chd_img->chd) != CHDERR_NONE))
959 goto fail_io;
ce188d4d 960
aeb82099 961 chd_img->header = chd_get_header(chd_img->chd);
ce188d4d 962
aeb82099 963 chd_img->buffer = malloc(chd_img->header->hunkbytes * 2);
964 if (chd_img->buffer == NULL)
ce188d4d 965 goto fail_io;
966
aeb82099 967 chd_img->sectors_per_hunk = chd_img->header->hunkbytes / (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
968 chd_img->current_hunk[0] = (unsigned int)-1;
969 chd_img->current_hunk[1] = (unsigned int)-1;
ce188d4d 970
aeb82099 971 cddaBigEndian = TRUE;
ce188d4d 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
78bb116f 1080#if !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
aeb82099 1421static unsigned char *chd_get_sector(unsigned int current_buffer, unsigned int sector_in_hunk)
1422{
1423 return chd_img->buffer
1424 + current_buffer * chd_img->header->hunkbytes
1425 + sector_in_hunk * (CD_FRAMESIZE_RAW + SUB_FRAMESIZE);
1426}
1427
ce188d4d 1428static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
1429{
1430 int hunk;
1431
f02c57ea 1432 sector += base;
ce188d4d 1433
1434 hunk = sector / chd_img->sectors_per_hunk;
1435 chd_img->sector_in_hunk = sector % chd_img->sectors_per_hunk;
1436
aeb82099 1437 if (hunk == chd_img->current_hunk[0])
1438 chd_img->current_buffer = 0;
1439 else if (hunk == chd_img->current_hunk[1])
1440 chd_img->current_buffer = 1;
1441 else
055b81e1 1442 {
aeb82099 1443 chd_read(chd_img->chd, hunk, chd_img->buffer +
1444 chd_img->current_buffer * chd_img->header->hunkbytes);
1445 chd_img->current_hunk[chd_img->current_buffer] = hunk;
055b81e1 1446 }
ce188d4d 1447
ce188d4d 1448 if (dest != cdbuffer) // copy avoid HACK
aeb82099 1449 memcpy(dest, chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk),
ce188d4d 1450 CD_FRAMESIZE_RAW);
1451 return CD_FRAMESIZE_RAW;
1452}
0eacae49 1453
1454static int cdread_sub_chd(FILE *f, int sector)
1455{
aeb82099 1456 unsigned int sector_in_hunk;
1457 unsigned int buffer;
0eacae49 1458 int hunk;
1459
1460 if (!subChanMixed)
1461 return -1;
1462
1463 hunk = sector / chd_img->sectors_per_hunk;
aeb82099 1464 sector_in_hunk = sector % chd_img->sectors_per_hunk;
0eacae49 1465
aeb82099 1466 if (hunk == chd_img->current_hunk[0])
1467 buffer = 0;
1468 else if (hunk == chd_img->current_hunk[1])
1469 buffer = 1;
1470 else
0eacae49 1471 {
aeb82099 1472 buffer = chd_img->current_buffer ^ 1;
1473 chd_read(chd_img->chd, hunk, chd_img->buffer +
1474 buffer * chd_img->header->hunkbytes);
1475 chd_img->current_hunk[buffer] = hunk;
0eacae49 1476 }
1477
aeb82099 1478 memcpy(subbuffer, chd_get_sector(buffer, sector_in_hunk) + CD_FRAMESIZE_RAW, SUB_FRAMESIZE);
0eacae49 1479 return SUB_FRAMESIZE;
1480}
b0ec2e6d 1481#endif
5b568098 1482
77160d47 1483static int cdread_2048(FILE *f, unsigned int base, void *dest, int sector)
9a92bffb 1484{
1485 int ret;
1486
77160d47 1487 fseek(f, base + sector * 2048, SEEK_SET);
81abe4d5 1488 ret = fread((char *)dest + 12 * 2, 1, 2048, f);
9a92bffb 1489
1490 // not really necessary, fake mode 2 header
81abe4d5 1491 memset(cdbuffer, 0, 12 * 2);
1492 sec2msf(sector + 2 * 75, (char *)&cdbuffer[12]);
1493 cdbuffer[12 + 3] = 1;
9a92bffb 1494
1f665cdd 1495 return 12*2 + ret;
9a92bffb 1496}
1497
78bb116f 1498#if USE_READ_THREAD
679b71e2
JW
1499
1500static int cdread_async(FILE *f, unsigned int base, void *dest, int sector) {
1501 boolean found = FALSE;
1502 int i = sector % SECTOR_BUFFER_SIZE;
1503 long ret;
1504
1505 if (f != cdHandle || base != 0 || dest != cdbuffer) {
1506 // Async reads are only supported for cdbuffer, so call the sync
1507 // function directly.
1508 return sync_cdimg_read_func(f, base, dest, sector);
1509 }
1510
1511 pthread_mutex_lock(&read_thread_msg_lock);
1512
1513 // Only wait if we're not trying to read the next sector and
1514 // sector_start is set (meaning the last request hasn't been
1515 // processed yet)
1516 while(read_thread_sector_start != -1 && read_thread_sector_end + 1 != sector) {
1517 pthread_cond_wait(&read_thread_msg_done, &read_thread_msg_lock);
1518 }
1519
1520 if (read_thread_sector_start == -1)
1521 read_thread_sector_start = sector;
1522
1523 read_thread_sector_end = sector;
1524 pthread_cond_signal(&read_thread_msg_avail);
1525 pthread_mutex_unlock(&read_thread_msg_lock);
1526
1527 do {
1528 pthread_mutex_lock(&sectorbuffer_lock);
1529 if (sectorbuffer[i].sector == sector) {
1530 sectorbuffer_index = i;
1531 ret = sectorbuffer[i].ret;
1532 found = TRUE;
1533 }
1534
1535 if (!found) {
1536 pthread_cond_wait(&sectorbuffer_cond, &sectorbuffer_lock);
1537 }
1538 pthread_mutex_unlock(&sectorbuffer_lock);
1539 } while (!found);
1540
1541 return ret;
1542}
1543
1544#endif
1545
9a92bffb 1546static unsigned char * CALLBACK ISOgetBuffer_compr(void) {
1547 return compr_img->buff_raw[compr_img->sector_in_blk] + 12;
1548}
1549
b0ec2e6d 1550#ifdef HAVE_CHD
ce188d4d 1551static unsigned char * CALLBACK ISOgetBuffer_chd(void) {
aeb82099 1552 return chd_get_sector(chd_img->current_buffer, chd_img->sector_in_hunk) + 12;
ce188d4d 1553}
b0ec2e6d 1554#endif
ce188d4d 1555
78bb116f 1556#if USE_READ_THREAD
679b71e2
JW
1557static unsigned char * CALLBACK ISOgetBuffer_async(void) {
1558 unsigned char *buffer;
1559 pthread_mutex_lock(&sectorbuffer_lock);
1560 buffer = sectorbuffer[sectorbuffer_index].data;
1561 pthread_mutex_unlock(&sectorbuffer_lock);
1562 return buffer + 12;
1563}
679b71e2
JW
1564#endif
1565
9a92bffb 1566static unsigned char * CALLBACK ISOgetBuffer(void) {
81abe4d5 1567 return cdbuffer + 12;
9a92bffb 1568}
1569
ef79bbde
P
1570static void PrintTracks(void) {
1571 int i;
1572
1573 for (i = 1; i <= numtracks; i++) {
1574 SysPrintf(_("Track %.2d (%s) - Start %.2d:%.2d:%.2d, Length %.2d:%.2d:%.2d\n"),
1575 i, (ti[i].type == DATA ? "DATA" : "AUDIO"),
1576 ti[i].start[0], ti[i].start[1], ti[i].start[2],
1577 ti[i].length[0], ti[i].length[1], ti[i].length[2]);
1578 }
1579}
1580
1581// This function is invoked by the front-end when opening an ISO
1582// file for playback
1583static long CALLBACK ISOopen(void) {
9a92bffb 1584 boolean isMode1ISO = FALSE;
689e0447 1585 char alt_bin_filename[MAXPATHLEN];
1586 const char *bin_filename;
75d5614b 1587 char image_str[1024];
9a92bffb 1588
ef79bbde
P
1589 if (cdHandle != NULL) {
1590 return 0; // it's already open
1591 }
1592
226a5691 1593 cdHandle = fopen(GetIsoFile(), "rb");
ef79bbde 1594 if (cdHandle == NULL) {
2e058581 1595 SysPrintf(_("Could't open '%s' for reading: %s\n"),
1596 GetIsoFile(), strerror(errno));
ef79bbde
P
1597 return -1;
1598 }
1599
75d5614b 1600 snprintf(image_str, sizeof(image_str) - 6*4 - 1,
1601 "Loaded CD Image: %s", GetIsoFile());
ef79bbde
P
1602
1603 cddaBigEndian = FALSE;
1604 subChanMixed = FALSE;
1605 subChanRaw = FALSE;
8aa91443 1606 pregapOffset = 0;
0c2871a7 1607 cdrIsoMultidiskCount = 1;
deebc67f 1608 multifile = 0;
ef79bbde 1609
9a92bffb 1610 CDR_getBuffer = ISOgetBuffer;
1611 cdimg_read_func = cdread_normal;
0eacae49 1612 cdimg_read_sub_func = NULL;
9a92bffb 1613
92f43ab0 1614 if (parsetoc(GetIsoFile()) == 0) {
208177a7 1615 strcat(image_str, "[+toc]");
ef79bbde
P
1616 }
1617 else if (parseccd(GetIsoFile()) == 0) {
208177a7 1618 strcat(image_str, "[+ccd]");
ef79bbde
P
1619 }
1620 else if (parsemds(GetIsoFile()) == 0) {
208177a7 1621 strcat(image_str, "[+mds]");
ef79bbde 1622 }
92f43ab0 1623 else if (parsecue(GetIsoFile()) == 0) {
208177a7 1624 strcat(image_str, "[+cue]");
92f43ab0 1625 }
0877957a 1626 if (handlepbp(GetIsoFile()) == 0) {
208177a7 1627 strcat(image_str, "[+pbp]");
9a92bffb 1628 CDR_getBuffer = ISOgetBuffer_compr;
1629 cdimg_read_func = cdread_compressed;
1630 }
0877957a 1631 else if (handlecbin(GetIsoFile()) == 0) {
208177a7 1632 strcat(image_str, "[+cbin]");
0877957a 1633 CDR_getBuffer = ISOgetBuffer_compr;
1634 cdimg_read_func = cdread_compressed;
1635 }
b0ec2e6d 1636#ifdef HAVE_CHD
ce188d4d 1637 else if (handlechd(GetIsoFile()) == 0) {
208177a7 1638 strcat(image_str, "[+chd]");
ce188d4d 1639 CDR_getBuffer = ISOgetBuffer_chd;
1640 cdimg_read_func = cdread_chd;
0eacae49 1641 cdimg_read_sub_func = cdread_sub_chd;
ce188d4d 1642 }
b0ec2e6d 1643#endif
ef79bbde
P
1644
1645 if (!subChanMixed && opensubfile(GetIsoFile()) == 0) {
208177a7 1646 strcat(image_str, "[+sub]");
ef79bbde 1647 }
ae4e7dc9 1648 if (opensbifile(GetIsoFile()) == 0) {
208177a7 1649 strcat(image_str, "[+sbi]");
ae4e7dc9 1650 }
ef79bbde 1651
cc376814 1652 fseeko(cdHandle, 0, SEEK_END);
c9e5423e 1653
1654 // maybe user selected metadata file instead of main .bin ..
689e0447 1655 bin_filename = GetIsoFile();
cc376814 1656 if (ftello(cdHandle) < 2352 * 0x10) {
c9e5423e 1657 static const char *exts[] = { ".bin", ".BIN", ".img", ".IMG" };
689e0447 1658 FILE *tmpf = NULL;
c9e5423e 1659 size_t i;
689e0447 1660 char *p;
c9e5423e 1661
689e0447 1662 strncpy(alt_bin_filename, bin_filename, sizeof(alt_bin_filename));
1663 alt_bin_filename[MAXPATHLEN - 1] = '\0';
1664 if (strlen(alt_bin_filename) >= 4) {
1665 p = alt_bin_filename + strlen(alt_bin_filename) - 4;
c9e5423e 1666 for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
1667 strcpy(p, exts[i]);
226a5691 1668 tmpf = fopen(alt_bin_filename, "rb");
689e0447 1669 if (tmpf != NULL)
c9e5423e 1670 break;
c9e5423e 1671 }
1672 }
689e0447 1673 if (tmpf != NULL) {
1674 bin_filename = alt_bin_filename;
1675 fclose(cdHandle);
1676 cdHandle = tmpf;
cc376814 1677 fseeko(cdHandle, 0, SEEK_END);
689e0447 1678 }
c9e5423e 1679 }
1680
1681 // guess whether it is mode1/2048
7e49a25d 1682 if (cdimg_read_func == cdread_normal && ftello(cdHandle) % 2048 == 0) {
9a92bffb 1683 unsigned int modeTest = 0;
1684 fseek(cdHandle, 0, SEEK_SET);
4f0c5e3f 1685 if (!fread(&modeTest, sizeof(modeTest), 1, cdHandle)) {
9361a5aa 1686 SysPrintf(_("File IO error in <%s:%s>.\n"), __FILE__, __func__);
9361a5aa 1687 }
9a92bffb 1688 if (SWAP32(modeTest) != 0xffffff00) {
208177a7 1689 strcat(image_str, "[2048]");
9a92bffb 1690 isMode1ISO = TRUE;
1691 }
1692 }
1693 fseek(cdHandle, 0, SEEK_SET);
1694
208177a7 1695 SysPrintf("%s.\n", image_str);
ef79bbde
P
1696
1697 PrintTracks();
1698
7e49a25d 1699 if (subChanMixed && cdimg_read_func == cdread_normal) {
9a92bffb 1700 cdimg_read_func = cdread_sub_mixed;
0eacae49 1701 cdimg_read_sub_func = cdread_sub_sub_mixed;
1702 }
1703 else if (isMode1ISO) {
9a92bffb 1704 cdimg_read_func = cdread_2048;
0eacae49 1705 cdimg_read_sub_func = NULL;
1706 }
9a92bffb 1707
38b8102c 1708 // make sure we have another handle open for cdda
1709 if (numtracks > 1 && ti[1].handle == NULL) {
226a5691 1710 ti[1].handle = fopen(bin_filename, "rb");
38b8102c 1711 }
1712
679b71e2
JW
1713 if (Config.AsyncCD) {
1714 readThreadStart();
1715 }
ef79bbde
P
1716 return 0;
1717}
1718
1719static long CALLBACK ISOclose(void) {
38b8102c 1720 int i;
1721
ef79bbde
P
1722 if (cdHandle != NULL) {
1723 fclose(cdHandle);
1724 cdHandle = NULL;
1725 }
1726 if (subHandle != NULL) {
1727 fclose(subHandle);
1728 subHandle = NULL;
1729 }
6e537c6d 1730 playing = FALSE;
38b8102c 1731 cddaHandle = NULL;
1732
9a92bffb 1733 if (compr_img != NULL) {
1734 free(compr_img->index_table);
1735 free(compr_img);
1736 compr_img = NULL;
1737 }
1738
b0ec2e6d 1739#ifdef HAVE_CHD
ce188d4d 1740 if (chd_img != NULL) {
1741 chd_close(chd_img->chd);
1742 free(chd_img->buffer);
1743 free(chd_img);
1744 chd_img = NULL;
1745 }
b0ec2e6d 1746#endif
ce188d4d 1747
38b8102c 1748 for (i = 1; i <= numtracks; i++) {
1749 if (ti[i].handle != NULL) {
1750 fclose(ti[i].handle);
1751 ti[i].handle = NULL;
1752 }
1753 }
1754 numtracks = 0;
c0ee7ac6 1755 ti[1].type = 0;
ae4e7dc9 1756 UnloadSBI();
38b8102c 1757
c0ee7ac6 1758 memset(cdbuffer, 0, sizeof(cdbuffer));
1759 CDR_getBuffer = ISOgetBuffer;
1760
49942a16 1761 if (Config.AsyncCD) {
1762 readThreadStop();
1763 }
1764
38b8102c 1765 return 0;
1766}
1767
1768static long CALLBACK ISOinit(void) {
1769 assert(cdHandle == NULL);
1770 assert(subHandle == NULL);
1771
1772 return 0; // do nothing
1773}
1774
1775static long CALLBACK ISOshutdown(void) {
1776 ISOclose();
ef79bbde
P
1777 return 0;
1778}
1779
1780// return Starting and Ending Track
1781// buffer:
1782// byte 0 - start track
1783// byte 1 - end track
1784static long CALLBACK ISOgetTN(unsigned char *buffer) {
1785 buffer[0] = 1;
1786
1787 if (numtracks > 0) {
1788 buffer[1] = numtracks;
1789 }
1790 else {
1791 buffer[1] = 1;
1792 }
1793
1794 return 0;
1795}
1796
1797// return Track Time
1798// buffer:
1799// byte 0 - frame
1800// byte 1 - second
1801// byte 2 - minute
1802static long CALLBACK ISOgetTD(unsigned char track, unsigned char *buffer) {
858ad511 1803 if (track == 0) {
858ad511 1804 unsigned int sect;
1805 unsigned char time[3];
1806 sect = msf2sec(ti[numtracks].start) + msf2sec(ti[numtracks].length);
ab948f7e 1807 sec2msf(sect, (char *)time);
858ad511 1808 buffer[2] = time[0];
1809 buffer[1] = time[1];
1810 buffer[0] = time[2];
1811 }
1812 else if (numtracks > 0 && track <= numtracks) {
ef79bbde
P
1813 buffer[2] = ti[track].start[0];
1814 buffer[1] = ti[track].start[1];
1815 buffer[0] = ti[track].start[2];
1816 }
1817 else {
1818 buffer[2] = 0;
1819 buffer[1] = 2;
1820 buffer[0] = 0;
1821 }
1822
1823 return 0;
1824}
1825
1826// decode 'raw' subchannel data ripped by cdrdao
1827static void DecodeRawSubData(void) {
1828 unsigned char subQData[12];
1829 int i;
1830
1831 memset(subQData, 0, sizeof(subQData));
1832
1833 for (i = 0; i < 8 * 12; i++) {
1834 if (subbuffer[i] & (1 << 6)) { // only subchannel Q is needed
1835 subQData[i >> 3] |= (1 << (7 - (i & 7)));
1836 }
1837 }
1838
1839 memcpy(&subbuffer[12], subQData, 12);
1840}
1841
1842// read track
1843// time: byte 0 - minute; byte 1 - second; byte 2 - frame
1844// uses bcd format
d2e271b2 1845static boolean CALLBACK ISOreadTrack(unsigned char *time) {
19c03d80 1846 int sector = MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2]));
c0ee7ac6 1847 long ret;
19c03d80 1848
ef79bbde 1849 if (cdHandle == NULL) {
d2e271b2 1850 return 0;
ef79bbde
P
1851 }
1852
0eacae49 1853 if (pregapOffset && sector >= pregapOffset)
1854 sector -= 2 * 75;
8aa91443 1855
c0ee7ac6 1856 ret = cdimg_read_func(cdHandle, 0, cdbuffer, sector);
1f665cdd 1857 if (ret < 12*2 + 2048)
d2e271b2 1858 return 0;
ef79bbde 1859
d2e271b2 1860 return 1;
ef79bbde
P
1861}
1862
ef79bbde
P
1863// plays cdda audio
1864// sector: byte 0 - minute; byte 1 - second; byte 2 - frame
1865// does NOT uses bcd format
2e88c317 1866static long CALLBACK ISOplay(unsigned char *time) {
66425c25 1867 playing = TRUE;
ef79bbde
P
1868 return 0;
1869}
1870
1871// stops cdda audio
1872static long CALLBACK ISOstop(void) {
66425c25 1873 playing = FALSE;
ef79bbde
P
1874 return 0;
1875}
1876
1877// gets subchannel data
0eacae49 1878static unsigned char* CALLBACK ISOgetBufferSub(int sector) {
1879 if (pregapOffset && sector >= pregapOffset) {
1880 sector -= 2 * 75;
1881 if (sector < pregapOffset) // ?
1882 return NULL;
ef79bbde
P
1883 }
1884
0eacae49 1885 if (cdimg_read_sub_func != NULL) {
1886 if (cdimg_read_sub_func(cdHandle, sector) != SUB_FRAMESIZE)
1887 return NULL;
1888 }
1889 else if (subHandle != NULL) {
1890 if (fseek(subHandle, sector * SUB_FRAMESIZE, SEEK_SET))
1891 return NULL;
1892 if (fread(subbuffer, 1, SUB_FRAMESIZE, subHandle) != SUB_FRAMESIZE)
1893 return NULL;
1894 }
1895 else {
1896 return NULL;
1897 }
1898
1899 if (subChanRaw) DecodeRawSubData();
1900 return subbuffer;
ef79bbde
P
1901}
1902
1903static long CALLBACK ISOgetStatus(struct CdrStat *stat) {
deebc67f 1904 u32 sect;
1905
ef79bbde 1906 CDR__getStatus(stat);
deebc67f 1907
ef79bbde
P
1908 if (playing) {
1909 stat->Type = 0x02;
1910 stat->Status |= 0x80;
ef79bbde
P
1911 }
1912 else {
deebc67f 1913 // BIOS - boot ID (CD type)
1914 stat->Type = ti[1].type;
1915 }
1916
1917 // relative -> absolute time
1918 sect = cddaCurPos;
1919 sec2msf(sect, (char *)stat->Time);
1920
1921 return 0;
1922}
1923
1924// read CDDA sector into buffer
1925long CALLBACK ISOreadCDDA(unsigned char m, unsigned char s, unsigned char f, unsigned char *buffer) {
1926 unsigned char msf[3] = {m, s, f};
1927 unsigned int file, track, track_start = 0;
1928 int ret;
1929
1930 cddaCurPos = msf2sec((char *)msf);
1931
1932 // find current track index
1933 for (track = numtracks; ; track--) {
1934 track_start = msf2sec(ti[track].start);
1935 if (track_start <= cddaCurPos)
1936 break;
1937 if (track == 1)
1938 break;
1939 }
1940
1941 // data tracks play silent
1942 if (ti[track].type != CDDA) {
1943 memset(buffer, 0, CD_FRAMESIZE_RAW);
1944 return 0;
1945 }
1946
1947 file = 1;
1948 if (multifile) {
1949 // find the file that contains this track
1950 for (file = track; file > 1; file--)
1951 if (ti[file].handle != NULL)
1952 break;
ef79bbde
P
1953 }
1954
deebc67f 1955 ret = cdimg_read_func(ti[file].handle, ti[track].start_offset,
1956 buffer, cddaCurPos - track_start);
1957 if (ret != CD_FRAMESIZE_RAW) {
1958 memset(buffer, 0, CD_FRAMESIZE_RAW);
1959 return -1;
1960 }
1961
1962 if (cddaBigEndian) {
1963 int i;
1964 unsigned char tmp;
1965
1966 for (i = 0; i < CD_FRAMESIZE_RAW / 2; i++) {
1967 tmp = buffer[i * 2];
1968 buffer[i * 2] = buffer[i * 2 + 1];
1969 buffer[i * 2 + 1] = tmp;
1970 }
1971 }
858ad511 1972
ef79bbde
P
1973 return 0;
1974}
1975
1976void cdrIsoInit(void) {
1977 CDR_init = ISOinit;
1978 CDR_shutdown = ISOshutdown;
1979 CDR_open = ISOopen;
1980 CDR_close = ISOclose;
1981 CDR_getTN = ISOgetTN;
1982 CDR_getTD = ISOgetTD;
1983 CDR_readTrack = ISOreadTrack;
1984 CDR_getBuffer = ISOgetBuffer;
1985 CDR_play = ISOplay;
1986 CDR_stop = ISOstop;
1987 CDR_getBufferSub = ISOgetBufferSub;
1988 CDR_getStatus = ISOgetStatus;
deebc67f 1989 CDR_readCDDA = ISOreadCDDA;
ef79bbde
P
1990
1991 CDR_getDriveLetter = CDR__getDriveLetter;
1992 CDR_configure = CDR__configure;
1993 CDR_test = CDR__test;
1994 CDR_about = CDR__about;
1995 CDR_setfilename = CDR__setfilename;
1996
1997 numtracks = 0;
1998}
1999
2000int cdrIsoActive(void) {
2001 return (cdHandle != NULL);
2002}