Skip to content

πŸŽ› πŸ”Š A Python library for audio.

Bound WAV frame counts to available uncompressed audio

Christopher Jacobyb856b739d64d
diff --git a/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h b/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h
index 9133bb8..dce88e1 100644
--- a/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h
+++ b/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h
@@ -18,6 +18,7 @@
#pragma once
#include "../JuceHeader.h"
+#include "../io/PythonFileLike.h"
#include "juce_PatchedMP3AudioFormat.h"
// dr_wav for ADPCM decoding (public domain / MIT-0)
@@ -224,90 +225,220 @@ public:
AudioFormatReader *createReaderFor(InputStream *sourceStream,
bool deleteStreamIfOpeningFails) override {
- auto streamStartPos = sourceStream->getPosition();
-
- // Helper to delegate to the parent WavAudioFormat implementation
- auto useDefaultReader = [&]() {
- sourceStream->setPosition(streamStartPos);
+ const auto streamStartPos = sourceStream->getPosition();
+ const auto invalidFormat = [&](const char *message) -> AudioFormatReader * {
+ std::unique_ptr<InputStream> cleanup(
+ deleteStreamIfOpeningFails ? sourceStream : nullptr);
+ // File-like callbacks retain Python errors for the caller. Do not replace
+ // an original read/seek error with a secondary format error.
+ Pedalboard::PythonException::raise();
+ throw std::domain_error(std::string("Invalid WAV format: ") + message);
+ };
+ const auto seekTo = [&](int64 position) {
+ return sourceStream->setPosition(position) &&
+ sourceStream->getPosition() == position;
+ };
+ const auto useDefaultReader = [&]() -> AudioFormatReader * {
+ if (!seekTo(streamStartPos))
+ return invalidFormat("failed to seek to the RIFF header");
return WavAudioFormat::createReaderFor(sourceStream,
deleteStreamIfOpeningFails);
};
- // Read the RIFF header
- auto firstChunkType = sourceStream->readInt();
- if (firstChunkType != chunkName("RIFF") &&
- firstChunkType != chunkName("RF64")) {
+ uint8 header[12];
+ if (sourceStream->read(header, sizeof(header)) != sizeof(header))
return useDefaultReader();
- }
-
- // Skip the size field
- sourceStream->readInt();
-
- // Check for WAVE identifier
- if (sourceStream->readInt() != chunkName("WAVE")) {
+ const auto firstChunkType = (int)ByteOrder::littleEndianInt(header);
+ const bool isRF64 = firstChunkType == chunkName("RF64");
+ if ((!isRF64 && firstChunkType != chunkName("RIFF")) ||
+ (int)ByteOrder::littleEndianInt(header + 8) != chunkName("WAVE"))
return useDefaultReader();
- }
- // Look for the fmt chunk to check the format tag
- while (!sourceStream->isExhausted()) {
- auto chunkType = sourceStream->readInt();
- auto length = (uint32)sourceStream->readInt();
- auto chunkEnd = sourceStream->getPosition() + length + (length & 1);
+ const auto totalLength = sourceStream->getTotalLength();
+ if (totalLength < 0) {
+ // A pending Python error is propagated by ReadableAudioFile, whereas a
+ // genuinely unknown length retains the existing codec dispatch below.
+ if (Pedalboard::PythonException::isPending()) {
+ if (deleteStreamIfOpeningFails)
+ delete sourceStream;
+ return nullptr;
+ }
+ }
+ const auto riffLength = ByteOrder::littleEndianInt(header + 4);
+ if (streamStartPos < 0 ||
+ streamStartPos > std::numeric_limits<int64>::max() - 8 - riffLength)
+ return invalidFormat("RIFF size exceeds the stream position range");
+ const auto containerEnd =
+ isRF64 ? totalLength : streamStartPos + 8 + (int64)riffLength;
+ auto scanEnd = totalLength < 0 ? containerEnd
+ : isRF64 ? totalLength
+ : std::min(totalLength, containerEnd);
+ bool foundFormat = false;
+ int64 dataOffset = -1;
+ int64 ds64Offset = -1;
+ int64 bytesPerFrame = 0;
+ bool eligible = false;
+
+ while (totalLength < 0 ? !sourceStream->isExhausted()
+ : sourceStream->getPosition() < scanEnd) {
+ const auto chunkStart = sourceStream->getPosition();
+ if (totalLength >= 0 && scanEnd - chunkStart < 8)
+ return invalidFormat("truncated chunk header");
+ uint8 chunkHeader[8];
+ if (sourceStream->read(chunkHeader, sizeof(chunkHeader)) !=
+ sizeof(chunkHeader))
+ return invalidFormat("truncated chunk header");
+ const auto chunkType = (int)ByteOrder::littleEndianInt(chunkHeader);
+ const auto length = ByteOrder::littleEndianInt(chunkHeader + 4);
+ const auto payloadStart = sourceStream->getPosition();
+ const int64 paddedLength = (int64)length + (length & 1);
+ if (payloadStart <= chunkStart ||
+ payloadStart > std::numeric_limits<int64>::max() - paddedLength)
+ return invalidFormat("invalid chunk position or size");
+ auto chunkEnd = payloadStart + paddedLength;
+ int64 payloadLength = length;
+ if (isRF64 && chunkType == chunkName("ds64") &&
+ chunkStart == streamStartPos + 12 && length >= 28)
+ ds64Offset = payloadStart;
if (chunkType == chunkName("fmt ")) {
- auto format = (unsigned short)sourceStream->readShort();
-
+ if (foundFormat)
+ return invalidFormat("ambiguous repeated fmt chunk");
+ foundFormat = true;
+ uint8 fmt[40];
+ if (length < 2 || (totalLength >= 0 && scanEnd - payloadStart < 2) ||
+ sourceStream->read(fmt, 2) != 2)
+ return invalidFormat("truncated fmt fields");
+ const auto format = ByteOrder::littleEndianShort(fmt);
switch (static_cast<WavFormatTag>(format)) {
case WavFormatTag::MPEGLayer3:
return createMP3ReaderForWav(sourceStream, chunkEnd, streamStartPos,
deleteStreamIfOpeningFails);
-
case WavFormatTag::ADPCM:
case WavFormatTag::IMAADPCM:
case WavFormatTag::ALaw:
case WavFormatTag::MuLaw:
return createDrWavReaderForWav(sourceStream, streamStartPos,
deleteStreamIfOpeningFails);
-
- case WavFormatTag::IEEEFloat: {
- // JUCE doesn't support 64-bit float WAV, but dr_wav does.
- // Read bitsPerSample from fmt chunk to check.
- // fmt chunk layout after formatTag: channels(2), sampleRate(4),
- // byteRate(4), blockAlign(2), bitsPerSample(2)
- sourceStream->skipNextBytes(12);
- auto bitsPerSample = (unsigned short)sourceStream->readShort();
- if (bitsPerSample == 64) {
- return createDrWavReaderForWav(sourceStream, streamStartPos,
- deleteStreamIfOpeningFails);
- }
- // 32-bit float is handled fine by JUCE
- return useDefaultReader();
- }
-
- default:
- // Check for known-but-unsupported formats and throw helpful errors
- const char *unsupportedCodecName = getUnsupportedCodecName(format);
- if (unsupportedCodecName != nullptr) {
+ case WavFormatTag::PCM:
+ case WavFormatTag::IEEEFloat:
+ case WavFormatTag::Extensible:
+ break;
+ default: {
+ const auto *codec = getUnsupportedCodecName(format);
+ if (codec != nullptr) {
if (deleteStreamIfOpeningFails)
delete sourceStream;
throw std::domain_error(
- "This WAV file uses the " + std::string(unsupportedCodecName) +
+ "This WAV file uses the " + std::string(codec) +
" audio codec (format tag 0x" + toHexString(format) +
"), which is not supported. "
"Please convert the file to a standard PCM WAV, FLAC, or MP3 "
"format before loading.");
}
+ // In particular, JUCE may delegate Ogg-in-WAV to a compressed reader.
+ return useDefaultReader();
+ }
+ }
+ const int fmtSize =
+ format == (uint16)WavFormatTag::Extensible ? 40 : 16;
+ if (length < (uint32)fmtSize ||
+ (totalLength >= 0 && scanEnd - payloadStart < fmtSize) ||
+ sourceStream->read(fmt + 2, fmtSize - 2) != fmtSize - 2)
+ return invalidFormat("truncated required fmt fields");
+ const auto channels = ByteOrder::littleEndianShort(fmt + 2);
+ const auto sampleRate = (int32)ByteOrder::littleEndianInt(fmt + 4);
+ const auto byteRate = (int32)ByteOrder::littleEndianInt(fmt + 8);
+ const auto bits = ByteOrder::littleEndianShort(fmt + 14);
+ if (format == (uint16)WavFormatTag::IEEEFloat && bits == 64)
+ return createDrWavReaderForWav(sourceStream, streamStartPos,
+ deleteStreamIfOpeningFails);
- // All other formats: delegate to JUCE's WavAudioFormat
+ // Match JUCE 6.1.4's decoder stride, including its legacy bit-depth
+ // normalization. The untrusted blockAlign field is deliberately unused.
+ bytesPerFrame = bits > 64 && sampleRate != 0
+ ? (int64)byteRate / sampleRate
+ : (int64)channels * bits / 8;
+ eligible = format == (uint16)WavFormatTag::PCM ||
+ (format == (uint16)WavFormatTag::IEEEFloat && bits == 32);
+ if (format == (uint16)WavFormatTag::Extensible) {
+ // Standard PCM/float and the ambisonic PCM GUID supported by JUCE.
+ static const uint8 pcm[] = {1, 0, 0, 0, 0, 0, 0x10, 0,
+ 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71};
+ static const uint8 floating[] = {
+ 3, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71};
+ static const uint8 ambisonic[] = {1, 0, 0, 0, 0x21, 7,
+ 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
+ 0xca, 0, 0, 0};
+ eligible = std::memcmp(fmt + 24, pcm, 16) == 0 ||
+ std::memcmp(fmt + 24, ambisonic, 16) == 0 ||
+ (bits == 32 && std::memcmp(fmt + 24, floating, 16) == 0);
+ if (!eligible)
+ return useDefaultReader();
+ }
+ if (totalLength < 0)
return useDefaultReader();
+ } else if (chunkType == chunkName("data")) {
+ if (dataOffset >= 0)
+ return invalidFormat("ambiguous repeated data chunk");
+ dataOffset = payloadStart;
+ if (isRF64 && ds64Offset >= 0 && totalLength >= 0) {
+ // Only resolve ds64 when traversal needs it: JUCE skips RF64 data
+ // using this size even if its chunk header is not the sentinel.
+ // Inspect subsequent headers so they cannot change JUCE's selected
+ // payload/stride behind our clamp. Respect its container end too.
+ uint8 sizes[16];
+ if (!seekTo(ds64Offset) ||
+ sourceStream->read(sizes, sizeof(sizes)) != sizeof(sizes))
+ return invalidFormat("failed to read RF64 traversal sizes");
+ const auto riffSize = ByteOrder::littleEndianInt64(sizes);
+ const auto dataSize = ByteOrder::littleEndianInt64(sizes + 8);
+ const auto riffStart = streamStartPos + 8;
+ if (riffSize >
+ (uint64)(std::numeric_limits<int64>::max() - riffStart))
+ return invalidFormat("RF64 size exceeds the stream position range");
+ scanEnd = std::min(totalLength, riffStart + (int64)riffSize);
+ if (dataSize == 0 ||
+ dataSize > (uint64)std::numeric_limits<int64>::max())
+ break; // Leave invalid/empty ds64 frame semantics to JUCE.
+ payloadLength = (int64)dataSize;
+ if (payloadLength > scanEnd - payloadStart)
+ break;
+ // The subtraction above bounds the addition by the physical end.
+ chunkEnd = payloadStart + payloadLength;
+ if ((payloadLength & 1) != 0) {
+ if (chunkEnd == scanEnd)
+ break; // The final pad byte may be absent.
+ ++chunkEnd;
+ }
+ } else if (isRF64 && length == 0xffffffffu) {
+ break; // Never interpret an unresolved sentinel as a payload size.
}
+ // An oversized data chunk consumes the available tail.
+ if (totalLength >= 0 && payloadLength > scanEnd - payloadStart)
+ break;
}
- sourceStream->setPosition(chunkEnd);
+ if (totalLength >= 0 && chunkEnd > scanEnd) {
+ // A final odd data payload need not have a physically present pad byte.
+ if (chunkType == chunkName("data") &&
+ payloadLength == scanEnd - payloadStart)
+ break;
+ return invalidFormat("truncated chunk payload");
+ }
+ if (!seekTo(chunkEnd) || sourceStream->getPosition() <= chunkStart)
+ return invalidFormat("failed or nonadvancing chunk seek");
}
- // Couldn't find fmt chunk - let JUCE handle it
- return useDefaultReader();
+ auto *reader = useDefaultReader();
+ // Do not touch the stream after delegation: JUCE may have deleted it.
+ if (reader != nullptr && eligible && totalLength >= 0 && dataOffset >= 0 &&
+ bytesPerFrame > 0) {
+ const auto available = std::max<int64>(0, totalLength - dataOffset);
+ reader->lengthInSamples =
+ std::min(reader->lengthInSamples, available / bytesPerFrame);
+ }
+ return reader;
}
private:
diff --git a/tests/test_wav_header_length.py b/tests/test_wav_header_length.py
new file mode 100644
index 0000000..f4f8449
--- /dev/null
+++ b/tests/test_wav_header_length.py
@@ -0,0 +1,414 @@
+"""Finite WAV streams must never expose samples beyond their real contents."""
+
+import struct
+from io import BytesIO
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from pedalboard import Resample
+from pedalboard.io import AudioFile
+
+SAMPLE_RATE = 48_000
+NUM_CHANNELS = 2
+NUM_FRAMES = 4_800
+TARGET_SAMPLE_RATE = 22_050
+TARGET_NUM_FRAMES = 2_205
+
+
+def _chunk(tag, payload, declared_size=None):
+ return (
+ tag
+ + struct.pack("<I", len(payload) if declared_size is None else declared_size)
+ + payload
+ + (b"\0" if len(payload) % 2 else b"")
+ )
+
+
+def _fmt(*, tag=1, bits=16, block_align=None, guid=None):
+ alignment = NUM_CHANNELS * ((bits + 7) // 8) if block_align is None else block_align
+ result = struct.pack(
+ "<HHIIHH", tag, NUM_CHANNELS, SAMPLE_RATE, SAMPLE_RATE * alignment, alignment, bits
+ )
+ if tag == 0xFFFE:
+ result += struct.pack("<HHI", 22, bits, 3) + guid
+ return result
+
+
+def _wav(
+ payload, *, fmt=None, data_size=None, riff_size=None, before=b"", after=b"", rf64_size=None
+):
+ chunks = (
+ before
+ + _chunk(b"fmt ", _fmt() if fmt is None else fmt)
+ + _chunk(b"data", payload, data_size)
+ + after
+ )
+ if rf64_size is not None:
+ ds64 = _chunk(
+ b"ds64", struct.pack("<QQQI", len(chunks) + 40, rf64_size, len(payload) // 4, 0)
+ )
+ return b"RF64\xff\xff\xff\xffWAVE" + ds64 + chunks
+ return (
+ b"RIFF"
+ + struct.pack("<I", len(chunks) + 4 if riff_size is None else riff_size)
+ + b"WAVE"
+ + chunks
+ )
+
+
+def _pcm16(frames):
+ return struct.pack("<hh", 8192, -8192) * frames
+
+
[email protected](params=["path", "bytes_io", "offset_bytes_io"])
+def wav_source(request, tmp_path):
+ def make_source(contents):
+ if request.param == "path":
+ path = tmp_path / "header-length.wav"
+ path.write_bytes(contents)
+ return str(path)
+ if request.param == "offset_bytes_io":
+ stream = BytesIO(b"prefix!" + contents)
+ stream.seek(7)
+ return stream
+ return BytesIO(contents)
+
+ return make_source
+
+
[email protected]("oversized", [False, True], ids=["healthy", "oversized-data"])
+def test_wav_length_reads_and_seeks_stop_at_real_frames(wav_source, oversized):
+ contents = _wav(_pcm16(NUM_FRAMES), data_size=0xFFFFFFFF if oversized else None)
+ with AudioFile(wav_source(contents)) as audio:
+ assert audio.frames == NUM_FRAMES
+ assert audio.duration == pytest.approx(0.1)
+ samples = audio.read(2 * NUM_FRAMES)
+ assert samples.shape == (2, NUM_FRAMES)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ np.testing.assert_allclose(samples[1], -0.25, atol=1 / 32767)
+ assert audio.read(1).shape == (2, 0)
+ audio.seek(NUM_FRAMES - 2)
+ np.testing.assert_array_equal(audio.read(8), samples[:, -2:])
+ audio.seek(NUM_FRAMES)
+ assert audio.read(1).shape == (2, 0)
+ audio.seek(0)
+ raw = audio.read_raw(2 * NUM_FRAMES)
+ assert raw.shape == (2, NUM_FRAMES)
+ assert np.all(raw[0] == 8192)
+ assert np.all(raw[1] == -8192)
+ assert audio.read_raw(1).shape == (2, 0)
+
+
+def test_oversized_wav_resampling_matches_healthy_control(wav_source):
+ decoded = []
+ for size in (None, 0xFFFFFFFF):
+ with AudioFile(wav_source(_wav(_pcm16(NUM_FRAMES), data_size=size))).resampled_to(
+ TARGET_SAMPLE_RATE, Resample.Quality.WindowedSinc256
+ ) as audio:
+ assert audio.frames == TARGET_NUM_FRAMES
+ assert audio.duration == pytest.approx(0.1)
+ samples = audio.read(2 * TARGET_NUM_FRAMES)
+ assert samples.shape == (2, TARGET_NUM_FRAMES)
+ assert audio.read(1).shape == (2, 0)
+ audio.seek(TARGET_NUM_FRAMES - 3)
+ np.testing.assert_allclose(audio.read(10), samples[:, -3:], atol=1e-6)
+ decoded.append(samples)
+ np.testing.assert_array_equal(*decoded)
+
+
+def test_oversized_wav_resample_to_wav_roundtrip_is_bounded(wav_source):
+ output = BytesIO()
+ with AudioFile(wav_source(_wav(_pcm16(NUM_FRAMES), data_size=0xFFFFFFFF))).resampled_to(
+ TARGET_SAMPLE_RATE, Resample.Quality.WindowedSinc256
+ ) as reader:
+ with AudioFile(output, "w", TARGET_SAMPLE_RATE, 2, format="wav") as writer:
+ for _ in range(12):
+ samples = reader.read(256)
+ if not samples.shape[1]:
+ break
+ writer.write(samples)
+ else:
+ pytest.fail("resampling did not terminate within the real audio duration")
+ assert output.getbuffer().nbytes < 20_000
+ output.seek(0)
+ with AudioFile(output) as audio:
+ assert audio.frames == TARGET_NUM_FRAMES
+ assert audio.duration == pytest.approx(0.1)
+ samples = audio.read(2 * TARGET_NUM_FRAMES)
+ assert samples.shape == (2, TARGET_NUM_FRAMES)
+ assert np.max(np.abs(samples)) > 0.2
+
+
+ "case",
+ [
+ "riff",
+ "data",
+ "both",
+ "odd-junk",
+ "partial-frame",
+ "short-data-list",
+ "rf64",
+ "oversized-rf64",
+ ],
+)
+def test_wav_chunk_boundaries_preserve_only_real_complete_frames(wav_source, case):
+ payload = _pcm16(6)
+ options = {}
+ if case in ("riff", "both"):
+ options["riff_size"] = 0xFFFFFFF0
+ if case in ("data", "both", "odd-junk", "partial-frame"):
+ options["data_size"] = 0xFFFFFFF0
+ if case == "odd-junk":
+ options["before"] = _chunk(b"JUNK", b"x")
+ if case == "partial-frame":
+ payload += b"\x12\x34"
+ if case == "short-data-list":
+ options["after"] = _chunk(b"LIST", b"INFO" + b"metadata")
+ if case in ("rf64", "oversized-rf64"):
+ options.update(data_size=0xFFFFFFFF, rf64_size=24 if case == "rf64" else 0x100000000)
+ with AudioFile(wav_source(_wav(payload, **options))) as audio:
+ assert audio.frames == 6
+ assert audio.duration == pytest.approx(6 / SAMPLE_RATE)
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ assert audio.read(1).shape == (2, 0)
+
+
+def test_oversized_data_with_trailing_chunk_remains_physically_bounded(wav_source):
+ contents = _wav(_pcm16(6), data_size=0xFFFFFFFF, after=_chunk(b"LIST", b"INFOmetadata"))
+ # With a corrupt data size the trailing bytes cannot be distinguished from PCM.
+ with AudioFile(wav_source(contents)) as audio:
+ assert 6 <= audio.frames <= 11
+ samples = audio.read(32)
+ assert samples.shape[1] == audio.frames
+ assert audio.read(1).shape == (2, 0)
+
+
[email protected]("block_align", [2, 8])
+def test_wav_inconsistent_block_alignment_uses_actual_pcm_frame_width(wav_source, block_align):
+ with AudioFile(
+ wav_source(_wav(_pcm16(6), fmt=_fmt(block_align=block_align), data_size=0xFFFFFFFF))
+ ) as audio:
+ assert audio.frames == 6
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ np.testing.assert_allclose(samples[1], -0.25, atol=1 / 32767)
+
+
+_PCM_GUID = bytes.fromhex("0100000000001000800000aa00389b71")
+_FLOAT_GUID = bytes.fromhex("0300000000001000800000aa00389b71")
+_AMBISONIC_PCM_GUID = bytes.fromhex("010000002107d3118644c8c1ca000000")
+_AMBISONIC_FLOAT_GUID = bytes.fromhex("030000002107d3118644c8c1ca000000")
+
+
+ "encoding", ["pcm24", "float32", "extensible-pcm", "extensible-float", "ambisonic-pcm"]
+)
+def test_oversized_wav_supported_sample_formats_match_healthy_control(wav_source, encoding):
+ if encoding == "pcm24":
+ fmt = _fmt(bits=24)
+ payload = bytes.fromhex("0000200000e0") * 6
+ elif encoding == "float32":
+ fmt = _fmt(tag=3, bits=32)
+ payload = struct.pack("<ff", 0.25, -0.25) * 6
+ else:
+ is_float = encoding.endswith("float")
+ guid = {
+ "extensible-pcm": _PCM_GUID,
+ "extensible-float": _FLOAT_GUID,
+ "ambisonic-pcm": _AMBISONIC_PCM_GUID,
+ "ambisonic-float": _AMBISONIC_FLOAT_GUID,
+ }[encoding]
+ fmt = _fmt(tag=0xFFFE, bits=32 if is_float else 16, guid=guid)
+ payload = struct.pack("<ff", 0.25, -0.25) * 6 if is_float else _pcm16(6)
+ decoded = []
+ for size in (None, 0xFFFFFFFF):
+ with AudioFile(wav_source(_wav(payload, fmt=fmt, data_size=size))) as audio:
+ assert audio.frames == 6
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ np.testing.assert_allclose(samples[1], -0.25, atol=1 / 32767)
+ assert audio.read(1).shape == (2, 0)
+ decoded.append(samples)
+ np.testing.assert_array_equal(*decoded)
+
+
[email protected]("data_size", [None, 0xFFFFFFFF])
+def test_wav_unsupported_ambisonic_float_guid_raises(data_size):
+ contents = _wav(
+ struct.pack("<ff", 0.25, -0.25) * 6,
+ fmt=_fmt(tag=0xFFFE, bits=32, guid=_AMBISONIC_FLOAT_GUID),
+ data_size=data_size,
+ )
+ with pytest.raises((RuntimeError, ValueError), match="(?i)(wav|format|unsupported)"):
+ AudioFile(BytesIO(contents))
+
+
[email protected]("data_size", [None, 0xFFFFFFFF])
+def test_wav_legacy_oversized_bit_depth_preserves_accepted_pcm(data_size):
+ # Legacy WAVs can report a nonsensical bit depth while their byte rate and
+ # block alignment still describe ordinary stereo PCM16.
+ legacy_fmt = struct.pack("<HHIIHH", 1, 2, SAMPLE_RATE, SAMPLE_RATE * 4, 4, 128)
+ decoded = []
+ for fmt in (_fmt(), legacy_fmt):
+ with AudioFile(BytesIO(_wav(_pcm16(6), fmt=fmt, data_size=data_size))) as audio:
+ assert audio.frames == 6
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ decoded.append(samples)
+ np.testing.assert_array_equal(*decoded)
+
+
+class _BoundedStream:
+ """Fail the test instead of hanging if parsing stops making progress."""
+
+ def __init__(self, contents):
+ self._stream = BytesIO(contents)
+ self.remaining_operations = 256
+
+ def _tick(self):
+ self.remaining_operations -= 1
+ if self.remaining_operations < 0:
+ raise AssertionError("WAV parsing exceeded its bounded I/O budget")
+
+ def read(self, size=-1):
+ self._tick()
+ if size > 1_000_000:
+ raise AssertionError("WAV parsing requested a reported oversized payload")
+ return self._stream.read(size)
+
+ def seek(self, offset, whence=0):
+ self._tick()
+ return self._stream.seek(offset, whence)
+
+ def tell(self):
+ self._tick()
+ return self._stream.tell()
+
+ def seekable(self):
+ return True
+
+
+ "malformation",
+ ["truncated-chunk-header", "truncated-fmt", "duplicate-fmt", "duplicate-data"]
+ + [f"trailing-header-{size}" for size in range(1, 8)]
+ + [f"short-extensible-{size}" for size in (17, 18, 24, 39)],
+)
+def test_malformed_wav_headers_raise_without_hanging(malformation):
+ if malformation == "truncated-chunk-header":
+ contents = b"RIFF" + struct.pack("<I", 100) + b"WAVEJUNK\x01\x00"
+ elif malformation == "truncated-fmt":
+ contents = _wav(_pcm16(6), fmt=_fmt()[:12])
+ elif malformation == "duplicate-fmt":
+ contents = _wav(_pcm16(6), before=_chunk(b"fmt ", _fmt()))
+ elif malformation == "duplicate-data":
+ contents = _wav(_pcm16(6), after=_chunk(b"data", _pcm16(6)))
+ elif malformation.startswith("short-extensible-"):
+ length = int(malformation.rsplit("-", 1)[1])
+ contents = _wav(_pcm16(6), fmt=_fmt(tag=0xFFFE, guid=_PCM_GUID)[:length])
+ else:
+ length = int(malformation.rsplit("-", 1)[1])
+ contents = _wav(_pcm16(6), after=(b"JUNK" + struct.pack("<I", 0))[:length])
+ with pytest.raises(
+ (RuntimeError, ValueError), match="(?i)(wav|format|chunk|fmt|data|unsupported)"
+ ):
+ with AudioFile(_BoundedStream(contents)) as audio:
+ audio.read(20)
+
+
[email protected]("failure", ["returns-failure", "does-not-advance"])
+def test_wav_failed_seeks_raise_without_hanging(failure):
+ class BrokenSeek(_BoundedStream):
+ def seek(self, offset, whence=0):
+ self._tick()
+ # Initial sizing and restoration work; actual forward chunk skips fail.
+ current = self.tell()
+ if (whence == 1 and offset > 0) or (whence == 0 and offset > current >= 12):
+ return -1 if failure == "returns-failure" else current
+ return super().seek(offset, whence)
+
+ with pytest.raises(
+ (RuntimeError, ValueError, OSError), match="(?i)(wav|format|seek|stream|file|unsupported)"
+ ):
+ with AudioFile(BrokenSeek(_wav(_pcm16(6), before=_chunk(b"JUNK", b"skip me")))) as audio:
+ audio.read(20)
+
+
+def test_wav_seek_to_end_preserves_original_python_exception():
+ class EndSeekFailure(_BoundedStream):
+ def seek(self, offset, whence=0):
+ if whence == 2:
+ raise NotImplementedError("original seek-to-end exception")
+ return super().seek(offset, whence)
+
+ with pytest.raises(NotImplementedError, match="original seek-to-end exception"):
+ AudioFile(EndSeekFailure(_wav(_pcm16(6), data_size=0xFFFFFFFF)))
+
+
[email protected]("data_size", [None, 0xFFFFFFFF])
+def test_ogg_in_wav_uses_compressed_decoder(data_size):
+ source = Path(__file__).parent / "audio" / "correct" / "mono_sine_at_48000Hz.ogg"
+ with AudioFile(str(source)) as control:
+ expected = control.read(256)
+ contents = _wav(source.read_bytes(), fmt=_fmt(tag=0x674F), data_size=data_size)
+ with AudioFile(BytesIO(contents)) as audio:
+ assert audio.frames == 240_000
+ assert audio.samplerate == 48_000
+ assert audio.num_channels == 1
+ np.testing.assert_array_equal(audio.read(256), expected)
+
+
[email protected]("duplicate_chunk", ["fmt", "data"])
[email protected]("data_size", [0xFFFFFFFF, 4], ids=["sentinel", "short-data-header"])
+def test_rf64_sentinel_data_rejects_following_duplicate_chunks(
+ wav_source, duplicate_chunk, data_size
+):
+ trailing = _chunk(b"fmt ", _fmt()) if duplicate_chunk == "fmt" else _chunk(b"data", _pcm16(6))
+ contents = _wav(_pcm16(6), data_size=data_size, rf64_size=24, after=trailing)
+ with pytest.raises(
+ (RuntimeError, ValueError), match="(?i)(wav|format|chunk|fmt|data|unsupported)"
+ ):
+ with AudioFile(wav_source(contents)) as audio:
+ audio.read(20)
+
+
[email protected]("data_size", [None, 0xFFFFFFFF, 4])
+def test_rf64_trailing_list_preserves_declared_data_length(wav_source, data_size):
+ contents = _wav(
+ _pcm16(6),
+ data_size=data_size,
+ rf64_size=24,
+ after=_chunk(b"LIST", b"INFOmetadata"),
+ )
+ with AudioFile(wav_source(contents)) as audio:
+ assert audio.frames == 6
+ assert audio.duration == pytest.approx(6 / SAMPLE_RATE)
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ np.testing.assert_allclose(samples[1], -0.25, atol=1 / 32767)
+ assert audio.read(1).shape == (2, 0)
+
+
[email protected]("duplicate_chunk", ["fmt", "data"])
+def test_rf64_ignores_duplicate_chunks_outside_declared_container(wav_source, duplicate_chunk):
+ contents = _wav(_pcm16(6), data_size=0xFFFFFFFF, rf64_size=24)
+ # Appending bytes does not extend the ds64 RIFF size: these bytes are outside
+ # the RF64 container and must not become audio or duplicate container chunks.
+ contents += _chunk(b"fmt ", _fmt()) if duplicate_chunk == "fmt" else _chunk(b"data", _pcm16(6))
+ with AudioFile(wav_source(contents)) as audio:
+ assert audio.frames == 6
+ assert audio.duration == pytest.approx(6 / SAMPLE_RATE)
+ samples = audio.read(20)
+ assert samples.shape == (2, 6)
+ np.testing.assert_allclose(samples[0], 0.25, atol=1 / 32767)
+ np.testing.assert_allclose(samples[1], -0.25, atol=1 / 32767)
+ assert audio.read(1).shape == (2, 0)