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