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