DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
FlacFile.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
25#include "AudioFile.h"
26
27#include <algorithm>
28#include <array>
29#include <bit>
30#include <cmath>
31#include <cstddef>
32#include <cstdlib>
33#include <cstdint>
34#include <cstring>
35#include <filesystem>
36#include <fstream>
37#include <limits>
38#include <span>
39#include <string_view>
40#include <utility>
41#include <vector>
42
43#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64)
44#include <intrin.h>
45#endif
46
47namespace dspark {
48
53class FlacFile : public AudioFile
54{
55public:
57 static constexpr uint64_t kMaxInputBytes = 256ull * 1024 * 1024;
59 static constexpr uint64_t kMaxMetadataBlocks = 65536;
61 static constexpr uint64_t kMaxFrames = 1048576;
63 static constexpr uint64_t kMaxInterchannelSamples = 1ull << 31;
65 static constexpr uint64_t kMaxDecodedPcmBytes = 8ull << 30;
67 static constexpr uint64_t kMaxRiceUnaryZeros = 1ull << 20;
69 static constexpr std::string_view kWriteUnsupportedReason =
70 "FlacFile is decode-only; FLAC encoding is not supported.";
71
72 ~FlacFile() override { close(); }
73
78 [[nodiscard]] bool openRead(const std::filesystem::path& path) override
79 {
80 close();
81
82 std::ifstream input(path, std::ios::binary | std::ios::ate);
83 if (!input.is_open())
84 return false;
85 const std::streampos end = input.tellg();
86 if (end <= std::streampos(0))
87 return false;
88 const uint64_t fileSize = static_cast<uint64_t>(end);
89 if (fileSize > kMaxInputBytes
90 || fileSize > static_cast<uint64_t>(std::numeric_limits<size_t>::max()))
91 return false;
92
93 OpenState candidate;
94 candidate.bytes.resize(static_cast<size_t>(fileSize));
95 input.seekg(0, std::ios::beg);
96 input.read(reinterpret_cast<char*>(candidate.bytes.data()),
97 static_cast<std::streamsize>(candidate.bytes.size()));
98 if (input.gcount() != static_cast<std::streamsize>(candidate.bytes.size()))
99 return false;
100 if (!validateOpen(candidate))
101 return false;
102
103 bytes_ = std::move(candidate.bytes);
104 frames_ = std::move(candidate.frames);
105 stream_ = candidate.stream;
106 info_ = candidate.info;
107 open_ = true;
108 return true;
109 }
110
116 [[nodiscard]] bool openWrite(const std::filesystem::path& path,
117 const AudioFileInfo& info) override
118 {
119 (void)path;
120 (void)info;
121 close();
122 return false;
123 }
124
126 [[nodiscard]] AudioFileInfo getInfo() const override { return info_; }
127
129 [[nodiscard]] bool readSamples(AudioBufferView<float> dest) override
130 {
131 if (!open_) return false;
132 return readSamples(dest, 0, info_.numSamples);
133 }
134
141 [[nodiscard]] bool readSamples(AudioBufferView<float> dest,
142 int64_t startFrame,
143 int64_t numFrames) override
144 {
145 if (!open_ || startFrame < 0 || numFrames <= 0)
146 return false;
147 if (startFrame > info_.numSamples
148 || numFrames > info_.numSamples - startFrame)
149 return false;
150
151 const int destChannels = std::max(0, dest.getNumChannels());
152 const int destSamples = std::max(0, dest.getNumSamples());
153 const int channelsToCopy = std::min(destChannels,
154 static_cast<int>(info_.numChannels));
155 const int64_t framesToCopy = std::min<int64_t>(numFrames, destSamples);
156 if (channelsToCopy == 0 || framesToCopy == 0)
157 return true;
158
159 const uint64_t first = static_cast<uint64_t>(startFrame);
160 const uint64_t last = first + static_cast<uint64_t>(framesToCopy);
161 auto it = std::lower_bound(frames_.begin(), frames_.end(), first,
162 [](const FrameIndex& frame, uint64_t sample) {
163 return frame.firstSample + frame.blockSize <= sample;
164 });
165
166 int64_t written = 0;
167 std::vector<int64_t> pcm;
168 while (it != frames_.end() && it->firstSample < last)
169 {
170 const size_t frameNumber = static_cast<size_t>(it - frames_.begin());
171 DecodedFrame decoded;
172 if (!decodeFrame(bytes_, it->offset, stream_, frameNumber,
173 it->firstSample, pcm, decoded)
174 || decoded.endOffset != it->offset + it->size
175 || decoded.blockSize != it->blockSize)
176 {
177 close();
178 return false;
179 }
180
181 const uint64_t overlapBegin = std::max(first, it->firstSample);
182 const uint64_t overlapEnd = std::min(last,
183 it->firstSample + static_cast<uint64_t>(it->blockSize));
184 const size_t sourceOffset = static_cast<size_t>(overlapBegin - it->firstSample);
185 const size_t count = static_cast<size_t>(overlapEnd - overlapBegin);
186 const size_t destinationOffset = static_cast<size_t>(overlapBegin - first);
187
188 // A power-of-two scale is exact, so this matches ldexp() bit
189 // for bit; restored samples always fit int32.
190 const float scale = std::ldexp(1.0f, 1 - static_cast<int>(stream_.bitsPerSample));
191 for (int channel = 0; channel < channelsToCopy; ++channel)
192 {
193 float* output = dest.getChannel(channel) + destinationOffset;
194 const int64_t* source = pcm.data()
195 + static_cast<size_t>(channel) * it->blockSize + sourceOffset;
196 for (size_t i = 0; i < count; ++i)
197 output[i] = static_cast<float>(static_cast<int32_t>(source[i])) * scale;
198 }
199 written += static_cast<int64_t>(count);
200 ++it;
201 }
202 if (written != framesToCopy)
203 {
204 close();
205 return false;
206 }
207 return true;
208 }
209
211 [[nodiscard]] bool writeSamples(AudioBufferView<const float> src) override
212 {
213 (void)src;
214 return false;
215 }
216
218 void close() override
219 {
220 std::vector<uint8_t>().swap(bytes_);
221 std::vector<FrameIndex>().swap(frames_);
222 stream_ = {};
223 info_ = {};
224 open_ = false;
225 }
226
228 [[nodiscard]] bool isOpen() const noexcept override { return open_; }
229
230private:
231 struct StreamInfo
232 {
233 uint16_t minBlockSize = 0;
234 uint16_t maxBlockSize = 0;
235 uint32_t minFrameSize = 0;
236 uint32_t maxFrameSize = 0;
237 uint32_t sampleRate = 0;
238 uint8_t channels = 0;
239 uint8_t bitsPerSample = 0;
240 uint64_t declaredSamples = 0;
241 std::array<uint8_t, 16> md5 {};
242 };
243
244 struct FrameIndex
245 {
246 size_t offset = 0;
247 size_t size = 0;
248 uint64_t firstSample = 0;
249 uint32_t blockSize = 0;
250 };
251
252 struct DecodedFrame
253 {
254 size_t endOffset = 0;
255 uint32_t blockSize = 0;
256 bool variableBlock = false;
257 bool numberIsSample = false;
258 bool numberIsFrame = false;
259 };
260
261 struct OpenState
262 {
263 std::vector<uint8_t> bytes;
264 std::vector<FrameIndex> frames;
265 StreamInfo stream;
266 AudioFileInfo info;
267 };
268
269 class ByteCursor
270 {
271 public:
272 ByteCursor(const std::vector<uint8_t>& bytes, size_t begin, size_t end)
273 : bytes_(bytes), pos_(begin), end_(end)
274 {
275 }
276
277 [[nodiscard]] size_t position() const noexcept { return pos_; }
278 [[nodiscard]] size_t remaining() const noexcept { return end_ - pos_; }
279
280 bool readU8(uint8_t& value) noexcept
281 {
282 if (pos_ >= end_) return false;
283 value = bytes_[pos_++];
284 return true;
285 }
286
287 bool readBE16(uint16_t& value) noexcept
288 {
289 uint8_t a = 0, b = 0;
290 if (!readU8(a) || !readU8(b)) return false;
291 value = static_cast<uint16_t>((static_cast<uint16_t>(a) << 8)
292 | static_cast<uint16_t>(b));
293 return true;
294 }
295
296 bool readBE24(uint32_t& value) noexcept
297 {
298 uint8_t a = 0, b = 0, c = 0;
299 if (!readU8(a) || !readU8(b) || !readU8(c)) return false;
300 value = (static_cast<uint32_t>(a) << 16)
301 | (static_cast<uint32_t>(b) << 8)
302 | static_cast<uint32_t>(c);
303 return true;
304 }
305
306 bool readSpan(size_t length, const uint8_t*& data) noexcept
307 {
308 if (length > remaining()) return false;
309 data = bytes_.data() + pos_;
310 pos_ += length;
311 return true;
312 }
313
314 bool skip(size_t length) noexcept
315 {
316 const uint8_t* ignored = nullptr;
317 return readSpan(length, ignored);
318 }
319
320 private:
321 const std::vector<uint8_t>& bytes_;
322 size_t pos_ = 0;
323 size_t end_ = 0;
324 };
325
326 class BitCursor
327 {
328 public:
329 BitCursor(const std::vector<uint8_t>& bytes, size_t beginByte,
330 size_t endByte)
331 : bytes_(bytes), bitPos_(beginByte * 8), endBit_(endByte * 8)
332 {
333 }
334
335 [[nodiscard]] size_t bitPosition() const noexcept { return bitPos_; }
336 [[nodiscard]] size_t bytePosition() const noexcept { return bitPos_ / 8; }
337 [[nodiscard]] uint64_t remainingBits() const noexcept
338 {
339 return static_cast<uint64_t>(endBit_ - bitPos_);
340 }
341
342 bool readBits(unsigned count, uint64_t& value) noexcept
343 {
344 value = 0;
345 if (count > 64 || static_cast<uint64_t>(count) > remainingBits())
346 return false;
347 if (count == 0)
348 return true;
349 const size_t byte = bitPos_ >> 3;
350 const unsigned offset = static_cast<unsigned>(bitPos_ & 7u);
351 // One 64-bit big-endian load serves any field that fits in it;
352 // the bit-at-a-time loop remains for the last bytes of the buffer
353 // and for 58..64-bit fields that straddle nine bytes.
354 if (count + offset <= 64 && byte + 8 <= bytes_.size())
355 {
356 value = (loadBigEndian64(bytes_.data() + byte) << offset) >> (64u - count);
357 bitPos_ += count;
358 return true;
359 }
360 for (unsigned i = 0; i < count; ++i)
361 {
362 const uint8_t b = bytes_[bitPos_ / 8];
363 const unsigned shift = 7u - static_cast<unsigned>(bitPos_ & 7u);
364 value = (value << 1) | ((b >> shift) & 1u);
365 ++bitPos_;
366 }
367 return true;
368 }
369
370 bool readSigned(unsigned count, int64_t& value) noexcept
371 {
372 if (count == 0)
373 {
374 value = 0;
375 return true;
376 }
377 if (count > 63) return false;
378 uint64_t raw = 0;
379 if (!readBits(count, raw)) return false;
380 const uint64_t sign = uint64_t { 1 } << (count - 1);
381 if ((raw & sign) == 0)
382 {
383 value = static_cast<int64_t>(raw);
384 return true;
385 }
386 const uint64_t magnitude = (uint64_t { 1 } << count) - raw;
387 value = -static_cast<int64_t>(magnitude);
388 return true;
389 }
390
391 bool readUnary(uint64_t limit, uint64_t& zeros) noexcept
392 {
393 zeros = 0;
394 for (;;)
395 {
396 // Count leading zeros 56 bits at a time while a whole word
397 // is available inside both the buffer and the read bound.
398 const size_t byte = bitPos_ >> 3;
399 if (byte + 8 <= bytes_.size() && endBit_ - bitPos_ >= 64)
400 {
401 const unsigned offset = static_cast<unsigned>(bitPos_ & 7u);
402 const uint64_t window = (loadBigEndian64(bytes_.data() + byte) << offset)
403 & ~uint64_t { 0xff };
404 if (window != 0)
405 {
406 const unsigned run = static_cast<unsigned>(std::countl_zero(window));
407 if (zeros + run > limit) return false;
408 zeros += run;
409 bitPos_ += run + 1u;
410 return true;
411 }
412 const unsigned run = 56u - offset;
413 if (zeros + run <= limit)
414 {
415 zeros += run;
416 bitPos_ += run;
417 continue;
418 }
419 }
420 uint64_t bit = 0;
421 if (!readBits(1, bit)) return false;
422 if (bit != 0) return true;
423 if (zeros >= limit) return false;
424 ++zeros;
425 }
426 }
427
434 bool readRiceCode(unsigned k, uint64_t unaryLimit, int64_t& residual) noexcept
435 {
436 uint64_t quotient = 0, remainder = 0;
437 if (!readUnary(unaryLimit, quotient)
438 || !readBits(k, remainder)
439 || quotient > (std::numeric_limits<uint64_t>::max() >> k))
440 return false;
441 const uint64_t folded = (quotient << k) | remainder;
442 if (folded > 4294967294ull)
443 return false;
444 residual = static_cast<int64_t>(folded >> 1)
445 ^ -static_cast<int64_t>(folded & 1u);
446 return true;
447 }
448
449 // Raw access for decoders that take the bits in larger steps: the
450 // buffer, the end of the bytes that may be loaded, and the bit
451 // position to resume from.
452 [[nodiscard]] const uint8_t* data() const noexcept { return bytes_.data(); }
453 [[nodiscard]] size_t loadEnd() const noexcept
454 {
455 return std::min(endBit_ >> 3, bytes_.size());
456 }
457 void setBitPosition(size_t position) noexcept { bitPos_ = position; }
458
459 bool alignWithZeroPadding() noexcept
460 {
461 while ((bitPos_ & 7u) != 0)
462 {
463 uint64_t bit = 0;
464 if (!readBits(1, bit) || bit != 0) return false;
465 }
466 return true;
467 }
468
469 // Leading zero count of a nonzero word. Where LZCNT is not assumed,
470 // the standard library may check the CPU on every std::countl_zero
471 // call (a load and a branch in the Rice loop); BSR needs no check
472 // once the word cannot be zero.
473 static unsigned leadingZeros(uint64_t nonZero) noexcept
474 {
475#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64)
476 unsigned long index = 0;
477 _BitScanReverse64(&index, nonZero);
478 return 63u - static_cast<unsigned>(index);
479#else
480 return static_cast<unsigned>(std::countl_zero(nonZero));
481#endif
482 }
483
484 static uint64_t loadBigEndian64(const uint8_t* p) noexcept
485 {
486 uint64_t word = 0;
487 std::memcpy(&word, p, sizeof(word));
488 if constexpr (std::endian::native == std::endian::little)
489 {
490#if defined(_MSC_VER) && !defined(__clang__)
491 word = _byteswap_uint64(word);
492#else
493 word = __builtin_bswap64(word);
494#endif
495 }
496 return word;
497 }
498
499 private:
500 const std::vector<uint8_t>& bytes_;
501 size_t bitPos_ = 0;
502 size_t endBit_ = 0;
503 };
504
505 class Md5
506 {
507 public:
508 Md5() noexcept { reset(); }
509
510 void update(std::span<const uint8_t> data) noexcept
511 {
512 totalBytes_ += data.size();
513 while (!data.empty())
514 {
515 // Whole blocks are hashed straight from the input.
516 if (bufferSize_ == 0 && data.size() >= buffer_.size())
517 {
518 transform(data.data());
519 data = data.subspan(buffer_.size());
520 continue;
521 }
522 const size_t take = std::min(data.size(), buffer_.size() - bufferSize_);
523 std::memcpy(buffer_.data() + bufferSize_, data.data(), take);
524 bufferSize_ += take;
525 data = data.subspan(take);
526 if (bufferSize_ == buffer_.size())
527 {
528 transform(buffer_.data());
529 bufferSize_ = 0;
530 }
531 }
532 }
533
534 [[nodiscard]] std::array<uint8_t, 16> finish() noexcept
535 {
536 const uint64_t messageBits = totalBytes_ * 8;
537 std::array<uint8_t, 120> padding {};
538 padding[0] = 0x80;
539 const size_t paddingSize = bufferSize_ < 56
540 ? 56 - bufferSize_ : 64 + 56 - bufferSize_;
541 update(std::span<const uint8_t>(padding.data(), paddingSize));
542 uint8_t length[8] = {};
543 for (unsigned i = 0; i < 8; ++i)
544 length[i] = static_cast<uint8_t>(messageBits >> (8 * i));
545 update(length);
546
547 std::array<uint8_t, 16> digest {};
548 for (size_t word = 0; word < 4; ++word)
549 for (unsigned byte = 0; byte < 4; ++byte)
550 digest[word * 4 + byte] = static_cast<uint8_t>(
551 state_[word] >> (8 * byte));
552 return digest;
553 }
554
555 private:
556 std::array<uint32_t, 4> state_ {};
557 std::array<uint8_t, 64> buffer_ {};
558 size_t bufferSize_ = 0;
559 uint64_t totalBytes_ = 0;
560
561 void reset() noexcept
562 {
563 state_ = { 0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u };
564 bufferSize_ = 0;
565 totalBytes_ = 0;
566 }
567
568 static uint32_t rotateLeft(uint32_t value, unsigned count) noexcept
569 {
570 return static_cast<uint32_t>((value << count) | (value >> (32 - count)));
571 }
572
573 void transform(const uint8_t* block) noexcept
574 {
575 static constexpr uint32_t constants[64] = {
576 0xd76aa478u,0xe8c7b756u,0x242070dbu,0xc1bdceeeu,
577 0xf57c0fafu,0x4787c62au,0xa8304613u,0xfd469501u,
578 0x698098d8u,0x8b44f7afu,0xffff5bb1u,0x895cd7beu,
579 0x6b901122u,0xfd987193u,0xa679438eu,0x49b40821u,
580 0xf61e2562u,0xc040b340u,0x265e5a51u,0xe9b6c7aau,
581 0xd62f105du,0x02441453u,0xd8a1e681u,0xe7d3fbc8u,
582 0x21e1cde6u,0xc33707d6u,0xf4d50d87u,0x455a14edu,
583 0xa9e3e905u,0xfcefa3f8u,0x676f02d9u,0x8d2a4c8au,
584 0xfffa3942u,0x8771f681u,0x6d9d6122u,0xfde5380cu,
585 0xa4beea44u,0x4bdecfa9u,0xf6bb4b60u,0xbebfbc70u,
586 0x289b7ec6u,0xeaa127fau,0xd4ef3085u,0x04881d05u,
587 0xd9d4d039u,0xe6db99e5u,0x1fa27cf8u,0xc4ac5665u,
588 0xf4292244u,0x432aff97u,0xab9423a7u,0xfc93a039u,
589 0x655b59c3u,0x8f0ccc92u,0xffeff47du,0x85845dd1u,
590 0x6fa87e4fu,0xfe2ce6e0u,0xa3014314u,0x4e0811a1u,
591 0xf7537e82u,0xbd3af235u,0x2ad7d2bbu,0xeb86d391u
592 };
593 static constexpr unsigned shifts[64] = {
594 7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,
595 5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,
596 4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
597 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
598 };
599
600 uint32_t words[16] = {};
601 for (size_t i = 0; i < 16; ++i)
602 words[i] = static_cast<uint32_t>(block[i * 4])
603 | (static_cast<uint32_t>(block[i * 4 + 1]) << 8)
604 | (static_cast<uint32_t>(block[i * 4 + 2]) << 16)
605 | (static_cast<uint32_t>(block[i * 4 + 3]) << 24);
606
607 uint32_t a = state_[0], b = state_[1], c = state_[2], d = state_[3];
608 for (unsigned i = 0; i < 64; ++i)
609 {
610 uint32_t f = 0;
611 unsigned index = 0;
612 if (i < 16) { f = (b & c) | (~b & d); index = i; }
613 else if (i < 32) { f = (d & b) | (~d & c); index = (5 * i + 1) & 15u; }
614 else if (i < 48) { f = b ^ c ^ d; index = (3 * i + 5) & 15u; }
615 else { f = c ^ (b | ~d); index = (7 * i) & 15u; }
616 const uint32_t next = b + rotateLeft(a + f + constants[i]
617 + words[index], shifts[i]);
618 a = d; d = c; c = b; b = next;
619 }
620 state_[0] += a;
621 state_[1] += b;
622 state_[2] += c;
623 state_[3] += d;
624 }
625 };
626
627 std::vector<uint8_t> bytes_;
628 std::vector<FrameIndex> frames_;
629 StreamInfo stream_;
630 AudioFileInfo info_ {};
631 bool open_ = false;
632
633 static uint8_t crc8(std::span<const uint8_t> data) noexcept
634 {
635 uint8_t crc = 0;
636 for (uint8_t byte : data)
637 {
638 crc ^= byte;
639 for (unsigned bit = 0; bit < 8; ++bit)
640 crc = static_cast<uint8_t>((crc & 0x80u) != 0
641 ? static_cast<uint8_t>((crc << 1) ^ 0x07u)
642 : static_cast<uint8_t>(crc << 1));
643 }
644 return crc;
645 }
646
647 static uint16_t crc16(std::span<const uint8_t> data) noexcept
648 {
649 // Slice-by-8 tables of the same polynomial (x^16 + x^15 + x^2 + 1,
650 // MSB first, initial value 0). kTables[0] is the byte-wise table;
651 // kTables[k][v] is the CRC of byte v followed by k zero bytes, so by
652 // linearity eight bytes fold into one XOR of eight lookups, the
653 // register entering through the first two. The frame CRC covers
654 // every byte of the file, and the byte-wise form was a serial chain
655 // of about 7 cycles per byte.
656 static constexpr auto kTables = [] {
657 std::array<std::array<uint16_t, 256>, 8> tables {};
658 for (unsigned i = 0; i < 256; ++i)
659 {
660 uint16_t crc = static_cast<uint16_t>(i << 8);
661 for (unsigned bit = 0; bit < 8; ++bit)
662 crc = static_cast<uint16_t>((crc & 0x8000u) != 0
663 ? static_cast<uint16_t>((crc << 1) ^ 0x8005u)
664 : static_cast<uint16_t>(crc << 1));
665 tables[0][i] = crc;
666 }
667 for (unsigned k = 1; k < 8; ++k)
668 for (unsigned i = 0; i < 256; ++i)
669 tables[k][i] = static_cast<uint16_t>(
670 (tables[k - 1][i] << 8)
671 ^ tables[0][tables[k - 1][i] >> 8]);
672 return tables;
673 }();
674 const uint8_t* p = data.data();
675 size_t n = data.size();
676 uint32_t crc = 0;
677 for (; n >= 8; n -= 8, p += 8)
678 crc = static_cast<uint32_t>(kTables[7][p[0] ^ (crc >> 8)]
679 ^ kTables[6][p[1] ^ (crc & 0xffu)]
680 ^ kTables[5][p[2]] ^ kTables[4][p[3]]
681 ^ kTables[3][p[4]] ^ kTables[2][p[5]]
682 ^ kTables[1][p[6]] ^ kTables[0][p[7]]);
683 for (; n > 0; --n, ++p)
684 crc = static_cast<uint32_t>(((crc << 8) & 0xff00u)
685 ^ kTables[0][(crc >> 8) ^ *p]);
686 return static_cast<uint16_t>(crc);
687 }
688
689 static bool sampleInDepth(int64_t value, unsigned depth) noexcept
690 {
691 if (depth == 0 || depth > 33) return false;
692 const int64_t magnitude = int64_t { 1 } << (depth - 1);
693 return value >= -magnitude && value <= magnitude - 1;
694 }
695
696 static bool parseStreamInfo(const uint8_t* data, StreamInfo& info) noexcept
697 {
698 info.minBlockSize = static_cast<uint16_t>(
699 (static_cast<uint16_t>(data[0]) << 8) | data[1]);
700 info.maxBlockSize = static_cast<uint16_t>(
701 (static_cast<uint16_t>(data[2]) << 8) | data[3]);
702 info.minFrameSize = (static_cast<uint32_t>(data[4]) << 16)
703 | (static_cast<uint32_t>(data[5]) << 8) | data[6];
704 info.maxFrameSize = (static_cast<uint32_t>(data[7]) << 16)
705 | (static_cast<uint32_t>(data[8]) << 8) | data[9];
706 const uint64_t packed = (static_cast<uint64_t>(data[10]) << 56)
707 | (static_cast<uint64_t>(data[11]) << 48)
708 | (static_cast<uint64_t>(data[12]) << 40)
709 | (static_cast<uint64_t>(data[13]) << 32)
710 | (static_cast<uint64_t>(data[14]) << 24)
711 | (static_cast<uint64_t>(data[15]) << 16)
712 | (static_cast<uint64_t>(data[16]) << 8)
713 | static_cast<uint64_t>(data[17]);
714 info.sampleRate = static_cast<uint32_t>(packed >> 44);
715 info.channels = static_cast<uint8_t>(((packed >> 41) & 7u) + 1u);
716 info.bitsPerSample = static_cast<uint8_t>(((packed >> 36) & 31u) + 1u);
717 info.declaredSamples = packed & 0xfffffffffull;
718 std::copy(data + 18, data + 34, info.md5.begin());
719
720 if (info.minBlockSize < 16 || info.maxBlockSize < 16
721 || info.minBlockSize > info.maxBlockSize)
722 return false;
723 if (info.minFrameSize != 0 && info.maxFrameSize != 0
724 && info.minFrameSize > info.maxFrameSize)
725 return false;
726 if (info.sampleRate == 0 || info.sampleRate > 1048575
727 || info.channels == 0 || info.channels > 8
728 || info.bitsPerSample < 4 || info.bitsPerSample > 32
729 || info.declaredSamples > kMaxInterchannelSamples)
730 return false;
731 return true;
732 }
733
734 static bool parseCodedNumber(ByteCursor& cursor, bool variable,
735 uint64_t& value) noexcept
736 {
737 uint8_t first = 0;
738 if (!cursor.readU8(first)) return false;
739 unsigned length = 0;
740 uint64_t minimum = 0;
741 if (first < 0x80) { length = 1; value = first; }
742 else if ((first & 0xe0u) == 0xc0u) { length = 2; value = first & 0x1fu; minimum = 0x80; }
743 else if ((first & 0xf0u) == 0xe0u) { length = 3; value = first & 0x0fu; minimum = 0x800; }
744 else if ((first & 0xf8u) == 0xf0u) { length = 4; value = first & 0x07u; minimum = 0x10000; }
745 else if ((first & 0xfcu) == 0xf8u) { length = 5; value = first & 0x03u; minimum = 0x200000; }
746 else if ((first & 0xfeu) == 0xfcu) { length = 6; value = first & 0x01u; minimum = 0x4000000; }
747 else if (first == 0xfeu) { length = 7; value = 0; minimum = 0x80000000ull; }
748 else return false;
749
750 for (unsigned i = 1; i < length; ++i)
751 {
752 uint8_t continuation = 0;
753 if (!cursor.readU8(continuation) || (continuation & 0xc0u) != 0x80u)
754 return false;
755 value = (value << 6) | (continuation & 0x3fu);
756 }
757 if (length > 1 && value < minimum)
758 return false;
759 if (variable)
760 return value <= 0xfffffffffull;
761 return length <= 6 && value <= 0x7fffffffu;
762 }
763
764 static bool decodeBlockSize(uint8_t code, ByteCursor& cursor,
765 uint32_t& blockSize) noexcept
766 {
767 if (code == 0) return false;
768 if (code == 1) blockSize = 192;
769 else if (code >= 2 && code <= 5)
770 blockSize = 576u << (code - 2u);
771 else if (code == 6)
772 {
773 uint8_t value = 0;
774 if (!cursor.readU8(value)) return false;
775 blockSize = static_cast<uint32_t>(value) + 1u;
776 }
777 else if (code == 7)
778 {
779 uint16_t value = 0;
780 if (!cursor.readBE16(value) || value == 0xffffu) return false;
781 blockSize = static_cast<uint32_t>(value) + 1u;
782 }
783 else
784 blockSize = 1u << code;
785 return blockSize > 0 && blockSize <= 65535;
786 }
787
788 static bool decodeSampleRate(uint8_t code, ByteCursor& cursor,
789 const StreamInfo& stream,
790 uint32_t& sampleRate) noexcept
791 {
792 static constexpr uint32_t rates[12] = {
793 0, 88200, 176400, 192000, 8000, 16000,
794 22050, 24000, 32000, 44100, 48000, 96000
795 };
796 if (code <= 11)
797 sampleRate = code == 0 ? stream.sampleRate : rates[code];
798 else if (code == 12)
799 {
800 uint8_t value = 0;
801 if (!cursor.readU8(value)) return false;
802 sampleRate = static_cast<uint32_t>(value) * 1000u;
803 }
804 else if (code == 13)
805 {
806 uint16_t value = 0;
807 if (!cursor.readBE16(value)) return false;
808 sampleRate = value;
809 }
810 else if (code == 14)
811 {
812 uint16_t value = 0;
813 if (!cursor.readBE16(value)) return false;
814 sampleRate = static_cast<uint32_t>(value) * 10u;
815 }
816 else return false;
817 return sampleRate != 0 && sampleRate == stream.sampleRate;
818 }
819
820 // A subframe predictor: `order` warm-up samples, then each sample is its
821 // residual plus a prediction from the samples before it. Fixed
822 // predictors use the RFC 9639 polynomials; LPC ones `coefficients`,
823 // with the sum shifted right by `shift`. Every restored sample must lie
824 // within the subframe depth, checked before the next prediction reads
825 // it: that bound keeps the arithmetic inside int64 (fixed: |prediction|
826 // < 2^37; LPC: |coefficient| < 2^14 and order <= 32, so |sum| < 2^52).
827 // An arithmetic right shift is the floor division RFC 9639 asks for
828 // (C++20 defines >> on negative values as arithmetic).
829 struct Predictor
830 {
831 unsigned order = 0;
832 bool fixed = true;
833 unsigned shift = 0;
834 std::array<int64_t, 32> coefficients {};
835 int64_t low = 0;
836 uint64_t span = 0;
837 };
838
839 // Prediction for x[i]. `newest` is x[i-1], carried in a register and
840 // added last, so it ends the dependency chain; `c` holds the LPC
841 // coefficients. Generic serves LPC orders above 12 (runtime order).
842 template <unsigned Order, bool Fixed, bool Generic>
843 static int64_t predict([[maybe_unused]] const Predictor& p,
844 [[maybe_unused]] const int64_t* c,
845 [[maybe_unused]] const int64_t* x,
846 [[maybe_unused]] size_t i,
847 [[maybe_unused]] int64_t newest) noexcept
848 {
849 if constexpr (Fixed)
850 {
851 if constexpr (Order == 0) return 0;
852 else if constexpr (Order == 1) return newest;
853 else if constexpr (Order == 2) return 2 * newest - x[i - 2];
854 else if constexpr (Order == 3) return 3 * (newest - x[i - 2]) + x[i - 3];
855 else return 4 * (newest + x[i - 3]) - 6 * x[i - 2] - x[i - 4];
856 }
857 else
858 {
859 const unsigned order = Generic ? p.order : Order;
860 int64_t sum = 0;
861 for (unsigned j = order - 1; j > 0; --j)
862 sum += c[j] * x[i - 1 - j];
863 sum += c[0] * newest;
864 return sum >> p.shift;
865 }
866 }
867
868 // Decodes one Rice partition, x[begin, end), restoring each sample as
869 // its residual arrives, so the bit decoding overlaps the predictor's
870 // multiplies. The codes are taken from a 64-bit register refilled whole
871 // bytes at a time; one longer than the bits in hand, or near the end of
872 // the buffer, goes through BitCursor::readRiceCode(). Results,
873 // rejections and the final bit position are those of that code-by-code
874 // reader.
875 template <unsigned Order, bool Fixed, bool Generic>
876 static bool decodeRicePartitionWith(BitCursor& bits, unsigned k,
877 const Predictor& p, int64_t* x,
878 size_t begin, size_t end) noexcept
879 {
880 static_assert(kMaxRiceUnaryZeros >= 64);
881 int64_t c[Fixed ? 1 : (Generic ? 32 : Order)] = {};
882 if constexpr (!Fixed)
883 for (unsigned j = 0; j < (Generic ? 32u : Order); ++j)
884 c[j] = p.coefficients[j];
885 const int64_t low = p.low;
886 const uint64_t span = p.span;
887 const unsigned tail = k + 1u; // stop bit + remainder
888 const uint8_t* data = bits.data();
889 const size_t loadEnd = bits.loadEnd();
890 int64_t newest = begin > 0 ? x[begin - 1] : 0;
891 size_t i = begin;
892 while (i < end)
893 {
894 const size_t position = bits.bitPosition();
895 const size_t byte = position >> 3;
896 if (byte + 8 <= loadEnd)
897 {
898 // The top `avail` bits of `cache` are the stream from
899 // `position` on, and `next` * 8 == position + avail. Bits
900 // below them are zero or the correct following bits, so
901 // OR-ing the next word in at `avail` keeps it exact.
902 const unsigned skip = static_cast<unsigned>(position & 7u);
903 uint64_t cache = BitCursor::loadBigEndian64(data + byte) << skip;
904 unsigned avail = 64u - skip;
905 size_t next = byte + 8;
906 for (; i < end; ++i)
907 {
908 if (avail < 56u)
909 {
910 if (next + 8 > loadEnd) break;
911 cache |= BitCursor::loadBigEndian64(data + next) >> avail;
912 const unsigned take = (63u - avail) >> 3;
913 next += take;
914 avail += take * 8u;
915 }
916 // The low sentinel bit keeps the count defined; a run
917 // that reaches it is longer than `avail` and takes the
918 // code-by-code path. Runs of 63 zeros or fewer are far
919 // below kMaxRiceUnaryZeros.
920 const unsigned zeros = BitCursor::leadingZeros(cache | 1u);
921 if (zeros + tail > avail) break;
922 // `top` starts with the stop bit, so its first k + 1
923 // bits read 2^k + remainder.
924 const uint64_t top = cache << zeros;
925 cache = top << tail;
926 avail -= zeros + tail;
927 const uint64_t folded = (top >> (63u - k))
928 + ((static_cast<uint64_t>(zeros) - 1u) << k);
929 // At most 2^32 - 2 unfolds within +-(2^31 - 1), the
930 // RFC 9639 residual bound.
931 if (folded > 4294967294ull)
932 return false;
933 const int64_t value = (static_cast<int64_t>(folded >> 1)
934 ^ -static_cast<int64_t>(folded & 1u))
935 + predict<Order, Fixed, Generic>(p, c, x, i, newest);
936 if (static_cast<uint64_t>(value - low) >= span)
937 return false;
938 x[i] = value;
939 newest = value;
940 }
941 bits.setBitPosition(next * 8 - avail);
942 if (i == end) break;
943 }
944 int64_t residual = 0;
945 if (!bits.readRiceCode(k, kMaxRiceUnaryZeros, residual))
946 return false;
947 const int64_t value = residual
948 + predict<Order, Fixed, Generic>(p, c, x, i, newest);
949 if (static_cast<uint64_t>(value - low) >= span)
950 return false;
951 x[i++] = value;
952 newest = value;
953 }
954 return true;
955 }
956
957 static bool decodeRicePartition(BitCursor& bits, unsigned k,
958 const Predictor& p, int64_t* x,
959 size_t begin, size_t end) noexcept
960 {
961 if (p.fixed)
962 {
963 switch (p.order)
964 {
965 case 0: return decodeRicePartitionWith<0, true, false>(bits, k, p, x, begin, end);
966 case 1: return decodeRicePartitionWith<1, true, false>(bits, k, p, x, begin, end);
967 case 2: return decodeRicePartitionWith<2, true, false>(bits, k, p, x, begin, end);
968 case 3: return decodeRicePartitionWith<3, true, false>(bits, k, p, x, begin, end);
969 default: return decodeRicePartitionWith<4, true, false>(bits, k, p, x, begin, end);
970 }
971 }
972 switch (p.order)
973 {
974 case 1: return decodeRicePartitionWith<1, false, false>(bits, k, p, x, begin, end);
975 case 2: return decodeRicePartitionWith<2, false, false>(bits, k, p, x, begin, end);
976 case 3: return decodeRicePartitionWith<3, false, false>(bits, k, p, x, begin, end);
977 case 4: return decodeRicePartitionWith<4, false, false>(bits, k, p, x, begin, end);
978 case 5: return decodeRicePartitionWith<5, false, false>(bits, k, p, x, begin, end);
979 case 6: return decodeRicePartitionWith<6, false, false>(bits, k, p, x, begin, end);
980 case 7: return decodeRicePartitionWith<7, false, false>(bits, k, p, x, begin, end);
981 case 8: return decodeRicePartitionWith<8, false, false>(bits, k, p, x, begin, end);
982 case 9: return decodeRicePartitionWith<9, false, false>(bits, k, p, x, begin, end);
983 case 10: return decodeRicePartitionWith<10, false, false>(bits, k, p, x, begin, end);
984 case 11: return decodeRicePartitionWith<11, false, false>(bits, k, p, x, begin, end);
985 case 12: return decodeRicePartitionWith<12, false, false>(bits, k, p, x, begin, end);
986 default: return decodeRicePartitionWith<0, false, true>(bits, k, p, x, begin, end);
987 }
988 }
989
990 // Restores x[begin, end) in place after an escaped (verbatim residual)
991 // partition, with the same arithmetic and checks as the Rice path.
992 static bool restorePartition(const Predictor& p, int64_t* x,
993 size_t begin, size_t end) noexcept
994 {
995 static constexpr int64_t kFixed[5][4] = {
996 { 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 2, -1, 0, 0 },
997 { 3, -3, 1, 0 }, { 4, -6, 4, -1 }
998 };
999 const int64_t* c = p.fixed ? kFixed[p.order] : p.coefficients.data();
1000 const unsigned shift = p.fixed ? 0u : p.shift;
1001 for (size_t i = begin; i < end; ++i)
1002 {
1003 int64_t sum = 0;
1004 for (unsigned j = p.order; j-- > 0;)
1005 sum += c[j] * x[i - 1 - j];
1006 const int64_t value = x[i] + (sum >> shift);
1007 if (static_cast<uint64_t>(value - p.low) >= p.span)
1008 return false;
1009 x[i] = value;
1010 }
1011 return true;
1012 }
1013
1014 // Reads the residual partitions of a predicted subframe whose warm-up
1015 // samples are already in `output`, restoring the samples as it goes.
1016 static bool decodeResidual(BitCursor& bits, uint32_t blockSize,
1017 const Predictor& predictor,
1018 std::span<int64_t> output) noexcept
1019 {
1020 const unsigned predictorOrder = predictor.order;
1021 uint64_t method = 0, partitionOrder = 0;
1022 if (!bits.readBits(2, method) || method > 1
1023 || !bits.readBits(4, partitionOrder))
1024 return false;
1025 const uint32_t partitions = 1u << static_cast<unsigned>(partitionOrder);
1026 if (partitions == 0 || blockSize % partitions != 0)
1027 return false;
1028 const uint32_t partitionSize = blockSize / partitions;
1029 if (partitionSize <= predictorOrder)
1030 return false;
1031 const unsigned parameterBits = method == 0 ? 4u : 5u;
1032 const uint64_t escape = (uint64_t { 1 } << parameterBits) - 1u;
1033 size_t outputIndex = predictorOrder;
1034
1035 for (uint32_t partition = 0; partition < partitions; ++partition)
1036 {
1037 uint64_t parameter = 0;
1038 if (!bits.readBits(parameterBits, parameter)) return false;
1039 const uint32_t count = partitionSize
1040 - (partition == 0 ? static_cast<uint32_t>(predictorOrder) : 0u);
1041 const size_t begin = outputIndex;
1042 outputIndex += count;
1043 if (parameter == escape)
1044 {
1045 uint64_t width = 0;
1046 if (!bits.readBits(5, width) || width > 31) return false;
1047 for (size_t i = begin; i < outputIndex; ++i)
1048 {
1049 int64_t residual = 0;
1050 if (!bits.readSigned(static_cast<unsigned>(width), residual)
1051 || residual < -2147483647ll || residual > 2147483647ll)
1052 return false;
1053 output[i] = residual;
1054 }
1055 if (!restorePartition(predictor, output.data(), begin, outputIndex))
1056 return false;
1057 }
1058 else if (!decodeRicePartition(bits, static_cast<unsigned>(parameter),
1059 predictor, output.data(), begin,
1060 outputIndex))
1061 return false;
1062 }
1063 return outputIndex == output.size();
1064 }
1065
1066 static bool decodeSubframe(BitCursor& bits, uint32_t blockSize,
1067 unsigned storedDepth,
1068 std::span<int64_t> output) noexcept
1069 {
1070 uint64_t zero = 0, type = 0, wastedFlag = 0;
1071 if (!bits.readBits(1, zero) || zero != 0
1072 || !bits.readBits(6, type)
1073 || !bits.readBits(1, wastedFlag))
1074 return false;
1075
1076 unsigned wasted = 0;
1077 if (wastedFlag != 0)
1078 {
1079 uint64_t zeros = 0;
1080 if (!bits.readUnary(32, zeros) || zeros >= storedDepth)
1081 return false;
1082 wasted = static_cast<unsigned>(zeros + 1);
1083 }
1084 if (storedDepth <= wasted)
1085 return false;
1086 const unsigned depth = storedDepth - wasted;
1087
1088 unsigned predictorOrder = 0;
1089 Predictor predictor;
1090 predictor.low = -(int64_t { 1 } << (depth - 1));
1091 predictor.span = uint64_t { 1 } << depth;
1092 if (type == 0)
1093 {
1094 int64_t value = 0;
1095 if (!bits.readSigned(depth, value)) return false;
1096 std::fill(output.begin(), output.end(), value);
1097 }
1098 else if (type == 1)
1099 {
1100 for (int64_t& value : output)
1101 if (!bits.readSigned(depth, value)) return false;
1102 }
1103 else if (type >= 8 && type <= 12)
1104 {
1105 predictorOrder = static_cast<unsigned>(type - 8);
1106 if (predictorOrder > blockSize) return false;
1107 for (unsigned i = 0; i < predictorOrder; ++i)
1108 if (!bits.readSigned(depth, output[i])) return false;
1109 predictor.order = predictorOrder;
1110 if (!decodeResidual(bits, blockSize, predictor, output))
1111 return false;
1112 }
1113 else if (type >= 32 && type <= 63)
1114 {
1115 predictorOrder = static_cast<unsigned>(type - 31);
1116 if (predictorOrder > blockSize) return false;
1117 for (unsigned i = 0; i < predictorOrder; ++i)
1118 if (!bits.readSigned(depth, output[i])) return false;
1119 uint64_t precisionMinusOne = 0;
1120 int64_t shift = 0;
1121 if (!bits.readBits(4, precisionMinusOne) || precisionMinusOne == 15
1122 || !bits.readSigned(5, shift) || shift < 0)
1123 return false;
1124 const unsigned precision = static_cast<unsigned>(precisionMinusOne + 1);
1125 predictor.order = predictorOrder;
1126 predictor.fixed = false;
1127 predictor.shift = static_cast<unsigned>(shift);
1128 for (unsigned i = 0; i < predictorOrder; ++i)
1129 if (!bits.readSigned(precision, predictor.coefficients[i])) return false;
1130 if (!decodeResidual(bits, blockSize, predictor, output))
1131 return false;
1132 }
1133 else
1134 return false;
1135
1136 if (type <= 1)
1137 for (int64_t value : output)
1138 if (!sampleInDepth(value, depth)) return false;
1139
1140 if (wasted != 0)
1141 {
1142 // |value| <= 2^(depth - 1), so value * 2^wasted stays within
1143 // storedDepth <= 33 bits: no overflow is possible.
1144 const int64_t factor = int64_t { 1 } << wasted;
1145 for (int64_t& value : output)
1146 {
1147 value *= factor;
1148 if (!sampleInDepth(value, storedDepth))
1149 return false;
1150 }
1151 }
1152 return true;
1153 }
1154
1155 static bool restoreChannels(uint8_t channelCode, uint8_t bitsPerSample,
1156 uint32_t blockSize,
1157 std::vector<int64_t>& pcm) noexcept
1158 {
1159 // Independent channels were decoded at the stream depth, every
1160 // sample checked against it as it was produced (decodeSubframe), so
1161 // they need no second pass.
1162 if (channelCode < 8)
1163 return true;
1164
1165 // Both inputs are within 33 bits (the side channel's depth + 1), so
1166 // none of the sums below can overflow int64; only the restored
1167 // samples need their range checked. An arithmetic right shift is
1168 // the floor division by two that RFC 9639 specifies.
1169 int64_t* first = pcm.data();
1170 int64_t* second = pcm.data() + blockSize;
1171 const int64_t low = -(int64_t { 1 } << (bitsPerSample - 1));
1172 const uint64_t span = uint64_t { 1 } << bitsPerSample;
1173 uint64_t outside = 0;
1174 if (channelCode == 8)
1175 {
1176 for (uint32_t i = 0; i < blockSize; ++i)
1177 {
1178 const int64_t right = first[i] - second[i];
1179 outside |= static_cast<uint64_t>(static_cast<uint64_t>(right - low) >= span);
1180 second[i] = right;
1181 }
1182 }
1183 else if (channelCode == 9)
1184 {
1185 for (uint32_t i = 0; i < blockSize; ++i)
1186 {
1187 const int64_t left = first[i] + second[i];
1188 outside |= static_cast<uint64_t>(static_cast<uint64_t>(left - low) >= span);
1189 first[i] = left;
1190 }
1191 }
1192 else
1193 {
1194 for (uint32_t i = 0; i < blockSize; ++i)
1195 {
1196 const int64_t side = second[i];
1197 const int64_t mid = first[i] * 2 + (side & 1);
1198 const int64_t left = (mid + side) >> 1;
1199 const int64_t right = (mid - side) >> 1;
1200 outside |= static_cast<uint64_t>(static_cast<uint64_t>(left - low) >= span)
1201 | static_cast<uint64_t>(static_cast<uint64_t>(right - low) >= span);
1202 first[i] = left;
1203 second[i] = right;
1204 }
1205 }
1206 return outside == 0;
1207 }
1208
1209 static bool decodeFrame(const std::vector<uint8_t>& bytes, size_t offset,
1210 const StreamInfo& stream, size_t expectedFrameNumber,
1211 uint64_t expectedFirstSample,
1212 std::vector<int64_t>& pcm,
1213 DecodedFrame& decoded)
1214 {
1215 if (offset > bytes.size() || bytes.size() - offset < 8)
1216 return false;
1217 ByteCursor cursor(bytes, offset, bytes.size());
1218 uint8_t first = 0, second = 0, third = 0, fourth = 0;
1219 if (!cursor.readU8(first) || !cursor.readU8(second)
1220 || !cursor.readU8(third) || !cursor.readU8(fourth)
1221 || first != 0xff || (second & 0xfeu) != 0xf8u
1222 || (fourth & 1u) != 0)
1223 return false;
1224 // The strategy bit chooses what the coded number counts. RFC 9639
1225 // B.1: before the bit existed (2007) a variable stream was marked
1226 // only by STREAMINFO min != max, with the bit at 0 and sample
1227 // numbers coded, so such a frame may carry either kind; a modern
1228 // fixed stream whose STREAMINFO lists unequal bounds is also legal.
1229 // (Encoders also write the bit with min == max; reference decoders
1230 // accept that, and so does this one.)
1231 const bool variable = (second & 1u) != 0;
1232 const bool legacyCandidate = !variable
1233 && stream.minBlockSize != stream.maxBlockSize;
1234 const uint8_t blockCode = third >> 4;
1235 const uint8_t rateCode = third & 0x0fu;
1236 const uint8_t channelCode = fourth >> 4;
1237 const uint8_t depthCode = (fourth >> 1) & 7u;
1238 if (channelCode > 10 || depthCode == 3)
1239 return false;
1240 const uint8_t channels = channelCode <= 7
1241 ? static_cast<uint8_t>(channelCode + 1) : uint8_t { 2 };
1242 static constexpr uint8_t depths[8] = { 0, 8, 12, 0, 16, 20, 24, 32 };
1243 const uint8_t bitDepth = depthCode == 0 ? stream.bitsPerSample : depths[depthCode];
1244 if (channels != stream.channels || bitDepth != stream.bitsPerSample)
1245 return false;
1246
1247 uint64_t codedNumber = 0;
1248 if (!parseCodedNumber(cursor, variable || legacyCandidate, codedNumber))
1249 return false;
1250 decoded.numberIsSample = (variable || legacyCandidate)
1251 && codedNumber == expectedFirstSample;
1252 decoded.numberIsFrame = !variable && codedNumber == expectedFrameNumber;
1253 if (!decoded.numberIsSample && !decoded.numberIsFrame)
1254 return false;
1255
1256 uint32_t blockSize = 0, sampleRate = 0;
1257 if (!decodeBlockSize(blockCode, cursor, blockSize)
1258 || !decodeSampleRate(rateCode, cursor, stream, sampleRate)
1259 || blockSize > stream.maxBlockSize)
1260 return false;
1261
1262 const size_t crcPosition = cursor.position();
1263 uint8_t storedCrc8 = 0;
1264 if (!cursor.readU8(storedCrc8)
1265 || crc8(std::span<const uint8_t>(bytes.data() + offset,
1266 crcPosition - offset)) != storedCrc8)
1267 return false;
1268
1269 if (static_cast<uint64_t>(blockSize) * channels
1270 > static_cast<uint64_t>(std::numeric_limits<size_t>::max()))
1271 return false;
1272 pcm.resize(static_cast<size_t>(blockSize) * channels);
1273 BitCursor bits(bytes, cursor.position(), bytes.size());
1274 for (uint8_t channel = 0; channel < channels; ++channel)
1275 {
1276 unsigned depth = bitDepth;
1277 if ((channelCode == 8 && channel == 1)
1278 || (channelCode == 9 && channel == 0)
1279 || (channelCode == 10 && channel == 1))
1280 ++depth;
1281 std::span<int64_t> channelPcm(
1282 pcm.data() + static_cast<size_t>(channel) * blockSize, blockSize);
1283 if (!decodeSubframe(bits, blockSize, depth, channelPcm))
1284 return false;
1285 }
1286 if (!bits.alignWithZeroPadding())
1287 return false;
1288 const size_t footerPosition = bits.bytePosition();
1289 if (footerPosition > bytes.size() || bytes.size() - footerPosition < 2)
1290 return false;
1291 const uint16_t storedCrc16 = static_cast<uint16_t>(
1292 (static_cast<uint16_t>(bytes[footerPosition]) << 8)
1293 | bytes[footerPosition + 1]);
1294 if (crc16(std::span<const uint8_t>(bytes.data() + offset,
1295 footerPosition - offset)) != storedCrc16)
1296 return false;
1297 if (!restoreChannels(channelCode, bitDepth, blockSize, pcm))
1298 return false;
1299
1300 decoded.endOffset = footerPosition + 2;
1301 decoded.blockSize = blockSize;
1302 decoded.variableBlock = variable;
1303 return true;
1304 }
1305
1306 static bool updateMd5(Md5& md5, const std::vector<int64_t>& pcm,
1307 uint8_t channels, uint8_t bitsPerSample,
1308 uint32_t blockSize, std::vector<uint8_t>& scratch)
1309 {
1310 // Interleaved little-endian samples of ceil(depth / 8) bytes (RFC
1311 // 9639 8.2), built for the whole block and hashed in one call.
1312 const unsigned bytesPerSample = (bitsPerSample + 7u) / 8u;
1313 if (bytesPerSample < 1 || bytesPerSample > 4)
1314 return false;
1315 scratch.resize(static_cast<size_t>(blockSize) * channels * bytesPerSample);
1316 switch (bytesPerSample)
1317 {
1318 case 1: interleaveLittleEndian<1>(pcm.data(), channels, blockSize, scratch.data()); break;
1319 case 2: interleaveLittleEndian<2>(pcm.data(), channels, blockSize, scratch.data()); break;
1320 case 3: interleaveLittleEndian<3>(pcm.data(), channels, blockSize, scratch.data()); break;
1321 default: interleaveLittleEndian<4>(pcm.data(), channels, blockSize, scratch.data()); break;
1322 }
1323 md5.update(std::span<const uint8_t>(scratch.data(), scratch.size()));
1324 return true;
1325 }
1326
1327 template <unsigned Bytes>
1328 static void interleaveLittleEndian(const int64_t* pcm, uint8_t channels,
1329 uint32_t blockSize, uint8_t* scratch) noexcept
1330 {
1331 const size_t stride = static_cast<size_t>(channels) * Bytes;
1332 for (uint8_t channel = 0; channel < channels; ++channel)
1333 {
1334 const int64_t* source = pcm + static_cast<size_t>(channel) * blockSize;
1335 uint8_t* out = scratch + static_cast<size_t>(channel) * Bytes;
1336 for (uint32_t sample = 0; sample < blockSize; ++sample, out += stride)
1337 {
1338 const auto value = static_cast<uint32_t>(static_cast<uint64_t>(source[sample]));
1339 for (unsigned k = 0; k < Bytes; ++k)
1340 out[k] = static_cast<uint8_t>(value >> (8 * k));
1341 }
1342 }
1343 }
1344
1345 static bool allZero(const std::array<uint8_t, 16>& value) noexcept
1346 {
1347 for (uint8_t byte : value) if (byte != 0) return false;
1348 return true;
1349 }
1350
1351 static bool validateOpen(OpenState& state)
1352 {
1353 if (state.bytes.size() < 4
1354 || std::memcmp(state.bytes.data(), "fLaC", 4) != 0)
1355 return false;
1356 ByteCursor cursor(state.bytes, 4, state.bytes.size());
1357 uint64_t metadataBlocks = 0;
1358 bool sawStreamInfo = false;
1359 bool lastMetadata = false;
1360
1361 while (!lastMetadata)
1362 {
1363 if (metadataBlocks >= kMaxMetadataBlocks) return false;
1364 ++metadataBlocks;
1365 uint8_t header = 0;
1366 uint32_t length = 0;
1367 if (!cursor.readU8(header) || !cursor.readBE24(length))
1368 return false;
1369 lastMetadata = (header & 0x80u) != 0;
1370 const uint8_t type = header & 0x7fu;
1371 if (type == 127 || length > cursor.remaining())
1372 return false;
1373 const uint8_t* data = nullptr;
1374 if (!cursor.readSpan(length, data))
1375 return false;
1376 if (!sawStreamInfo)
1377 {
1378 if (type != 0 || length != 34
1379 || !parseStreamInfo(data, state.stream))
1380 return false;
1381 sawStreamInfo = true;
1382 }
1383 else if (type == 0)
1384 return false;
1385 }
1386 if (!sawStreamInfo || cursor.remaining() == 0)
1387 return false;
1388
1389 Md5 md5;
1390 // A zero digest means "not computed": there is nothing to compare,
1391 // so the work is skipped (it dominated the open time of large files).
1392 const bool checkMd5 = !allZero(state.stream.md5);
1393 std::vector<uint8_t> md5Scratch;
1394 uint64_t coverage = 0;
1395 bool haveStrategy = false;
1396 bool strategy = false;
1397 int numbering = 0; // 0 undecided, 1 frame numbers, 2 sample numbers
1398 uint32_t firstBlockSize = 0;
1399 uint32_t previousBlockSize = 0;
1400 std::vector<int64_t> pcm;
1401 while (cursor.remaining() > 0)
1402 {
1403 if (state.frames.size() >= kMaxFrames)
1404 return false;
1405
1406 DecodedFrame decoded;
1407 const size_t frameOffset = cursor.position();
1408 if (!decodeFrame(state.bytes, frameOffset, state.stream,
1409 state.frames.size(), coverage, pcm, decoded)
1410 || decoded.endOffset <= frameOffset
1411 || decoded.endOffset > state.bytes.size())
1412 return false;
1413 if (haveStrategy && decoded.variableBlock != strategy)
1414 return false;
1415 // The first frame numbers both ways (0); the first frame that
1416 // tells them apart fixes the numbering for the whole stream.
1417 const int frameNumbering = decoded.numberIsFrame == decoded.numberIsSample
1418 ? 0 : (decoded.numberIsFrame ? 1 : 2);
1419 if (frameNumbering != 0)
1420 {
1421 if (numbering != 0 && numbering != frameNumbering)
1422 return false;
1423 numbering = frameNumbering;
1424 }
1425 // Rules for every frame but the last, checked now that a later
1426 // frame exists: at least the STREAMINFO minimum, and in a
1427 // frame-numbered (fixed) stream the size of the first frame.
1428 if (haveStrategy)
1429 {
1430 if (previousBlockSize < state.stream.minBlockSize)
1431 return false;
1432 if (numbering == 1 && previousBlockSize != firstBlockSize)
1433 return false;
1434 }
1435 if (!haveStrategy)
1436 firstBlockSize = decoded.blockSize;
1437 haveStrategy = true;
1438 strategy = decoded.variableBlock;
1439 previousBlockSize = decoded.blockSize;
1440 const size_t frameSize = decoded.endOffset - frameOffset;
1441 if ((state.stream.minFrameSize != 0
1442 && frameSize < state.stream.minFrameSize)
1443 || (state.stream.maxFrameSize != 0
1444 && frameSize > state.stream.maxFrameSize))
1445 return false;
1446 if (coverage > kMaxInterchannelSamples - decoded.blockSize)
1447 return false;
1448 const uint64_t firstSample = coverage;
1449 coverage += decoded.blockSize;
1450 const uint64_t bytesPerSample = (state.stream.bitsPerSample + 7u) / 8u;
1451 if (coverage > kMaxDecodedPcmBytes
1452 / (static_cast<uint64_t>(state.stream.channels) * bytesPerSample))
1453 return false;
1454 if (checkMd5 && !updateMd5(md5, pcm, state.stream.channels,
1455 state.stream.bitsPerSample, decoded.blockSize,
1456 md5Scratch))
1457 return false;
1458 state.frames.push_back({ frameOffset, frameSize, firstSample,
1459 decoded.blockSize });
1460 if (!cursor.skip(frameSize))
1461 return false;
1462 }
1463
1464 if (state.frames.empty() || coverage == 0
1465 || (state.stream.declaredSamples != 0
1466 && state.stream.declaredSamples != coverage))
1467 return false;
1468 if (checkMd5 && md5.finish() != state.stream.md5)
1469 return false;
1470
1471 state.info.sampleRate = static_cast<double>(state.stream.sampleRate);
1472 state.info.numChannels = state.stream.channels;
1473 state.info.numSamples = static_cast<int64_t>(coverage);
1474 state.info.bitsPerSample = state.stream.bitsPerSample;
1475 state.info.isFloatingPoint = false;
1476 return true;
1477 }
1478};
1479
1480} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Abstract base class for audio file readers and writers.
Definition AudioFile.h:111
Decode-only native FLAC implementation with eager integrity checks.
Definition FlacFile.h:54
static constexpr uint64_t kMaxDecodedPcmBytes
Maximum logical decoded PCM byte count.
Definition FlacFile.h:65
bool isOpen() const noexcept override
True only after a complete stream has passed eager validation.
Definition FlacFile.h:228
bool openRead(const std::filesystem::path &path) override
Opens and fully validates a native FLAC stream.
Definition FlacFile.h:78
static constexpr uint64_t kMaxInterchannelSamples
Maximum decoded interchannel sample count.
Definition FlacFile.h:63
static constexpr uint64_t kMaxFrames
Maximum number of indexed audio frames.
Definition FlacFile.h:61
bool openWrite(const std::filesystem::path &path, const AudioFileInfo &info) override
FLAC encoding is unsupported; closes prior state and returns false.
Definition FlacFile.h:116
static constexpr uint64_t kMaxMetadataBlocks
Maximum number of metadata block headers scanned.
Definition FlacFile.h:59
AudioFileInfo getInfo() const override
Returns current stream metadata, or default metadata when closed.
Definition FlacFile.h:126
static constexpr uint64_t kMaxInputBytes
Maximum compressed input retained by one instance.
Definition FlacFile.h:57
static constexpr std::string_view kWriteUnsupportedReason
Stable explanation returned by documentation for write failure.
Definition FlacFile.h:69
bool readSamples(AudioBufferView< float > dest) override
Reads from sample zero, clamped to the destination dimensions.
Definition FlacFile.h:129
~FlacFile() override
Definition FlacFile.h:72
bool writeSamples(AudioBufferView< const float > src) override
Always returns false because this class is decode-only.
Definition FlacFile.h:211
bool readSamples(AudioBufferView< float > dest, int64_t startFrame, int64_t numFrames) override
Decodes an exact valid file range into the destination capacity.
Definition FlacFile.h:141
void close() override
Releases compressed data, metadata, and the frame index.
Definition FlacFile.h:218
static constexpr uint64_t kMaxRiceUnaryZeros
Maximum zero run accepted in one Rice unary code.
Definition FlacFile.h:67
@ Fixed
The window is exactly editorSize; hosts cannot drag-resize it.
Main namespace for the DSPark framework.
Metadata describing an audio file's format and dimensions.
Definition AudioFile.h:39
uint32_t numChannels
Number of audio channels (1 = mono, 2 = stereo).
Definition AudioFile.h:44
int64_t numSamples
Total number of sample frames in the file.
Definition AudioFile.h:47