70 "FlacFile is decode-only; FLAC encoding is not supported.";
78 [[nodiscard]]
bool openRead(
const std::filesystem::path& path)
override
82 std::ifstream input(path, std::ios::binary | std::ios::ate);
85 const std::streampos end = input.tellg();
86 if (end <= std::streampos(0))
88 const uint64_t fileSize =
static_cast<uint64_t
>(end);
90 || fileSize >
static_cast<uint64_t
>(std::numeric_limits<size_t>::max()))
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()))
100 if (!validateOpen(candidate))
103 bytes_ = std::move(candidate.bytes);
104 frames_ = std::move(candidate.frames);
105 stream_ = candidate.stream;
106 info_ = candidate.info;
116 [[nodiscard]]
bool openWrite(
const std::filesystem::path& path,
131 if (!open_)
return false;
143 int64_t numFrames)
override
145 if (!open_ || startFrame < 0 || numFrames <= 0)
153 const int channelsToCopy = std::min(destChannels,
155 const int64_t framesToCopy = std::min<int64_t>(numFrames, destSamples);
156 if (channelsToCopy == 0 || framesToCopy == 0)
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;
167 std::vector<int64_t> pcm;
168 while (it != frames_.end() && it->firstSample < last)
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)
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);
190 const float scale = std::ldexp(1.0f, 1 -
static_cast<int>(stream_.bitsPerSample));
191 for (
int channel = 0; channel < channelsToCopy; ++channel)
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;
199 written +=
static_cast<int64_t
>(count);
202 if (written != framesToCopy)
220 std::vector<uint8_t>().swap(bytes_);
221 std::vector<FrameIndex>().swap(frames_);
228 [[nodiscard]]
bool isOpen() const noexcept
override {
return open_; }
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 {};
248 uint64_t firstSample = 0;
249 uint32_t blockSize = 0;
254 size_t endOffset = 0;
255 uint32_t blockSize = 0;
256 bool variableBlock =
false;
257 bool numberIsSample =
false;
258 bool numberIsFrame =
false;
263 std::vector<uint8_t> bytes;
264 std::vector<FrameIndex> frames;
272 ByteCursor(
const std::vector<uint8_t>& bytes,
size_t begin,
size_t end)
273 : bytes_(bytes), pos_(begin), end_(end)
277 [[nodiscard]]
size_t position() const noexcept {
return pos_; }
278 [[nodiscard]]
size_t remaining() const noexcept {
return end_ - pos_; }
280 bool readU8(uint8_t& value)
noexcept
282 if (pos_ >= end_)
return false;
283 value = bytes_[pos_++];
287 bool readBE16(uint16_t& value)
noexcept
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));
296 bool readBE24(uint32_t& value)
noexcept
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);
306 bool readSpan(
size_t length,
const uint8_t*& data)
noexcept
308 if (length > remaining())
return false;
309 data = bytes_.data() + pos_;
314 bool skip(
size_t length)
noexcept
316 const uint8_t* ignored =
nullptr;
317 return readSpan(length, ignored);
321 const std::vector<uint8_t>& bytes_;
329 BitCursor(
const std::vector<uint8_t>& bytes,
size_t beginByte,
331 : bytes_(bytes), bitPos_(beginByte * 8), endBit_(endByte * 8)
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
339 return static_cast<uint64_t
>(endBit_ - bitPos_);
342 bool readBits(
unsigned count, uint64_t& value)
noexcept
345 if (count > 64 ||
static_cast<uint64_t
>(count) > remainingBits())
349 const size_t byte = bitPos_ >> 3;
350 const unsigned offset =
static_cast<unsigned>(bitPos_ & 7u);
354 if (count + offset <= 64 &&
byte + 8 <= bytes_.size())
356 value = (loadBigEndian64(bytes_.data() +
byte) << offset) >> (64u - count);
360 for (
unsigned i = 0; i < count; ++i)
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);
370 bool readSigned(
unsigned count, int64_t& value)
noexcept
377 if (count > 63)
return false;
379 if (!readBits(count, raw))
return false;
380 const uint64_t sign = uint64_t { 1 } << (count - 1);
381 if ((raw & sign) == 0)
383 value =
static_cast<int64_t
>(raw);
386 const uint64_t magnitude = (uint64_t { 1 } << count) - raw;
387 value = -
static_cast<int64_t
>(magnitude);
391 bool readUnary(uint64_t limit, uint64_t& zeros)
noexcept
398 const size_t byte = bitPos_ >> 3;
399 if (
byte + 8 <= bytes_.size() && endBit_ - bitPos_ >= 64)
401 const unsigned offset =
static_cast<unsigned>(bitPos_ & 7u);
402 const uint64_t window = (loadBigEndian64(bytes_.data() +
byte) << offset)
403 & ~uint64_t { 0xff };
406 const unsigned run =
static_cast<unsigned>(std::countl_zero(window));
407 if (zeros + run > limit)
return false;
412 const unsigned run = 56u - offset;
413 if (zeros + run <= limit)
421 if (!readBits(1, bit))
return false;
422 if (bit != 0)
return true;
423 if (zeros >= limit)
return false;
434 bool readRiceCode(
unsigned k, uint64_t unaryLimit, int64_t& residual)
noexcept
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))
441 const uint64_t folded = (quotient << k) | remainder;
442 if (folded > 4294967294ull)
444 residual =
static_cast<int64_t
>(folded >> 1)
445 ^ -
static_cast<int64_t
>(folded & 1u);
452 [[nodiscard]]
const uint8_t* data() const noexcept {
return bytes_.data(); }
453 [[nodiscard]]
size_t loadEnd() const noexcept
455 return std::min(endBit_ >> 3, bytes_.size());
457 void setBitPosition(
size_t position)
noexcept { bitPos_ = position; }
459 bool alignWithZeroPadding() noexcept
461 while ((bitPos_ & 7u) != 0)
464 if (!readBits(1, bit) || bit != 0)
return false;
473 static unsigned leadingZeros(uint64_t nonZero)
noexcept
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);
480 return static_cast<unsigned>(std::countl_zero(nonZero));
484 static uint64_t loadBigEndian64(
const uint8_t* p)
noexcept
487 std::memcpy(&word, p,
sizeof(word));
488 if constexpr (std::endian::native == std::endian::little)
490#if defined(_MSC_VER) && !defined(__clang__)
491 word = _byteswap_uint64(word);
493 word = __builtin_bswap64(word);
500 const std::vector<uint8_t>& bytes_;
508 Md5() noexcept { reset(); }
510 void update(std::span<const uint8_t> data)
noexcept
512 totalBytes_ += data.size();
513 while (!data.empty())
516 if (bufferSize_ == 0 && data.size() >= buffer_.size())
518 transform(data.data());
519 data = data.subspan(buffer_.size());
522 const size_t take = std::min(data.size(), buffer_.size() - bufferSize_);
523 std::memcpy(buffer_.data() + bufferSize_, data.data(), take);
525 data = data.subspan(take);
526 if (bufferSize_ == buffer_.size())
528 transform(buffer_.data());
534 [[nodiscard]] std::array<uint8_t, 16> finish() noexcept
536 const uint64_t messageBits = totalBytes_ * 8;
537 std::array<uint8_t, 120> padding {};
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));
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));
556 std::array<uint32_t, 4> state_ {};
557 std::array<uint8_t, 64> buffer_ {};
558 size_t bufferSize_ = 0;
559 uint64_t totalBytes_ = 0;
561 void reset() noexcept
563 state_ = { 0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u };
568 static uint32_t rotateLeft(uint32_t value,
unsigned count)
noexcept
570 return static_cast<uint32_t
>((value << count) | (value >> (32 - count)));
573 void transform(
const uint8_t* block)
noexcept
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
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
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);
607 uint32_t a = state_[0], b = state_[1], c = state_[2], d = state_[3];
608 for (
unsigned i = 0; i < 64; ++i)
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;
627 std::vector<uint8_t> bytes_;
628 std::vector<FrameIndex> frames_;
630 AudioFileInfo info_ {};
633 static uint8_t crc8(std::span<const uint8_t> data)
noexcept
636 for (uint8_t
byte : data)
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));
647 static uint16_t crc16(std::span<const uint8_t> data)
noexcept
656 static constexpr auto kTables = [] {
657 std::array<std::array<uint16_t, 256>, 8> tables {};
658 for (
unsigned i = 0; i < 256; ++i)
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));
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]);
674 const uint8_t* p = data.data();
675 size_t n = data.size();
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);
689 static bool sampleInDepth(int64_t value,
unsigned depth)
noexcept
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;
696 static bool parseStreamInfo(
const uint8_t* data, StreamInfo& info)
noexcept
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());
720 if (info.minBlockSize < 16 || info.maxBlockSize < 16
721 || info.minBlockSize > info.maxBlockSize)
723 if (info.minFrameSize != 0 && info.maxFrameSize != 0
724 && info.minFrameSize > info.maxFrameSize)
726 if (info.sampleRate == 0 || info.sampleRate > 1048575
727 || info.channels == 0 || info.channels > 8
728 || info.bitsPerSample < 4 || info.bitsPerSample > 32
734 static bool parseCodedNumber(ByteCursor& cursor,
bool variable,
735 uint64_t& value)
noexcept
738 if (!cursor.readU8(first))
return false;
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; }
750 for (
unsigned i = 1; i < length; ++i)
752 uint8_t continuation = 0;
753 if (!cursor.readU8(continuation) || (continuation & 0xc0u) != 0x80u)
755 value = (value << 6) | (continuation & 0x3fu);
757 if (length > 1 && value < minimum)
760 return value <= 0xfffffffffull;
761 return length <= 6 && value <= 0x7fffffffu;
764 static bool decodeBlockSize(uint8_t code, ByteCursor& cursor,
765 uint32_t& blockSize)
noexcept
767 if (code == 0)
return false;
768 if (code == 1) blockSize = 192;
769 else if (code >= 2 && code <= 5)
770 blockSize = 576u << (code - 2u);
774 if (!cursor.readU8(value))
return false;
775 blockSize =
static_cast<uint32_t
>(value) + 1u;
780 if (!cursor.readBE16(value) || value == 0xffffu)
return false;
781 blockSize =
static_cast<uint32_t
>(value) + 1u;
784 blockSize = 1u << code;
785 return blockSize > 0 && blockSize <= 65535;
788 static bool decodeSampleRate(uint8_t code, ByteCursor& cursor,
789 const StreamInfo& stream,
790 uint32_t& sampleRate)
noexcept
792 static constexpr uint32_t rates[12] = {
793 0, 88200, 176400, 192000, 8000, 16000,
794 22050, 24000, 32000, 44100, 48000, 96000
797 sampleRate = code == 0 ? stream.sampleRate : rates[code];
801 if (!cursor.readU8(value))
return false;
802 sampleRate =
static_cast<uint32_t
>(value) * 1000u;
807 if (!cursor.readBE16(value))
return false;
813 if (!cursor.readBE16(value))
return false;
814 sampleRate =
static_cast<uint32_t
>(value) * 10u;
817 return sampleRate != 0 && sampleRate == stream.sampleRate;
834 std::array<int64_t, 32> coefficients {};
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
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];
859 const unsigned order = Generic ? p.order : Order;
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;
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
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;
888 const uint8_t* data = bits.data();
889 const size_t loadEnd = bits.loadEnd();
890 int64_t newest = begin > 0 ? x[begin - 1] : 0;
894 const size_t position = bits.bitPosition();
895 const size_t byte = position >> 3;
896 if (
byte + 8 <= loadEnd)
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;
910 if (next + 8 > loadEnd)
break;
911 cache |= BitCursor::loadBigEndian64(data + next) >> avail;
912 const unsigned take = (63u - avail) >> 3;
920 const unsigned zeros = BitCursor::leadingZeros(cache | 1u);
921 if (zeros + tail > avail)
break;
924 const uint64_t top = cache << zeros;
926 avail -= zeros + tail;
927 const uint64_t folded = (top >> (63u - k))
928 + ((
static_cast<uint64_t
>(zeros) - 1u) << k);
931 if (folded > 4294967294ull)
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)
941 bits.setBitPosition(next * 8 - avail);
944 int64_t residual = 0;
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)
957 static bool decodeRicePartition(BitCursor& bits,
unsigned k,
958 const Predictor& p, int64_t* x,
959 size_t begin,
size_t end)
noexcept
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);
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);
992 static bool restorePartition(
const Predictor& p, int64_t* x,
993 size_t begin,
size_t end)
noexcept
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 }
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)
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)
1016 static bool decodeResidual(BitCursor& bits, uint32_t blockSize,
1017 const Predictor& predictor,
1018 std::span<int64_t> output)
noexcept
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))
1025 const uint32_t partitions = 1u <<
static_cast<unsigned>(partitionOrder);
1026 if (partitions == 0 || blockSize % partitions != 0)
1028 const uint32_t partitionSize = blockSize / partitions;
1029 if (partitionSize <= predictorOrder)
1031 const unsigned parameterBits = method == 0 ? 4u : 5u;
1032 const uint64_t escape = (uint64_t { 1 } << parameterBits) - 1u;
1033 size_t outputIndex = predictorOrder;
1035 for (uint32_t partition = 0; partition < partitions; ++partition)
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)
1046 if (!bits.readBits(5, width) || width > 31)
return false;
1047 for (
size_t i = begin; i < outputIndex; ++i)
1049 int64_t residual = 0;
1050 if (!bits.readSigned(
static_cast<unsigned>(width), residual)
1051 || residual < -2147483647ll || residual > 2147483647ll)
1053 output[i] = residual;
1055 if (!restorePartition(predictor, output.data(), begin, outputIndex))
1058 else if (!decodeRicePartition(bits,
static_cast<unsigned>(parameter),
1059 predictor, output.data(), begin,
1063 return outputIndex == output.size();
1066 static bool decodeSubframe(BitCursor& bits, uint32_t blockSize,
1067 unsigned storedDepth,
1068 std::span<int64_t> output)
noexcept
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))
1076 unsigned wasted = 0;
1077 if (wastedFlag != 0)
1080 if (!bits.readUnary(32, zeros) || zeros >= storedDepth)
1082 wasted =
static_cast<unsigned>(zeros + 1);
1084 if (storedDepth <= wasted)
1086 const unsigned depth = storedDepth - wasted;
1088 unsigned predictorOrder = 0;
1089 Predictor predictor;
1090 predictor.low = -(int64_t { 1 } << (depth - 1));
1091 predictor.span = uint64_t { 1 } << depth;
1095 if (!bits.readSigned(depth, value))
return false;
1096 std::fill(output.begin(), output.end(), value);
1100 for (int64_t& value : output)
1101 if (!bits.readSigned(depth, value)) return false;
1103 else if (type >= 8 && type <= 12)
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))
1113 else if (type >= 32 && type <= 63)
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;
1121 if (!bits.readBits(4, precisionMinusOne) || precisionMinusOne == 15
1122 || !bits.readSigned(5, shift) || shift < 0)
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))
1137 for (int64_t value : output)
1138 if (!sampleInDepth(value, depth)) return false;
1144 const int64_t factor = int64_t { 1 } << wasted;
1145 for (int64_t& value : output)
1148 if (!sampleInDepth(value, storedDepth))
1155 static bool restoreChannels(uint8_t channelCode, uint8_t bitsPerSample,
1157 std::vector<int64_t>& pcm)
noexcept
1162 if (channelCode < 8)
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)
1176 for (uint32_t i = 0; i < blockSize; ++i)
1178 const int64_t right = first[i] - second[i];
1179 outside |=
static_cast<uint64_t
>(
static_cast<uint64_t
>(right - low) >= span);
1183 else if (channelCode == 9)
1185 for (uint32_t i = 0; i < blockSize; ++i)
1187 const int64_t left = first[i] + second[i];
1188 outside |=
static_cast<uint64_t
>(
static_cast<uint64_t
>(left - low) >= span);
1194 for (uint32_t i = 0; i < blockSize; ++i)
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);
1206 return outside == 0;
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)
1215 if (offset > bytes.size() || bytes.size() - offset < 8)
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)
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)
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)
1247 uint64_t codedNumber = 0;
1248 if (!parseCodedNumber(cursor, variable || legacyCandidate, codedNumber))
1250 decoded.numberIsSample = (variable || legacyCandidate)
1251 && codedNumber == expectedFirstSample;
1252 decoded.numberIsFrame = !variable && codedNumber == expectedFrameNumber;
1253 if (!decoded.numberIsSample && !decoded.numberIsFrame)
1256 uint32_t blockSize = 0, sampleRate = 0;
1257 if (!decodeBlockSize(blockCode, cursor, blockSize)
1258 || !decodeSampleRate(rateCode, cursor, stream, sampleRate)
1259 || blockSize > stream.maxBlockSize)
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)
1269 if (
static_cast<uint64_t
>(blockSize) * channels
1270 >
static_cast<uint64_t
>(std::numeric_limits<size_t>::max()))
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)
1276 unsigned depth = bitDepth;
1277 if ((channelCode == 8 && channel == 1)
1278 || (channelCode == 9 && channel == 0)
1279 || (channelCode == 10 && channel == 1))
1281 std::span<int64_t> channelPcm(
1282 pcm.data() +
static_cast<size_t>(channel) * blockSize, blockSize);
1283 if (!decodeSubframe(bits, blockSize, depth, channelPcm))
1286 if (!bits.alignWithZeroPadding())
1288 const size_t footerPosition = bits.bytePosition();
1289 if (footerPosition > bytes.size() || bytes.size() - footerPosition < 2)
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)
1297 if (!restoreChannels(channelCode, bitDepth, blockSize, pcm))
1300 decoded.endOffset = footerPosition + 2;
1301 decoded.blockSize = blockSize;
1302 decoded.variableBlock = variable;
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)
1312 const unsigned bytesPerSample = (bitsPerSample + 7u) / 8u;
1313 if (bytesPerSample < 1 || bytesPerSample > 4)
1315 scratch.resize(
static_cast<size_t>(blockSize) * channels * bytesPerSample);
1316 switch (bytesPerSample)
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;
1323 md5.update(std::span<const uint8_t>(scratch.data(), scratch.size()));
1327 template <
unsigned Bytes>
1328 static void interleaveLittleEndian(
const int64_t* pcm, uint8_t channels,
1329 uint32_t blockSize, uint8_t* scratch)
noexcept
1331 const size_t stride =
static_cast<size_t>(channels) * Bytes;
1332 for (uint8_t channel = 0; channel < channels; ++channel)
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)
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));
1345 static bool allZero(
const std::array<uint8_t, 16>& value)
noexcept
1347 for (uint8_t
byte : value) if (byte != 0) return false;
1351 static bool validateOpen(OpenState& state)
1353 if (state.bytes.size() < 4
1354 || std::memcmp(state.bytes.data(),
"fLaC", 4) != 0)
1356 ByteCursor cursor(state.bytes, 4, state.bytes.size());
1357 uint64_t metadataBlocks = 0;
1358 bool sawStreamInfo =
false;
1359 bool lastMetadata =
false;
1361 while (!lastMetadata)
1366 uint32_t length = 0;
1367 if (!cursor.readU8(header) || !cursor.readBE24(length))
1369 lastMetadata = (header & 0x80u) != 0;
1370 const uint8_t type = header & 0x7fu;
1371 if (type == 127 || length > cursor.remaining())
1373 const uint8_t* data =
nullptr;
1374 if (!cursor.readSpan(length, data))
1378 if (type != 0 || length != 34
1379 || !parseStreamInfo(data, state.stream))
1381 sawStreamInfo =
true;
1386 if (!sawStreamInfo || cursor.remaining() == 0)
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;
1398 uint32_t firstBlockSize = 0;
1399 uint32_t previousBlockSize = 0;
1400 std::vector<int64_t> pcm;
1401 while (cursor.remaining() > 0)
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())
1413 if (haveStrategy && decoded.variableBlock != strategy)
1417 const int frameNumbering = decoded.numberIsFrame == decoded.numberIsSample
1418 ? 0 : (decoded.numberIsFrame ? 1 : 2);
1419 if (frameNumbering != 0)
1421 if (numbering != 0 && numbering != frameNumbering)
1423 numbering = frameNumbering;
1430 if (previousBlockSize < state.stream.minBlockSize)
1432 if (numbering == 1 && previousBlockSize != firstBlockSize)
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))
1448 const uint64_t firstSample = coverage;
1449 coverage += decoded.blockSize;
1450 const uint64_t bytesPerSample = (state.stream.bitsPerSample + 7u) / 8u;
1452 / (
static_cast<uint64_t
>(state.stream.channels) * bytesPerSample))
1454 if (checkMd5 && !updateMd5(md5, pcm, state.stream.channels,
1455 state.stream.bitsPerSample, decoded.blockSize,
1458 state.frames.push_back({ frameOffset, frameSize, firstSample,
1459 decoded.blockSize });
1460 if (!cursor.skip(frameSize))
1464 if (state.frames.empty() || coverage == 0
1465 || (state.stream.declaredSamples != 0
1466 && state.stream.declaredSamples != coverage))
1468 if (checkMd5 && md5.finish() != state.stream.md5)
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;