133 [[nodiscard]]
bool openRead(
const std::filesystem::path& path)
override
137 file_.open(path, std::ios::binary | std::ios::in);
138 if (!file_.is_open())
return false;
184 file_.open(path, std::ios::binary | std::ios::out | std::ios::trunc);
185 if (!file_.is_open())
return false;
189 totalFramesWritten_ = 0;
190 writeContainer_ = rf64Mode_;
223 if (mode_ == Mode::Read && file_.is_open() && info_.
numSamples == 0)
229 int64_t startFrame, int64_t numFrames)
override
231 if (mode_ != Mode::Read || !file_.is_open())
return false;
232 if (startFrame < 0 || numFrames <= 0)
return false;
239 int64_t framesRemaining = std::min(numFrames,
static_cast<int64_t
>(dest.
getNumSamples()));
242 return readAdpcm(dest, nCh, startFrame, framesRemaining);
244 const int frameSize = containerBytes_ *
static_cast<int>(info_.
numChannels);
247 auto seekPos = dataChunkOffset_ +
static_cast<std::streamoff
>(startFrame * frameSize);
248 file_.seekg(seekPos, std::ios::beg);
249 if (!file_.good())
return false;
251 int64_t destOffset = 0;
253 while (framesRemaining > 0)
255 const auto toRead = std::min<int64_t>(framesRemaining, kChunkFrames);
256 const auto rawBytes =
static_cast<std::streamsize
>(toRead * frameSize);
258 file_.read(
reinterpret_cast<char*
>(ioBuffer_.data()), rawBytes);
259 if (file_.gcount() != rawBytes)
return false;
261 deinterleave(ioBuffer_.data(), dest, nCh,
static_cast<int>(toRead),
static_cast<int>(destOffset));
263 destOffset += toRead;
264 framesRemaining -= toRead;
272 if (mode_ != Mode::Write || !file_.is_open())
return false;
274 const int nCh =
static_cast<int>(info_.
numChannels);
277 const int frameSize =
static_cast<int>(info_.
bitsPerSample / 8) * nCh;
282 const int64_t dataAfter = (totalFramesWritten_ + nS) *
static_cast<int64_t
>(frameSize);
284 ?
static_cast<int64_t
>(0xFFFFFFFFu) - 128
285 : (int64_t { 1 } << 62);
286 if (dataAfter > limit)
return false;
288 int framesRemaining = nS;
291 while (framesRemaining > 0)
293 const int toWrite = std::min(framesRemaining, kChunkFrames);
295 interleave(src, ioBuffer_.data(), nCh, srcCh, toWrite, srcOffset);
297 auto rawBytes =
static_cast<std::streamsize
>(
static_cast<int64_t
>(toWrite) * frameSize);
298 file_.write(
reinterpret_cast<const char*
>(ioBuffer_.data()), rawBytes);
305 srcOffset += toWrite;
306 framesRemaining -= toWrite;
309 totalFramesWritten_ += nS;
316 if (!file_.is_open()) { mode_ = Mode::Closed; info_ = {};
return; }
318 if (mode_ == Mode::Write)
321 if (!file_.good()) writeError_ =
true;
325 if (file_.fail()) writeError_ =
true;
327 ioBuffer_.shrink_to_fit();
329 blockPcm_.shrink_to_fit();
330 mode_ = Mode::Closed;
334 [[nodiscard]]
bool isOpen() const noexcept
override
336 return file_.is_open() && mode_ != Mode::Closed;
345 [[nodiscard]]
bool hasWriteError() const noexcept
override {
return writeError_; }
350 static constexpr uint16_t kFormatPCM = 1;
351 static constexpr uint16_t kFormatMsAdpcm = 2;
352 static constexpr uint16_t kFormatIEEEFloat = 3;
353 static constexpr uint16_t kFormatALaw = 6;
354 static constexpr uint16_t kFormatMuLaw = 7;
355 static constexpr uint16_t kFormatImaAdpcm = 0x11;
356 static constexpr uint16_t kFormatExtensible = 0xFFFE;
357 static constexpr int kChunkFrames = 8192;
358 static constexpr uint32_t kMaxChannels = 64;
359 static constexpr uint32_t kMaxMsCoefficients = 256;
360 static constexpr uint32_t kMaxAdpcmChannels = 2;
362 enum class Mode { Closed, Read, Write };
365 Mode mode_ = Mode::Closed;
366 AudioFileInfo info_ {};
367 std::vector<uint8_t> ioBuffer_;
369 std::streamoff dataChunkOffset_ = 0;
370 std::streamoff dataChunkSizeOffset_ = 0;
371 uint64_t dataChunkSize_ = 0;
372 int64_t totalFramesWritten_ = 0;
375 bool writeError_ =
false;
381 int containerBytes_ = 0;
382 uint32_t blockAlign_ = 0;
383 uint32_t samplesPerBlock_ = 0;
384 uint32_t factFrames_ = 0;
385 bool hasFact_ =
false;
386 std::vector<int16_t> msCoefficients_;
387 std::vector<int16_t> blockPcm_;
389 static constexpr uint32_t kRf64Unknown = 0xFFFFFFFFu;
390 static constexpr std::streamoff kDs64Offset = 12;
391 static constexpr uint32_t kDs64Size = 28;
393 [[nodiscard]]
bool isAdpcm() const noexcept
398 void resetReadFormat() noexcept
403 samplesPerBlock_ = 0;
408 void resizeIoBuffer()
410 size_t bytesNeeded = 0;
411 if (mode_ == Mode::Read && isAdpcm())
415 bytesNeeded = blockAlign_;
416 blockPcm_.assign(
static_cast<size_t>(samplesPerBlock_) * info_.
numChannels, 0);
420 const size_t sampleBytes = (mode_ == Mode::Read)
421 ?
static_cast<size_t>(containerBytes_)
423 bytesNeeded =
static_cast<size_t>(kChunkFrames) * info_.
numChannels * sampleBytes;
425 if (ioBuffer_.size() < bytesNeeded)
426 ioBuffer_.resize(bytesNeeded);
434 if (!readBytes(riffId, 4))
return false;
435 const bool rf64 = std::memcmp(riffId,
"RF64", 4) == 0
436 || std::memcmp(riffId,
"BW64", 4) == 0;
437 if (!rf64 && std::memcmp(riffId,
"RIFF", 4) != 0)
return false;
439 uint32_t riffSize = 0;
440 if (!readLE32(riffSize))
return false;
444 if (!readBytes(waveId, 4))
return false;
445 if (std::memcmp(waveId,
"WAVE", 4) != 0)
return false;
449 uint64_t ds64DataSize = 0;
453 uint32_t ds64Size = 0;
454 uint64_t riffSize64 = 0;
455 if (!readBytes(ds64Id, 4) || std::memcmp(ds64Id,
"ds64", 4) != 0)
return false;
456 if (!readLE32(ds64Size) || ds64Size < 24)
return false;
457 if (!readLE64(riffSize64) || !readLE64(ds64DataSize))
return false;
459 file_.seekg(
static_cast<std::streamoff
>(ds64Size) - 16 + (ds64Size & 1), std::ios::cur);
460 if (!file_.good())
return false;
463 bool hasFmt =
false, hasData =
false;
465 while (file_.good() && !(hasFmt && hasData))
468 uint32_t chunkSize32 = 0;
469 if (!readBytes(chunkId, 4))
break;
470 if (!readLE32(chunkSize32))
break;
471 uint64_t chunkSize = chunkSize32;
472 if (rf64 && chunkSize32 == kRf64Unknown && std::memcmp(chunkId,
"data", 4) == 0)
473 chunkSize = ds64DataSize;
479 const std::streamoff pad =
static_cast<std::streamoff
>(chunkSize & 1);
481 if (std::memcmp(chunkId,
"fmt ", 4) == 0)
483 if (chunkSize > 0xFFFFu || !parseFmtChunk(
static_cast<uint32_t
>(chunkSize)))
return false;
484 if (pad) file_.seekg(pad, std::ios::cur);
487 else if (std::memcmp(chunkId,
"data", 4) == 0)
489 auto currentPos = file_.tellg();
490 file_.seekg(0, std::ios::end);
491 auto fileEnd = file_.tellg();
492 file_.seekg(currentPos);
494 const auto remaining =
static_cast<std::streamoff
>(fileEnd - currentPos);
495 if (remaining < 0)
return false;
496 if (chunkSize >
static_cast<uint64_t
>(remaining))
497 chunkSize =
static_cast<uint64_t
>(remaining);
499 dataChunkOffset_ = file_.tellg();
500 dataChunkSize_ = chunkSize;
505 file_.seekg(
static_cast<std::streamoff
>(chunkSize) + pad, std::ios::cur);
508 else if (std::memcmp(chunkId,
"fact", 4) == 0 && chunkSize >= 4)
512 if (!readLE32(factFrames_))
break;
514 file_.seekg(
static_cast<std::streamoff
>(chunkSize) - 4 + pad, std::ios::cur);
518 file_.seekg(
static_cast<std::streamoff
>(chunkSize) + pad, std::ios::cur);
525 if (hasFmt && hasData)
533 const uint64_t bytesPerFrame =
static_cast<uint64_t
>(containerBytes_) * info_.
numChannels;
534 if (bytesPerFrame > 0)
535 info_.
numSamples =
static_cast<int64_t
>(dataChunkSize_ / bytesPerFrame);
539 return hasFmt && hasData;
544 [[nodiscard]] uint32_t adpcmFramesInBlock(uint64_t bytes)
const noexcept
552 if (bytes >= 4 * nCh) frames = 1 + ((bytes - 4 * nCh) / (4 * nCh)) * 8;
558 if (bytes >= 7 * nCh) frames = 2 + ((bytes - 7 * nCh) * 2) / nCh;
560 return static_cast<uint32_t
>(std::min<uint64_t>(frames, samplesPerBlock_));
563 [[nodiscard]] int64_t adpcmFrameCount() const noexcept
565 const uint64_t blocks = dataChunkSize_ / blockAlign_;
566 const uint64_t tail = dataChunkSize_ % blockAlign_;
567 const uint64_t lastBlockFrames = adpcmFramesInBlock(tail);
568 const uint64_t frames = blocks * samplesPerBlock_ + lastBlockFrames;
573 const uint64_t lastBlock = (lastBlockFrames > 0) ? lastBlockFrames : samplesPerBlock_;
574 if (hasFact_ && factFrames_ <= frames && factFrames_ + lastBlock > frames)
575 return static_cast<int64_t
>(factFrames_);
576 return static_cast<int64_t
>(frames);
579 bool parseFmtChunk(uint32_t chunkSize)
581 if (chunkSize < 16)
return false;
583 uint16_t audioFormat = 0;
584 uint16_t numChannels = 0;
585 uint32_t sampleRate = 0;
586 uint32_t byteRate = 0;
587 uint16_t blockAlign = 0;
588 uint16_t bitsPerSample = 0;
590 if (!readLE16(audioFormat))
return false;
591 if (!readLE16(numChannels))
return false;
592 if (!readLE32(sampleRate))
return false;
593 if (!readLE32(byteRate))
return false;
595 if (!readLE16(blockAlign))
return false;
596 if (!readLE16(bitsPerSample))
return false;
599 uint32_t fmtSamplesPerBlock = 0;
600 bool hasMsCoefficients =
false;
602 if (audioFormat == kFormatExtensible && chunkSize >= 40)
613 uint16_t validBitsPerSample = 0;
614 readLE16(validBitsPerSample);
615 if (validBitsPerSample > bitsPerSample)
return false;
617 uint32_t channelMask = 0;
618 readLE32(channelMask);
621 uint16_t subFormat = 0;
622 if (!readLE16(subFormat))
return false;
623 audioFormat = subFormat;
625 file_.seekg(14, std::ios::cur);
630 file_.seekg(
static_cast<std::streamoff
>(chunkSize - 40), std::ios::cur);
635 if (audioFormat == kFormatImaAdpcm || audioFormat == kFormatMsAdpcm)
return false;
637 else if ((audioFormat == kFormatImaAdpcm || audioFormat == kFormatMsAdpcm) && chunkSize >= 18)
640 if (!readLE16(cbSize))
return false;
641 const uint32_t extBytes = std::min<uint32_t>(cbSize, chunkSize - 18);
642 uint32_t consumed = 18;
647 if (!readLE16(spb))
return false;
648 fmtSamplesPerBlock = spb;
651 if (audioFormat == kFormatMsAdpcm && extBytes >= 4)
653 uint16_t numCoef = 0;
654 if (!readLE16(numCoef))
return false;
659 if (numCoef == 0 || numCoef > kMaxMsCoefficients)
return false;
660 if (extBytes < 4 + 4u * numCoef)
return false;
661 msCoefficients_.resize(2u * numCoef);
662 for (
auto& c : msCoefficients_)
665 if (!readLE16(v))
return false;
666 c =
static_cast<int16_t
>(v);
668 consumed += 4u * numCoef;
669 hasMsCoefficients =
true;
671 if (chunkSize > consumed)
672 file_.seekg(
static_cast<std::streamoff
>(chunkSize - consumed), std::ios::cur);
674 else if (chunkSize > 16)
676 auto skip =
static_cast<std::streamoff
>(chunkSize - 16);
677 file_.seekg(skip, std::ios::cur);
680 info_.
sampleRate =
static_cast<double>(sampleRate);
685 if (sampleRate == 0)
return false;
686 if (numChannels == 0 || numChannels > kMaxChannels)
return false;
693 if (bitsPerSample == 0 || bitsPerSample > 32)
return false;
696 if ((bitsPerSample & 7) == 0)
698 containerBytes_ = bitsPerSample / 8;
706 if (blockAlign == 0 || blockAlign % numChannels != 0)
return false;
707 containerBytes_ = blockAlign / numChannels;
708 if (containerBytes_ < (bitsPerSample + 7) / 8 || containerBytes_ > 4)
return false;
712 case kFormatIEEEFloat:
714 if (bitsPerSample != 32 && bitsPerSample != 64)
return false;
715 containerBytes_ = bitsPerSample / 8;
720 if (bitsPerSample != 8)
return false;
724 case kFormatImaAdpcm:
728 if (bitsPerSample != 4)
return false;
731 if (numChannels > kMaxAdpcmChannels)
return false;
732 const uint32_t headerBytes = (encoding_ ==
Encoding::ImaAdpcm ? 4u : 7u) * numChannels;
733 if (blockAlign < headerBytes)
return false;
736 blockAlign_ = blockAlign;
737 samplesPerBlock_ = std::numeric_limits<uint32_t>::max();
738 const uint32_t maxFrames = adpcmFramesInBlock(blockAlign);
743 if (fmtSamplesPerBlock != 0
744 && (fmtSamplesPerBlock < minFrames || fmtSamplesPerBlock > maxFrames))
746 samplesPerBlock_ = (fmtSamplesPerBlock != 0) ? fmtSamplesPerBlock : maxFrames;
750 static constexpr int16_t kStandard[14] = {
751 256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232
753 msCoefficients_.assign(std::begin(kStandard), std::end(kStandard));
767 [[nodiscard]]
static constexpr int16_t aLawToLinear(uint8_t code)
noexcept
769 const int v = code ^ 0x55;
770 const int mantissa = v & 0x0F;
771 const int segment = (v >> 4) & 0x07;
772 int magnitude = (mantissa << 4) + 8;
773 if (segment > 0) magnitude = ((mantissa << 4) + 0x108) << (segment - 1);
774 return static_cast<int16_t
>((v & 0x80) ? magnitude : -magnitude);
777 [[nodiscard]]
static constexpr int16_t muLawToLinear(uint8_t code)
noexcept
779 const int v = ~code & 0xFF;
780 const int magnitude = (((v & 0x0F) << 3) + 0x84) << ((v >> 4) & 0x07);
781 return static_cast<int16_t
>((v & 0x80) ? (0x84 - magnitude) : (magnitude - 0x84));
785 [[nodiscard]]
static constexpr std::array<float, 256> makeG711Table() noexcept
787 std::array<float, 256> t {};
788 for (
int i = 0; i < 256; ++i)
790 const int16_t s =
ALaw ? aLawToLinear(
static_cast<uint8_t
>(i))
791 : muLawToLinear(static_cast<uint8_t>(i));
792 t[
static_cast<size_t>(i)] =
static_cast<float>(s) * (1.0f / 32768.0f);
798 static constexpr int16_t kImaStep[89] = {
799 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
800 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230,
801 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963,
802 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327,
803 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487,
804 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
811 struct ImaTables { std::array<int32_t, 89 * 8> diff {}; std::array<uint8_t, 89 * 8> next {}; };
813 [[nodiscard]]
static constexpr ImaTables makeImaTables() noexcept
815 constexpr int indexStep[8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
817 for (
int i = 0; i < 89; ++i)
818 for (
int m = 0; m < 8; ++m)
820 const int step = kImaStep[i];
821 int diff = step >> 3;
822 if (m & 1) diff += step >> 2;
823 if (m & 2) diff += step >> 1;
824 if (m & 4) diff += step;
825 t.diff[
static_cast<size_t>(i * 8 + m)] = diff;
826 t.next[
static_cast<size_t>(i * 8 + m)] =
827 static_cast<uint8_t
>(std::clamp(i + indexStep[m], 0, 88));
834 [[nodiscard]] uint32_t decodeImaBlock(uint64_t bytes)
noexcept
836 static constexpr ImaTables kTables = makeImaTables();
839 const uint32_t frames = adpcmFramesInBlock(bytes);
840 if (frames == 0)
return 0;
841 const uint8_t* b = ioBuffer_.data();
842 int16_t* out = blockPcm_.data();
844 for (uint32_t ch = 0; ch < nCh; ++ch)
846 const uint8_t* h = b + 4 * ch;
847 int predictor =
static_cast<int16_t
>(
static_cast<uint16_t
>(h[0] | (h[1] << 8)));
848 uint32_t index = h[2];
849 if (index > 88)
return 0;
850 out[ch] =
static_cast<int16_t
>(predictor);
853 int16_t* o = out + nCh + ch;
854 const uint8_t* w = b + 4 * nCh + 4 * ch;
855 for (uint32_t done = 1; done < frames; done += 8, w += 4 * nCh)
857 const uint32_t count = std::min<uint32_t>(8, frames - done);
858 for (uint32_t k = 0; k < count; ++k, o += nCh)
860 const uint32_t nibble = (w[k >> 1] >> ((k & 1) * 4)) & 0x0F;
861 const uint32_t slot = index * 8 + (nibble & 7);
862 const int diff = kTables.diff[slot];
863 predictor = std::clamp(predictor + ((nibble & 8) ? -diff : diff), -32768, 32767);
864 index = kTables.next[slot];
865 *o =
static_cast<int16_t
>(predictor);
873 [[nodiscard]] uint32_t decodeMsBlock(uint64_t bytes)
noexcept
875 static constexpr int16_t kAdaptation[16] = {
876 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230
878 struct State { int64_t coef1, coef2, delta, s1, s2; };
879 std::array<State, kMaxAdpcmChannels> st {};
882 const uint32_t frames = adpcmFramesInBlock(bytes);
883 if (frames == 0)
return 0;
884 const uint8_t* b = ioBuffer_.data();
885 int16_t* out = blockPcm_.data();
886 const auto le16 = [](
const uint8_t* p)
noexcept
888 return static_cast<int64_t
>(
static_cast<int16_t
>(
static_cast<uint16_t
>(p[0] | (p[1] << 8))));
891 const size_t numCoef = msCoefficients_.size() / 2;
892 for (uint32_t ch = 0; ch < nCh; ++ch)
894 const uint8_t predictor = b[ch];
895 if (predictor >= numCoef)
return 0;
897 s.coef1 = msCoefficients_[2u * predictor];
898 s.coef2 = msCoefficients_[2u * predictor + 1];
899 s.delta = le16(b + nCh + 2 * ch);
900 s.s1 = le16(b + 3 * nCh + 2 * ch);
901 s.s2 = le16(b + 5 * nCh + 2 * ch);
902 out[ch] =
static_cast<int16_t
>(s.s2);
903 out[nCh + ch] =
static_cast<int16_t
>(s.s1);
907 const uint8_t* data = b + 7 * nCh;
909 for (uint32_t frame = 2; frame < frames; ++frame)
911 for (uint32_t ch = 0; ch < nCh; ++ch, ++i)
913 const int nibble = (data[i >> 1] >> ((i & 1) ? 0 : 4)) & 0x0F;
918 const int64_t prediction = (s.s1 * s.coef1 + s.s2 * s.coef2) / 256;
919 const int64_t sample = std::clamp<int64_t>(
920 prediction + (nibble >= 8 ? nibble - 16 : nibble) * s.delta, -32768, 32767);
923 s.delta = std::clamp<int64_t>((kAdaptation[nibble] * s.delta) / 256, 16, 0x7FFFFFFF);
924 out[
static_cast<size_t>(frame) * nCh + ch] =
static_cast<int16_t
>(sample);
930 bool readAdpcm(AudioBufferView<float>& dest,
int nCh, int64_t startFrame, int64_t frames)
933 uint64_t block =
static_cast<uint64_t
>(startFrame) / samplesPerBlock_;
934 uint32_t offset =
static_cast<uint32_t
>(
static_cast<uint64_t
>(startFrame) % samplesPerBlock_);
935 int64_t destOffset = 0;
939 const uint64_t blockStart = block * blockAlign_;
940 if (blockStart >= dataChunkSize_)
return false;
941 const uint64_t bytes = std::min<uint64_t>(blockAlign_, dataChunkSize_ - blockStart);
943 file_.seekg(dataChunkOffset_ +
static_cast<std::streamoff
>(blockStart), std::ios::beg);
944 if (!file_.good())
return false;
945 file_.read(
reinterpret_cast<char*
>(ioBuffer_.data()),
static_cast<std::streamsize
>(bytes));
946 if (file_.gcount() !=
static_cast<std::streamsize
>(bytes))
return false;
949 : decodeMsBlock(bytes);
950 if (decoded <= offset)
return false;
952 const int64_t take = std::min<int64_t>(frames, decoded - offset);
953 for (
int ch = 0; ch < nCh; ++ch)
955 float* out = dest.getChannel(ch) + destOffset;
956 const int16_t* in = blockPcm_.data() +
static_cast<size_t>(offset) * fileCh
957 +
static_cast<size_t>(ch);
958 for (int64_t f = 0; f < take; ++f)
959 out[f] =
static_cast<float>(in[
static_cast<size_t>(f) * fileCh]) * (1.0f / 32768.0f);
974 const uint16_t formatTag = getWriteFormatTag();
975 const bool extensible = (formatTag == kFormatExtensible);
976 const uint32_t fmtChunkSize = extensible ? 40u : 16u;
978 const int bytesPerSample =
static_cast<int>(info_.
bitsPerSample / 8);
979 const auto blockAlign =
static_cast<uint16_t
>(info_.
numChannels * bytesPerSample);
980 const auto rate =
static_cast<uint32_t
>(std::llround(info_.
sampleRate));
981 const uint64_t byteRate64 =
static_cast<uint64_t
>(rate) * blockAlign;
982 const auto byteRate =
static_cast<uint32_t
>(
983 std::min<uint64_t>(byteRate64, 0xFFFFFFFFu));
987 writeBytes(
"WAVE", 4);
994 writeLE32(kDs64Size);
995 for (uint32_t i = 0; i < kDs64Size; ++i) file_.put(
'\0');
998 writeBytes(
"fmt ", 4);
999 writeLE32(fmtChunkSize);
1000 writeLE16(formatTag);
1001 writeLE16(
static_cast<uint16_t
>(info_.
numChannels));
1003 writeLE32(byteRate);
1004 writeLE16(blockAlign);
1013 uint16_t subFormat = info_.
isFloatingPoint ? kFormatIEEEFloat : kFormatPCM;
1014 writeLE16(subFormat);
1015 static constexpr uint8_t kGuidSuffix[14] = {
1016 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00,
1017 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71
1019 writeBytes(
reinterpret_cast<const char*
>(kGuidSuffix), 14);
1022 writeBytes(
"data", 4);
1023 dataChunkSizeOffset_ = file_.tellp();
1026 dataChunkOffset_ = file_.tellp();
1027 return file_.good();
1030 void finaliseHeader()
1032 if (!file_.is_open())
return;
1039 const int bytesPerSample =
static_cast<int>(info_.
bitsPerSample / 8);
1040 const uint64_t dataSize =
static_cast<uint64_t
>(totalFramesWritten_)
1041 * info_.
numChannels *
static_cast<uint64_t
>(bytesPerSample);
1046 file_.seekp(0, std::ios::end);
1047 if ((dataSize & 1u) != 0) file_.put(
'\0');
1048 const auto fileSize =
static_cast<uint64_t
>(
static_cast<std::streamoff
>(file_.tellp()));
1049 const uint64_t riffSize = fileSize - 8;
1052 || (writeContainer_ ==
Rf64Mode::Auto && riffSize > 0xFFFFFFFFull);
1055 const int frameBytes = bytesPerSample *
static_cast<int>(info_.
numChannels);
1056 file_.seekp(0, std::ios::beg);
1057 writeBytes(
"RF64", 4);
1058 writeLE32(kRf64Unknown);
1059 file_.seekp(kDs64Offset, std::ios::beg);
1060 writeBytes(
"ds64", 4);
1061 writeLE32(kDs64Size);
1062 writeLE64(riffSize);
1063 writeLE64(dataSize);
1064 writeLE64(frameBytes > 0 ? dataSize /
static_cast<uint64_t
>(frameBytes) : 0);
1066 file_.seekp(dataChunkSizeOffset_, std::ios::beg);
1067 writeLE32(kRf64Unknown);
1071 file_.seekp(dataChunkSizeOffset_, std::ios::beg);
1072 writeLE32(
static_cast<uint32_t
>(dataSize));
1073 file_.seekp(4, std::ios::beg);
1074 writeLE32(
static_cast<uint32_t
>(riffSize));
1080 [[nodiscard]] uint16_t getWriteFormatTag() const noexcept
1089 void deinterleave(
const uint8_t* raw, AudioBufferView<float>& dest,
int nCh,
int numFrames,
int destOffset)
const
1093 static constexpr std::array<float, 256> kALaw = makeG711Table<true>();
1094 static constexpr std::array<float, 256> kMuLaw = makeG711Table<false>();
1095 const float* table = (encoding_ ==
Encoding::ALaw) ? kALaw.data() : kMuLaw.data();
1096 const int stride =
static_cast<int>(info_.
numChannels);
1097 for (
int ch = 0; ch < nCh; ++ch)
1099 float* out = dest.getChannel(ch) + destOffset;
1100 const uint8_t* in = raw + ch;
1101 for (
int f = 0; f < numFrames; ++f)
1102 out[f] = table[in[f * stride]];
1110 if (containerBytes_ == 4) deinterleaveImpl<float, 32>(raw, dest, nCh, numFrames, destOffset);
1111 else deinterleaveImpl<double, 64>(raw, dest, nCh, numFrames, destOffset);
1113 switch (containerBytes_) {
1114 case 1: deinterleaveImpl<uint8_t, 8>(raw, dest, nCh, numFrames, destOffset);
break;
1115 case 2: deinterleaveImpl<int16_t, 16>(raw, dest, nCh, numFrames, destOffset);
break;
1116 case 3: deinterleaveImpl<int32_t, 24>(raw, dest, nCh, numFrames, destOffset);
break;
1117 case 4: deinterleaveImpl<int32_t, 32>(raw, dest, nCh, numFrames, destOffset);
break;
1123 template <
typename T,
int Bits>
1124 void deinterleaveImpl(
const uint8_t* raw, AudioBufferView<float>& dest,
int nCh,
int numFrames,
int destOffset)
const
1126 const int bytesPerSample = Bits / 8;
1127 const int stride =
static_cast<int>(info_.
numChannels) * bytesPerSample;
1132 for (
int ch = 0; ch < nCh; ++ch)
1134 float* out = dest.getChannel(ch) + destOffset;
1135 const uint8_t* channelRaw = raw + (ch * bytesPerSample);
1137 for (
int f = 0; f < numFrames; ++f)
1139 const uint8_t* ptr = channelRaw + (f * stride);
1141 if constexpr (Bits == 8) {
1142 out[f] = (
static_cast<float>(ptr[0]) - 128.0f) * (1.0f / 128.0f);
1144 else if constexpr (Bits == 16) {
1145 auto val =
static_cast<int16_t
>(ptr[0] | (ptr[1] << 8));
1146 out[f] =
static_cast<float>(val) * (1.0f / 32768.0f);
1148 else if constexpr (Bits == 24) {
1149 int32_t val = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16);
1150 if (val & 0x800000) val |= 0xFF000000;
1151 out[f] =
static_cast<float>(val) * (1.0f / 8388608.0f);
1153 else if constexpr (Bits == 32 && std::is_same_v<T, int32_t>) {
1156 int32_t val =
static_cast<int32_t
>(
1157 static_cast<uint32_t
>(ptr[0])
1158 | (
static_cast<uint32_t
>(ptr[1]) << 8)
1159 | (
static_cast<uint32_t
>(ptr[2]) << 16)
1160 | (
static_cast<uint32_t
>(ptr[3]) << 24));
1161 out[f] =
static_cast<float>(val) * (1.0f / 2147483648.0f);
1163 else if constexpr (Bits == 32 && std::is_same_v<T, float>) {
1164 float v; std::memcpy(&v, ptr, 4); out[f] = v;
1166 else if constexpr (Bits == 64) {
1167 double v; std::memcpy(&v, ptr, 8); out[f] =
static_cast<float>(v);
1175 void interleave(AudioBufferView<const float> src, uint8_t* raw,
1176 int fileCh,
int srcCh,
int numFrames,
int srcOffset)
const
1179 if (info_.
bitsPerSample == 32) interleaveImpl<float, 32>(src, raw, fileCh, srcCh, numFrames, srcOffset);
1180 else interleaveImpl<double, 64>(src, raw, fileCh, srcCh, numFrames, srcOffset);
1183 case 8: interleaveImpl<uint8_t, 8>(src, raw, fileCh, srcCh, numFrames, srcOffset);
break;
1184 case 16: interleaveImpl<int16_t, 16>(src, raw, fileCh, srcCh, numFrames, srcOffset);
break;
1185 case 24: interleaveImpl<int32_t, 24>(src, raw, fileCh, srcCh, numFrames, srcOffset);
break;
1186 case 32: interleaveImpl<int32_t, 32>(src, raw, fileCh, srcCh, numFrames, srcOffset);
break;
1191 template <
typename T,
int Bits>
1192 void interleaveImpl(AudioBufferView<const float> src, uint8_t* raw,
1193 int fileCh,
int srcCh,
int numFrames,
int srcOffset)
const
1195 const int bytesPerSample = Bits / 8;
1200 for (
int f = 0; f < numFrames; ++f)
1202 for (
int ch = 0; ch < fileCh; ++ch)
1204 float value = (ch < srcCh) ? src.getChannel(ch)[srcOffset + f] : 0.0f;
1205 uint8_t* ptr = raw + ((f * fileCh + ch) * bytesPerSample);
1211 if constexpr (std::is_integral_v<T>)
1212 if (value != value) value = 0.0f;
1215 if constexpr (Bits == 8) {
1222 auto val =
static_cast<uint8_t
>(std::clamp(std::round(value * 128.0f) + 128.0f, 0.0f, 255.0f));
1225 else if constexpr (Bits == 16) {
1226 auto val =
static_cast<int16_t
>(std::clamp(std::round(value * 32768.0f), -32768.0f, 32767.0f));
1227 ptr[0] = val & 0xFF; ptr[1] = (val >> 8) & 0xFF;
1229 else if constexpr (Bits == 24) {
1230 auto val =
static_cast<int32_t
>(std::clamp(std::round(value * 8388608.0f), -8388608.0f, 8388607.0f));
1231 ptr[0] = val & 0xFF; ptr[1] = (val >> 8) & 0xFF; ptr[2] = (val >> 16) & 0xFF;
1233 else if constexpr (Bits == 32 && std::is_same_v<T, int32_t>) {
1234 auto val =
static_cast<int32_t
>(std::clamp(std::round(
static_cast<double>(value) * 2147483648.0), -2147483648.0, 2147483647.0));
1235 ptr[0] = val & 0xFF; ptr[1] = (val >> 8) & 0xFF; ptr[2] = (val >> 16) & 0xFF; ptr[3] = (val >> 24) & 0xFF;
1237 else if constexpr (Bits == 32 && std::is_same_v<T, float>) {
1238 std::memcpy(ptr, &value, 4);
1240 else if constexpr (Bits == 64) {
1241 double d =
static_cast<double>(value);
1242 std::memcpy(ptr, &d, 8);
1250 bool readBytes(
char* buf,
int n)
1253 return file_.gcount() == n;
1256 bool readLE16(uint16_t& val)
1259 file_.read(
reinterpret_cast<char*
>(b), 2);
1260 if (file_.gcount() != 2)
return false;
1261 val =
static_cast<uint16_t
>(b[0]) | (
static_cast<uint16_t
>(b[1]) << 8);
1265 bool readLE64(uint64_t& val)
1267 uint32_t lo = 0, hi = 0;
1268 if (!readLE32(lo) || !readLE32(hi))
return false;
1269 val =
static_cast<uint64_t
>(lo) | (
static_cast<uint64_t
>(hi) << 32);
1273 bool readLE32(uint32_t& val)
1276 file_.read(
reinterpret_cast<char*
>(b), 4);
1277 if (file_.gcount() != 4)
return false;
1278 val =
static_cast<uint32_t
>(b[0])
1279 | (
static_cast<uint32_t
>(b[1]) << 8)
1280 | (
static_cast<uint32_t
>(b[2]) << 16)
1281 | (
static_cast<uint32_t
>(b[3]) << 24);
1285 void writeBytes(
const char* buf,
int n)
1287 file_.write(buf, n);
1290 void writeLE16(uint16_t val)
1293 static_cast<uint8_t
>(val & 0xFF),
1294 static_cast<uint8_t
>((val >> 8) & 0xFF)
1296 file_.write(
reinterpret_cast<const char*
>(b), 2);
1299 void writeLE64(uint64_t val)
1301 writeLE32(
static_cast<uint32_t
>(val));
1302 writeLE32(
static_cast<uint32_t
>(val >> 32));
1305 void writeLE32(uint32_t val)
1308 static_cast<uint8_t
>(val & 0xFF),
1309 static_cast<uint8_t
>((val >> 8) & 0xFF),
1310 static_cast<uint8_t
>((val >> 16) & 0xFF),
1311 static_cast<uint8_t
>((val >> 24) & 0xFF)
1313 file_.write(
reinterpret_cast<const char*
>(b), 4);