Debian Codegraph @

mednafen/cdrom/CDAccess_Image.cpp

raw symbols SCIP
1 /* Mednafen - Multi-system Emulator
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 */
17
18 /*
19 Notes and TODO:
20
21 POSTGAP in CUE sheets may not be handled properly, should the directive automatically increment the index number?
22
23 INDEX nn where 02 <= nn <= 99 is not supported in CUE sheets.
24
25 TOC reading code is extremely barebones, leaving out support for more esoteric features.
26
27 A PREGAP statement in the first track definition in a CUE sheet may not work properly(depends on what is proper);
28 it will be added onto the implicit default 00:02:00 of pregap.
29
30 Trying to read sectors at an LBA of less than 0 is not supported. TODO: support it(at least up to -150).
31 */
32
33 #include "../mednafen.h"
34
35 #include <sys/types.h>
36
37 #include <string.h>
38 #include <errno.h>
39 #include <time.h>
40
41 #include "../general.h"
42 #include "../FileStream.h"
43 #include "../MemoryStream.h"
44
45 #include "CDAccess.h"
46 #include "CDAccess_Image.h"
47
48 #include "audioreader.h"
49
50 #include <map>
51
52 using namespace CDUtility;
53
54 enum
55 {
56 CDRF_SUBM_NONE = 0,
57 CDRF_SUBM_RW = 1,
58 CDRF_SUBM_RW_RAW = 2
59 };
60
61 // Disk-image(rip) track/sector formats
62 enum
63 {
64 DI_FORMAT_AUDIO = 0x00,
65 DI_FORMAT_MODE1 = 0x01,
66 DI_FORMAT_MODE1_RAW = 0x02,
67 DI_FORMAT_MODE2 = 0x03,
68 DI_FORMAT_MODE2_FORM1 = 0x04,
69 DI_FORMAT_MODE2_FORM2 = 0x05,
70 DI_FORMAT_MODE2_RAW = 0x06,
71 _DI_FORMAT_COUNT
72 };
73
74 static const int32 DI_Size_Table[7] =
75 {
76 2352, // Audio
77 2048, // MODE1
78 2352, // MODE1 RAW
79 2336, // MODE2
80 2048, // MODE2 Form 1
81 2324, // Mode 2 Form 2
82 2352
83 };
84
85 static const char *DI_CDRDAO_Strings[7] =
86 {
87 "AUDIO",
88 "MODE1",
89 "MODE1_RAW",
90 "MODE2",
91 "MODE2_FORM1",
92 "MODE2_FORM2",
93 "MODE2_RAW"
94 };
95
96 static const char *DI_CUE_Strings[7] =
97 {
98 "AUDIO",
99 "MODE1/2048",
100 "MODE1/2352",
101
102 // FIXME: These are just guesses:
103 "MODE2/2336",
104 "MODE2/2048",
105 "MODE2/2324",
106 "MODE2/2352"
107 };
108
109 // Should return an offset to the start of the next argument(past any whitespace), or if there isn't a next argument,
110 // it'll return the length of the src string.
111 static size_t UnQuotify(const std::string &src, size_t source_offset, std::string &dest, bool parse_quotes = true)
112 {
113 const size_t source_len = src.length();
114 bool in_quote = 0;
115 bool already_normal = 0;
116
117 dest.clear();
118
119 while(source_offset < source_len)
120 {
121 if(src[source_offset] == ' ' || src[source_offset] == '\t')
122 {
123 if(!in_quote)
124 {
125 if(already_normal) // Trailing whitespace(IE we're done with this argument)
126 break;
127 else // Leading whitespace, ignore it.
128 {
129 source_offset++;
130 continue;
131 }
132 }
133 }
134
135 if(src[source_offset] == '"' && parse_quotes)
136 {
137 if(in_quote)
138 {
139 source_offset++;
140 // Not sure which behavior is most useful(or correct :b).
141 #if 0
142 in_quote = false;
143 already_normal = true;
144 #else
145 break;
146 #endif
147 }
148 else
149 in_quote = 1;
150 }
151 else
152 {
153 dest.push_back(src[source_offset]);
154 already_normal = 1;
155 }
156 source_offset++;
157 }
158
159 while(source_offset < source_len)
160 {
161 if(src[source_offset] != ' ' && src[source_offset] != '\t')
162 break;
163
164 source_offset++;
165 }
166
167 return source_offset;
168 }
169
170 uint32 CDAccess_Image::GetSectorCount(CDRFILE_TRACK_INFO *track)
171 {
172 if(track->DIFormat == DI_FORMAT_AUDIO)
173 {
174 if(track->AReader)
175 return(((track->AReader->FrameCount() * 4) - track->FileOffset) / 2352);
176 else
177 {
178 const int64 size = track->fp->size();
179
180 //printf("%d %d %d\n", (int)stat_buf.st_size, (int)track->FileOffset, (int)stat_buf.st_size - (int)track->FileOffset);
181 if(track->SubchannelMode)
182 return((size - track->FileOffset) / (2352 + 96));
183 else
184 return((size - track->FileOffset) / 2352);
185 }
186 }
187 else
188 {
189 const int64 size = track->fp->size();
190
191 return((size - track->FileOffset) / DI_Size_Table[track->DIFormat]);
192 }
193
194 return(0);
195 }
196
197 void CDAccess_Image::ParseTOCFileLineInfo(CDRFILE_TRACK_INFO *track, const int tracknum, const std::string &filename, const char *binoffset, const char *msfoffset, const char *length, bool image_memcache, std::map<std::string, Stream*> &toc_streamcache)
198 {
199 long offset = 0; // In bytes!
200 long tmp_long;
201 int m, s, f;
202 uint32 sector_mult;
203 long sectors;
204 std::map<std::string, Stream*>::iterator ribbit;
205
206 ribbit = toc_streamcache.find(filename);
207
208 if(ribbit != toc_streamcache.end())
209 {
210 track->FirstFileInstance = 0;
211
212 track->fp = ribbit->second;
213 }
214 else
215 {
216 std::string efn;
217
218 track->FirstFileInstance = 1;
219
220 efn = MDFN_EvalFIP(base_dir, filename);
221
222 if(image_memcache)
223 track->fp = new MemoryStream(new FileStream(efn.c_str(), MODE_READ));
224 else
225 track->fp = new FileStream(efn.c_str(), MODE_READ);
226
227 toc_streamcache[filename] = track->fp;
228 }
229
230 if(filename.length() >= 4 && !strcasecmp(filename.c_str() + filename.length() - 4, ".wav"))
231 {
232 track->AReader = AR_Open(track->fp);
233
234 if(!track->AReader)
235 throw MDFN_Error(0, "TODO ERROR");
236 }
237
238 sector_mult = DI_Size_Table[track->DIFormat];
239
240 if(track->SubchannelMode)
241 sector_mult += 96;
242
243 if(binoffset && sscanf(binoffset, "%ld", &tmp_long) == 1)
244 {
245 offset += tmp_long;
246 }
247
248 if(msfoffset && sscanf(msfoffset, "%d:%d:%d", &m, &s, &f) == 3)
249 {
250 offset += ((m * 60 + s) * 75 + f) * sector_mult;
251 }
252
253 track->FileOffset = offset; // Make sure this is set before calling GetSectorCount()!
254 sectors = GetSectorCount(track);
255 //printf("Track: %d, offset: %ld, %ld\n", tracknum, offset, sectors);
256
257 if(length)
258 {
259 tmp_long = sectors;
260
261 if(sscanf(length, "%d:%d:%d", &m, &s, &f) == 3)
262 tmp_long = (m * 60 + s) * 75 + f;
263 else if(track->DIFormat == DI_FORMAT_AUDIO)
264 {
265 char *endptr = NULL;
266
267 tmp_long = strtol(length, &endptr, 10);
268
269 // Error?
270 if(endptr == length)
271 {
272 tmp_long = sectors;
273 }
274 else
275 tmp_long /= 588;
276
277 }
278
279 if(tmp_long > sectors)
280 {
281 throw MDFN_Error(0, _("Length specified in TOC file for track %d is too large by %ld sectors!\n"), tracknum, (long)(tmp_long - sectors));
282 }
283 sectors = tmp_long;
284 }
285
286 track->sectors = sectors;
287 }
288
289
290 static void MDFN_strtoupper(char *str)
291 {
292 for(size_t x = 0; str[x]; x++)
293 {
294 if(str[x] >= 'a' && str[x] <= 'z')
295 {
296 str[x] = str[x] - 'a' + 'A';
297 }
298 }
299 }
300
301 static void MDFN_strtoupper(std::string &str)
302 {
303 const size_t len = str.length();
304
305 for(size_t x = 0; x < len; x++)
306 {
307 if(str[x] >= 'a' && str[x] <= 'z')
308 {
309 str[x] = str[x] - 'a' + 'A';
310 }
311 }
312 }
313
314 #if 0
315 std::string MDFN_toupper(const std::string &str)
316 {
317 const size_t len = str.length();
318 std::string new_str;
319
320 new_str.reserve(len);
321
322 for(size_t x = 0; x < len; x++)
323 {
324 int c = str[x];
325
326 if(c >= 'a' && c <= 'z')
327 c = c - 'a' + 'A';
328
329 new_str.push_back(c);
330 }
331 }
332 #endif
333
334 void CDAccess_Image::ImageOpen(const char *path, bool image_memcache)
335 {
336 MemoryStream fp(new FileStream(path, MODE_READ));
337 static const unsigned max_args = 4;
338 std::string linebuf;
339 std::string cmdbuf, args[max_args];
340 bool IsTOC = FALSE;
341 int32 active_track = -1;
342 int32 AutoTrackInc = 1; // For TOC
343 CDRFILE_TRACK_INFO TmpTrack;
344 std::string file_base, file_ext;
345 std::map<std::string, Stream*> toc_streamcache;
346
347 disc_type = DISC_TYPE_CDDA_OR_M1;
348 memset(&TmpTrack, 0, sizeof(TmpTrack));
349
350 MDFN_GetFilePathComponents(path, &base_dir, &file_base, &file_ext);
351
352 if(!strcasecmp(file_ext.c_str(), ".toc"))
353 {
354 MDFN_printf(_("TOC file detected.\n"));
355 IsTOC = true;
356 }
357
358 // Check for annoying UTF-8 BOM.
359 if(!IsTOC)
360 {
361 uint8 bom_tmp[3];
362
363 if(fp.read(bom_tmp, 3, false) == 3 && bom_tmp[0] == 0xEF && bom_tmp[1] == 0xBB && bom_tmp[2] == 0xBF)
364 {
365 // Print an annoying error message, but don't actually error out.
366 MDFN_PrintError(_("UTF-8 BOM detected at start of CUE sheet."));
367 }
368 else
369 fp.seek(0, SEEK_SET);
370 }
371
372
373 // Assign opposite maximum values so our tests will work!
374 FirstTrack = 99;
375 LastTrack = 0;
376
377 linebuf.reserve(1024);
378 while(fp.get_line(linebuf) >= 0)
379 {
380 unsigned argcount = 0;
381
382 if(IsTOC)
383 {
384 // Handle TOC format comments
385 size_t ss_loc = linebuf.find("//");
386
387 if(ss_loc != std::string::npos)
388 linebuf.resize(ss_loc);
389 }
390
391 // Call trim AFTER we handle TOC-style comments, so we'll be sure to remove trailing whitespace in lines like: MONKEY // BABIES
392 MDFN_trim(linebuf);
393
394 if(linebuf.length() == 0) // Skip blank lines.
395 continue;
396
397 // Grab command and arguments.
398 {
399 size_t offs = 0;
400
401 offs = UnQuotify(linebuf, offs, cmdbuf, false);
402 for(argcount = 0; argcount < max_args && offs < linebuf.length(); argcount++)
403 offs = UnQuotify(linebuf, offs, args[argcount]);
404
405 // Make sure unused arguments are cleared out so we don't have inter-line leaks!
406 for(unsigned x = argcount; x < max_args; x++)
407 args[x].clear();
408
409 MDFN_strtoupper(cmdbuf);
410 }
411
412 //printf("%s\n", cmdbuf.c_str()); //: %s %s %s %s\n", cmdbuf.c_str(), args[0].c_str(), args[1].c_str(), args[2].c_str(), args[3].c_str());
413
414 if(IsTOC)
415 {
416 if(cmdbuf == "TRACK")
417 {
418 if(active_track >= 0)
419 {
420 memcpy(&Tracks[active_track], &TmpTrack, sizeof(TmpTrack));
421 memset(&TmpTrack, 0, sizeof(TmpTrack));
422 active_track = -1;
423 }
424
425 if(AutoTrackInc > 99)
426 {
427 throw(MDFN_Error(0, _("Invalid track number: %d"), AutoTrackInc));
428 }
429
430 active_track = AutoTrackInc++;
431 if(active_track < FirstTrack)
432 FirstTrack = active_track;
433 if(active_track > LastTrack)
434 LastTrack = active_track;
435
436 int format_lookup;
437 for(format_lookup = 0; format_lookup < _DI_FORMAT_COUNT; format_lookup++)
438 {
439 if(!strcasecmp(args[0].c_str(), DI_CDRDAO_Strings[format_lookup]))
440 {
441 TmpTrack.DIFormat = format_lookup;
442 break;
443 }
444 }
445
446 if(format_lookup == _DI_FORMAT_COUNT)
447 {
448 throw(MDFN_Error(0, _("Invalid track format: %s"), args[0].c_str()));
449 }
450
451 if(TmpTrack.DIFormat == DI_FORMAT_AUDIO)
452 TmpTrack.RawAudioMSBFirst = TRUE; // Silly cdrdao...
453
454 if(!strcasecmp(args[1].c_str(), "RW"))
455 {
456 TmpTrack.SubchannelMode = CDRF_SUBM_RW;
457 throw(MDFN_Error(0, _("\"RW\" format subchannel data not supported, only \"RW_RAW\" is!")));
458 }
459 else if(!strcasecmp(args[1].c_str(), "RW_RAW"))
460 TmpTrack.SubchannelMode = CDRF_SUBM_RW_RAW;
461
462 } // end to TRACK
463 else if(cmdbuf == "SILENCE")
464 {
465 //throw MDFN_Error(0, _("Unsupported directive: %s"), cmdbuf.c_str());
466 }
467 else if(cmdbuf == "ZERO")
468 {
469 //throw MDFN_Error(0, _("Unsupported directive: %s"), cmdbuf.c_str());
470 }
471 else if(cmdbuf == "FIFO")
472 {
473 throw MDFN_Error(0, _("Unsupported directive: %s"), cmdbuf.c_str());
474 }
475 else if(cmdbuf == "FILE" || cmdbuf == "AUDIOFILE")
476 {
477 const char *binoffset = NULL;
478 const char *msfoffset = NULL;
479 const char *length = NULL;
480
481 if(args[1].c_str()[0] == '#')
482 {
483 binoffset = args[1].c_str() + 1;
484 msfoffset = args[2].c_str();
485 length = args[3].c_str();
486 }
487 else
488 {
489 msfoffset = args[1].c_str();
490 length = args[2].c_str();
491 }
492 //printf("%s, %s, %s, %s\n", args[0].c_str(), binoffset, msfoffset, length);
493 ParseTOCFileLineInfo(&TmpTrack, active_track, args[0], binoffset, msfoffset, length, image_memcache, toc_streamcache);
494 }
495 else if(cmdbuf == "DATAFILE")
496 {
497 const char *binoffset = NULL;
498 const char *length = NULL;
499
500 if(args[1].c_str()[0] == '#')
501 {
502 binoffset = args[1].c_str() + 1;
503 length = args[2].c_str();
504 }
505 else
506 length = args[1].c_str();
507
508 ParseTOCFileLineInfo(&TmpTrack, active_track, args[0], binoffset, NULL, length, image_memcache, toc_streamcache);
509 }
510 else if(cmdbuf == "INDEX")
511 {
512
513 }
514 else if(cmdbuf == "PREGAP")
515 {
516 if(active_track < 0)
517 {
518 throw(MDFN_Error(0, _("Command %s is outside of a TRACK definition!\n"), cmdbuf.c_str()));
519 }
520 int m,s,f;
521 sscanf(args[0].c_str(), "%d:%d:%d", &m, &s, &f);
522 TmpTrack.pregap = (m * 60 + s) * 75 + f;
523 } // end to PREGAP
524 else if(cmdbuf == "START")
525 {
526 if(active_track < 0)
527 {
528 throw(MDFN_Error(0, _("Command %s is outside of a TRACK definition!\n"), cmdbuf.c_str()));
529 }
530 int m,s,f;
531 sscanf(args[0].c_str(), "%d:%d:%d", &m, &s, &f);
532 TmpTrack.pregap = (m * 60 + s) * 75 + f;
533 }
534 else if(cmdbuf == "TWO_CHANNEL_AUDIO")
535 {
536 TmpTrack.subq_control &= ~SUBQ_CTRLF_4CH;
537 }
538 else if(cmdbuf == "FOUR_CHANNEL_AUDIO")
539 {
540 TmpTrack.subq_control |= SUBQ_CTRLF_4CH;
541 }
542 else if(cmdbuf == "NO")
543 {
544 MDFN_strtoupper(args[0]);
545
546 if(args[0] == "COPY")
547 {
548 TmpTrack.subq_control &= ~SUBQ_CTRLF_DCP;
549 }
550 else if(args[0] == "PRE_EMPHASIS")
551 {
552 TmpTrack.subq_control &= ~SUBQ_CTRLF_PRE;
553 }
554 else
555 {
556 throw MDFN_Error(0, _("Unsupported argument to \"NO\" directive: %s"), args[0].c_str());
557 }
558 }
559 else if(cmdbuf == "COPY")
560 {
561 TmpTrack.subq_control |= SUBQ_CTRLF_DCP;
562 }
563 else if(cmdbuf == "PRE_EMPHASIS")
564 {
565 TmpTrack.subq_control |= SUBQ_CTRLF_PRE;
566 }
567 // TODO: Confirm that these are taken from the TOC of the disc, and not synthesized by cdrdao.
568 else if(cmdbuf == "CD_DA")
569 disc_type = DISC_TYPE_CDDA_OR_M1;
570 else if(cmdbuf == "CD_ROM")
571 disc_type = DISC_TYPE_CDDA_OR_M1;
572 else if(cmdbuf == "CD_ROM_XA")
573 disc_type = DISC_TYPE_CD_XA;
574 else
575 {
576 //throw MDFN_Error(0, _("Unsupported directive: %s"), cmdbuf.c_str());
577 }
578 // TODO: CATALOG
579
580 } /*********** END TOC HANDLING ************/
581 else // now for CUE sheet handling
582 {
583 if(cmdbuf == "FILE")
584 {
585 if(active_track >= 0)
586 {
587 memcpy(&Tracks[active_track], &TmpTrack, sizeof(TmpTrack));
588 memset(&TmpTrack, 0, sizeof(TmpTrack));
589 active_track = -1;
590 }
591
592 if(!MDFN_IsFIROPSafe(args[0]))
593 {
594 throw(MDFN_Error(0, _("Referenced path \"%s\" is potentially unsafe. See \"filesys.untrusted_fip_check\" setting.\n"), args[0].c_str()));
595 }
596
597 std::string efn = MDFN_EvalFIP(base_dir, args[0]);
598 TmpTrack.fp = new FileStream(efn.c_str(), MODE_READ);
599 TmpTrack.FirstFileInstance = 1;
600
601 if(image_memcache)
602 TmpTrack.fp = new MemoryStream(TmpTrack.fp);
603
604 if(!strcasecmp(args[1].c_str(), "BINARY"))
605 {
606 //TmpTrack.Format = TRACK_FORMAT_DATA;
607 //struct stat stat_buf;
608 //fstat(fileno(TmpTrack.fp), &stat_buf);
609 //TmpTrack.sectors = stat_buf.st_size; // / 2048;
610 }
611 else if(!strcasecmp(args[1].c_str(), "OGG") || !strcasecmp(args[1].c_str(), "VORBIS") || !strcasecmp(args[1].c_str(), "WAVE") || !strcasecmp(args[1].c_str(), "WAV") || !strcasecmp(args[1].c_str(), "PCM")
612 || !strcasecmp(args[1].c_str(), "MPC") || !strcasecmp(args[1].c_str(), "MP+"))
613 {
614 TmpTrack.AReader = AR_Open(TmpTrack.fp);
615 if(!TmpTrack.AReader)
616 {
617 throw(MDFN_Error(0, _("Unsupported audio track file format: %s\n"), args[0].c_str()));
618 }
619 }
620 else
621 {
622 throw(MDFN_Error(0, _("Unsupported track format: %s\n"), args[1].c_str()));
623 }
624 }
625 else if(cmdbuf == "TRACK")
626 {
627 if(active_track >= 0)
628 {
629 memcpy(&Tracks[active_track], &TmpTrack, sizeof(TmpTrack));
630 TmpTrack.FirstFileInstance = 0;
631 TmpTrack.pregap = 0;
632 TmpTrack.pregap_dv = 0;
633 TmpTrack.postgap = 0;
634 TmpTrack.index[0] = -1;
635 TmpTrack.index[1] = 0;
636 }
637 active_track = atoi(args[0].c_str());
638
639 if(active_track < FirstTrack)
640 FirstTrack = active_track;
641 if(active_track > LastTrack)
642 LastTrack = active_track;
643
644 int format_lookup;
645 for(format_lookup = 0; format_lookup < _DI_FORMAT_COUNT; format_lookup++)
646 {
647 if(!strcasecmp(args[1].c_str(), DI_CUE_Strings[format_lookup]))
648 {
649 TmpTrack.DIFormat = format_lookup;
650 break;
651 }
652 }
653
654 if(format_lookup == _DI_FORMAT_COUNT)
655 {
656 throw(MDFN_Error(0, _("Invalid track format: %s\n"), args[1].c_str()));
657 }
658
659 if(active_track < 0 || active_track > 99)
660 {
661 throw(MDFN_Error(0, _("Invalid track number: %d\n"), active_track));
662 }
663 }
664 else if(cmdbuf == "INDEX")
665 {
666 if(active_track >= 0)
667 {
668 unsigned int m,s,f;
669
670 if(sscanf(args[1].c_str(), "%u:%u:%u", &m, &s, &f) != 3)
671 {
672 throw MDFN_Error(0, _("Malformed m:s:f time in \"%s\" directive: %s"), cmdbuf.c_str(), args[0].c_str());
673 }
674
675 if(!strcasecmp(args[0].c_str(), "01") || !strcasecmp(args[0].c_str(), "1"))
676 TmpTrack.index[1] = (m * 60 + s) * 75 + f;
677 else if(!strcasecmp(args[0].c_str(), "00") || !strcasecmp(args[0].c_str(), "0"))
678 TmpTrack.index[0] = (m * 60 + s) * 75 + f;
679 }
680 }
681 else if(cmdbuf == "PREGAP")
682 {
683 if(active_track >= 0)
684 {
685 unsigned int m,s,f;
686
687 if(sscanf(args[0].c_str(), "%u:%u:%u", &m, &s, &f) != 3)
688 {
689 throw MDFN_Error(0, _("Malformed m:s:f time in \"%s\" directive: %s"), cmdbuf.c_str(), args[0].c_str());
690 }
691
692 TmpTrack.pregap = (m * 60 + s) * 75 + f;
693 }
694 }
695 else if(cmdbuf == "POSTGAP")
696 {
697 if(active_track >= 0)
698 {
699 unsigned int m,s,f;
700
701 if(sscanf(args[0].c_str(), "%u:%u:%u", &m, &s, &f) != 3)
702 {
703 throw MDFN_Error(0, _("Malformed m:s:f time in \"%s\" directive: %s"), cmdbuf.c_str(), args[0].c_str());
704 }
705
706 TmpTrack.postgap = (m * 60 + s) * 75 + f;
707 }
708 }
709 else if(cmdbuf == "REM")
710 {
711
712 }
713 else if(cmdbuf == "FLAGS")
714 {
715 TmpTrack.subq_control &= ~(SUBQ_CTRLF_PRE | SUBQ_CTRLF_DCP | SUBQ_CTRLF_4CH);
716 for(unsigned i = 0; i < argcount; i++)
717 {
718 if(args[i] == "DCP")
719 {
720 TmpTrack.subq_control |= SUBQ_CTRLF_DCP;
721 }
722 else if(args[i] == "4CH")
723 {
724 TmpTrack.subq_control |= SUBQ_CTRLF_4CH;
725 }
726 else if(args[i] == "PRE")
727 {
728 TmpTrack.subq_control |= SUBQ_CTRLF_PRE;
729 }
730 else if(args[i] == "SCMS")
731 {
732 // Not implemented, likely pointless. PROBABLY indicates that the copy bit of the subchannel Q control field is supposed to
733 // alternate between 1 and 0 at 9.375 Hz(four 1, four 0, four 1, four 0, etc.).
734 }
735 else
736 {
737 throw MDFN_Error(0, _("Unknown CUE sheet \"FLAGS\" directive flag \"%s\".\n"), args[i].c_str());
738 }
739 }
740 }
741 else if(cmdbuf == "CDTEXTFILE" || cmdbuf == "CATALOG" || cmdbuf == "ISRC" ||
742 cmdbuf == "TITLE" || cmdbuf == "PERFORMER" || cmdbuf == "SONGWRITER")
743 {
744 MDFN_printf(_("Unsupported CUE sheet directive: \"%s\".\n"), cmdbuf.c_str()); // FIXME, generic logger passed by pointer to constructor
745 }
746 else
747 {
748 throw MDFN_Error(0, _("Unknown CUE sheet directive \"%s\".\n"), cmdbuf.c_str());
749 }
750 } // end of CUE sheet handling
751 } // end of fgets() loop
752
753 if(active_track >= 0)
754 memcpy(&Tracks[active_track], &TmpTrack, sizeof(TmpTrack));
755
756 if(FirstTrack > LastTrack)
757 {
758 throw(MDFN_Error(0, _("No tracks found!\n")));
759 }
760
761 FirstTrack = FirstTrack;
762 NumTracks = 1 + LastTrack - FirstTrack;
763
764 int32 RunningLBA = 0;
765 int32 LastIndex = 0;
766 long FileOffset = 0;
767
768 for(int x = FirstTrack; x < (FirstTrack + NumTracks); x++)
769 {
770 if(Tracks[x].DIFormat == DI_FORMAT_AUDIO)
771 Tracks[x].subq_control &= ~SUBQ_CTRLF_DATA;
772 else
773 Tracks[x].subq_control |= SUBQ_CTRLF_DATA;
774
775 if(!IsTOC) // TOC-format disc_type calculation is handled differently.
776 {
777 switch(Tracks[x].DIFormat)
778 {
779 default: break;
780
781 case DI_FORMAT_MODE2:
782 case DI_FORMAT_MODE2_FORM1:
783 case DI_FORMAT_MODE2_FORM2:
784 case DI_FORMAT_MODE2_RAW:
785 disc_type = DISC_TYPE_CD_XA;
786 break;
787 }
788 }
789
790 if(IsTOC)
791 {
792 RunningLBA += Tracks[x].pregap;
793 Tracks[x].LBA = RunningLBA;
794 RunningLBA += Tracks[x].sectors;
795 RunningLBA += Tracks[x].postgap;
796 }
797 else // else handle CUE sheet...
798 {
799 if(Tracks[x].FirstFileInstance)
800 {
801 LastIndex = 0;
802 FileOffset = 0;
803 }
804
805 RunningLBA += Tracks[x].pregap;
806
807 Tracks[x].pregap_dv = 0;
808
809 if(Tracks[x].index[0] != -1)
810 Tracks[x].pregap_dv = Tracks[x].index[1] - Tracks[x].index[0];
811
812 FileOffset += Tracks[x].pregap_dv * DI_Size_Table[Tracks[x].DIFormat];
813
814 RunningLBA += Tracks[x].pregap_dv;
815
816 Tracks[x].LBA = RunningLBA;
817
818 // Make sure FileOffset this is set before the call to GetSectorCount()
819 Tracks[x].FileOffset = FileOffset;
820 Tracks[x].sectors = GetSectorCount(&Tracks[x]);
821
822 if((x + 1) >= (FirstTrack + NumTracks) || Tracks[x+1].FirstFileInstance)
823 {
824
825 }
826 else
827 {
828 // Fix the sector count if we have multiple tracks per one binary image file.
829 if(Tracks[x + 1].index[0] == -1)
830 Tracks[x].sectors = Tracks[x + 1].index[1] - Tracks[x].index[1];
831 else
832 Tracks[x].sectors = Tracks[x + 1].index[0] - Tracks[x].index[1]; //Tracks[x + 1].index - Tracks[x].index;
833 }
834
835 //printf("Poo: %d %d\n", x, Tracks[x].sectors);
836 RunningLBA += Tracks[x].sectors;
837 RunningLBA += Tracks[x].postgap;
838
839 //printf("%d, %ld %d %d %d %d\n", x, FileOffset, Tracks[x].index, Tracks[x].pregap, Tracks[x].sectors, Tracks[x].LBA);
840
841 FileOffset += Tracks[x].sectors * DI_Size_Table[Tracks[x].DIFormat];
842 } // end to cue sheet handling
843 } // end to track loop
844
845 total_sectors = RunningLBA;
846 }
847
848 void CDAccess_Image::Cleanup(void)
849 {
850 for(int32 track = 0; track < 100; track++)
851 {
852 CDRFILE_TRACK_INFO *this_track = &Tracks[track];
853
854 if(this_track->FirstFileInstance)
855 {
856 if(Tracks[track].AReader)
857 {
858 delete Tracks[track].AReader;
859 Tracks[track].AReader = NULL;
860 }
861
862 if(this_track->fp)
863 {
864 delete this_track->fp;
865 this_track->fp = NULL;
866 }
867 }
868 }
869 }
870
871 CDAccess_Image::CDAccess_Image(const char *path, bool image_memcache) : NumTracks(0), FirstTrack(0), LastTrack(0), total_sectors(0)
872 {
873 memset(Tracks, 0, sizeof(Tracks));
874
875 ImageOpen(path, image_memcache);
876 }
877
878 CDAccess_Image::~CDAccess_Image()
879 {
880 Cleanup();
881 }
882
883 void CDAccess_Image::Read_Raw_Sector(uint8 *buf, int32 lba)
884 {
885 bool TrackFound = FALSE;
886 uint8 SimuQ[0xC];
887
888 memset(buf + 2352, 0, 96);
889
890 MakeSubPQ(lba, buf + 2352);
891
892 subq_deinterleave(buf + 2352, SimuQ);
893
894 for(int32 track = FirstTrack; track < (FirstTrack + NumTracks); track++)
895 {
896 CDRFILE_TRACK_INFO *ct = &Tracks[track];
897
898 if(lba >= (ct->LBA - ct->pregap_dv - ct->pregap) && lba < (ct->LBA + ct->sectors + ct->postgap))
899 {
900 TrackFound = TRUE;
901
902 // Handle pregap and postgap reading
903 if(lba < (ct->LBA - ct->pregap_dv) || lba >= (ct->LBA + ct->sectors))
904 {
905 //printf("Pre/post-gap read, LBA=%d(LBA-track_start_LBA=%d)\n", lba, lba - ct->LBA);
906 memset(buf, 0, 2352); // Null sector data, per spec
907 }
908 else
909 {
910 if(ct->AReader)
911 {
912 int16 AudioBuf[588 * 2];
913 int frames_read = ct->AReader->Read((ct->FileOffset / 4) + (lba - ct->LBA) * 588, AudioBuf, 588);
914
915 ct->LastSamplePos += frames_read;
916
917 if(frames_read < 0 || frames_read > 588) // This shouldn't happen.
918 {
919 printf("Error: frames_read out of range: %d\n", frames_read);
920 frames_read = 0;
921 }
922
923 if(frames_read < 588)
924 memset((uint8 *)AudioBuf + frames_read * 2 * sizeof(int16), 0, (588 - frames_read) * 2 * sizeof(int16));
925
926 for(int i = 0; i < 588 * 2; i++)
927 MDFN_en16lsb(buf + i * 2, AudioBuf[i]);
928 }
929 else // Binary, woo.
930 {
931 long SeekPos = ct->FileOffset;
932 long LBARelPos = lba - ct->LBA;
933
934 SeekPos += LBARelPos * DI_Size_Table[ct->DIFormat];
935
936 if(ct->SubchannelMode)
937 SeekPos += 96 * (lba - ct->LBA);
938
939 ct->fp->seek(SeekPos, SEEK_SET);
940
941 switch(ct->DIFormat)
942 {
943 case DI_FORMAT_AUDIO:
944 ct->fp->read(buf, 2352);
945
946 if(ct->RawAudioMSBFirst)
947 Endian_A16_Swap(buf, 588 * 2);
948 break;
949
950 case DI_FORMAT_MODE1:
951 ct->fp->read(buf + 12 + 3 + 1, 2048);
952 encode_mode1_sector(lba + 150, buf);
953 break;
954
955 case DI_FORMAT_MODE1_RAW:
956 case DI_FORMAT_MODE2_RAW:
957 ct->fp->read(buf, 2352);
958 break;
959
960 case DI_FORMAT_MODE2:
961 ct->fp->read(buf + 16, 2336);
962 encode_mode2_sector(lba + 150, buf);
963 break;
964
965
966 // FIXME: M2F1, M2F2, does sub-header come before or after user data(standards say before, but I wonder
967 // about cdrdao...).
968 case DI_FORMAT_MODE2_FORM1:
969 ct->fp->read(buf + 24, 2048);
970 //encode_mode2_form1_sector(lba + 150, buf);
971 break;
972
973 case DI_FORMAT_MODE2_FORM2:
974 ct->fp->read(buf + 24, 2324);
975 //encode_mode2_form2_sector(lba + 150, buf);
976 break;
977
978 }
979
980 if(ct->SubchannelMode)
981 ct->fp->read(buf + 2352, 96);
982 }
983 } // end if audible part of audio track read.
984 break;
985 } // End if LBA is in range
986 } // end track search loop
987
988 if(!TrackFound)
989 {
990 throw(MDFN_Error(0, _("Could not find track for sector %u!"), lba));
991 }
992
993 #if 0
994 if(qbuf[0] & 0x40)
995 {
996 uint8 dummy_buf[2352 + 96];
997 bool any_mismatch = FALSE;
998
999 memcpy(dummy_buf + 16, buf + 16, 2048);
1000 memset(dummy_buf + 2352, 0, 96);
1001
1002 MakeSubPQ(lba, dummy_buf + 2352);
1003 encode_mode1_sector(lba + 150, dummy_buf);
1004
1005 for(int i = 0; i < 2352 + 96; i++)
1006 {
1007 if(dummy_buf[i] != buf[i])
1008 {
1009 printf("Mismatch at %d, %d: %02x:%02x; ", lba, i, dummy_buf[i], buf[i]);
1010 any_mismatch = TRUE;
1011 }
1012 }
1013 if(any_mismatch)
1014 puts("\n");
1015 }
1016 #endif
1017
1018 //subq_deinterleave(buf + 2352, qbuf);
1019 //printf("%02x\n", qbuf[0]);
1020 //printf("%02x\n", buf[12 + 3]);
1021 }
1022
1023 //
1024 // Note: this function makes use of the current contents(as in |=) in SubPWBuf.
1025 //
1026 void CDAccess_Image::MakeSubPQ(int32 lba, uint8 *SubPWBuf)
1027 {
1028 uint8 buf[0xC];
1029 int32 track;
1030 uint32 lba_relative;
1031 uint32 ma, sa, fa;
1032 uint32 m, s, f;
1033 uint8 pause_or = 0x00;
1034 bool track_found = FALSE;
1035
1036 for(track = FirstTrack; track < (FirstTrack + NumTracks); track++)
1037 {
1038 if(lba >= (Tracks[track].LBA - Tracks[track].pregap_dv - Tracks[track].pregap) && lba < (Tracks[track].LBA + Tracks[track].sectors + Tracks[track].postgap))
1039 {
1040 track_found = TRUE;
1041 break;
1042 }
1043 }
1044
1045 //printf("%d %d\n", Tracks[1].LBA, Tracks[1].sectors);
1046
1047 if(!track_found)
1048 {
1049 printf("MakeSubPQ error for sector %u!", lba);
1050 track = FirstTrack;
1051 }
1052
1053 lba_relative = abs((int32)lba - Tracks[track].LBA);
1054
1055 f = (lba_relative % 75);
1056 s = ((lba_relative / 75) % 60);
1057 m = (lba_relative / 75 / 60);
1058
1059 fa = (lba + 150) % 75;
1060 sa = ((lba + 150) / 75) % 60;
1061 ma = ((lba + 150) / 75 / 60);
1062
1063 uint8 adr = 0x1; // Q channel data encodes position
1064 uint8 control = Tracks[track].subq_control;
1065
1066 // Handle pause(D7 of interleaved subchannel byte) bit, should be set to 1 when in pregap or postgap.
1067 if((lba < Tracks[track].LBA) || (lba >= Tracks[track].LBA + Tracks[track].sectors))
1068 {
1069 //printf("pause_or = 0x80 --- %d\n", lba);
1070 pause_or = 0x80;
1071 }
1072
1073 // Handle pregap between audio->data track
1074 {
1075 int32 pg_offset = (int32)lba - Tracks[track].LBA;
1076
1077 // If we're more than 2 seconds(150 sectors) from the real "start" of the track/INDEX 01, and the track is a data track,
1078 // and the preceding track is an audio track, encode it as audio(by taking the SubQ control field from the preceding track).
1079 //
1080 // TODO: Look into how we're supposed to handle subq control field in the four combinations of track types(data/audio).
1081 //
1082 if(pg_offset < -150)
1083 {
1084 if((Tracks[track].subq_control & SUBQ_CTRLF_DATA) && (FirstTrack < track) && !(Tracks[track - 1].subq_control & SUBQ_CTRLF_DATA))
1085 {
1086 //printf("Pregap part 1 audio->data: lba=%d track_lba=%d\n", lba, Tracks[track].LBA);
1087 control = Tracks[track - 1].subq_control;
1088 }
1089 }
1090 }
1091
1092
1093 memset(buf, 0, 0xC);
1094 buf[0] = (adr << 0) | (control << 4);
1095 buf[1] = U8_to_BCD(track);
1096
1097 if(lba < Tracks[track].LBA) // Index is 00 in pregap
1098 buf[2] = U8_to_BCD(0x00);
1099 else
1100 buf[2] = U8_to_BCD(0x01);
1101
1102 // Track relative MSF address
1103 buf[3] = U8_to_BCD(m);
1104 buf[4] = U8_to_BCD(s);
1105 buf[5] = U8_to_BCD(f);
1106
1107 buf[6] = 0; // Zerroooo
1108
1109 // Absolute MSF address
1110 buf[7] = U8_to_BCD(ma);
1111 buf[8] = U8_to_BCD(sa);
1112 buf[9] = U8_to_BCD(fa);
1113
1114 subq_generate_checksum(buf);
1115
1116 for(int i = 0; i < 96; i++)
1117 SubPWBuf[i] |= (((buf[i >> 3] >> (7 - (i & 0x7))) & 1) ? 0x40 : 0x00) | pause_or;
1118 }
1119
1120 void CDAccess_Image::Read_TOC(TOC *toc)
1121 {
1122 toc->Clear();
1123
1124 toc->first_track = FirstTrack;
1125 toc->last_track = FirstTrack + NumTracks - 1;
1126 toc->disc_type = disc_type;
1127
1128 for(int i = toc->first_track; i <= toc->last_track; i++)
1129 {
1130 toc->tracks[i].lba = Tracks[i].LBA;
1131 toc->tracks[i].adr = ADR_CURPOS;
1132 toc->tracks[i].control = Tracks[i].subq_control;
1133 }
1134
1135 toc->tracks[100].lba = total_sectors;
1136 toc->tracks[100].adr = ADR_CURPOS;
1137 toc->tracks[100].control = toc->tracks[toc->last_track].control & 0x4;
1138
1139 // Convenience leadout track duplication.
1140 if(toc->last_track < 99)
1141 toc->tracks[toc->last_track + 1] = toc->tracks[100];
1142 }
1143
1144 bool CDAccess_Image::Is_Physical(void) throw()
1145 {
1146 return(false);
1147 }
1148
1149 void CDAccess_Image::Eject(bool eject_status)
1150 {
1151
1152 }
1153