π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
io: Preserve WAV compatibility when capping audio length
Christopher Jacobyba3e59cd4cdf
diff --git a/docs/source/reference/pedalboard.io.rst b/docs/source/reference/pedalboard.io.rstindex b9578d7..8b107ec 100644--- a/docs/source/reference/pedalboard.io.rst+++ b/docs/source/reference/pedalboard.io.rst@@ -36,15 +36,16 @@ a regular file in Python::you *probably don't need to do that* - :class:`pedalboard.io.AudioFile` has you covered... note::- For finite, seekable WAV and RF64 files containing PCM, 32-bit IEEE float,- or supported WAVE_FORMAT_EXTENSIBLE audio, oversized data-chunk lengths- are limited to the complete frames physically available when the file is- opened. Reported duration, reads, and resampling use this recovered length.- Ambiguous repeated format or data chunks may cause the file to be rejected.-- Trailing metadata swallowed by an oversized data chunk may still be decoded- as audio. This recovery does not cover every WAV codec or streams of unknown- length, and it does not add support for growing files.+ For finite, seekable WAV and RF64 files containing supported PCM or 32-bit+ floating-point audio, overstated lengths are capped at the complete frames+ physically available when the file is opened, when the audio layout can be+ identified. Reported duration, reads, and resampling use this recovered length.++ Only overstated audio lengths are corrected. Shorter declarations and the+ handling of other malformed file contents follow the existing decoder.+ Physically present trailing metadata may still be decoded as audio when an+ oversized data chunk includes it. Recovery does not cover every WAV codec or+ streams of unknown length, and it does not add support for growing files.The following documentation lists all of the available I/O classes.diff --git a/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h b/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.hindex dce88e1..48b2ea0 100644--- a/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h+++ b/pedalboard/juce_overrides/juce_PatchedWavAudioFormat.h@@ -18,7 +18,6 @@#pragma once#include "../JuceHeader.h"-#include "../io/PythonFileLike.h"#include "juce_PatchedMP3AudioFormat.h"// dr_wav for ADPCM decoding (public domain / MIT-0)@@ -225,223 +224,244 @@ public:AudioFormatReader *createReaderFor(InputStream *sourceStream,bool deleteStreamIfOpeningFails) override {- 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);- };-- uint8 header[12];- if (sourceStream->read(header, sizeof(header)) != sizeof(header))- return useDefaultReader();- 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();+ auto streamStartPos = sourceStream->getPosition();- 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()) {+ auto useDefaultReader = [&]() -> AudioFormatReader * {+ if (!sourceStream->setPosition(streamStartPos)) {if (deleteStreamIfOpeningFails)delete sourceStream;return nullptr;}+ const auto layout = scanWavLayout(*sourceStream, streamStartPos);+ // Let JUCE establish the final stream state, including native fallback+ // behavior for file-like objects whose seeks do not always succeed.+ if (!sourceStream->setPosition(streamStartPos)) {+ if (deleteStreamIfOpeningFails)+ delete sourceStream;+ return nullptr;+ }+ std::unique_ptr<AudioFormatReader> reader(WavAudioFormat::createReaderFor(+ sourceStream, deleteStreamIfOpeningFails));+ // The default factory can delegate Ogg-in-WAV to a compressed reader.+ // Only JUCE's native WAV reader has the byte stride described below.+ if (reader && reader->getFormatName() == getFormatName()) {+ // JUCE validates extensible GUIDs and normalizes legacy bit depths.+ // Use that validated depth for float32 eligibility, preserving the+ // existing float64 and unsupported-float dispatch paths.+ const bool canCapLength =+ layout.format == (uint16)WavFormatTag::PCM ||+ (layout.format == (uint16)WavFormatTag::IEEEFloat &&+ reader->bitsPerSample == 32) ||+ (layout.format == (uint16)WavFormatTag::Extensible &&+ (!reader->usesFloatingPointData || reader->bitsPerSample == 32));+ if (canCapLength && layout.dataOffset >= 0 &&+ layout.bytesPerFrame > 0) {+ const auto available =+ std::max<int64>(0, layout.totalLength - layout.dataOffset);+ reader->lengthInSamples = std::min(reader->lengthInSamples,+ available / layout.bytesPerFrame);+ }+ }+ // Null readers may already have deleted the stream. Callback errors stay+ // pending for ReadableAudioFile's existing Python exception propagation.+ return reader.release();+ };++ // Read the RIFF header+ auto firstChunkType = sourceStream->readInt();+ if (firstChunkType != chunkName("RIFF") &&+ firstChunkType != chunkName("RF64")) {+ return useDefaultReader();}- 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;++ // Skip the size field+ sourceStream->readInt();++ // Check for WAVE identifier+ if (sourceStream->readInt() != 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);if (chunkType == chunkName("fmt ")) {- 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);+ auto format = (unsigned short)sourceStream->readShort();+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::PCM:- case WavFormatTag::IEEEFloat:- case WavFormatTag::Extensible:- break;- default: {- const auto *codec = getUnsupportedCodecName(format);- if (codec != nullptr) {++ 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) {if (deleteStreamIfOpeningFails)delete sourceStream;throw std::domain_error(- "This WAV file uses the " + std::string(codec) ++ "This WAV file uses the " + std::string(unsupportedCodecName) +" 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);- // 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)+ // All other formats: delegate to JUCE's WavAudioFormatreturn 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;}- 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)+ sourceStream->setPosition(chunkEnd);+ }++ // Couldn't find fmt chunk - let JUCE handle it+ return useDefaultReader();+ }++private:+ struct WavDataLayout {+ int64 totalLength = -1;+ int64 dataOffset = -1;+ int64 bytesPerFrame = 0;+ unsigned short format = 0;+ unsigned int bitsPerSample = 0;+ };++ // This is a best-effort lookup, not a second format validator. An unfamiliar+ // or incomplete layout leaves JUCE's result unchanged rather than rejecting+ // a file that the original reader could open.+ static WavDataLayout scanWavLayout(InputStream &stream, int64 start) {+ static_assert(JUCE_VERSION == 0x060104,+ "Review WAV traversal and decoder stride when updating JUCE");+ WavDataLayout layout;+ layout.totalLength = stream.getTotalLength();+ if (layout.totalLength < 0 || start < 0 || !stream.setPosition(start))+ return {};++ uint8 header[12];+ if (stream.read(header, sizeof(header)) != sizeof(header) ||+ (int)ByteOrder::littleEndianInt(header + 8) != chunkName("WAVE"))+ return {};+ const auto container = (int)ByteOrder::littleEndianInt(header);+ const bool isRF64 = container == chunkName("RF64");+ if (!isRF64 && container != chunkName("RIFF"))+ return {};++ uint64 riffSize = ByteOrder::littleEndianInt(header + 4);+ int64 rf64DataSize = 0;+ if (isRF64) {+ uint8 ds64[24];+ if (stream.read(ds64, sizeof(ds64)) != sizeof(ds64) ||+ (int)ByteOrder::littleEndianInt(ds64) != chunkName("ds64"))+ return {};+ const auto size = ByteOrder::littleEndianInt(ds64 + 4);+ riffSize = ByteOrder::littleEndianInt64(ds64 + 8);+ const auto dataSize = ByteOrder::littleEndianInt64(ds64 + 16);+ if (size < 28 || dataSize > (uint64)std::numeric_limits<int64>::max())+ return {};+ rf64DataSize = (int64)dataSize;+ const int64 remaining = (int64)size + (size & 1) - 16;+ if (remaining > layout.totalLength - stream.getPosition() ||+ !stream.setPosition(stream.getPosition() + remaining))+ return {};+ }+ if (start > std::numeric_limits<int64>::max() - 8 ||+ riffSize > (uint64)(std::numeric_limits<int64>::max() - start - 8))+ return {};+ const auto scanEnd =+ std::min(layout.totalLength, start + 8 + (int64)riffSize);++ while (stream.getPosition() < scanEnd) {+ const auto chunkStart = stream.getPosition();+ uint8 chunk[8];+ // JUCE tests only the chunk start against RIFF end. The header itself+ // can cross an understated container boundary if physically present.+ if (stream.read(chunk, sizeof(chunk)) != sizeof(chunk))+ return {};+ const auto type = (int)ByteOrder::littleEndianInt(chunk);+ const auto length = ByteOrder::littleEndianInt(chunk + 4);+ const auto payload = stream.getPosition();+ int64 payloadLength = length;+ if (payload <= chunkStart)+ return {};++ if (type == chunkName("fmt ")) {+ uint8 fmt[16];+ // JUCE reads these fields even when the declared fmt size is short.+ // Follow that layout without imposing stricter header validation.+ if (stream.read(fmt, sizeof(fmt)) != sizeof(fmt))+ return {};+ layout.format = ByteOrder::littleEndianShort(fmt);+ const auto channels =+ (unsigned int)(short)ByteOrder::littleEndianShort(fmt + 2);+ const auto sampleRate = (int32)ByteOrder::littleEndianInt(fmt + 4);+ const auto byteRate = (int32)ByteOrder::littleEndianInt(fmt + 8);+ layout.bitsPerSample =+ (unsigned int)(int)(short)ByteOrder::littleEndianShort(fmt + 14);+ // Mirror JUCE 6.1.4, including legacy bit-depth normalization. The+ // blockAlign field does not determine the decoder's byte stride.+ layout.bytesPerFrame = layout.bitsPerSample > 64 && sampleRate != 0+ ? (int64)byteRate / sampleRate+ : (int)(channels * layout.bitsPerSample / 8);+ } else if (type == chunkName("data")) {+ // JUCE selects the last data chunk it visits, using its current format.+ // Retain the final decoding stride even if another fmt follows data.+ layout.dataOffset = payload;+ if (isRF64 && rf64DataSize > 0)+ payloadLength = rf64DataSize;+ } else if (length == 0) {+ // JUCE stops at zero-sized unknown chunks, but continues past metadata+ // it recognises. Match that distinction before selecting a later data.+ const int metadata[] = {+ chunkName("bext"), chunkName("smpl"), chunkName("inst"),+ chunkName("INST"), chunkName("cue "), chunkName("axml"),+ chunkName("LIST"), chunkName("acid"), chunkName("Trkn")};+ if (std::find(std::begin(metadata), std::end(metadata), type) ==+ std::end(metadata))break;- return invalidFormat("truncated chunk payload");}- if (!seekTo(chunkEnd) || sourceStream->getPosition() <= chunkStart)- return invalidFormat("failed or nonadvancing chunk seek");- }- 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);+ // A short final payload (including metadata or a missing pad byte) is+ // accepted or rejected by JUCE, not by this lookup. Oversized audio uses+ // the physical tail below; an understated RIFF end never expands length.+ if (payloadLength > scanEnd - payload)+ break;+ const auto end = payload + payloadLength;+ if ((payloadLength & 1) != 0 && end == scanEnd)+ break;+ const auto next = end + (payloadLength & 1);+ if (!stream.setPosition(next) || stream.getPosition() != next)+ return {};}- return reader;+ return layout;}-private:/*** Creates an MP3 reader for a WAV file containing MP3-compressed audio data.* Finds the data chunk and wraps it in a SubregionStream for the MP3 decoder.diff --git a/tests/test_wav_header_length.py b/tests/test_wav_header_length.pyindex bba2e3c..f137ff3 100644--- a/tests/test_wav_header_length.py+++ b/tests/test_wav_header_length.py@@ -1,6 +1,7 @@"""Finite WAV streams must never expose samples beyond their real contents."""import struct+import sysfrom io import BytesIOfrom pathlib import Pathfrom typing import BinaryIO, Optional@@ -315,36 +316,128 @@ class _BoundedStream(BinaryIO):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)"- ):+def _riff(chunks, declared_size=None):+ return (+ b"RIFF"+ + struct.pack("<I", len(chunks) + 4 if declared_size is None else declared_size)+ + b"WAVE"+ + chunks+ )+++def _assert_pcm_frames(audio, frames, raw_pair=(8192, -8192)):+ assert audio.frames == frames+ assert audio.duration == pytest.approx(frames / SAMPLE_RATE)+ samples = audio.read(20)+ assert samples.shape == (2, frames)+ expected = np.repeat(np.array(raw_pair)[:, None], frames, axis=1) / 32767+ np.testing.assert_allclose(samples, expected, atol=1e-7)+ assert audio.read(1).shape == (2, 0)+++def _compatibility_cases():+ prefix = _chunk(b"fmt ", _fmt())+ payload = _pcm16(6)+ data = _chunk(b"data", payload)+ later = _chunk(b"data", struct.pack("<hh", -16384, 4096) * 2)+ cases = [+ pytest.param(+ _wav(payload, after=_chunk(b"id3 ", b"x")[:-1]),+ 6,+ (8192, -8192),+ id="missing-metadata-pad",+ ),+ pytest.param(+ _wav(payload, after=_chunk(b"id3 ", b"xxxx", 12)),+ 6,+ (8192, -8192),+ id="truncated-final-metadata",+ ),+ pytest.param(_wav(payload, after=prefix), 6, (8192, -8192), id="duplicate-fmt"),+ pytest.param(_wav(payload, after=later), 2, (-16384, 4096), id="later-data-selected"),+ pytest.param(+ _wav(payload, after=_chunk(b"JUNK", b"") + later),+ 6,+ (8192, -8192),+ id="zero-junk-keeps-first-data",+ ),+ pytest.param(_wav(payload, fmt=_fmt()[:12]), 6, (8192, -8192), id="short-pcm-fmt"),+ pytest.param(_wav(payload, data_size=4), 1, (8192, -8192), id="short-data-stays-short"),+ pytest.param(+ _wav(payload, riff_size=40), 6, (8192, -8192), id="short-riff-keeps-selected-data"+ ),+ pytest.param(+ _wav(payload, riff_size=16), 0, (8192, -8192), id="short-riff-no-selected-data"+ ),+ pytest.param(_wav(b""), 0, (8192, -8192), id="empty-data"),+ pytest.param(_riff(prefix), 0, (8192, -8192), id="no-data"),+ pytest.param(_riff(data + prefix), 0, (8192, -8192), id="data-before-fmt"),+ pytest.param(+ _wav(payload + b"X", after=_chunk(b"LIST", b"INFO")),+ 6,+ (8192, -8192),+ id="odd-data-before-metadata",+ ),+ ]+ cases.extend(+ pytest.param(_wav(payload, after=b"X" * size), 6, (8192, -8192), id=f"trailing-junk-{size}")+ for size in range(1, 8)+ )+ return cases++[email protected]("contents,frames,raw_pair", _compatibility_cases())+def test_wav_preserves_accepted_layouts_and_selected_audio(wav_source, contents, frames, raw_pair):+ # Expectations were observed independently with release 0.9.26 and bounded reads.+ with AudioFile(wav_source(contents)) as audio:+ _assert_pcm_frames(audio, frames, raw_pair)++[email protected]("riff_size", [40, None])+def test_later_oversized_data_is_bounded_at_its_selected_payload(wav_source, riff_size):+ later = struct.pack("<hh", -16384, 4096) * 2+ # A normal container scans both chunks; a short one selects only the first.+ contents = _wav(_pcm16(6), riff_size=riff_size, after=_chunk(b"data", later, 0xFFFFFFFF))+ with AudioFile(wav_source(contents)) as audio:+ if riff_size is None:+ _assert_pcm_frames(audio, 2, (-16384, 4096))+ else:+ _assert_pcm_frames(audio, 6)+++def test_oversized_data_is_bounded_physically_despite_short_riff(wav_source):+ with AudioFile(wav_source(_wav(_pcm16(6), data_size=0xFFFFFFFF, riff_size=40))) as audio:+ _assert_pcm_frames(audio, 6)+++def test_oversized_data_can_include_bytes_beyond_declared_riff(wav_source):+ contents = _wav(_pcm16(6), data_size=0xFFFFFFFF) + b"X" * 16+ with AudioFile(wav_source(contents)) as audio:+ assert audio.frames == 10+ samples = audio.read(20)+ assert samples.shape == (2, 10)+ np.testing.assert_allclose(samples[0, :6], 8192 / 32767, atol=1e-7)+ np.testing.assert_allclose(samples[1, :6], -8192 / 32767, atol=1e-7)+ assert audio.read(1).shape == (2, 0)++[email protected]("length", [17, 18, 24, 39])+def test_wav_truncated_extensible_fmt_retains_rejection(length):+ contents = _wav(_pcm16(6), fmt=_fmt(tag=0xFFFE, guid=_PCM_GUID)[:length])+ with pytest.raises((RuntimeError, ValueError)):+ with AudioFile(_BoundedStream(contents)) as audio:+ audio.read(20)+++def test_wav_without_complete_chunk_header_retains_rejection():+ contents = b"RIFF" + struct.pack("<I", 100) + b"WAVEJUNK\x01\x00"+ with pytest.raises((RuntimeError, ValueError)):with AudioFile(_BoundedStream(contents)) as audio:audio.read(20)@pytest.mark.parametrize("failure", ["returns-failure", "does-not-advance"])-def test_wav_failed_seeks_raise_without_hanging(failure):+def test_wav_failed_seeks_preserve_fallback_and_terminate(failure):class BrokenSeek(_BoundedStream):def seek(self, offset, whence=0):self._tick()@@ -354,11 +447,14 @@ def test_wav_failed_seeks_raise_without_hanging(failure):return -1 if failure == "returns-failure" else currentreturn super().seek(offset, whence)- with pytest.raises(- (RuntimeError, ValueError, OSError), match="(?i)(wav|format|seek|stream|file|unsupported)"- ):+ try:with AudioFile(BrokenSeek(_wav(_pcm16(6), before=_chunk(b"JUNK", b"skip me")))) as audio:- audio.read(20)+ _assert_pcm_frames(audio, 6)+ except (RuntimeError, ValueError, OSError):+ # Release 0.9.26 recovers these streams on macOS. Other platforms may+ # lack its native decoder fallback, but must still terminate promptly.+ if sys.platform == "darwin":+ raisedef test_wav_seek_to_end_preserves_original_python_exception():@@ -385,18 +481,25 @@ def test_ogg_in_wav_uses_compressed_decoder(data_size):np.testing.assert_array_equal(audio.read(256), expected)[email protected]("duplicate_chunk", ["fmt", "data"])[email protected]("duplicate_chunk", ["fmt", "data", "oversized-data"])@pytest.mark.parametrize("data_size", [0xFFFFFFFF, 4], ids=["sentinel", "short-data-header"])-def test_rf64_sentinel_data_rejects_following_duplicate_chunks(+def test_rf64_later_chunks_preserve_selected_payload_and_bound_eof(wav_source, duplicate_chunk, data_size):- trailing = _chunk(b"fmt ", _fmt()) if duplicate_chunk == "fmt" else _chunk(b"data", _pcm16(6))+ later = struct.pack("<hh", -16384, 4096) * 2+ trailing = (+ _chunk(b"fmt ", _fmt())+ if duplicate_chunk == "fmt"+ else _chunk(b"data", later, 0xFFFFFFFF if duplicate_chunk == "oversized-data" else None)+ )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)+ with AudioFile(wav_source(contents)) as audio:+ if duplicate_chunk == "fmt":+ _assert_pcm_frames(audio, 6)+ else:+ # JUCE selects the later audio but applies ds64's six-frame length.+ # Only two selected frames physically exist, so only these remain.+ _assert_pcm_frames(audio, 2, (-16384, 4096))@pytest.mark.parametrize("data_size", [None, 0xFFFFFFFF, 4])@@ -431,3 +534,40 @@ def test_rf64_ignores_duplicate_chunks_outside_declared_container(wav_source, dunp.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)+++ "riff_size,expected_frames",+ [(28, 0)] + [(size, 6) for size in range(29, 36)] + [(40, 6)],+)+def test_wav_selected_data_header_crossing_riff_end_is_physically_bounded(+ wav_source, riff_size, expected_frames+):+ # JUCE selects data if its header begins before the declared RIFF end,+ # including when the header's remaining bytes lie outside that boundary.+ contents = _wav(_pcm16(6), data_size=0xFFFFFFFF, riff_size=riff_size)+ with AudioFile(wav_source(contents)) as audio:+ _assert_pcm_frames(audio, expected_frames)++[email protected]("tag", [3, 0xFFFE], ids=["ieee-float", "extensible-float"])[email protected]("data_size", [None, 0xFFFFFFFF], ids=["healthy", "oversized-data"])+def test_wav_legacy_float_bit_depth_uses_decoded_frame_width(wav_source, tag, data_size):+ fmt = _fmt(+ tag=tag,+ bits=128,+ block_align=8,+ guid=_FLOAT_GUID if tag == 0xFFFE else None,+ )+ contents = _wav(struct.pack("<ff", 0.25, -0.25) * 6, fmt=fmt, data_size=data_size)+ with AudioFile(wav_source(contents)) as audio:+ assert audio.frames == 6+ assert audio.duration == pytest.approx(6 / SAMPLE_RATE)+ assert audio.file_dtype == "float32"+ samples = audio.read(20)+ assert samples.shape == (2, 6)+ np.testing.assert_array_equal(samples, [[0.25] * 6, [-0.25] * 6])+ assert audio.read(1).shape == (2, 0)+ audio.seek(0)+ np.testing.assert_array_equal(audio.read_raw(20), [[0.25] * 6, [-0.25] * 6])+ assert audio.read_raw(1).shape == (2, 0)