DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
WavFile.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
63#include "AudioFile.h"
64
65#include <algorithm>
66#include <array>
67#include <cmath>
68#include <cstddef>
69#include <cstdint>
70#include <cstring>
71#include <filesystem>
72#include <fstream>
73#include <iterator>
74#include <limits>
75#include <type_traits>
76#include <vector>
77
78namespace dspark {
79
96class WavFile : public AudioFile
97{
98public:
100 enum class Encoding
101 {
102 Pcm,
103 Float,
104 ALaw,
105 MuLaw,
106 ImaAdpcm,
107 MsAdpcm
108 };
109
111 enum class Rf64Mode
112 {
113 Never,
114 Auto,
115 Always
116 };
117
118 ~WavFile() override { close(); }
119
121 void setRf64Mode(Rf64Mode mode) noexcept { rf64Mode_ = mode; }
122
124 [[nodiscard]] Rf64Mode getRf64Mode() const noexcept { return rf64Mode_; }
125
126 // -- AudioFile interface ---------------------------------------------------
127
133 [[nodiscard]] bool openRead(const std::filesystem::path& path) override
134 {
135 close();
136 writeError_ = false;
137 file_.open(path, std::ios::binary | std::ios::in);
138 if (!file_.is_open()) return false;
139
140 if (!parseHeader())
141 {
142 close();
143 return false;
144 }
145
146 mode_ = Mode::Read;
147 resizeIoBuffer();
148 return true;
149 }
150
162 [[nodiscard]] bool openWrite(const std::filesystem::path& path, const AudioFileInfo& info) override
163 {
164 close();
165
166 // Validate/normalize the requested format first so we never emit a
167 // corrupt header AND never destroy an existing file on a doomed
168 // request. WAV supports PCM at 8/16/24/32-bit and IEEE float at
169 // 32/64-bit; the fmt chunk stores the rate as uint32.
170 if (info.numChannels < 1 || info.numChannels > kMaxChannels) return false;
171 if (!(info.sampleRate >= 1.0) || info.sampleRate > 4294967295.0) return false;
172 if (info.isFloatingPoint)
173 {
174 if (info.bitsPerSample != 32 && info.bitsPerSample != 64)
175 return false;
176 }
177 else if (info.bitsPerSample != 8 && info.bitsPerSample != 16 &&
178 info.bitsPerSample != 24 && info.bitsPerSample != 32)
179 {
180 return false;
181 }
182
183 writeError_ = false;
184 file_.open(path, std::ios::binary | std::ios::out | std::ios::trunc);
185 if (!file_.is_open()) return false;
186
187 info_ = info;
188 mode_ = Mode::Write;
189 totalFramesWritten_ = 0;
190 writeContainer_ = rf64Mode_;
191
192 // Write placeholder header (sizes will be patched on close)
193 if (!writeHeader())
194 {
195 writeError_ = true;
196 close();
197 return false;
198 }
199
200 resizeIoBuffer();
201 return true;
202 }
203
214 [[nodiscard]] AudioFileInfo getInfo() const override { return info_; }
215
217 [[nodiscard]] Encoding getEncoding() const noexcept { return encoding_; }
218
219 [[nodiscard]] bool readSamples(AudioBufferView<float> dest) override
220 {
221 // An open-but-empty file (zero-length data chunk) reads zero frames
222 // successfully; only unopened handles or I/O errors report failure.
223 if (mode_ == Mode::Read && file_.is_open() && info_.numSamples == 0)
224 return true;
225 return readSamples(dest, 0, info_.numSamples);
226 }
227
228 [[nodiscard]] bool readSamples(AudioBufferView<float> dest,
229 int64_t startFrame, int64_t numFrames) override
230 {
231 if (mode_ != Mode::Read || !file_.is_open()) return false;
232 if (startFrame < 0 || numFrames <= 0) return false;
233 // Subtraction form: startFrame + numFrames can overflow int64, and
234 // the wrapped sum used to pass this check and seek into the header.
235 if (startFrame > info_.numSamples || numFrames > info_.numSamples - startFrame)
236 return false;
237
238 const int nCh = std::min(dest.getNumChannels(), static_cast<int>(info_.numChannels));
239 int64_t framesRemaining = std::min(numFrames, static_cast<int64_t>(dest.getNumSamples()));
240
241 if (encoding_ == Encoding::ImaAdpcm || encoding_ == Encoding::MsAdpcm)
242 return readAdpcm(dest, nCh, startFrame, framesRemaining);
243
244 const int frameSize = containerBytes_ * static_cast<int>(info_.numChannels);
245
246 // Seek to the exact start frame within the 'data' chunk
247 auto seekPos = dataChunkOffset_ + static_cast<std::streamoff>(startFrame * frameSize);
248 file_.seekg(seekPos, std::ios::beg);
249 if (!file_.good()) return false;
250
251 int64_t destOffset = 0;
252
253 while (framesRemaining > 0)
254 {
255 const auto toRead = std::min<int64_t>(framesRemaining, kChunkFrames);
256 const auto rawBytes = static_cast<std::streamsize>(toRead * frameSize);
257
258 file_.read(reinterpret_cast<char*>(ioBuffer_.data()), rawBytes);
259 if (file_.gcount() != rawBytes) return false;
260
261 deinterleave(ioBuffer_.data(), dest, nCh, static_cast<int>(toRead), static_cast<int>(destOffset));
262
263 destOffset += toRead;
264 framesRemaining -= toRead;
265 }
266
267 return true;
268 }
269
270 [[nodiscard]] bool writeSamples(AudioBufferView<const float> src) override
271 {
272 if (mode_ != Mode::Write || !file_.is_open()) return false;
273
274 const int nCh = static_cast<int>(info_.numChannels);
275 const int srcCh = std::min(src.getNumChannels(), nCh);
276 const int nS = src.getNumSamples();
277 const int frameSize = static_cast<int>(info_.bitsPerSample / 8) * nCh;
278
279 // Classic RIFF sizes are 32-bit: refuse a write that would push the
280 // data chunk past what the header can describe (header <= 128 bytes,
281 // plus the pad byte). RF64 sizes are 64-bit.
282 const int64_t dataAfter = (totalFramesWritten_ + nS) * static_cast<int64_t>(frameSize);
283 const int64_t limit = (writeContainer_ == Rf64Mode::Never)
284 ? static_cast<int64_t>(0xFFFFFFFFu) - 128
285 : (int64_t { 1 } << 62);
286 if (dataAfter > limit) return false;
287
288 int framesRemaining = nS;
289 int srcOffset = 0;
290
291 while (framesRemaining > 0)
292 {
293 const int toWrite = std::min(framesRemaining, kChunkFrames);
294
295 interleave(src, ioBuffer_.data(), nCh, srcCh, toWrite, srcOffset);
296
297 auto rawBytes = static_cast<std::streamsize>(static_cast<int64_t>(toWrite) * frameSize);
298 file_.write(reinterpret_cast<const char*>(ioBuffer_.data()), rawBytes);
299 if (!file_.good())
300 {
301 writeError_ = true;
302 return false;
303 }
304
305 srcOffset += toWrite;
306 framesRemaining -= toWrite;
307 }
308
309 totalFramesWritten_ += nS;
310 return true;
311 }
312
313 void close() override
314 {
315 resetReadFormat();
316 if (!file_.is_open()) { mode_ = Mode::Closed; info_ = {}; return; }
317
318 if (mode_ == Mode::Write)
319 {
320 finaliseHeader();
321 if (!file_.good()) writeError_ = true;
322 }
323
324 file_.close();
325 if (file_.fail()) writeError_ = true;
326 ioBuffer_.clear();
327 ioBuffer_.shrink_to_fit();
328 blockPcm_.clear();
329 blockPcm_.shrink_to_fit();
330 mode_ = Mode::Closed;
331 info_ = {}; // getInfo() contract: defaults once no file is open
332 }
333
334 [[nodiscard]] bool isOpen() const noexcept override
335 {
336 return file_.is_open() && mode_ != Mode::Closed;
337 }
338
345 [[nodiscard]] bool hasWriteError() const noexcept override { return writeError_; }
346
347private:
348 // -- RIFF/WAV constants ----------------------------------------------------
349
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; // indexed by a byte
360 static constexpr uint32_t kMaxAdpcmChannels = 2;
361
362 enum class Mode { Closed, Read, Write };
363
364 std::fstream file_;
365 Mode mode_ = Mode::Closed;
366 AudioFileInfo info_ {};
367 std::vector<uint8_t> ioBuffer_;
368
369 std::streamoff dataChunkOffset_ = 0;
370 std::streamoff dataChunkSizeOffset_ = 0;
371 uint64_t dataChunkSize_ = 0;
372 int64_t totalFramesWritten_ = 0;
373 Rf64Mode rf64Mode_ = Rf64Mode::Never; // for the next openWrite()
374 Rf64Mode writeContainer_ = Rf64Mode::Never; // of the file being written
375 bool writeError_ = false;
376
377 // Read-side format, set by parseFmtChunk(). PCM, float and G.711 read
378 // containerBytes_ per sample; ADPCM reads blockAlign_-byte blocks of
379 // samplesPerBlock_ frames into blockPcm_ (interleaved 16-bit).
380 Encoding encoding_ = Encoding::Pcm;
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_; // pairs: coef1, coef2
387 std::vector<int16_t> blockPcm_;
388
389 static constexpr uint32_t kRf64Unknown = 0xFFFFFFFFu;
390 static constexpr std::streamoff kDs64Offset = 12; // right after "WAVE"
391 static constexpr uint32_t kDs64Size = 28; // without a chunk table
392
393 [[nodiscard]] bool isAdpcm() const noexcept
394 {
395 return encoding_ == Encoding::ImaAdpcm || encoding_ == Encoding::MsAdpcm;
396 }
397
398 void resetReadFormat() noexcept
399 {
400 encoding_ = Encoding::Pcm;
401 containerBytes_ = 0;
402 blockAlign_ = 0;
403 samplesPerBlock_ = 0;
404 factFrames_ = 0;
405 hasFact_ = false;
406 }
407
408 void resizeIoBuffer()
409 {
410 size_t bytesNeeded = 0;
411 if (mode_ == Mode::Read && isAdpcm())
412 {
413 // Both are bounded by the 16-bit nBlockAlign: at most 64 KiB of
414 // block bytes and about 2 * nBlockAlign + nChannels samples.
415 bytesNeeded = blockAlign_;
416 blockPcm_.assign(static_cast<size_t>(samplesPerBlock_) * info_.numChannels, 0);
417 }
418 else
419 {
420 const size_t sampleBytes = (mode_ == Mode::Read)
421 ? static_cast<size_t>(containerBytes_)
422 : static_cast<size_t>(info_.bitsPerSample / 8);
423 bytesNeeded = static_cast<size_t>(kChunkFrames) * info_.numChannels * sampleBytes;
424 }
425 if (ioBuffer_.size() < bytesNeeded)
426 ioBuffer_.resize(bytesNeeded);
427 }
428
429 // -- Header parsing (read) -------------------------------------------------
430
431 bool parseHeader()
432 {
433 char riffId[4];
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;
438
439 uint32_t riffSize = 0;
440 if (!readLE32(riffSize)) return false;
441 (void)riffSize; // Deliberately ignored; many DAWs write invalid lengths
442
443 char waveId[4];
444 if (!readBytes(waveId, 4)) return false;
445 if (std::memcmp(waveId, "WAVE", 4) != 0) return false;
446
447 // RF64/BW64: the ds64 chunk comes first and holds the 64-bit sizes
448 // that the 32-bit fields mark with 0xFFFFFFFF.
449 uint64_t ds64DataSize = 0;
450 if (rf64)
451 {
452 char ds64Id[4];
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;
458 (void)riffSize64;
459 file_.seekg(static_cast<std::streamoff>(ds64Size) - 16 + (ds64Size & 1), std::ios::cur);
460 if (!file_.good()) return false;
461 }
462
463 bool hasFmt = false, hasData = false;
464
465 while (file_.good() && !(hasFmt && hasData))
466 {
467 char chunkId[4];
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;
474
475 // RIFF chunks are word-aligned: an odd-sized chunk is followed by
476 // one pad byte that is not part of the declared size. All skips
477 // below must account for it (in 64-bit arithmetic, so a corrupt
478 // size near UINT32_MAX cannot wrap the seek to zero).
479 const std::streamoff pad = static_cast<std::streamoff>(chunkSize & 1);
480
481 if (std::memcmp(chunkId, "fmt ", 4) == 0)
482 {
483 if (chunkSize > 0xFFFFu || !parseFmtChunk(static_cast<uint32_t>(chunkSize))) return false;
484 if (pad) file_.seekg(pad, std::ios::cur);
485 hasFmt = true;
486 }
487 else if (std::memcmp(chunkId, "data", 4) == 0)
488 {
489 auto currentPos = file_.tellg();
490 file_.seekg(0, std::ios::end);
491 auto fileEnd = file_.tellg();
492 file_.seekg(currentPos);
493
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);
498
499 dataChunkOffset_ = file_.tellg();
500 dataChunkSize_ = chunkSize;
501 hasData = true;
502
503 if (!hasFmt)
504 {
505 file_.seekg(static_cast<std::streamoff>(chunkSize) + pad, std::ios::cur);
506 }
507 }
508 else if (std::memcmp(chunkId, "fact", 4) == 0 && chunkSize >= 4)
509 {
510 // Frame count of a compressed stream; only used to trim the
511 // padding of the last ADPCM block (see adpcmFrameCount()).
512 if (!readLE32(factFrames_)) break;
513 hasFact_ = true;
514 file_.seekg(static_cast<std::streamoff>(chunkSize) - 4 + pad, std::ios::cur);
515 }
516 else
517 {
518 file_.seekg(static_cast<std::streamoff>(chunkSize) + pad, std::ios::cur);
519 }
520 }
521
522 // numSamples is derived here rather than inside the 'data' branch: if
523 // 'data' precedes 'fmt ' (legal but unusual chunk order), bit depth
524 // and channel count were still unknown at that point.
525 if (hasFmt && hasData)
526 {
527 if (isAdpcm())
528 {
529 info_.numSamples = adpcmFrameCount();
530 }
531 else
532 {
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);
536 }
537 }
538
539 return hasFmt && hasData;
540 }
541
542 // Frames held by an ADPCM block of `bytes` bytes (a full block or the
543 // short last one), or 0 when the bytes cannot hold the block header.
544 [[nodiscard]] uint32_t adpcmFramesInBlock(uint64_t bytes) const noexcept
545 {
546 const uint64_t nCh = info_.numChannels;
547 uint64_t frames = 0;
548 if (encoding_ == Encoding::ImaAdpcm)
549 {
550 // Header: one 4-byte word per channel holding the first sample;
551 // then 4-byte words per channel, 8 samples each, interleaved.
552 if (bytes >= 4 * nCh) frames = 1 + ((bytes - 4 * nCh) / (4 * nCh)) * 8;
553 }
554 else
555 {
556 // Header: 7 bytes per channel holding the first two samples;
557 // then one nibble per sample, channel-interleaved.
558 if (bytes >= 7 * nCh) frames = 2 + ((bytes - 7 * nCh) * 2) / nCh;
559 }
560 return static_cast<uint32_t>(std::min<uint64_t>(frames, samplesPerBlock_));
561 }
562
563 [[nodiscard]] int64_t adpcmFrameCount() const noexcept
564 {
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;
569
570 // Encoders pad the last block to nBlockAlign and record the true
571 // length in the fact chunk. Trust it only when it ends inside the
572 // last block: a stale or foreign count must not cut whole blocks.
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);
577 }
578
579 bool parseFmtChunk(uint32_t chunkSize)
580 {
581 if (chunkSize < 16) return false;
582
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;
589
590 if (!readLE16(audioFormat)) return false;
591 if (!readLE16(numChannels)) return false;
592 if (!readLE32(sampleRate)) return false;
593 if (!readLE32(byteRate)) return false;
594 (void)byteRate;
595 if (!readLE16(blockAlign)) return false;
596 if (!readLE16(bitsPerSample)) return false;
597
598 // ADPCM extension (WAVEFORMATEX cbSize + format-specific fields).
599 uint32_t fmtSamplesPerBlock = 0;
600 bool hasMsCoefficients = false;
601
602 if (audioFormat == kFormatExtensible && chunkSize >= 40)
603 {
604 uint16_t cbSize = 0;
605 readLE16(cbSize);
606 (void)cbSize; // Standard layout assumed; trailing bytes skipped below
607
608 // wValidBitsPerSample tells how many bits are significant, but the
609 // container width (wBitsPerSample) governs the stored layout: valid
610 // bits are left-justified, so decoding by container width yields
611 // the exact same values. Do NOT adopt validBits as the frame size
612 // (that mis-strides real 24-in-32 files). Read it only for sanity.
613 uint16_t validBitsPerSample = 0;
614 readLE16(validBitsPerSample);
615 if (validBitsPerSample > bitsPerSample) return false;
616
617 uint32_t channelMask = 0;
618 readLE32(channelMask);
619 (void)channelMask;
620
621 uint16_t subFormat = 0;
622 if (!readLE16(subFormat)) return false;
623 audioFormat = subFormat;
624
625 file_.seekg(14, std::ios::cur); // rest of the 16-byte subformat GUID
626
627 // Skip any extra bytes after the 40 standard EXTENSIBLE bytes so
628 // the chunk walker stays aligned on unusual writers.
629 if (chunkSize > 40)
630 file_.seekg(static_cast<std::streamoff>(chunkSize - 40), std::ios::cur);
631
632 // The ADPCM parameters live where EXTENSIBLE keeps its own
633 // fields, so an ADPCM subformat has no samples-per-block or
634 // coefficient table to decode with.
635 if (audioFormat == kFormatImaAdpcm || audioFormat == kFormatMsAdpcm) return false;
636 }
637 else if ((audioFormat == kFormatImaAdpcm || audioFormat == kFormatMsAdpcm) && chunkSize >= 18)
638 {
639 uint16_t cbSize = 0;
640 if (!readLE16(cbSize)) return false;
641 const uint32_t extBytes = std::min<uint32_t>(cbSize, chunkSize - 18);
642 uint32_t consumed = 18;
643
644 if (extBytes >= 2)
645 {
646 uint16_t spb = 0;
647 if (!readLE16(spb)) return false;
648 fmtSamplesPerBlock = spb;
649 consumed += 2;
650 }
651 if (audioFormat == kFormatMsAdpcm && extBytes >= 4)
652 {
653 uint16_t numCoef = 0;
654 if (!readLE16(numCoef)) return false;
655 consumed += 2;
656 // The block header indexes the table with one byte; a table
657 // that is empty, longer than that, or not all present in the
658 // chunk is malformed.
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_)
663 {
664 uint16_t v = 0;
665 if (!readLE16(v)) return false;
666 c = static_cast<int16_t>(v);
667 }
668 consumed += 4u * numCoef;
669 hasMsCoefficients = true;
670 }
671 if (chunkSize > consumed)
672 file_.seekg(static_cast<std::streamoff>(chunkSize - consumed), std::ios::cur);
673 }
674 else if (chunkSize > 16)
675 {
676 auto skip = static_cast<std::streamoff>(chunkSize - 16);
677 file_.seekg(skip, std::ios::cur);
678 }
679
680 info_.sampleRate = static_cast<double>(sampleRate);
681 info_.numChannels = numChannels;
682 info_.bitsPerSample = bitsPerSample;
683 info_.isFloatingPoint = (audioFormat == kFormatIEEEFloat);
684
685 if (sampleRate == 0) return false;
686 if (numChannels == 0 || numChannels > kMaxChannels) return false;
687
688 switch (audioFormat)
689 {
690 case kFormatPCM:
691 {
692 encoding_ = Encoding::Pcm;
693 if (bitsPerSample == 0 || bitsPerSample > 32) return false;
694 // Integer PCM has no 64-bit variant; without the gate above a
695 // PCM-64 header would pass validation and then "read" silence.
696 if ((bitsPerSample & 7) == 0)
697 {
698 containerBytes_ = bitsPerSample / 8;
699 }
700 else
701 {
702 // A depth that is not a whole number of bytes (12, 20...)
703 // is stored left-justified in a container the block
704 // alignment defines; the low padding bits are zero, so
705 // decoding the whole container is exact.
706 if (blockAlign == 0 || blockAlign % numChannels != 0) return false;
707 containerBytes_ = blockAlign / numChannels;
708 if (containerBytes_ < (bitsPerSample + 7) / 8 || containerBytes_ > 4) return false;
709 }
710 return true;
711 }
712 case kFormatIEEEFloat:
713 encoding_ = Encoding::Float;
714 if (bitsPerSample != 32 && bitsPerSample != 64) return false;
715 containerBytes_ = bitsPerSample / 8;
716 return true;
717 case kFormatALaw:
718 case kFormatMuLaw:
719 encoding_ = (audioFormat == kFormatALaw) ? Encoding::ALaw : Encoding::MuLaw;
720 if (bitsPerSample != 8) return false;
721 containerBytes_ = 1;
722 info_.bitsPerSample = 16;
723 return true;
724 case kFormatImaAdpcm:
725 case kFormatMsAdpcm:
726 {
727 encoding_ = (audioFormat == kFormatImaAdpcm) ? Encoding::ImaAdpcm : Encoding::MsAdpcm;
728 if (bitsPerSample != 4) return false;
729 // Mono and stereo only: no layout for more channels is
730 // agreed between encoders and decoders.
731 if (numChannels > kMaxAdpcmChannels) return false;
732 const uint32_t headerBytes = (encoding_ == Encoding::ImaAdpcm ? 4u : 7u) * numChannels;
733 if (blockAlign < headerBytes) return false;
734 // IMA data comes in one 4-byte word per channel at a time.
735 if (encoding_ == Encoding::ImaAdpcm && blockAlign % headerBytes != 0) return false;
736 blockAlign_ = blockAlign;
737 samplesPerBlock_ = std::numeric_limits<uint32_t>::max();
738 const uint32_t maxFrames = adpcmFramesInBlock(blockAlign);
739 // wSamplesPerBlock may be smaller than the block can hold
740 // (the decoder then stops there), never larger, and never
741 // smaller than the samples the block header itself carries.
742 const uint32_t minFrames = (encoding_ == Encoding::ImaAdpcm) ? 1u : 2u;
743 if (fmtSamplesPerBlock != 0
744 && (fmtSamplesPerBlock < minFrames || fmtSamplesPerBlock > maxFrames))
745 return false;
746 samplesPerBlock_ = (fmtSamplesPerBlock != 0) ? fmtSamplesPerBlock : maxFrames;
747 if (encoding_ == Encoding::MsAdpcm && !hasMsCoefficients)
748 {
749 // No table in the fmt chunk: the seven standard pairs.
750 static constexpr int16_t kStandard[14] = {
751 256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232
752 };
753 msCoefficients_.assign(std::begin(kStandard), std::end(kStandard));
754 }
755 info_.bitsPerSample = 16;
756 return true;
757 }
758 default:
759 return false;
760 }
761 }
762
763 // -- Compressed sample decoding (read only) --------------------------------
764
765 // ITU-T G.711 expansion to the 16-bit grid (A-law: 13-bit magnitudes x 8,
766 // mu-law: 14-bit magnitudes x 4).
767 [[nodiscard]] static constexpr int16_t aLawToLinear(uint8_t code) noexcept
768 {
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);
775 }
776
777 [[nodiscard]] static constexpr int16_t muLawToLinear(uint8_t code) noexcept
778 {
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));
782 }
783
784 template <bool ALaw>
785 [[nodiscard]] static constexpr std::array<float, 256> makeG711Table() noexcept
786 {
787 std::array<float, 256> t {};
788 for (int i = 0; i < 256; ++i)
789 {
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);
793 }
794 return t;
795 }
796
797 // IMA ADPCM step size per step index (the reference table).
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
805 };
806
807 // Per (step index, 3-bit magnitude): the difference the reference's
808 // "series of shifts" adds (not (2n + 1) * step / 8, which rounds
809 // differently) and the next step index. The lookup shortens the serial
810 // dependency between consecutive samples.
811 struct ImaTables { std::array<int32_t, 89 * 8> diff {}; std::array<uint8_t, 89 * 8> next {}; };
812
813 [[nodiscard]] static constexpr ImaTables makeImaTables() noexcept
814 {
815 constexpr int indexStep[8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
816 ImaTables t;
817 for (int i = 0; i < 89; ++i)
818 for (int m = 0; m < 8; ++m)
819 {
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; // up to 61436
826 t.next[static_cast<size_t>(i * 8 + m)] =
827 static_cast<uint8_t>(std::clamp(i + indexStep[m], 0, 88));
828 }
829 return t;
830 }
831
832 // Decodes the IMA ADPCM block of `bytes` bytes in ioBuffer_ into
833 // blockPcm_; returns the frames decoded, or 0 when a header is invalid.
834 [[nodiscard]] uint32_t decodeImaBlock(uint64_t bytes) noexcept
835 {
836 static constexpr ImaTables kTables = makeImaTables();
837
838 const uint32_t nCh = info_.numChannels;
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();
843
844 for (uint32_t ch = 0; ch < nCh; ++ch)
845 {
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]; // h[3] is reserved
849 if (index > 88) return 0;
850 out[ch] = static_cast<int16_t>(predictor);
851
852 // Words of 8 samples, low nibble first, channel words interleaved.
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)
856 {
857 const uint32_t count = std::min<uint32_t>(8, frames - done);
858 for (uint32_t k = 0; k < count; ++k, o += nCh)
859 {
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);
866 }
867 }
868 }
869 return frames;
870 }
871
872 // Microsoft ADPCM counterpart of decodeImaBlock().
873 [[nodiscard]] uint32_t decodeMsBlock(uint64_t bytes) noexcept
874 {
875 static constexpr int16_t kAdaptation[16] = {
876 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230
877 };
878 struct State { int64_t coef1, coef2, delta, s1, s2; };
879 std::array<State, kMaxAdpcmChannels> st {};
880
881 const uint32_t nCh = info_.numChannels;
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
887 {
888 return static_cast<int64_t>(static_cast<int16_t>(static_cast<uint16_t>(p[0] | (p[1] << 8))));
889 };
890
891 const size_t numCoef = msCoefficients_.size() / 2;
892 for (uint32_t ch = 0; ch < nCh; ++ch)
893 {
894 const uint8_t predictor = b[ch];
895 if (predictor >= numCoef) return 0;
896 State& s = st[ch];
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); // the newer sample
901 s.s2 = le16(b + 5 * nCh + 2 * ch); // the older, output first
902 out[ch] = static_cast<int16_t>(s.s2);
903 out[nCh + ch] = static_cast<int16_t>(s.s1);
904 }
905
906 // One nibble per sample, high nibble first, channel-interleaved.
907 const uint8_t* data = b + 7 * nCh;
908 uint32_t i = 0;
909 for (uint32_t frame = 2; frame < frames; ++frame)
910 {
911 for (uint32_t ch = 0; ch < nCh; ++ch, ++i)
912 {
913 const int nibble = (data[i >> 1] >> ((i & 1) ? 0 : 4)) & 0x0F;
914 State& s = st[ch];
915 // Division by 256 truncates toward zero, the common decoder
916 // convention; an arithmetic shift would floor and drift by a
917 // few LSB. The step size is held to 32 bits.
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);
921 s.s2 = s.s1;
922 s.s1 = sample;
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);
925 }
926 }
927 return frames;
928 }
929
930 bool readAdpcm(AudioBufferView<float>& dest, int nCh, int64_t startFrame, int64_t frames)
931 {
932 const uint32_t fileCh = info_.numChannels;
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;
936
937 while (frames > 0)
938 {
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);
942
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;
947
948 const uint32_t decoded = (encoding_ == Encoding::ImaAdpcm) ? decodeImaBlock(bytes)
949 : decodeMsBlock(bytes);
950 if (decoded <= offset) return false; // corrupt block header
951
952 const int64_t take = std::min<int64_t>(frames, decoded - offset);
953 for (int ch = 0; ch < nCh; ++ch)
954 {
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);
960 }
961
962 destOffset += take;
963 frames -= take;
964 offset = 0;
965 ++block;
966 }
967 return true;
968 }
969
970 // -- Header writing --------------------------------------------------------
971
972 bool writeHeader()
973 {
974 const uint16_t formatTag = getWriteFormatTag();
975 const bool extensible = (formatTag == kFormatExtensible);
976 const uint32_t fmtChunkSize = extensible ? 40u : 16u;
977
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));
984
985 writeBytes(writeContainer_ == Rf64Mode::Always ? "RF64" : "RIFF", 4);
986 writeLE32(0); // Patched on close
987 writeBytes("WAVE", 4);
988
989 if (writeContainer_ != Rf64Mode::Never)
990 {
991 // ds64 slot (EBU Tech 3306): a JUNK chunk of the same size that
992 // close() turns into ds64 when the file becomes RF64.
993 writeBytes(writeContainer_ == Rf64Mode::Always ? "ds64" : "JUNK", 4);
994 writeLE32(kDs64Size);
995 for (uint32_t i = 0; i < kDs64Size; ++i) file_.put('\0');
996 }
997
998 writeBytes("fmt ", 4);
999 writeLE32(fmtChunkSize);
1000 writeLE16(formatTag);
1001 writeLE16(static_cast<uint16_t>(info_.numChannels));
1002 writeLE32(rate);
1003 writeLE32(byteRate);
1004 writeLE16(blockAlign);
1005 writeLE16(static_cast<uint16_t>(info_.bitsPerSample));
1006
1007 if (extensible)
1008 {
1009 writeLE16(22);
1010 writeLE16(static_cast<uint16_t>(info_.bitsPerSample));
1011 writeLE32(0);
1012
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
1018 };
1019 writeBytes(reinterpret_cast<const char*>(kGuidSuffix), 14);
1020 }
1021
1022 writeBytes("data", 4);
1023 dataChunkSizeOffset_ = file_.tellp();
1024 writeLE32(0); // Patched on close
1025
1026 dataChunkOffset_ = file_.tellp();
1027 return file_.good();
1028 }
1029
1030 void finaliseHeader()
1031 {
1032 if (!file_.is_open()) return;
1033
1034 // A transient failure (e.g. one failed writeSamples) leaves sticky
1035 // failbits that would turn the header patch into a silent no-op.
1036 // Clear them so whatever WAS written gets a consistent header.
1037 file_.clear();
1038
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);
1042
1043 // RIFF chunks are word-aligned: an odd data chunk (8-bit or 24-bit
1044 // with an odd frame count) is followed by one pad byte, counted in
1045 // the RIFF size but not in the data size.
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;
1050
1051 const bool asRf64 = writeContainer_ == Rf64Mode::Always
1052 || (writeContainer_ == Rf64Mode::Auto && riffSize > 0xFFFFFFFFull);
1053 if (asRf64)
1054 {
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);
1065 writeLE32(0); // no chunk size table
1066 file_.seekp(dataChunkSizeOffset_, std::ios::beg);
1067 writeLE32(kRf64Unknown);
1068 }
1069 else
1070 {
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));
1075 }
1076
1077 file_.flush();
1078 }
1079
1080 [[nodiscard]] uint16_t getWriteFormatTag() const noexcept
1081 {
1082 if (info_.numChannels > 2 || info_.bitsPerSample > 16) return kFormatExtensible;
1083 if (info_.isFloatingPoint) return kFormatIEEEFloat;
1084 return kFormatPCM;
1085 }
1086
1087 // -- Sample conversion (read: raw to float) --------------------------------
1088
1089 void deinterleave(const uint8_t* raw, AudioBufferView<float>& dest, int nCh, int numFrames, int destOffset) const
1090 {
1091 if (encoding_ == Encoding::ALaw || encoding_ == Encoding::MuLaw)
1092 {
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)
1098 {
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]];
1103 }
1104 return;
1105 }
1106
1107 // The container width, not the declared depth, sets the layout
1108 // (12-bit samples sit in 16-bit containers, 20-bit in 24-bit ones).
1109 if (encoding_ == Encoding::Float) {
1110 if (containerBytes_ == 4) deinterleaveImpl<float, 32>(raw, dest, nCh, numFrames, destOffset);
1111 else deinterleaveImpl<double, 64>(raw, dest, nCh, numFrames, destOffset);
1112 } else {
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;
1118 default: break;
1119 }
1120 }
1121 }
1122
1123 template <typename T, int Bits>
1124 void deinterleaveImpl(const uint8_t* raw, AudioBufferView<float>& dest, int nCh, int numFrames, int destOffset) const
1125 {
1126 const int bytesPerSample = Bits / 8;
1127 const int stride = static_cast<int>(info_.numChannels) * bytesPerSample;
1128
1129 // Channel-major loop: each output channel is written contiguously
1130 // (cache-friendly); the byte-wise strided source reads are the cost
1131 // of endian-safe decoding.
1132 for (int ch = 0; ch < nCh; ++ch)
1133 {
1134 float* out = dest.getChannel(ch) + destOffset;
1135 const uint8_t* channelRaw = raw + (ch * bytesPerSample);
1136
1137 for (int f = 0; f < numFrames; ++f)
1138 {
1139 const uint8_t* ptr = channelRaw + (f * stride);
1140
1141 if constexpr (Bits == 8) {
1142 out[f] = (static_cast<float>(ptr[0]) - 128.0f) * (1.0f / 128.0f);
1143 }
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);
1147 }
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);
1152 }
1153 else if constexpr (Bits == 32 && std::is_same_v<T, int32_t>) {
1154 // Assemble in unsigned to avoid signed overflow UB on the high
1155 // byte (ptr[3] << 24 with the top bit set), then reinterpret.
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);
1162 }
1163 else if constexpr (Bits == 32 && std::is_same_v<T, float>) {
1164 float v; std::memcpy(&v, ptr, 4); out[f] = v;
1165 }
1166 else if constexpr (Bits == 64) {
1167 double v; std::memcpy(&v, ptr, 8); out[f] = static_cast<float>(v);
1168 }
1169 }
1170 }
1171 }
1172
1173 // -- Sample conversion (write: float to raw) --------------------------------
1174
1175 void interleave(AudioBufferView<const float> src, uint8_t* raw,
1176 int fileCh, int srcCh, int numFrames, int srcOffset) const
1177 {
1178 if (info_.isFloatingPoint) {
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);
1181 } else {
1182 switch (info_.bitsPerSample) {
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;
1187 }
1188 }
1189 }
1190
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
1194 {
1195 const int bytesPerSample = Bits / 8;
1196
1197 // Frame-major loop is required here to emit contiguous interleaved
1198 // data. Channels the source view does not carry are written as
1199 // silence (same contract as Mp3File) instead of reading out of range.
1200 for (int f = 0; f < numFrames; ++f)
1201 {
1202 for (int ch = 0; ch < fileCh; ++ch)
1203 {
1204 float value = (ch < srcCh) ? src.getChannel(ch)[srcOffset + f] : 0.0f;
1205 uint8_t* ptr = raw + ((f * fileCh + ch) * bytesPerSample);
1206
1207 // A NaN has no integer code: std::clamp passes it through and
1208 // the float-to-int conversion is then undefined (x86 wrote the
1209 // most negative code, a full-scale click). Integer formats
1210 // write it as silence; +-Inf clamp to full scale below.
1211 if constexpr (std::is_integral_v<T>)
1212 if (value != value) value = 0.0f;
1213
1214 // Precise rounding & strict clipping bounds
1215 if constexpr (Bits == 8) {
1216 // 8-bit WAV is unsigned with 128 as zero, and the reader
1217 // scales by 128. Writing with 127 put every sample on a
1218 // different grid, so an 8-bit round trip came back 0.78%
1219 // quiet - a whole quantisation step of systematic error on
1220 // top of the quantisation itself. Only +1.0 now clamps,
1221 // which is inherent to the 128-step scale.
1222 auto val = static_cast<uint8_t>(std::clamp(std::round(value * 128.0f) + 128.0f, 0.0f, 255.0f));
1223 ptr[0] = val;
1224 }
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;
1228 }
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;
1232 }
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;
1236 }
1237 else if constexpr (Bits == 32 && std::is_same_v<T, float>) {
1238 std::memcpy(ptr, &value, 4);
1239 }
1240 else if constexpr (Bits == 64) {
1241 double d = static_cast<double>(value);
1242 std::memcpy(ptr, &d, 8);
1243 }
1244 }
1245 }
1246 }
1247
1248 // -- Low-level I/O helpers (little-endian) ---------------------------------
1249
1250 bool readBytes(char* buf, int n)
1251 {
1252 file_.read(buf, n);
1253 return file_.gcount() == n;
1254 }
1255
1256 bool readLE16(uint16_t& val)
1257 {
1258 uint8_t b[2];
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);
1262 return true;
1263 }
1264
1265 bool readLE64(uint64_t& val)
1266 {
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);
1270 return true;
1271 }
1272
1273 bool readLE32(uint32_t& val)
1274 {
1275 uint8_t b[4];
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);
1282 return true;
1283 }
1284
1285 void writeBytes(const char* buf, int n)
1286 {
1287 file_.write(buf, n);
1288 }
1289
1290 void writeLE16(uint16_t val)
1291 {
1292 uint8_t b[2] = {
1293 static_cast<uint8_t>(val & 0xFF),
1294 static_cast<uint8_t>((val >> 8) & 0xFF)
1295 };
1296 file_.write(reinterpret_cast<const char*>(b), 2);
1297 }
1298
1299 void writeLE64(uint64_t val)
1300 {
1301 writeLE32(static_cast<uint32_t>(val));
1302 writeLE32(static_cast<uint32_t>(val >> 32));
1303 }
1304
1305 void writeLE32(uint32_t val)
1306 {
1307 uint8_t b[4] = {
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)
1312 };
1313 file_.write(reinterpret_cast<const char*>(b), 4);
1314 }
1315};
1316
1317} // 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.
Abstract base class for audio file readers and writers.
Definition AudioFile.h:111
Complete WAV file reader and writer in pure C++20.
Definition WavFile.h:97
Rf64Mode getRf64Mode() const noexcept
Container chosen for files opened for writing.
Definition WavFile.h:124
Encoding getEncoding() const noexcept
Sample coding of the file open for reading (Pcm when none is).
Definition WavFile.h:217
AudioFileInfo getInfo() const override
Format of the open file.
Definition WavFile.h:214
bool readSamples(AudioBufferView< float > dest) override
Reads samples from the start of the file into the destination view.
Definition WavFile.h:219
Encoding
How the samples of the file open for reading are coded.
Definition WavFile.h:101
@ ImaAdpcm
IMA/DVI ADPCM, 4 bits per sample.
@ Float
IEEE 754 float.
@ MuLaw
ITU-T G.711 mu-law.
@ Pcm
Linear integer PCM (including EXTENSIBLE and 12/20-bit).
@ MsAdpcm
Microsoft ADPCM, 4 bits per sample.
@ ALaw
ITU-T G.711 A-law.
void setRf64Mode(Rf64Mode mode) noexcept
Chooses the container of files opened for writing from now on.
Definition WavFile.h:121
bool isOpen() const noexcept override
Checks if a valid file handle is currently open.
Definition WavFile.h:334
~WavFile() override
Definition WavFile.h:118
bool hasWriteError() const noexcept override
True when a write or the header finalisation of the current or most recent writer failed.
Definition WavFile.h:345
bool writeSamples(AudioBufferView< const float > src) override
Writes samples from the view to the file.
Definition WavFile.h:270
bool openRead(const std::filesystem::path &path) override
Opens a WAV file for reading.
Definition WavFile.h:133
bool openWrite(const std::filesystem::path &path, const AudioFileInfo &info) override
Opens a WAV file for writing, overwriting if it exists.
Definition WavFile.h:162
void close() override
Finalizes file headers and releases system handles.
Definition WavFile.h:313
Rf64Mode
Container used by the next openWrite().
Definition WavFile.h:112
@ Auto
RIFF with a reserved ds64 slot, promoted to RF64 beyond 4 GiB.
@ Always
RF64 whatever the size.
@ Never
Classic RIFF/WAVE, at most 4 GiB (the default).
bool readSamples(AudioBufferView< float > dest, int64_t startFrame, int64_t numFrames) override
Reads a specific range of sample frames. Useful for chunked streaming.
Definition WavFile.h:228
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
bool isFloatingPoint
True if the file stores floating-point samples (IEEE 754).
Definition AudioFile.h:63
uint32_t bitsPerSample
Bits per sample in the stored format (8, 16, 24, 32, 64).
Definition AudioFile.h:60
double sampleRate
Sample rate in Hz (e.g., 44100.0, 48000.0, 96000.0).
Definition AudioFile.h:41
int64_t numSamples
Total number of sample frames in the file.
Definition AudioFile.h:47