Accept a bare MPEG frame only when its whole header is valid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:38 +02:00
1 parent 2549e9e50d
commit 402ad0a03a
2 files changed
+31 -5

No files matched your search

+17 -5
View File
@@ -275,15 +275,27 @@ pub(crate) fn sniff_audio(head: &[u8]) -> Option<&'static str> {
{
return Some("audio/mp4");
}
if let [0xFF, second, ..] = head {
// ADTS AAC: sync, layer 00.
if second & 0xF6 == 0xF0 {
// A bare frame header has few fixed bits, so the whole header must be
// valid. Layer I (`FF FE`, `FF FF`: the UTF-16 byte order mark of text
// files) is never used by podcasts and is not accepted.
if let [0xFF, second, third, ..] = *head {
// ADTS AAC: sync, layer 00, a defined sampling frequency.
if second & 0xF6 == 0xF0 && (third >> 2) & 0b1111 < 13 {
return Some("audio/aac");
}
// MPEG audio frame: sync, a defined version and layer.
// MPEG audio frame: sync, a defined version, layer II or III, a
// bitrate index other than free (0) and bad (15), and a defined
// sampling rate.
let version = (second >> 3) & 0b11;
let layer = (second >> 1) & 0b11;
if second & 0xE0 == 0xE0 && version != 0b01 && layer != 0b00 {
let bitrate = third >> 4;
let sample_rate = (third >> 2) & 0b11;
if second & 0xE0 == 0xE0
&& version != 0b01
&& matches!(layer, 0b01 | 0b10)
&& (1..15).contains(&bitrate)
&& sample_rate != 0b11
{
return Some("audio/mpeg");
}
}
+14
View File
@@ -320,6 +320,9 @@ fn audio_formats_are_recognized_by_their_first_bytes() {
(&b"ID3\x04\0\0\0\0"[..], "audio/mpeg"),
(&[0xFF, 0xFB, 0x90, 0x64][..], "audio/mpeg"),
(&[0xFF, 0xF3, 0x48, 0xC4][..], "audio/mpeg"),
(&[0xFF, 0xFD, 0x94, 0x00][..], "audio/mpeg"),
(&[0xFF, 0xE3, 0x18, 0xC4][..], "audio/mpeg"),
(&[0xFF, 0xF9, 0x4C, 0x80][..], "audio/aac"),
(&[0xFF, 0xF1, 0x50, 0x80][..], "audio/aac"),
(&b"OggS\0\x02"[..], "audio/ogg"),
(&b"fLaC\0\0\0\x22"[..], "audio/flac"),
@@ -336,6 +339,17 @@ fn audio_formats_are_recognized_by_their_first_bytes() {
&b"%PDF-1.7"[..],
&b"RIFF\x24\x08\0\0AVI "[..],
&[0xFF, 0xD8, 0xFF, 0xE0][..],
// UTF-16LE text (byte order mark FF FE) and FF FF are not frames.
&[0xFF, 0xFE, 0x3C, 0x00, 0x68, 0x00][..],
&[0xFF, 0xFE, 0x41, 0x00][..],
&[0xFF, 0xFF, 0x90, 0x00][..],
// Frame sync with an invalid bitrate, free bitrate or sample rate.
&[0xFF, 0xFB, 0xF0, 0x00][..],
&[0xFF, 0xFB, 0x00, 0x00][..],
&[0xFF, 0xFB, 0x9C, 0x00][..],
// ADTS sync with a reserved sampling frequency index.
&[0xFF, 0xF1, 0x3C, 0x80][..],
&[0xFF, 0xFB][..],
&[0xFF][..],
&[][..],
] {