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