FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#809: MP2 Matroska oracle robust to older ffmpeg; bounded ID3 skip and subbands
vangel76a147e2551e08
diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rsindex dab8a49fe..dda0a4d15 100644--- a/crates/codecs/src/audio.rs+++ b/crates/codecs/src/audio.rs@@ -875,7 +875,7 @@ fn decode_mpeg_layer12(bytes: &[u8]) -> Option<(u8, u32, Vec<Vec<f32>>)> {// ID3v2: 10-byte header, a syncsafe size, and a 10-byte footer when flagged[b'I', b'D', b'3', _, _, flags, s0, s1, s2, s3, ..] => {let size = [*s0, *s1, *s2, *s3].iter().fold(0usize, |a, &b| (a << 7) | (b & 0x7F) as usize);- 10 + size + if flags & 0x10 != 0 { 10 } else { 0 }+ size.saturating_add(if flags & 0x10 != 0 { 20 } else { 10 })}_ => 0,};@@ -974,6 +974,8 @@ mod mpeg_layer12_tests {assert!(decode_mpeg_layer12(&file[..n]).is_none(), "{n}");}assert!(decode_mpeg_layer12(&[&mono[..], &[0x12; 50]].concat()).is_none());+ // an ID3v2 tag claiming the largest size (with a footer) points past the end+ assert!(decode_mpeg_layer12(&[&b"ID3\x04\0\x10\x7F\x7F\x7F\x7F"[..], &mono].concat()).is_none());}}diff --git a/crates/codecs/tests/mpeg_oracle.rs b/crates/codecs/tests/mpeg_oracle.rsindex 90cc6bd42..e6d5a39dd 100644--- a/crates/codecs/tests/mpeg_oracle.rs+++ b/crates/codecs/tests/mpeg_oracle.rs@@ -536,24 +536,41 @@ fn mono_mp2_at_ffmpegs_default_bit_rate() {assert_eq!(std::fs::read(&f).unwrap()[2] >> 4, 14, "384 kbit/s");let worst = check_audio(&ff, &make(&ff, "ts_mpeg2_mono_mp2.ts"), 2e-4);println!("ts_mpeg2_mono_mp2.ts: max error {worst}");- // Matroska: ffmpeg trims the 481-sample encoder delay; we trim `CodecDelay` rounded to the- // millisecond (#790), so allow a lag of a sample or two there- for (name, max_lag) in [("audio_mono.mp2", 0i64), ("mkv_mono_mp2.mkv", 2)] {+ // Matroska stores the encoder's 481-sample priming as `CodecDelay`. Whether ffmpeg's CLI trims+ // it depends on its version (9.x does; 2023-24 builds keep the priming samples), and until+ // #790 we trim it rounded to the millisecond. So for .mkv ffmpeg's decode is searched at+ // lags within a sample or two of 0 (trimmed) and of `CodecDelay` (kept). The plain .mp2 file+ // has no such ambiguity and must line up exactly.+ for name in ["audio_mono.mp2", "mkv_mono_mp2.mkv"] {let f = make(&ff, name);- let src = filmcraft_codecs::open_bytes(name, bytes(&f)).unwrap();+ let file = bytes(&f);+ let src = filmcraft_codecs::open_bytes(name, file.clone()).unwrap();let a = src.info().audio().cloned().unwrap();assert_eq!((a.sample_rate, a.channels), (48_000, 1), "{name}");let want = ffmpeg_audio_f32(&ff, &f, &[]);- let n = want.len() - 4;- let worst = (-max_lag..=max_lag)+ let (delay, lags): (usize, Vec<i64>) = match name.ends_with(".mkv") {+ true => {+ let mkv = filmcraft_matroska::open(file).unwrap();+ let ns = mkv.tracks.first().map_or(0, |t| t.codec_delay_ns);+ let delay = ((ns * 48_000 + 500_000_000) / 1_000_000_000) as usize;+ assert!(delay > 0, "{name}: no CodecDelay");+ (delay, (-2..=2).chain(delay as i64 - 2..=delay as i64 + 2).collect())+ }+ false => (0, vec![0]),+ };+ // ours from sample 2 on, against ffmpeg's from sample 2 + lag (inside both decodes)+ let n = want.len() - delay - 6;+ let buf = src.audio(0, n, 48_000).unwrap();+ let (worst, lag) = lags+ .into_iter().map(|lag| {- let buf = src.audio(2 + lag, n, 48_000).unwrap();- want[2..].iter().zip(&buf.channels[0]).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max)+ let err = (2..n - 2).map(|i| (want[(i as i64 + lag) as usize] - buf.channels[0][i]).abs()).fold(0f32, f32::max);+ (err, lag)})- .fold(f32::INFINITY, f32::min);+ .fold((f32::INFINITY, 0), |m, x| if x.0 < m.0 { x } else { m });let peak = want.iter().fold(0f32, |m, x| m.max(x.abs()));- println!("{name}: max error {worst}, peak {peak}");- assert!(peak > 0.1 && worst <= 2e-4, "{name}: peak {peak}, max error {worst}");+ println!("{name}: max error {worst} at lag {lag} (CodecDelay {delay}), peak {peak}");+ assert!(peak > 0.1 && worst <= 2e-4, "{name}: peak {peak}, max error {worst} at lag {lag}");}}diff --git a/crates/mpa/src/lib.rs b/crates/mpa/src/lib.rsindex 4dd32814d..9834e5292 100644--- a/crates/mpa/src/lib.rs+++ b/crates/mpa/src/lib.rs@@ -163,7 +163,7 @@ pub struct Frame {}/// Subband samples of one frame: `[channel][time slot][subband]`, up to 36 time slots.-type Subbands = [[[f32; 32]; 36]; 2];+type Subbands = [[[f32; tables::SUBBANDS]; 36]; 2];/// A Layer I / Layer II decoder. It keeps the synthesis filter state between frames, so frames/// must be fed in order; call [`Decoder::reset`] before decoding from another position.@@ -314,9 +314,11 @@ fn layer2(r: &mut BitReader, h: &Header, out: &mut Subbands) -> Result<()> {let nch = h.channels();let per_channel = h.bitrate_kbps / nch as u32;let table = AllocTable::select(h.version != Version::Mpeg1, h.sample_rate, per_channel);- let sblimit = table.sblimit();+ // at most 32 for every table (a compile-time check in `tables`); the clamp keeps every+ // `[sb]` below in bounds even so+ let sblimit = table.sblimit().min(tables::SUBBANDS);let bound = if nch == 1 { sblimit } else { h.bound().min(sblimit) };- let mut steps = [[0u16; 32]; 2];+ let mut steps = [[0u16; tables::SUBBANDS]; 2];for sb in 0..sblimit {let row = table.row(sb);let nbal = row.len().trailing_zeros();@@ -331,7 +333,7 @@ fn layer2(r: &mut BitReader, h: &Header, out: &mut Subbands) -> Result<()> {steps[1][sb] = s;}}- let mut scfsi = [[0u32; 32]; 2];+ let mut scfsi = [[0u32; tables::SUBBANDS]; 2];for sb in 0..sblimit {for ch in 0..nch {if steps[ch][sb] != 0 {@@ -340,7 +342,7 @@ fn layer2(r: &mut BitReader, h: &Header, out: &mut Subbands) -> Result<()> {}}// the scalefactor for each third of the frame (4 granules each)- let mut scf = [[[0f32; 3]; 32]; 2];+ let mut scf = [[[0f32; 3]; tables::SUBBANDS]; 2];for sb in 0..sblimit {for ch in 0..nch {if steps[ch][sb] == 0 {diff --git a/crates/mpa/src/tables.rs b/crates/mpa/src/tables.rsindex 4ca947566..11d56c5aa 100644--- a/crates/mpa/src/tables.rs+++ b/crates/mpa/src/tables.rs@@ -107,6 +107,19 @@ const LSF_LOW: [u16; 16] = [0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047/// 13818-3 B.1 subbands 11-29.const LSF_TOP: [u16; 4] = [0, 3, 5, 9];+/// Subbands of the polyphase filter bank: the size of the decoder's per-subband arrays.+pub(crate) const SUBBANDS: usize = 32;++// Every table's `sblimit` fits the per-subband arrays, so `sb < sblimit` indexes them in bounds.+const _: () = {+ let tables = [AllocTable::A, AllocTable::B, AllocTable::C, AllocTable::D, AllocTable::Lsf];+ let mut i = 0;+ while i < tables.len() {+ assert!(tables[i].sblimit() <= SUBBANDS);+ i += 1;+ }+};+/// A Layer II bit allocation table.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum AllocTable {@@ -145,8 +158,8 @@ impl AllocTable {}}- /// Subbands with an allocation (`sblimit`).- pub(crate) fn sblimit(self) -> usize {+ /// Subbands with an allocation (`sblimit`): at most [`SUBBANDS`] (checked at compile time).+ pub(crate) const fn sblimit(self) -> usize {match self {Self::A => 27,Self::B | Self::Lsf => 30,@@ -155,7 +168,8 @@ impl AllocTable {}}- /// The quantization steps per allocation value for subband `sb`; its length is 2^nbal.+ /// The quantization steps per allocation value for subband `sb`; its length is 2^nbal. A match,+ /// not an index: any `sb` gets a row (subbands past `sblimit` get the table's last one).pub(crate) fn row(self, sb: usize) -> &'static [u16] {match self {Self::A | Self::B => match sb {