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