Skip to content

Commit 6c9a732

Browse files
committed
[#20986][fix] Check the audio header before decoding
Reject audio whose header reports more than _MAX_AUDIO_SAMPLES samples before any samples are read, so an oversized file never allocates the read buffer. The bounded read stays for files of unknown length. Decode AudioMediaIO.load_base64 input with _decode_base64_with_limit, which bounds the encoded string before decoding. Drop the max(channels, 1) guard because libsndfile refuses to open a file with fewer than one channel. Tests use nonzero samples that differ per channel, cover the header check, the unknown-length fallback and the base64 limit, and test_media_io.py is added to l0_cpu.yml. Signed-off-by: LeizhenZhang <zhangleizhen645@gmail.com>
1 parent f7dd099 commit 6c9a732

3 files changed

Lines changed: 70 additions & 18 deletions

File tree

‎tensorrt_llm/inputs/media_io.py‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,15 @@ async def _get_aiohttp_session() -> aiohttp.ClientSession:
108108

109109
# Maximum number of decoded audio samples (frames x channels) per audio input.
110110
# Compressed formats such as FLAC can expand a few hundred kilobytes into
111-
# gigabytes of samples, so the encoded size limit alone does not bound memory.
112-
# The limit admits every 16-bit PCM file within _MAX_RESPONSE_BYTES, which is
113-
# about 100 Mi samples, or 800 MiB as float64.
111+
# gigabytes of samples, so decoded audio needs its own limit. The value is the
112+
# sample count of _MAX_RESPONSE_BYTES of 16-bit PCM, about 100 Mi samples, or
113+
# 800 MiB as float64.
114114
_MAX_AUDIO_SAMPLES = _MAX_RESPONSE_BYTES // 2
115115

116+
# Frame count that libsndfile reports when a file does not state its length,
117+
# such as a FLAC stream whose STREAMINFO total is 0.
118+
_SF_UNKNOWN_FRAMES = 2**63 - 1
119+
116120
_REDIRECT_STATUSES = (301, 302, 303, 307, 308)
117121

118122
# Opt-in switch relaxing the requirement that media URLs resolve to global
@@ -887,18 +891,24 @@ def _decode_base64_with_limit(data: str) -> bytes:
887891
def _read_audio_with_limit(source: Any) -> Tuple[np.ndarray, int]:
888892
"""Decode audio like ``soundfile.read`` with a cap on decoded samples.
889893
890-
Reads at most one frame beyond the limit, so a payload that decodes to more
891-
than ``_MAX_AUDIO_SAMPLES`` samples is rejected before it is fully decoded.
894+
A file whose header reports more than ``_MAX_AUDIO_SAMPLES`` samples is
895+
rejected before any samples are read. For a file of unknown length, the
896+
read stops at one frame beyond the limit, so an oversized payload is
897+
rejected before it is fully decoded.
892898
"""
899+
too_many_samples = (
900+
f"Audio input decodes to more than {_MAX_AUDIO_SAMPLES} samples "
901+
f"(frames x channels), the maximum allowed."
902+
)
893903
with soundfile.SoundFile(source) as audio_file:
894-
max_frames = _MAX_AUDIO_SAMPLES // max(audio_file.channels, 1)
904+
# libsndfile refuses to open a file with fewer than one channel.
905+
max_frames = _MAX_AUDIO_SAMPLES // audio_file.channels
906+
if audio_file.frames != _SF_UNKNOWN_FRAMES and audio_file.frames > max_frames:
907+
raise ValueError(too_many_samples)
895908
data = audio_file.read(frames=max_frames + 1)
896909
samplerate = audio_file.samplerate
897910
if len(data) > max_frames:
898-
raise ValueError(
899-
f"Audio input decodes to more than {_MAX_AUDIO_SAMPLES} samples "
900-
f"(frames x channels), the maximum allowed."
901-
)
911+
raise ValueError(too_many_samples)
902912
return data, samplerate
903913

904914

@@ -1133,7 +1143,7 @@ def load_bytes(self, data: bytes) -> Tuple[np.ndarray, int]:
11331143
return _read_audio_with_limit(BytesIO(data))
11341144

11351145
def load_base64(self, media_type: str, data: str) -> Tuple[np.ndarray, int]:
1136-
return _read_audio_with_limit(BytesIO(base64.b64decode(data)))
1146+
return _read_audio_with_limit(BytesIO(_decode_base64_with_limit(data)))
11371147

11381148
def load_file(self, url: str) -> Tuple[np.ndarray, int]:
11391149
# Strip `file://` and unquote the path for `file:` URIs; pass

‎tests/integration/test_lists/test-db/l0_cpu.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ l0_cpu:
204204
- unittest/llmapi/apps/test_harmony_channel_validation.py
205205
- unittest/llmapi/apps/test_harmony_parsing.py::TestStripIncompleteMessagesReporting
206206
- unittest/llmapi/apps/test_kimi_serve_extensions.py
207+
- unittest/llmapi/apps/test_media_io.py
207208
- unittest/llmapi/apps/test_openai_chat_disagg_multimodal.py
208209
- unittest/llmapi/apps/test_openai_chat_multimodal_prompt.py
209210
- unittest/llmapi/apps/test_openai_protocol_chat_store.py

‎tests/unittest/llmapi/apps/test_media_io.py‎

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,25 @@ def test_non_video_classes_use_plain_shallow_merge(self, media_io_cls):
9999

100100

101101
def _flac_bytes(frames: int, channels: int = 2) -> bytes:
102+
# Nonzero samples that differ per channel, so a loader that silences or
103+
# reorders channels fails the comparison with soundfile.read.
104+
t = np.arange(frames)[:, None]
105+
c = np.arange(channels)[None, :]
106+
pcm = ((t * (2 * c + 3)) % 20000 + 1) * (1 - 2 * (c % 2))
102107
buffer = BytesIO()
103-
soundfile.write(
104-
buffer,
105-
np.zeros((frames, channels), dtype=np.int16),
106-
16000,
107-
format="FLAC",
108-
subtype="PCM_16",
109-
)
108+
soundfile.write(buffer, pcm.astype(np.int16), 16000, format="FLAC", subtype="PCM_16")
110109
return buffer.getvalue()
111110

112111

112+
def _without_frame_count(flac: bytes) -> bytes:
113+
# Zero the 36-bit total-samples field of STREAMINFO, which starts in the
114+
# low nibble of byte 21, so the stream no longer states its length.
115+
data = bytearray(flac)
116+
data[21] &= 0xF0
117+
data[22:26] = bytes(4)
118+
return bytes(data)
119+
120+
113121
class TestAudioDecodedSizeLimit:
114122
"""Audio decoding stops at `_MAX_AUDIO_SAMPLES` decoded samples."""
115123

@@ -119,6 +127,19 @@ class TestAudioDecodedSizeLimit:
119127
def small_limit(self, monkeypatch):
120128
monkeypatch.setattr(media_io_module, "_MAX_AUDIO_SAMPLES", self.LIMIT)
121129

130+
@pytest.fixture
131+
def audio_reads(self, monkeypatch):
132+
"""Frame counts passed to each ``SoundFile.read`` call."""
133+
reads = []
134+
original_read = soundfile.SoundFile.read
135+
136+
def recording_read(audio_file, *args, **kwargs):
137+
reads.append(kwargs.get("frames"))
138+
return original_read(audio_file, *args, **kwargs)
139+
140+
monkeypatch.setattr(soundfile.SoundFile, "read", recording_read)
141+
return reads
142+
122143
def test_audio_within_limit_matches_soundfile(self, tmp_path):
123144
encoded = _flac_bytes(frames=self.LIMIT // 2, channels=2)
124145
path = tmp_path / "ok.flac"
@@ -147,6 +168,26 @@ def test_audio_over_limit_is_rejected(self, tmp_path):
147168
with pytest.raises(ValueError, match="more than 4000 samples"):
148169
loader.load_file(str(path))
149170

171+
def test_audio_over_limit_in_header_is_rejected_before_reading(self, audio_reads):
172+
encoded = _flac_bytes(frames=self.LIMIT // 2 + 1, channels=2)
173+
with pytest.raises(ValueError, match="more than 4000 samples"):
174+
AudioMediaIO().load_bytes(encoded)
175+
assert audio_reads == []
176+
177+
def test_audio_of_unknown_length_over_limit_is_rejected(self, audio_reads):
178+
encoded = _without_frame_count(_flac_bytes(frames=self.LIMIT, channels=2))
179+
with soundfile.SoundFile(BytesIO(encoded)) as audio_file:
180+
assert audio_file.frames == media_io_module._SF_UNKNOWN_FRAMES
181+
with pytest.raises(ValueError, match="more than 4000 samples"):
182+
AudioMediaIO().load_bytes(encoded)
183+
assert audio_reads == [self.LIMIT // 2 + 1]
184+
185+
def test_audio_base64_over_encoded_limit_is_rejected(self, monkeypatch):
186+
encoded = _flac_bytes(frames=self.LIMIT // 2, channels=2)
187+
monkeypatch.setattr(media_io_module, "_MAX_RESPONSE_BYTES", len(encoded) // 2)
188+
with pytest.raises(ValueError, match="Base64 media input exceeds"):
189+
AudioMediaIO().load_base64("audio/flac", base64.b64encode(encoded).decode())
190+
150191
@pytest.mark.asyncio
151192
async def test_chat_audio_part_over_limit_is_rejected(self):
152193
encoded = _flac_bytes(frames=self.LIMIT + 1, channels=1)

0 commit comments

Comments
 (0)