Repository navigation
Expand file tree
/
Copy pathmusic_stream.cpp
More file actions
701 lines (604 loc) · 21.3 KB
/
Copy pathmusic_stream.cpp
File metadata and controls
701 lines (604 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/* ================================================================================================
* File: music_stream.cpp
* Brief: Streamed music, SPU2 ADPCM or 16-bit PCM WAV. See music_stream.h.
*
* The read buffers cycle Empty -> Queued -> Ready -> Empty, always in index order: a
* released buffer is asked for the next range of the payload at once, as a loader request
* at Priority::Stream, and the decode side polls its ticket when it comes round to it. The
* loader serves Stream requests oldest first, so the two land in order. Everything here runs
* on the main thread; the loader only fills the buffer a ticket names (async_io.h's rules).
*
* Both formats stream the same way - a payload read in whole units, chunk groups or
* frames - and differ only in how a buffer turns into frames. ADPCM decoding walks the
* chunk interleave directly: block k of a buffer lives in chunk group k / blocksPerChunk,
* the right channel's copy of it one chunk further on. PCM is already frames.
*
* This source code is released under the GNU GPL v2 license.
* ================================================================================================ */
#include "ps2/audio/music_stream.h"
#include "ps2/common.h"
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
namespace ps2::audio {
namespace {
using ps2::heap::MemTag;
constexpr int kBlockBytes = spu_adpcm::kBlockBytes;
// ADPCM reads: one loader chunk, eight chunk groups of a stereo file (32 KB), ~1.3 s at
// 22050Hz. The 2 KB header puts every group 2 KB off a 4 KB boundary of the file, so a stereo
// request spans one 32 KB boundary and the loader reads it in two: two reads per 1.3 s, where
// 8 KB requests made five (one in four of them crossing a boundary).
constexpr int kAdpcmReadBytes = static_cast<int>(aio::kChunkBytes);
// PCM reads aim at ~3/8 s each within these, whole 4 KB pages. The cap is a 44.1kHz stereo
// CD rip: two 64 KB buffers, ~740 ms.
constexpr int kPcmMinReadBytes = 8 * 1024;
constexpr int kPcmMaxReadBytes = 64 * 1024;
// RIFF chunks walked looking for "data" before calling the file malformed.
constexpr int kMaxWavChunks = 32;
u32 LoadLe16(const u8 * const p)
{
return static_cast<u32>(p[0]) | (static_cast<u32>(p[1]) << 8);
}
u32 LoadLe32(const u8 * const p)
{
return LoadLe16(p) | (LoadLe16(p + 2) << 16);
}
bool HasId(const u8 * const p, const char * const id)
{
return std::memcmp(p, id, 4) == 0;
}
int RoundUp(const int value, const int multiple)
{
return ((value + multiple - 1) / multiple) * multiple;
}
} // namespace
// ------------------------------------------------------------------------------------------------
// Requests
// ------------------------------------------------------------------------------------------------
void MusicStream::RequestNext(const int bufferIndex)
{
if (m_nextOffset >= m_payloadBytes)
{
// End of the payload: wrap for another pass, or leave the buffer Empty - the decode
// side reaches the end of the music before it would ever look at it.
if (m_requestLoopsLeft == 0)
{
return;
}
if (m_requestLoopsLeft > 0)
{
--m_requestLoopsLeft;
}
m_nextOffset = 0;
}
Buffer & buffer = m_buffers[bufferIndex];
PS2_Assert(bufferIndex == m_requestIndex);
PS2_Assert(buffer.state == BufferState::Empty);
const u32 remaining = m_payloadBytes - m_nextOffset;
buffer.payloadOffset = m_nextOffset;
buffer.requestBytes = (remaining < static_cast<u32>(m_readBytes)) ? static_cast<int>(remaining) : m_readBytes;
buffer.resultBytes = 0;
m_nextOffset += static_cast<u32>(buffer.requestBytes);
m_requestIndex = (m_requestIndex + 1) % kNumBuffers;
// The buffer is a whole number of cache lines (AllocateBuffers' stride), so the rounded
// size the loader may write is all its own.
aio::Request request;
request.kind = aio::Kind::Read;
request.prio = aio::Priority::Stream;
request.fd = m_fd;
request.offset = m_payloadStart + buffer.payloadOffset;
request.bytes = static_cast<u32>(buffer.requestBytes);
request.dest = buffer.data;
request.destBytes = aio::RoundUp64(request.bytes);
request.sequential = !m_fdMoved; // the reads follow one another, but for a wrap
buffer.ticket = aio::Submit(request);
if (buffer.ticket.IsValid())
{
buffer.state = BufferState::Queued;
m_fdMoved = false;
}
else
{
buffer.state = BufferState::Deferred;
}
}
bool MusicStream::Collect(Buffer & buffer, const bool wait)
{
if (buffer.state == BufferState::Queued)
{
if (wait)
{
aio::Wait(buffer.ticket);
}
const aio::State state = aio::Poll(buffer.ticket);
if (state == aio::State::Queued || state == aio::State::Running)
{
return false;
}
// Done: the bytes delivered. Failed: a negative code, reported by AcquireBuffer.
buffer.resultBytes = (state == aio::State::Free) ? -1 : aio::Result(buffer.ticket);
aio::Release(buffer.ticket);
buffer.ticket = {};
buffer.state = BufferState::Ready;
}
else if (buffer.state == BufferState::Deferred)
{
ReadNow(buffer);
}
return buffer.state == BufferState::Ready;
}
void MusicStream::ReadNow(Buffer & buffer)
{
// The loader may have the other buffer's read in flight on this descriptor: let it land
// first, so the two never move the file position under each other.
for (Buffer & other : m_buffers)
{
if (&other != &buffer && other.state == BufferState::Queued)
{
Collect(other, true);
}
}
const u32 filePos = m_payloadStart + buffer.payloadOffset;
int result = -1;
if (lseek(m_fd, static_cast<off_t>(filePos), SEEK_SET) == static_cast<off_t>(filePos))
{
result = static_cast<int>(read(m_fd, buffer.data, static_cast<size_t>(buffer.requestBytes)));
}
buffer.resultBytes = result;
buffer.state = BufferState::Ready;
m_fdMoved = true;
}
void MusicStream::CancelReads()
{
// Cancel drops a request the loader hasn't started, waits out the chunk of one it has
// (into these buffers, on this descriptor), and releases one that has landed.
for (Buffer & buffer : m_buffers)
{
if (buffer.state == BufferState::Queued)
{
aio::Cancel(buffer.ticket);
buffer.ticket = {};
}
buffer.state = BufferState::Empty;
}
}
// ------------------------------------------------------------------------------------------------
// Headers (before any read is asked for)
// ------------------------------------------------------------------------------------------------
int MusicStream::ReadScratch(const int fd, const u32 filePos, const int sizeBytes)
{
PS2_Assert(sizeBytes <= kScratchBytes);
if (lseek(fd, static_cast<off_t>(filePos), SEEK_SET) != static_cast<off_t>(filePos))
{
return -1;
}
return static_cast<int>(read(fd, m_scratch, static_cast<size_t>(sizeBytes)));
}
const char * MusicStream::ParseAdpcmHeader()
{
music_file::Header header;
std::memcpy(&header, m_scratch, sizeof(header));
if (const char * const error = music_file::Validate(header))
{
return error;
}
if (header.chunkBytes > static_cast<u32>(kPcmMaxReadBytes) / header.channels)
{
return "chunk size too large";
}
m_format = Format::Adpcm;
m_channels = header.channels;
m_sampleRate = static_cast<int>(header.sampleRate);
m_frameCount = static_cast<int>(header.frameCount);
m_payloadStart = static_cast<u32>(music_file::kHeaderBytes);
m_payloadBytes = static_cast<u32>(header.dataBytes);
m_chunkBytes = static_cast<int>(header.chunkBytes);
m_groupBytes = m_chunkBytes * m_channels;
m_blocksPerChunk = m_chunkBytes / kBlockBytes;
m_frameBytes = 0;
// Whole chunk groups, so a buffer never splits one: as many as fit in the 8 KB target.
const int groups = (kAdpcmReadBytes / m_groupBytes > 0) ? (kAdpcmReadBytes / m_groupBytes) : 1;
m_readBytes = groups * m_groupBytes;
return nullptr;
}
const char * MusicStream::ParseWavHeader(const int fd)
{
// Walk the RIFF chunks for "fmt " and "data", skipping whatever else a ripper wrote
// (LIST, fact, cue, ...). One read per chunk, header plus the start of its body.
u32 formatTag = 0, channels = 0, sampleRate = 0, frameBytes = 0, bits = 0;
u32 dataStart = 0, dataBytes = 0;
bool haveFormat = false, haveData = false;
u32 pos = 12; // Past "RIFF", the file size and "WAVE".
for (int i = 0; i < kMaxWavChunks && !haveData; ++i)
{
const int got = ReadScratch(fd, pos, kScratchBytes);
if (got < 8)
{
break; // Out of chunks.
}
const u32 chunkBytes = LoadLe32(m_scratch + 4);
if (HasId(m_scratch, "fmt "))
{
if (chunkBytes < 16 || got < 8 + 16)
{
return "bad fmt chunk";
}
const u8 * const fmt = m_scratch + 8;
formatTag = LoadLe16(fmt);
channels = LoadLe16(fmt + 2);
sampleRate = LoadLe32(fmt + 4);
frameBytes = LoadLe16(fmt + 12);
bits = LoadLe16(fmt + 14);
// WAVE_FORMAT_EXTENSIBLE: the real format tag opens the subformat GUID.
if (formatTag == 0xFFFEu && chunkBytes >= 26 && got >= 8 + 26)
{
formatTag = LoadLe16(fmt + 24);
}
haveFormat = true;
}
else if (HasId(m_scratch, "data"))
{
dataStart = pos + 8;
dataBytes = chunkBytes;
haveData = true;
break;
}
// Next chunk, word aligned. A size that runs past the end of the file just makes
// the next read come up short.
const u32 next = pos + 8 + chunkBytes + (chunkBytes & 1u);
if (next <= pos)
{
break;
}
pos = next;
}
if (!haveData)
{
return "no data chunk";
}
if (!haveFormat)
{
return "no fmt chunk before the data";
}
if (formatTag != 1 || bits != 16)
{
return "not 16-bit PCM";
}
if (channels < 1 || channels > static_cast<u32>(music_file::kMaxChannels))
{
return "not mono or stereo";
}
if (frameBytes != channels * 2)
{
return "bad block alignment";
}
if (sampleRate < 4000 || sampleRate > 48000)
{
return "unsupported sample rate";
}
// Trust the file's size over the data chunk's, which a ripper that was cut short (or
// that streamed it) can leave wrong.
const off_t fileEnd = lseek(fd, 0, SEEK_END);
if (fileEnd < static_cast<off_t>(dataStart))
{
return "truncated";
}
const u32 available = static_cast<u32>(fileEnd) - dataStart;
if (dataBytes > available)
{
dataBytes = available;
}
dataBytes -= dataBytes % frameBytes;
if (dataBytes == 0)
{
return "no samples";
}
m_format = Format::Pcm16;
m_channels = static_cast<int>(channels);
m_sampleRate = static_cast<int>(sampleRate);
m_frameBytes = static_cast<int>(frameBytes);
m_frameCount = static_cast<int>(dataBytes / frameBytes);
m_payloadStart = dataStart;
m_payloadBytes = dataBytes;
m_chunkBytes = 0;
m_groupBytes = 0;
m_blocksPerChunk = 0;
// ~3/8 s per buffer, in whole 4 KB pages - which keeps every read a whole number of
// frames and of cache lines.
const int perBuffer = RoundUp((m_sampleRate * m_frameBytes * 3) / 8, 4096);
m_readBytes = (perBuffer < kPcmMinReadBytes) ? kPcmMinReadBytes : ((perBuffer > kPcmMaxReadBytes) ? kPcmMaxReadBytes : perBuffer);
return nullptr;
}
// ------------------------------------------------------------------------------------------------
// Buffers
// ------------------------------------------------------------------------------------------------
bool MusicStream::AllocateBuffers(const char * const path)
{
// One block for both, each buffer a whole number of cache lines, so the second starts
// line aligned too. TryAlloc: a track that doesn't fit is a silent track, not a halt.
const int stride = RoundUp(m_readBytes, 64);
const size_t bytes = static_cast<size_t>(stride) * kNumBuffers;
void * const memory = ps2::heap::TryAllocAligned(ps2::heap::MemAlign(64), bytes, MemTag::Music);
if (memory == nullptr)
{
Com_Printf("WARNING: %s: no memory for its %d KB of stream buffers, the track stays silent.\n",
path, static_cast<int>(bytes / 1024u));
return false;
}
m_bufferMemory = static_cast<u8 *>(memory);
m_bufferMemoryBytes = bytes;
for (int i = 0; i < kNumBuffers; ++i)
{
m_buffers[i].data = m_bufferMemory + (i * stride);
}
return true;
}
void MusicStream::FreeBuffers()
{
ps2::heap::Free(m_bufferMemory, m_bufferMemoryBytes, MemTag::Music);
m_bufferMemory = nullptr;
m_bufferMemoryBytes = 0;
for (Buffer & buffer : m_buffers)
{
buffer.data = nullptr;
}
}
// ------------------------------------------------------------------------------------------------
// Open / Close
// ------------------------------------------------------------------------------------------------
MusicStream::OpenResult MusicStream::Open(const char * const path, const int extraLoops)
{
Close();
const int fd = open(path, O_RDONLY);
if (fd < 0)
{
return OpenResult::Missing; // The caller tries every candidate, so this is quiet.
}
// The format comes from the header, whatever the extension says.
const int got = ReadScratch(fd, 0, kScratchBytes);
const char * error = nullptr;
if (got >= 4 && std::memcmp(m_scratch, music_file::kMagic, 4) == 0)
{
error = (got >= static_cast<int>(sizeof(music_file::Header))) ? ParseAdpcmHeader() : "truncated header";
}
else if (got >= 12 && HasId(m_scratch, "RIFF") && HasId(m_scratch + 8, "WAVE"))
{
error = ParseWavHeader(fd);
}
else
{
error = "not a music file (neither Q2MU ADPCM nor RIFF WAVE)";
}
if (error != nullptr)
{
Com_Printf("WARNING: %s: %s\n", path, error);
close(fd);
return OpenResult::Unusable;
}
if (!AllocateBuffers(path))
{
close(fd);
return OpenResult::Unusable;
}
m_fd = fd;
// The header reads left the file position wherever they did, so the first read seeks.
m_fdMoved = true;
m_nextOffset = 0;
m_requestLoopsLeft = extraLoops;
m_requestIndex = 0;
m_decodeIndex = 0;
m_haveBuffer = false;
m_unitPos = 0;
m_unitCount = 0;
m_framesDecoded = 0;
m_decodeLoopsLeft = extraLoops;
m_wraps = 0;
m_finished = false;
m_failed = false;
m_blockFrames = 0;
m_blockPos = 0;
for (spu_adpcm::History & history : m_history)
{
history = {};
}
for (int i = 0; i < kNumBuffers; ++i)
{
RequestNext(i);
}
// Sleeping here is what lets the loader run: the first buffer lands before this returns,
// the second carries on behind it.
Collect(m_buffers[0], true);
return OpenResult::Opened;
}
void MusicStream::Close()
{
if (m_fd < 0)
{
return;
}
// The loader may be inside read() on this fd - and into these buffers - right now.
CancelReads();
close(m_fd);
m_fd = -1;
FreeBuffers();
m_haveBuffer = false;
m_finished = false;
m_failed = false;
}
const char * MusicStream::FormatName() const
{
return (m_format == Format::Adpcm) ? "ADPCM" : "PCM";
}
// ------------------------------------------------------------------------------------------------
// Decoding (main thread)
// ------------------------------------------------------------------------------------------------
bool MusicStream::AcquireBuffer()
{
Buffer & buffer = m_buffers[m_decodeIndex];
if (!Collect(buffer, false) && buffer.state == BufferState::Queued)
{
return false; // Not landed yet; try again next frame.
}
if (buffer.state != BufferState::Ready || buffer.resultBytes != buffer.requestBytes)
{
Com_Printf("WARNING: music stream read failed (%d of %d bytes).\n",
static_cast<int>(buffer.resultBytes), buffer.requestBytes);
m_finished = true;
m_failed = true;
return false;
}
m_haveBuffer = true;
m_unitPos = 0;
m_unitCount = (m_format == Format::Adpcm) ? ((buffer.requestBytes / m_groupBytes) * m_blocksPerChunk)
: (buffer.requestBytes / m_frameBytes);
return true;
}
void MusicStream::ReleaseBuffer()
{
const int released = m_decodeIndex;
m_buffers[released].state = BufferState::Empty;
m_haveBuffer = false;
m_decodeIndex = (m_decodeIndex + 1) % kNumBuffers;
// Refill it straight away. The loader starts on it when the main thread next sleeps,
// within the frame.
RequestNext(released);
}
bool MusicStream::BufferReady()
{
if (m_fd < 0 || m_finished)
{
return false;
}
if (m_framesDecoded >= m_frameCount)
{
if (m_decodeLoopsLeft == 0)
{
m_finished = true;
return false;
}
if (m_decodeLoopsLeft > 0)
{
--m_decodeLoopsLeft;
}
// Wrap. The reads wrapped ahead of us, so the next buffer starts the payload over;
// whatever is left of the current one is ADPCM tail padding (a PCM pass always ends
// with its buffer). The ADPCM history restarts too, exactly as the encoder started it.
if (m_haveBuffer)
{
ReleaseBuffer();
}
for (spu_adpcm::History & history : m_history)
{
history = {};
}
m_framesDecoded = 0;
++m_wraps;
}
return m_haveBuffer || AcquireBuffer();
}
bool MusicStream::DecodeNextBlock()
{
if (!BufferReady())
{
return false;
}
const int group = m_unitPos / m_blocksPerChunk;
const int inChunk = m_unitPos % m_blocksPerChunk;
const u8 * const block = m_buffers[m_decodeIndex].data + (group * m_groupBytes) + (inChunk * kBlockBytes);
spu_adpcm::DecodeBlock(block, m_block, 2, m_history[0]);
if (m_channels > 1)
{
spu_adpcm::DecodeBlock(block + m_chunkBytes, m_block + 1, 2, m_history[1]);
}
else
{
for (int i = 0; i < spu_adpcm::kBlockSamples; ++i)
{
m_block[(i * 2) + 1] = m_block[i * 2];
}
}
// The last block of a pass is only partly music.
const int framesLeft = m_frameCount - m_framesDecoded;
m_blockFrames = (framesLeft < spu_adpcm::kBlockSamples) ? framesLeft : spu_adpcm::kBlockSamples;
m_blockPos = 0;
m_framesDecoded += m_blockFrames;
if (++m_unitPos == m_unitCount)
{
ReleaseBuffer();
}
return true;
}
int MusicStream::DecodeAdpcm(s16 * const outStereo, const int maxFrames)
{
int produced = 0;
while (produced < maxFrames)
{
if (m_blockPos == m_blockFrames && !DecodeNextBlock())
{
break;
}
int count = m_blockFrames - m_blockPos;
if (count > maxFrames - produced)
{
count = maxFrames - produced;
}
std::memcpy(outStereo + (produced * 2), m_block + (m_blockPos * 2),
static_cast<size_t>(count) * 2 * sizeof(s16));
m_blockPos += count;
produced += count;
}
return produced;
}
int MusicStream::DecodePcm(s16 * const outStereo, const int maxFrames)
{
int produced = 0;
while (produced < maxFrames && BufferReady())
{
int count = m_unitCount - m_unitPos;
if (count > maxFrames - produced)
{
count = maxFrames - produced;
}
if (count > m_frameCount - m_framesDecoded)
{
count = m_frameCount - m_framesDecoded;
}
// Little-endian on disk and on the EE: the frames copy straight out.
const u8 * const src = m_buffers[m_decodeIndex].data + (m_unitPos * m_frameBytes);
s16 * const dst = outStereo + (produced * 2);
if (m_channels > 1)
{
std::memcpy(dst, src, static_cast<size_t>(count) * 2 * sizeof(s16));
}
else
{
// The buffer is cache-line aligned and a mono frame two bytes, so this is aligned.
const s16 * const mono = static_cast<const s16 *>(static_cast<const void *>(src));
for (int i = 0; i < count; ++i)
{
dst[i * 2] = mono[i];
dst[(i * 2) + 1] = mono[i];
}
}
m_unitPos += count;
m_framesDecoded += count;
produced += count;
if (m_unitPos == m_unitCount)
{
ReleaseBuffer();
}
}
return produced;
}
int MusicStream::Decode(s16 * const outStereo, const int maxFrames)
{
return (m_format == Format::Adpcm) ? DecodeAdpcm(outStereo, maxFrames)
: DecodePcm(outStereo, maxFrames);
}
int MusicStream::TakeWraps()
{
const int wraps = m_wraps;
m_wraps = 0;
return wraps;
}
} // namespace ps2::audio