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