Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
stenzek
GitHub Repository: stenzek/duckstation
Path: blob/master/src/util/cd_image_cue.cpp
4223 views
1
// SPDX-FileCopyrightText: 2019-2024 Connor McLaughlin <[email protected]>
2
// SPDX-License-Identifier: CC-BY-NC-ND-4.0
3
4
#include "cd_image.h"
5
#include "cue_parser.h"
6
#include "host.h"
7
#include "wav_reader_writer.h"
8
9
#include "common/align.h"
10
#include "common/assert.h"
11
#include "common/error.h"
12
#include "common/file_system.h"
13
#include "common/log.h"
14
#include "common/path.h"
15
#include "common/string_util.h"
16
17
#include "fmt/format.h"
18
#include "libchdr/cdrom.h" // EDC functions
19
20
#include <algorithm>
21
#include <cinttypes>
22
#include <map>
23
24
LOG_CHANNEL(CDImage);
25
26
namespace {
27
28
class TrackFileInterface
29
{
30
public:
31
explicit TrackFileInterface(std::string filename);
32
virtual ~TrackFileInterface();
33
34
ALWAYS_INLINE const std::string& GetFileName() const { return m_filename; }
35
36
static std::unique_ptr<TrackFileInterface> OpenBinaryFile(const std::string_view filename, const std::string& path,
37
Error* error);
38
39
virtual u64 GetSize() = 0;
40
virtual u64 GetDiskSize() = 0;
41
42
virtual bool Read(void* buffer, u64 offset, u32 size, Error* error) = 0;
43
44
protected:
45
std::string m_filename;
46
};
47
48
class BinaryTrackFileInterface final : public TrackFileInterface
49
{
50
public:
51
BinaryTrackFileInterface(std::string filename, FileSystem::ManagedCFilePtr file);
52
~BinaryTrackFileInterface() override;
53
54
u64 GetSize() override;
55
u64 GetDiskSize() override;
56
57
bool Read(void* buffer, u64 offset, u32 size, Error* error) override;
58
59
private:
60
FileSystem::ManagedCFilePtr m_file;
61
u64 m_file_position = 0;
62
};
63
64
class ECMTrackFileInterface final : public TrackFileInterface
65
{
66
public:
67
ECMTrackFileInterface(std::string filename, FileSystem::ManagedCFilePtr file);
68
~ECMTrackFileInterface() override;
69
70
static std::unique_ptr<TrackFileInterface> Create(std::string filename, FileSystem::ManagedCFilePtr file,
71
Error* error);
72
73
u64 GetSize() override;
74
u64 GetDiskSize() override;
75
76
bool Read(void* buffer, u64 offset, u32 size, Error* error) override;
77
78
private:
79
enum class SectorType : u32
80
{
81
Raw = 0x00,
82
Mode1 = 0x01,
83
Mode2Form1 = 0x02,
84
Mode2Form2 = 0x03,
85
Count,
86
};
87
88
static constexpr std::array<u32, static_cast<u32>(SectorType::Count)> s_sector_sizes = {
89
0x930, // raw
90
0x803, // mode1
91
0x804, // mode2form1
92
0x918, // mode2form2
93
};
94
95
static constexpr std::array<u32, static_cast<u32>(SectorType::Count)> s_chunk_sizes = {
96
0, // raw
97
2352, // mode1
98
2336, // mode2form1
99
2336, // mode2form2
100
};
101
102
struct SectorEntry
103
{
104
u32 file_offset;
105
u32 chunk_size;
106
SectorType type;
107
};
108
109
using DataMap = std::map<u32, SectorEntry>;
110
111
bool BuildSectorMap(Error* error);
112
bool ReadChunks(u32 disc_offset, u32 size);
113
114
FileSystem::ManagedCFilePtr m_file;
115
116
DataMap m_data_map;
117
std::vector<u8> m_chunk_buffer;
118
u32 m_chunk_start = 0;
119
u32 m_lba_count = 0;
120
};
121
122
class WaveTrackFileInterface final : public TrackFileInterface
123
{
124
public:
125
WaveTrackFileInterface(std::string filename, WAVReader reader);
126
~WaveTrackFileInterface() override;
127
128
u64 GetSize() override;
129
u64 GetDiskSize() override;
130
131
bool Read(void* buffer, u64 offset, u32 size, Error* error) override;
132
133
private:
134
WAVReader m_reader;
135
};
136
137
class CDImageCueSheet : public CDImage
138
{
139
public:
140
CDImageCueSheet();
141
~CDImageCueSheet() override;
142
143
bool OpenAndParseCueSheet(const char* path, Error* error);
144
bool OpenAndParseSingleFile(const char* path, Error* error);
145
146
s64 GetSizeOnDisk() const override;
147
148
protected:
149
bool ReadSectorFromIndex(void* buffer, const Index& index, LBA lba_in_index) override;
150
151
private:
152
std::vector<std::unique_ptr<TrackFileInterface>> m_files;
153
};
154
155
} // namespace
156
157
//////////////////////////////////////////////////////////////////////////
158
159
TrackFileInterface::TrackFileInterface(std::string filename) : m_filename(std::move(filename))
160
{
161
}
162
163
TrackFileInterface::~TrackFileInterface() = default;
164
165
BinaryTrackFileInterface::BinaryTrackFileInterface(std::string filename, FileSystem::ManagedCFilePtr file)
166
: TrackFileInterface(std::move(filename)), m_file(std::move(file))
167
{
168
}
169
170
BinaryTrackFileInterface::~BinaryTrackFileInterface() = default;
171
172
std::unique_ptr<TrackFileInterface> TrackFileInterface::OpenBinaryFile(const std::string_view filename,
173
const std::string& path, Error* error)
174
{
175
std::unique_ptr<TrackFileInterface> fi;
176
177
FileSystem::ManagedCFilePtr file =
178
FileSystem::OpenManagedSharedCFile(path.c_str(), "rb", FileSystem::FileShareMode::DenyWrite, error);
179
if (!file)
180
{
181
Error::AddPrefixFmt(error, "Failed to open '{}': ", FileSystem::GetDisplayNameFromPath(path));
182
return fi;
183
}
184
185
// Check for ECM format.
186
if (StringUtil::EndsWithNoCase(FileSystem::GetDisplayNameFromPath(path), ".ecm"))
187
fi = ECMTrackFileInterface::Create(std::string(filename), std::move(file), error);
188
else
189
fi = std::make_unique<BinaryTrackFileInterface>(std::string(filename), std::move(file));
190
191
return fi;
192
}
193
194
bool BinaryTrackFileInterface::Read(void* buffer, u64 offset, u32 size, Error* error)
195
{
196
if (m_file_position != offset)
197
{
198
if (!FileSystem::FSeek64(m_file.get(), static_cast<s64>(offset), SEEK_SET, error)) [[unlikely]]
199
return false;
200
201
m_file_position = offset;
202
}
203
204
if (std::fread(buffer, size, 1, m_file.get()) != 1) [[unlikely]]
205
{
206
Error::SetErrno(error, "fread() failed: ", errno);
207
208
// position is indeterminate now
209
m_file_position = std::numeric_limits<decltype(m_file_position)>::max();
210
return false;
211
}
212
213
m_file_position += size;
214
return true;
215
}
216
217
u64 BinaryTrackFileInterface::GetSize()
218
{
219
return static_cast<u64>(std::max<s64>(FileSystem::FSize64(m_file.get()), 0));
220
}
221
222
u64 BinaryTrackFileInterface::GetDiskSize()
223
{
224
return static_cast<u64>(std::max<s64>(FileSystem::FSize64(m_file.get()), 0));
225
}
226
227
//////////////////////////////////////////////////////////////////////////
228
229
ECMTrackFileInterface::ECMTrackFileInterface(std::string path, FileSystem::ManagedCFilePtr file)
230
: TrackFileInterface(std::move(path)), m_file(std::move(file))
231
{
232
}
233
234
ECMTrackFileInterface::~ECMTrackFileInterface()
235
{
236
}
237
238
std::unique_ptr<TrackFileInterface> ECMTrackFileInterface::Create(std::string filename,
239
FileSystem::ManagedCFilePtr file, Error* error)
240
{
241
std::unique_ptr<ECMTrackFileInterface> fi =
242
std::make_unique<ECMTrackFileInterface>(std::move(filename), std::move(file));
243
if (!fi->BuildSectorMap(error))
244
fi.reset();
245
246
return fi;
247
}
248
249
bool ECMTrackFileInterface::BuildSectorMap(Error* error)
250
{
251
const s64 file_size = FileSystem::FSize64(m_file.get(), error);
252
if (file_size <= 0)
253
return false;
254
255
char header[4];
256
if (std::fread(header, sizeof(header), 1, m_file.get()) != 1 || header[0] != 'E' || header[1] != 'C' ||
257
header[2] != 'M' || header[3] != 0)
258
{
259
ERROR_LOG("Failed to read/invalid header");
260
Error::SetStringView(error, "Failed to read/invalid header");
261
return false;
262
}
263
264
// build sector map
265
u32 file_offset = Truncate32(FileSystem::FTell64(m_file.get()));
266
u32 disc_offset = 0;
267
268
for (;;)
269
{
270
int bits = std::fgetc(m_file.get());
271
if (bits == EOF)
272
{
273
ERROR_LOG("Unexpected EOF after {} chunks", m_data_map.size());
274
Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size());
275
return false;
276
}
277
278
file_offset++;
279
const SectorType type = static_cast<SectorType>(static_cast<u32>(bits) & 0x03u);
280
u32 count = (static_cast<u32>(bits) >> 2) & 0x1F;
281
u32 shift = 5;
282
while (bits & 0x80)
283
{
284
bits = std::fgetc(m_file.get());
285
if (bits == EOF)
286
{
287
ERROR_LOG("Unexpected EOF after {} chunks", m_data_map.size());
288
Error::SetStringFmt(error, "Unexpected EOF after {} chunks", m_data_map.size());
289
return false;
290
}
291
292
count |= (static_cast<u32>(bits) & 0x7F) << shift;
293
shift += 7;
294
file_offset++;
295
}
296
297
if (count == 0xFFFFFFFFu)
298
break;
299
300
// for this sector
301
count++;
302
303
if (count >= 0x80000000u)
304
{
305
ERROR_LOG("Corrupted header after {} chunks", m_data_map.size());
306
Error::SetStringFmt(error, "Corrupted header after {} chunks", m_data_map.size());
307
return false;
308
}
309
310
if (type == SectorType::Raw)
311
{
312
while (count > 0)
313
{
314
const u32 size = std::min<u32>(count, 2352);
315
m_data_map.emplace(disc_offset, SectorEntry{file_offset, size, type});
316
disc_offset += size;
317
file_offset += size;
318
count -= size;
319
320
if (static_cast<s64>(file_offset) > file_size)
321
{
322
ERROR_LOG("Out of file bounds after {} chunks", m_data_map.size());
323
Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size());
324
}
325
}
326
}
327
else
328
{
329
const u32 size = s_sector_sizes[static_cast<u32>(type)];
330
const u32 chunk_size = s_chunk_sizes[static_cast<u32>(type)];
331
for (u32 i = 0; i < count; i++)
332
{
333
m_data_map.emplace(disc_offset, SectorEntry{file_offset, chunk_size, type});
334
disc_offset += chunk_size;
335
file_offset += size;
336
337
if (static_cast<s64>(file_offset) > file_size)
338
{
339
ERROR_LOG("Out of file bounds after {} chunks", m_data_map.size());
340
Error::SetStringFmt(error, "Out of file bounds after {} chunks", m_data_map.size());
341
}
342
}
343
}
344
345
if (FileSystem::FSeek64(m_file.get(), file_offset, SEEK_SET) != 0)
346
{
347
ERROR_LOG("Failed to seek to offset {} after {} chunks", file_offset, m_data_map.size());
348
Error::SetStringFmt(error, "Failed to seek to offset {} after {} chunks", file_offset, m_data_map.size());
349
return false;
350
}
351
}
352
353
m_lba_count = disc_offset / CDImage::RAW_SECTOR_SIZE;
354
if ((disc_offset % CDImage::RAW_SECTOR_SIZE) != 0)
355
WARNING_LOG("ECM image is misaligned with offset {}", disc_offset);
356
357
if (m_data_map.empty() || m_lba_count == 0)
358
{
359
ERROR_LOG("No data in image '{}'", m_filename);
360
Error::SetStringView(error, "No sectors found");
361
return false;
362
}
363
364
return true;
365
}
366
367
bool ECMTrackFileInterface::ReadChunks(u32 disc_offset, u32 size)
368
{
369
DataMap::iterator next =
370
m_data_map.lower_bound((disc_offset > CDImage::RAW_SECTOR_SIZE) ? (disc_offset - CDImage::RAW_SECTOR_SIZE) : 0);
371
DataMap::iterator current = m_data_map.begin();
372
while (next != m_data_map.end() && next->first <= disc_offset)
373
current = next++;
374
375
// extra bytes if we need to buffer some at the start
376
m_chunk_start = current->first;
377
m_chunk_buffer.clear();
378
if (m_chunk_start < disc_offset)
379
size += (disc_offset - current->first);
380
381
u32 total_bytes_read = 0;
382
while (total_bytes_read < size)
383
{
384
if (current == m_data_map.end() || FileSystem::FSeek64(m_file.get(), current->second.file_offset, SEEK_SET) != 0)
385
return false;
386
387
const u32 chunk_size = current->second.chunk_size;
388
const u32 chunk_start = static_cast<u32>(m_chunk_buffer.size());
389
m_chunk_buffer.resize(chunk_start + chunk_size);
390
391
if (current->second.type == SectorType::Raw)
392
{
393
if (std::fread(&m_chunk_buffer[chunk_start], chunk_size, 1, m_file.get()) != 1)
394
return false;
395
396
total_bytes_read += chunk_size;
397
}
398
else
399
{
400
// u8* sector = &m_chunk_buffer[chunk_start];
401
u8 sector[CDImage::RAW_SECTOR_SIZE];
402
403
// TODO: needed?
404
std::memset(sector, 0, CDImage::RAW_SECTOR_SIZE);
405
std::memset(sector + 1, 0xFF, 10);
406
407
u32 skip;
408
switch (current->second.type)
409
{
410
case SectorType::Mode1:
411
{
412
sector[0x0F] = 0x01;
413
if (std::fread(sector + 0x00C, 0x003, 1, m_file.get()) != 1 ||
414
std::fread(sector + 0x010, 0x800, 1, m_file.get()) != 1)
415
{
416
return false;
417
}
418
419
edc_set(&sector[2064], edc_compute(sector, 2064));
420
ecc_generate(sector);
421
skip = 0;
422
}
423
break;
424
425
case SectorType::Mode2Form1:
426
{
427
sector[0x0F] = 0x02;
428
if (std::fread(sector + 0x014, 0x804, 1, m_file.get()) != 1)
429
return false;
430
431
sector[0x10] = sector[0x14];
432
sector[0x11] = sector[0x15];
433
sector[0x12] = sector[0x16];
434
sector[0x13] = sector[0x17];
435
436
edc_set(&sector[2072], edc_compute(&sector[16], 2056));
437
ecc_generate(sector);
438
skip = 0x10;
439
}
440
break;
441
442
case SectorType::Mode2Form2:
443
{
444
sector[0x0F] = 0x02;
445
if (std::fread(sector + 0x014, 0x918, 1, m_file.get()) != 1)
446
return false;
447
448
sector[0x10] = sector[0x14];
449
sector[0x11] = sector[0x15];
450
sector[0x12] = sector[0x16];
451
sector[0x13] = sector[0x17];
452
453
edc_set(&sector[2348], edc_compute(&sector[16], 2332));
454
skip = 0x10;
455
}
456
break;
457
458
default:
459
UnreachableCode();
460
return false;
461
}
462
463
std::memcpy(&m_chunk_buffer[chunk_start], sector + skip, chunk_size);
464
total_bytes_read += chunk_size;
465
}
466
467
++current;
468
}
469
470
return true;
471
}
472
473
u64 ECMTrackFileInterface::GetSize()
474
{
475
return static_cast<u64>(m_lba_count) * static_cast<u64>(CDImage::RAW_SECTOR_SIZE);
476
}
477
478
u64 ECMTrackFileInterface::GetDiskSize()
479
{
480
return static_cast<u64>(std::max<s64>(FileSystem::FSize64(m_file.get()), 0));
481
}
482
483
bool ECMTrackFileInterface::Read(void* buffer, u64 offset, u32 size, Error* error)
484
{
485
const u64 file_end = offset + size;
486
if (offset < m_chunk_start || file_end > (m_chunk_start + m_chunk_buffer.size()))
487
{
488
if (!ReadChunks(Truncate32(offset), CDImage::RAW_SECTOR_SIZE))
489
return false;
490
}
491
492
DebugAssert(offset >= m_chunk_start && file_end <= (m_chunk_start + m_chunk_buffer.size()));
493
494
const size_t chunk_offset = static_cast<size_t>(offset - m_chunk_start);
495
std::memcpy(buffer, &m_chunk_buffer[chunk_offset], CDImage::RAW_SECTOR_SIZE);
496
return true;
497
}
498
499
//////////////////////////////////////////////////////////////////////////
500
501
WaveTrackFileInterface::WaveTrackFileInterface(std::string filename, WAVReader reader)
502
: TrackFileInterface(std::move(filename)), m_reader(std::move(reader))
503
{
504
}
505
506
WaveTrackFileInterface::~WaveTrackFileInterface() = default;
507
508
bool WaveTrackFileInterface::Read(void* buffer, u64 offset, u32 size, Error* error)
509
{
510
// Should always be a multiple of 4 (sizeof frame).
511
if ((offset & 3) != 0 || (size & 3) != 0) [[unlikely]]
512
return false;
513
514
// We shouldn't have any extra CD frames.
515
const u32 frame_number = Truncate32(offset / 4);
516
if (frame_number >= m_reader.GetNumFrames()) [[unlikely]]
517
{
518
Error::SetStringView(error, "Attempted read past end of WAV file");
519
return false;
520
}
521
522
// Do we need to pad the read?
523
const u32 num_frames = size / 4;
524
const u32 num_frames_to_read = std::min(num_frames, m_reader.GetNumFrames() - frame_number);
525
if (num_frames_to_read > 0)
526
{
527
if (!m_reader.SeekToFrame(frame_number, error) || !m_reader.ReadFrames(buffer, num_frames_to_read, error))
528
return false;
529
}
530
531
// Padding.
532
const u32 padding = num_frames - num_frames_to_read;
533
if (padding > 0)
534
std::memset(static_cast<u8*>(buffer) + (num_frames_to_read * 4), 0, 4 * padding);
535
536
return true;
537
}
538
539
u64 WaveTrackFileInterface::GetSize()
540
{
541
return Common::AlignUp(static_cast<u64>(m_reader.GetNumFrames()) * 4, 2352);
542
}
543
544
u64 WaveTrackFileInterface::GetDiskSize()
545
{
546
return m_reader.GetFileSize();
547
}
548
549
CDImageCueSheet::CDImageCueSheet() = default;
550
551
CDImageCueSheet::~CDImageCueSheet() = default;
552
553
bool CDImageCueSheet::OpenAndParseCueSheet(const char* path, Error* error)
554
{
555
std::FILE* fp = FileSystem::OpenSharedCFile(path, "rb", FileSystem::FileShareMode::DenyWrite, error);
556
if (!fp)
557
{
558
Error::AddPrefixFmt(error, "Failed to open cuesheet '{}': ", Path::GetFileName(path));
559
return false;
560
}
561
562
CueParser::File parser;
563
if (!parser.Parse(fp, error))
564
{
565
std::fclose(fp);
566
return false;
567
}
568
569
std::fclose(fp);
570
571
m_filename = path;
572
573
u32 disc_lba = 0;
574
575
// for each track..
576
for (u32 track_num = 1; track_num <= CueParser::MAX_TRACK_NUMBER; track_num++)
577
{
578
const CueParser::Track* track = parser.GetTrack(track_num);
579
if (!track)
580
break;
581
582
const std::string& track_filename = track->file;
583
LBA track_start = track->start.ToLBA();
584
585
u32 track_file_index = 0;
586
for (; track_file_index < m_files.size(); track_file_index++)
587
{
588
if (m_files[track_file_index]->GetFileName() == track_filename)
589
break;
590
}
591
if (track_file_index == m_files.size())
592
{
593
std::string track_full_path =
594
!Path::IsAbsolute(track_filename) ? Path::BuildRelativePath(m_filename, track_filename) : track_filename;
595
Error track_error;
596
std::unique_ptr<TrackFileInterface> track_file;
597
598
if (track->file_format == CueParser::FileFormat::Binary)
599
{
600
track_file = TrackFileInterface::OpenBinaryFile(track_filename, track_full_path, error);
601
if (!track_file && track_file_index == 0)
602
{
603
// many users have bad cuesheets, or they're renamed the files without updating the cuesheet.
604
// so, try searching for a bin with the same name as the cue, but only for the first referenced file.
605
std::string alternative_filename = Path::ReplaceExtension(path, "bin");
606
track_file = TrackFileInterface::OpenBinaryFile(track_filename, alternative_filename, error);
607
if (track_file)
608
{
609
WARNING_LOG("Your cue sheet references an invalid file '{}', but this was found at '{}' instead.",
610
track_filename, alternative_filename);
611
}
612
}
613
}
614
else if (track->file_format == CueParser::FileFormat::Wave)
615
{
616
// Since all the frames are packed tightly in the wave file, we only need to get the start offset.
617
WAVReader reader;
618
if (reader.Open(track_full_path.c_str(), error))
619
{
620
if (reader.GetNumChannels() != AUDIO_CHANNELS || reader.GetSampleRate() != AUDIO_SAMPLE_RATE)
621
{
622
Error::SetStringFmt(error,
623
TRANSLATE_FS("CDImage", "{0} uses a sample rate of {1}hz and has {2} channels.\n"
624
"WAV files must be stereo and use a sample rate of 44100hz."),
625
Path::GetFileName(track_filename), reader.GetSampleRate(), reader.GetNumChannels());
626
return false;
627
}
628
629
track_file = std::make_unique<WaveTrackFileInterface>(track_filename, std::move(reader));
630
}
631
else
632
{
633
Error::AddPrefixFmt(error, "Failed to open '{}': ", track_filename);
634
}
635
}
636
637
if (!track_file)
638
return false;
639
640
m_files.push_back(std::move(track_file));
641
}
642
643
// data type determines the sector size
644
const TrackMode mode = track->mode;
645
const u32 track_sector_size = GetBytesPerSector(mode);
646
647
// precompute subchannel q flags for the whole track
648
SubChannelQ::Control control{};
649
control.data = mode != TrackMode::Audio;
650
control.audio_preemphasis = track->HasFlag(CueParser::TrackFlag::PreEmphasis);
651
control.digital_copy_permitted = track->HasFlag(CueParser::TrackFlag::CopyPermitted);
652
control.four_channel_audio = track->HasFlag(CueParser::TrackFlag::FourChannelAudio);
653
654
// determine the length from the file
655
LBA track_length;
656
if (!track->length.has_value())
657
{
658
u64 file_size = m_files[track_file_index]->GetSize();
659
660
file_size /= track_sector_size;
661
if (track_start >= file_size)
662
{
663
ERROR_LOG("Failed to open track {} in '{}': track start is out of range ({} vs {})", track_num, path,
664
track_start, file_size);
665
Error::SetStringFmt(error, "Failed to open track {} in '{}': track start is out of range ({} vs {}))",
666
track_num, Path::GetFileName(path), track_start, file_size);
667
return false;
668
}
669
670
track_length = static_cast<LBA>(file_size - track_start);
671
}
672
else
673
{
674
track_length = track->length.value().ToLBA();
675
}
676
677
const Position* index0 = track->GetIndex(0);
678
LBA pregap_frames;
679
if (index0)
680
{
681
// index 1 is always present, so this is safe
682
pregap_frames = track->GetIndex(1)->ToLBA() - index0->ToLBA();
683
684
// Pregap/index 0 is in the file, easy.
685
Index pregap_index = {};
686
pregap_index.start_lba_on_disc = disc_lba;
687
pregap_index.start_lba_in_track = static_cast<LBA>(-static_cast<s32>(pregap_frames));
688
pregap_index.length = pregap_frames;
689
pregap_index.track_number = track_num;
690
pregap_index.index_number = 0;
691
pregap_index.mode = mode;
692
pregap_index.submode = CDImage::SubchannelMode::None;
693
pregap_index.control.bits = control.bits;
694
pregap_index.is_pregap = true;
695
pregap_index.file_index = track_file_index;
696
pregap_index.file_offset = static_cast<u64>(static_cast<s64>(track_start - pregap_frames)) * track_sector_size;
697
pregap_index.file_sector_size = track_sector_size;
698
699
m_indices.push_back(pregap_index);
700
701
disc_lba += pregap_index.length;
702
}
703
else
704
{
705
// Two seconds pregap for track 1 is assumed if not specified.
706
// Some people have broken (older) dumps where a two second pregap was implicit but not specified in the
707
// cuesheet. The problem is we can't tell between a missing implicit two second pregap and a zero second pregap.
708
// Most of these seem to be a single bin file for all tracks. So if this is the case, we add the two seconds in
709
// if it's not specified. If this is an audio CD (likely when track 1 is not data), we don't add these pregaps,
710
// and rely on the cuesheet. If we did add them, it causes issues in some games (e.g. Dancing Stage featuring
711
// DREAMS COME TRUE).
712
const bool is_multi_track_bin = (track_num > 1 && track_file_index == m_indices[0].file_index);
713
const bool likely_audio_cd = (parser.GetTrack(1)->mode == TrackMode::Audio);
714
715
pregap_frames = track->zero_pregap.has_value() ? track->zero_pregap->ToLBA() : 0;
716
if ((track_num == 1 || is_multi_track_bin) && !track->zero_pregap.has_value() &&
717
(track_num == 1 || !likely_audio_cd))
718
{
719
pregap_frames = 2 * FRAMES_PER_SECOND;
720
}
721
722
// create the index for the pregap
723
if (pregap_frames > 0)
724
{
725
Index pregap_index = {};
726
pregap_index.start_lba_on_disc = disc_lba;
727
pregap_index.start_lba_in_track = static_cast<LBA>(-static_cast<s32>(pregap_frames));
728
pregap_index.length = pregap_frames;
729
pregap_index.track_number = track_num;
730
pregap_index.index_number = 0;
731
pregap_index.mode = mode;
732
pregap_index.submode = CDImage::SubchannelMode::None;
733
pregap_index.control.bits = control.bits;
734
pregap_index.is_pregap = true;
735
m_indices.push_back(pregap_index);
736
737
disc_lba += pregap_index.length;
738
}
739
}
740
741
// add the track itself
742
m_tracks.push_back(Track{track_num, disc_lba, static_cast<u32>(m_indices.size()), track_length + pregap_frames,
743
mode, SubchannelMode::None, control});
744
745
// how many indices in this track?
746
Index last_index;
747
last_index.start_lba_on_disc = disc_lba;
748
last_index.start_lba_in_track = 0;
749
last_index.track_number = track_num;
750
last_index.index_number = 1;
751
last_index.file_index = track_file_index;
752
last_index.file_sector_size = track_sector_size;
753
last_index.file_offset = static_cast<u64>(track_start) * track_sector_size;
754
last_index.mode = mode;
755
last_index.submode = CDImage::SubchannelMode::None;
756
last_index.control.bits = control.bits;
757
last_index.is_pregap = false;
758
759
u32 last_index_offset = track_start;
760
for (u32 index_num = 1;; index_num++)
761
{
762
const Position* pos = track->GetIndex(index_num);
763
if (!pos)
764
break;
765
766
const u32 index_offset = pos->ToLBA();
767
768
// add an index between the track indices
769
if (index_offset > last_index_offset)
770
{
771
last_index.length = index_offset - last_index_offset;
772
m_indices.push_back(last_index);
773
774
disc_lba += last_index.length;
775
last_index.start_lba_in_track += last_index.length;
776
last_index.start_lba_on_disc = disc_lba;
777
last_index.length = 0;
778
}
779
780
last_index.file_offset = index_offset * last_index.file_sector_size;
781
last_index.index_number = static_cast<u32>(index_num);
782
last_index_offset = index_offset;
783
}
784
785
// and the last index is added here
786
const u32 track_end_index = track_start + track_length;
787
DebugAssert(track_end_index >= last_index_offset);
788
if (track_end_index > last_index_offset)
789
{
790
last_index.length = track_end_index - last_index_offset;
791
m_indices.push_back(last_index);
792
793
disc_lba += last_index.length;
794
}
795
}
796
797
if (m_tracks.empty())
798
{
799
ERROR_LOG("File '{}' contains no tracks", path);
800
Error::SetStringFmt(error, "File '{}' contains no tracks", Path::GetFileName(path));
801
return false;
802
}
803
804
m_lba_count = disc_lba;
805
AddLeadOutIndex();
806
807
return Seek(1, Position{0, 0, 0});
808
}
809
810
bool CDImageCueSheet::OpenAndParseSingleFile(const char* path, Error* error)
811
{
812
m_filename = path;
813
814
std::unique_ptr<TrackFileInterface> fi = TrackFileInterface::OpenBinaryFile(Path::GetFileName(path), path, error);
815
if (!fi)
816
return false;
817
818
const u32 track_sector_size = RAW_SECTOR_SIZE;
819
m_lba_count = Truncate32(fi->GetSize() / track_sector_size);
820
m_files.push_back(std::move(fi));
821
822
SubChannelQ::Control control = {};
823
TrackMode mode = TrackMode::Mode2Raw;
824
control.data = mode != TrackMode::Audio;
825
826
// Two seconds default pregap.
827
const u32 pregap_frames = 2 * FRAMES_PER_SECOND;
828
Index pregap_index = {};
829
pregap_index.file_sector_size = track_sector_size;
830
pregap_index.start_lba_on_disc = 0;
831
pregap_index.start_lba_in_track = static_cast<LBA>(-static_cast<s32>(pregap_frames));
832
pregap_index.length = pregap_frames;
833
pregap_index.track_number = 1;
834
pregap_index.index_number = 0;
835
pregap_index.mode = mode;
836
pregap_index.submode = CDImage::SubchannelMode::None;
837
pregap_index.control.bits = control.bits;
838
pregap_index.is_pregap = true;
839
m_indices.push_back(pregap_index);
840
841
// Data index.
842
Index data_index = {};
843
data_index.file_index = 0;
844
data_index.file_offset = 0;
845
data_index.file_sector_size = track_sector_size;
846
data_index.start_lba_on_disc = pregap_index.length;
847
data_index.track_number = 1;
848
data_index.index_number = 1;
849
data_index.start_lba_in_track = 0;
850
data_index.length = m_lba_count;
851
data_index.mode = mode;
852
data_index.submode = CDImage::SubchannelMode::None;
853
data_index.control.bits = control.bits;
854
m_indices.push_back(data_index);
855
856
// Assume a single track.
857
m_tracks.push_back(Track{static_cast<u32>(1), data_index.start_lba_on_disc, static_cast<u32>(0),
858
m_lba_count + pregap_frames, mode, SubchannelMode::None, control});
859
860
AddLeadOutIndex();
861
862
return Seek(1, Position{0, 0, 0});
863
}
864
865
bool CDImageCueSheet::ReadSectorFromIndex(void* buffer, const Index& index, LBA lba_in_index)
866
{
867
DebugAssert(index.file_index < m_files.size());
868
869
TrackFileInterface* tf = m_files[index.file_index].get();
870
const u64 file_position = index.file_offset + (static_cast<u64>(lba_in_index) * index.file_sector_size);
871
Error error;
872
if (!tf->Read(buffer, file_position, index.file_sector_size, &error)) [[unlikely]]
873
{
874
ERROR_LOG("Failed to read LBA {}: {}", lba_in_index, error.GetDescription());
875
return false;
876
}
877
878
return true;
879
}
880
881
s64 CDImageCueSheet::GetSizeOnDisk() const
882
{
883
// Doesn't include the cue.. but they're tiny anyway, whatever.
884
u64 size = 0;
885
for (const std::unique_ptr<TrackFileInterface>& tf : m_files)
886
size += tf->GetDiskSize();
887
return size;
888
}
889
890
std::unique_ptr<CDImage> CDImage::OpenCueSheetImage(const char* path, Error* error)
891
{
892
std::unique_ptr<CDImageCueSheet> image = std::make_unique<CDImageCueSheet>();
893
if (!image->OpenAndParseCueSheet(path, error))
894
image.reset();
895
896
return image;
897
}
898
899
std::unique_ptr<CDImage> CDImage::OpenBinImage(const char* path, Error* error)
900
{
901
std::unique_ptr<CDImageCueSheet> image = std::make_unique<CDImageCueSheet>();
902
if (!image->OpenAndParseSingleFile(path, error))
903
image.reset();
904
905
return image;
906
}
907
908