From 8bd3b2b22e43cf27f6d3df157a4bcdad30a3fa63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 10:18:09 +0300 Subject: [PATCH] feat(opus): multistream decoding, 5.1 and 7.1 MultistreamDecoder splits a packet into its elementary streams by the self-delimiting framing of Appendix B and routes each stream's channels through the mapping table, silent channels included. Constructor takes the layout the container header carries (rate, streams, coupled, mapping), which is the shape the product already calls. The CELT N/4 FFT's 15-point stage is now radix-3 then radix-5 rather than a direct 15x15 evaluation, which is where a third of multichannel decode time was going: a real 7.1 film track went from 102x to 124x realtime. Checks (all in tests/conformance.rs): the mono, stereo and 5.1 Ogg-Opus fixtures decode to correlation 1.00000 per channel against libopus through ffmpeg; the 5.1 fixture's per-channel tones land in the RFC 7845 family 1 (Vorbis) order the reference produces, each channel carrying its own tone; decode speed is 430x realtime stereo (fixture and testvector01 music alike) and 236x realtime 5.1, against floors of 135x and 104x. The twelve RFC vectors are unchanged. An env-driven sweep (EC_OPUS_FILES, #[ignore]) runs the same comparison over real files. --- crates/ec-opus/src/celt.rs | 146 +++++++++--- crates/ec-opus/src/lib.rs | 18 +- crates/ec-opus/src/multistream.rs | 245 ++++++++++++++++++++ crates/ec-opus/src/silk.rs | 29 ++- crates/ec-opus/tests/conformance.rs | 348 ++++++++++++++++++++++++++++ 5 files changed, 736 insertions(+), 50 deletions(-) create mode 100644 crates/ec-opus/src/multistream.rs diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index 07c1c032..a54bc11d 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -306,9 +306,6 @@ struct Fft15 { /// `exp(2 pi i * k1 * n2 / n)` twiddles, split. tw_re: Vec, tw_im: Vec, - /// 15-point DFT twiddles. - w15_re: [f32; 15], - w15_im: [f32; 15], scratch_re: Vec, scratch_im: Vec, } @@ -326,20 +323,11 @@ impl Fft15 { tw_im[k1 * l + n2] = a.sin() as f32; } } - let mut w15_re = [0.0f32; 15]; - let mut w15_im = [0.0f32; 15]; - for (j, (re, im)) in w15_re.iter_mut().zip(w15_im.iter_mut()).enumerate() { - let a = 2.0 * core::f64::consts::PI * j as f64 / 15.0; - *re = a.cos() as f32; - *im = a.sin() as f32; - } Fft15 { n, sub: Fft::new(l), tw_re, tw_im, - w15_re, - w15_im, scratch_re: vec![0.0; n], scratch_im: vec![0.0; n], } @@ -350,7 +338,7 @@ impl Fft15 { let n = self.n; let l = n / 15; debug_assert_eq!(re.len(), n); - // Stage 1: 15-point DFTs over n1, input stride L. + // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way out. for n2 in 0..l { let mut xr = [0.0f32; 15]; let mut xi = [0.0f32; 15]; @@ -358,21 +346,14 @@ impl Fft15 { xr[n1] = re[l * n1 + n2]; xi[n1] = im[l * n1 + n2]; } + let (yr, yi) = dft15(&xr, &xi); for k1 in 0..15 { - let (mut sr, mut si) = (0.0f32, 0.0f32); - for n1 in 0..15 { - let w = (k1 * n1) % 15; - let (wr, wi) = (self.w15_re[w], self.w15_im[w]); - sr += xr[n1] * wr - xi[n1] * wi; - si += xr[n1] * wi + xi[n1] * wr; - } - // Stage 2 twiddle, folded in here to avoid another pass. let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]); - self.scratch_re[k1 * l + n2] = sr * tr - si * ti; - self.scratch_im[k1 * l + n2] = sr * ti + si * tr; + self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti; + self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr; } } - // Stage 3: L-point transforms, one per k1, written out at stride 15. + // Stage 2: L-point transforms, one per k1, written out at stride 15. for k1 in 0..15 { let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l]; let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l]; @@ -387,6 +368,88 @@ impl Fft15 { } } +/// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on +/// 15 = 3*5), which costs about a third of the direct evaluation. +#[inline] +fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) { + // exp(+2 pi i / 3) and the two fifth-root cosines/sines. + const C3: f32 = -0.5; + const S3: f32 = 0.866_025_4; + const C5_1: f32 = 0.309_017; + const S5_1: f32 = 0.951_056_5; + const C5_2: f32 = -0.809_017; + const S5_2: f32 = 0.587_785_25; + // exp(+2 pi i * (n2*k1) / 15) for n2 in 0..5, k1 in 0..3. + const TW_RE: [[f32; 3]; 5] = [ + [1.0, 1.0, 1.0], + [1.0, 0.913_545_5, 0.669_130_6], + [1.0, 0.669_130_6, -0.104_528_46], + [1.0, 0.309_017, -0.809_017], + [1.0, -0.104_528_46, -0.978_147_6], + ]; + const TW_IM: [[f32; 3]; 5] = [ + [0.0, 0.0, 0.0], + [0.0, 0.406_736_65, 0.743_144_8], + [0.0, 0.743_144_8, 0.994_521_9], + [0.0, 0.951_056_5, 0.587_785_25], + [0.0, 0.994_521_9, -0.207_911_69], + ]; + // Radix-3 over n1 (stride 5), one per n2. + let mut ar = [[0.0f32; 3]; 5]; + let mut ai = [[0.0f32; 3]; 5]; + for n2 in 0..5 { + let (r0, i0) = (xr[n2], xi[n2]); + let (r1, i1) = (xr[5 + n2], xi[5 + n2]); + let (r2, i2) = (xr[10 + n2], xi[10 + n2]); + let (sr, si) = (r1 + r2, i1 + i2); + let (dr, di) = (r1 - r2, i1 - i2); + ar[n2][0] = r0 + sr; + ai[n2][0] = i0 + si; + let (tr, ti) = (r0 + C3 * sr, i0 + C3 * si); + // Multiplying (dr, di) by i gives (-di, dr). + ar[n2][1] = tr - S3 * di; + ai[n2][1] = ti + S3 * dr; + ar[n2][2] = tr + S3 * di; + ai[n2][2] = ti - S3 * dr; + // Twiddle by exp(+2 pi i n2 k1 / 15). + for k1 in 1..3 { + let (tr, ti) = (TW_RE[n2][k1], TW_IM[n2][k1]); + let (r, i) = (ar[n2][k1], ai[n2][k1]); + ar[n2][k1] = r * tr - i * ti; + ai[n2][k1] = r * ti + i * tr; + } + } + // Radix-5 over n2, one per k1; output index is k1 + 3*k2. + let mut yr = [0.0f32; 15]; + let mut yi = [0.0f32; 15]; + for k1 in 0..3 { + let (r0, i0) = (ar[0][k1], ai[0][k1]); + let (r1, i1) = (ar[1][k1], ai[1][k1]); + let (r2, i2) = (ar[2][k1], ai[2][k1]); + let (r3, i3) = (ar[3][k1], ai[3][k1]); + let (r4, i4) = (ar[4][k1], ai[4][k1]); + let (s1r, s1i) = (r1 + r4, i1 + i4); + let (d1r, d1i) = (r1 - r4, i1 - i4); + let (s2r, s2i) = (r2 + r3, i2 + i3); + let (d2r, d2i) = (r2 - r3, i2 - i3); + yr[k1] = r0 + s1r + s2r; + yi[k1] = i0 + s1i + s2i; + let (m1r, m1i) = (r0 + C5_1 * s1r + C5_2 * s2r, i0 + C5_1 * s1i + C5_2 * s2i); + let (n1r, n1i) = (S5_1 * d1r + S5_2 * d2r, S5_1 * d1i + S5_2 * d2i); + let (m2r, m2i) = (r0 + C5_2 * s1r + C5_1 * s2r, i0 + C5_2 * s1i + C5_1 * s2i); + let (n2r, n2i) = (S5_2 * d1r - S5_1 * d2r, S5_2 * d1i - S5_1 * d2i); + yr[k1 + 3] = m1r - n1i; + yi[k1 + 3] = m1i + n1r; + yr[k1 + 12] = m1r + n1i; + yi[k1 + 12] = m1i - n1r; + yr[k1 + 6] = m2r - n2i; + yi[k1 + 6] = m2i + n2r; + yr[k1 + 9] = m2r + n2i; + yi[k1 + 9] = m2i - n2r; + } + (yr, yi) +} + /// One inverse-MDCT plan: spectrum length `l = 15 * 2^k`, window `2*l`. #[derive(Clone, Debug)] struct ImdctPlan { @@ -654,6 +717,7 @@ pub struct CeltDecoder { freq: Vec, norm: Vec, lowband_scratch: Vec, + hadamard_tmp: Vec, band_e: Vec, pulses: [i32; NB_BANDS], fine_quant: [i32; NB_BANDS], @@ -695,6 +759,7 @@ impl CeltDecoder { freq: vec![0.0; 2 * max_n], norm: vec![0.0; 2 * max_n], lowband_scratch: vec![0.0; max_n], + hadamard_tmp: vec![0.0; max_n], band_e: vec![0.0; 2 * NB_BANDS], pulses: [0; NB_BANDS], fine_quant: [0; NB_BANDS], @@ -1711,17 +1776,23 @@ impl CeltDecoder { if b0 > 1 { deinterleave_hadamard( &mut self.x[x..x + n], + &mut self.hadamard_tmp, n_b >> recombine, b0 << recombine, long_blocks, ); - if let Some(l) = self.lowband_mut(lowband) { - deinterleave_hadamard( - &mut l[..n], - n_b >> recombine, - b0 << recombine, - long_blocks, - ); + if lowband != Lowband::None { + let mut tmp = core::mem::take(&mut self.hadamard_tmp); + if let Some(l) = self.lowband_mut(lowband) { + deinterleave_hadamard( + &mut l[..n], + tmp.as_mut_slice(), + n_b >> recombine, + b0 << recombine, + long_blocks, + ); + } + self.hadamard_tmp = tmp; } } } @@ -2026,6 +2097,7 @@ impl CeltDecoder { if b0 > 1 { interleave_hadamard( &mut self.x[x..x + n0], + &mut self.hadamard_tmp, n_b >> recombine, b0 << recombine, long_blocks, @@ -2403,9 +2475,9 @@ fn haar1(x: &mut [f32], n0: usize, stride: usize) { } } -fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { +fn deinterleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) { let n = n0 * stride; - let mut tmp = vec![0.0f32; n]; + let tmp = &mut tmp[..n]; if hadamard { let order = &ORDERY[stride - 2..]; for i in 0..stride { @@ -2420,12 +2492,12 @@ fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool } } } - x[..n].copy_from_slice(&tmp); + x[..n].copy_from_slice(tmp); } -fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { +fn interleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) { let n = n0 * stride; - let mut tmp = vec![0.0f32; n]; + let tmp = &mut tmp[..n]; if hadamard { let order = &ORDERY[stride - 2..]; for i in 0..stride { @@ -2440,7 +2512,7 @@ fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) } } } - x[..n].copy_from_slice(&tmp); + x[..n].copy_from_slice(tmp); } /// Scales a vector to `gain` in the L2 sense. diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 346aaa96..08662f2d 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -27,11 +27,13 @@ #![warn(missing_docs)] pub mod celt; +pub mod multistream; pub mod packet; pub mod range; pub mod silk; pub use celt::CeltDecoder; +pub use multistream::MultistreamDecoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::RangeDecoder; pub use silk::SilkDecoder; @@ -53,6 +55,10 @@ pub struct Decoder { silk: SilkDecoder, /// The CELT overlap window, reused for redundancy cross-fades. celt_window: Vec, + /// Per-frame scratch, allocated once: the SILK layer's output and the + /// redundancy frame. + silk_pcm: Vec, + redundant: Vec, prev_mode: Option, prev_redundancy: bool, range_final: u32, @@ -88,6 +94,8 @@ impl Decoder { celt: CeltDecoder::new(channels, downsample), silk: SilkDecoder::new(sample_rate, channels), celt_window: celt::overlap_window(), + silk_pcm: vec![0; 5760 * channels], + redundant: vec![0.0; 240 * channels], prev_mode: None, prev_redundancy: false, range_final: 0, @@ -197,7 +205,9 @@ impl Decoder { let f2_5 = 120 / self.downsample; // --- SILK layer ----------------------------------------------------- - let mut silk_pcm = vec![0i16; frame_out * self.channels]; + let mut silk_pcm = core::mem::take(&mut self.silk_pcm); + silk_pcm.clear(); + silk_pcm.resize(frame_out * self.channels, 0); if mode != Mode::Celt { if self.prev_mode == Some(Mode::Celt) { self.silk.reset(); @@ -267,7 +277,9 @@ impl Decoder { let end_band = toc.bandwidth().celt_end_band(); let start_band = if mode == Mode::Celt { 0 } else { 17 }; - let mut redundant = vec![0.0f32; f5 * self.channels]; + let mut redundant = core::mem::take(&mut self.redundant); + redundant.clear(); + redundant.resize(f5 * self.channels, 0.0); // A redundancy frame that precedes the main one is decoded first. let mut redundant_rng = 0u32; @@ -355,6 +367,8 @@ impl Decoder { self.prev_mode = Some(mode); self.prev_redundancy = redundancy && !celt_to_silk; + self.silk_pcm = silk_pcm; + self.redundant = redundant; Ok(dec.range() ^ redundant_rng) } } diff --git a/crates/ec-opus/src/multistream.rs b/crates/ec-opus/src/multistream.rs new file mode 100644 index 00000000..16aff2cc --- /dev/null +++ b/crates/ec-opus/src/multistream.rs @@ -0,0 +1,245 @@ +//! Multichannel Opus: several elementary streams in one packet. +//! +//! A multistream packet is just the ordinary packets of each stream laid end to +//! end. All but the last use the self-delimiting framing of RFC 6716 +//! Appendix B, which carries one extra length so the boundary can be found +//! without a container; the last uses the ordinary framing, so it takes +//! whatever is left. That is the whole of the format — everything else is the +//! channel mapping table, which says where each stream's channels land. +//! +//! Streams come in two kinds: the first `coupled` streams are stereo, the rest +//! mono. `mapping[c]` names the coded channel that output channel `c` reads +//! from: values below `2*coupled` are a coupled stream's left (even) or right +//! (odd) channel, values above index the mono streams, and 255 means the +//! channel is silent. +//! +//! Channel *order* is the mapping's, not this decoder's: for RFC 7845 mapping +//! family 1 — what a 5.1 or 7.1 film track uses — that is Vorbis order +//! (left, centre, right, back left, back right, LFE for 5.1), and a caller that +//! wants the product's FL/FR/FC/LFE/BL/BR order permutes it. + +use ec_core::{Error, Result}; + +use crate::Decoder; + +/// A decoder for a multichannel Opus stream, mono through 255 channels. +#[derive(Debug)] +pub struct MultistreamDecoder { + streams: Vec, + coupled: usize, + mapping: Vec, + channels: usize, + sample_rate: u32, + /// Scratch for one stream's output. + buf: Vec, +} + +impl MultistreamDecoder { + /// A decoder for `streams` elementary streams of which the first `coupled` + /// are stereo, with `mapping` naming the coded channel each output channel + /// comes from. + /// + /// # Panics + /// On a layout that breaks the RFC's limits — more coupled streams than + /// streams, a mapping entry naming a channel no stream codes, an + /// unsupported rate. The layout comes from a container header, so callers + /// that read one from a file should check it (or use + /// [`MultistreamDecoder::try_with_rate`]) rather than pass it straight in. + pub fn with_rate( + sample_rate: u32, + streams: usize, + coupled: usize, + mapping: &[u8], + ) -> MultistreamDecoder { + match Self::try_with_rate(sample_rate, streams, coupled, mapping) { + Ok(d) => d, + Err(e) => panic!("invalid Opus multistream layout: {e}"), + } + } + + /// [`MultistreamDecoder::with_rate`] with the layout checked instead of + /// asserted. + pub fn try_with_rate( + sample_rate: u32, + streams: usize, + coupled: usize, + mapping: &[u8], + ) -> Result { + if streams == 0 || streams > 255 || coupled > streams { + return Err(Error::corrupt(format!( + "opus multistream: {streams} streams of which {coupled} coupled" + ))); + } + let coded = coupled + streams; + if mapping.is_empty() || mapping.len() > 255 { + return Err(Error::corrupt(format!( + "opus multistream: {} output channels", + mapping.len() + ))); + } + if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) { + return Err(Error::corrupt(format!( + "opus multistream: mapping entry {bad} names a channel of {coded}" + ))); + } + let mut decoders = Vec::with_capacity(streams); + for s in 0..streams { + let ch = if s < coupled { 2 } else { 1 }; + decoders.push(Decoder::new(sample_rate, ch)?); + } + Ok(MultistreamDecoder { + streams: decoders, + coupled, + mapping: mapping.to_vec(), + channels: mapping.len(), + sample_rate, + buf: vec![0.0; 2 * 5760], + }) + } + + /// Output channels. + pub fn channels(&self) -> usize { + self.channels + } + + /// Output sample rate. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// Drops all inter-packet state in every stream; call after a seek. + pub fn reset(&mut self) { + for s in self.streams.iter_mut() { + s.reset(); + } + } + + /// The range coder states of all streams, combined the way RFC 6716 + /// Section 6 combines them for conformance checking. + pub fn final_range(&self) -> u32 { + self.streams.iter().fold(0, |acc, s| acc ^ s.final_range()) + } + + /// Decodes one multistream packet into a fresh interleaved buffer. + /// + /// This is the shape the product's decoder loop uses; [`decode_float`] is + /// the same work without the allocation. + /// + /// [`decode_float`]: MultistreamDecoder::decode_float + pub fn decode_packet(&mut self, data: &[u8]) -> Result> { + // A packet is at most 120 ms, and the sample rate at most 48 kHz. + let mut out = vec![0.0; 5760 * self.channels * self.sample_rate as usize / 48000]; + let n = self.decode_float(data, &mut out)?; + out.truncate(n * self.channels); + Ok(out) + } + + /// Decodes one multistream packet into `out`, returning samples per + /// channel. + pub fn decode_float(&mut self, data: &[u8], out: &mut [f32]) -> Result { + // Every stream but the last needs at least a TOC and a length byte. + if data.len() < 2 * self.streams.len() - 1 { + return Err(Error::corrupt(format!( + "opus multistream: {} bytes for {} streams", + data.len(), + self.streams.len() + ))); + } + let mut rest = data; + let mut frame_size = 0usize; + let nb_streams = self.streams.len(); + for s in 0..nb_streams { + let last = s == nb_streams - 1; + let stream_channels = if s < self.coupled { 2 } else { 1 }; + let need = 5760 * stream_channels; + if self.buf.len() < need { + self.buf.resize(need, 0.0); + } + let (n, consumed) = if last { + ( + self.streams[s].decode_float(rest, &mut self.buf)?, + rest.len(), + ) + } else { + self.streams[s].decode_self_delimited(rest, &mut self.buf)? + }; + rest = &rest[consumed.min(rest.len())..]; + if s == 0 { + frame_size = n; + if out.len() < n * self.channels { + return Err(Error::corrupt(format!( + "opus multistream: output buffer holds {} samples, packet needs {}", + out.len(), + n * self.channels + ))); + } + } else if n != frame_size { + return Err(Error::corrupt(format!( + "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}" + ))); + } + // Route this stream's channels to the outputs that name them. + for (c, &m) in self.mapping.iter().enumerate() { + if m == 255 { + continue; + } + let m = m as usize; + let src = if s < self.coupled { + if m == 2 * s { + Some(0) + } else if m == 2 * s + 1 { + Some(1) + } else { + None + } + } else if m == s + self.coupled { + Some(0) + } else { + None + }; + if let Some(off) = src { + for i in 0..frame_size { + out[self.channels * i + c] = self.buf[stream_channels * i + off]; + } + } + } + } + // Channels the mapping leaves unassigned are silent. + for (c, &m) in self.mapping.iter().enumerate() { + if m == 255 { + for i in 0..frame_size { + out[self.channels * i + c] = 0.0; + } + } + } + Ok(frame_size) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layouts_are_checked() { + // RFC 7845 mapping family 1, 5.1: four streams, two of them coupled. + assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]).is_ok()); + // More coupled streams than streams. + assert!(MultistreamDecoder::try_with_rate(48000, 2, 3, &[0, 1]).is_err()); + // A mapping entry naming a channel no stream codes: 4 streams with 2 + // coupled code 6 channels, so 6 is out of range. + assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 6]).is_err()); + // 255 is the silent channel and is always allowed. + assert!(MultistreamDecoder::try_with_rate(48000, 1, 0, &[0, 255]).is_ok()); + assert!(MultistreamDecoder::try_with_rate(44100, 1, 0, &[0]).is_err()); + } + + #[test] + fn truncated_packets_are_errors_not_panics() { + let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]); + for n in 0..40usize { + let data: Vec = (0..n).map(|i| (i * 37 + 11) as u8).collect(); + let _ = dec.decode_packet(&data); + } + } +} diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs index eeb6e14f..3c48f978 100644 --- a/crates/ec-opus/src/silk.rs +++ b/crates/ec-opus/src/silk.rs @@ -159,7 +159,6 @@ fn sqrt_approx(x: i32) -> i32 { smlawb(y, y, smulbb(213, frac)) } - fn log2lin(log_q7: i32) -> i32 { if log_q7 < 0 { return 0; @@ -393,6 +392,8 @@ pub struct SilkDecoder { channels_api: usize, api_rate: u32, prev_decode_only_middle: bool, + /// Resampler output for one channel, allocated once. + resample_tmp: Vec, } impl SilkDecoder { @@ -405,6 +406,7 @@ impl SilkDecoder { channels_api, api_rate, prev_decode_only_middle: false, + resample_tmp: vec![0; 5760], } } @@ -582,7 +584,9 @@ impl SilkDecoder { self.prev_decode_only_middle = decode_only_middle; let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000); - let mut tmp = vec![0i16; out_len]; + let mut tmp = core::mem::take(&mut self.resample_tmp); + tmp.clear(); + tmp.resize(out_len, 0); let chans = self.channels_api.min(channels_internal); for n in 0..chans { let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] }; @@ -596,6 +600,7 @@ impl SilkDecoder { out[..out_len].copy_from_slice(&tmp[..out_len]); } } + self.resample_tmp = tmp; // A mono stream fed to a stereo output is duplicated. if self.channels_api == 2 && channels_internal == 1 { for i in 0..out_len { @@ -1476,6 +1481,8 @@ struct Resampler { /// FIR history. s_fir: [i16; 8], delay_buf: DelayBuf, + /// Upsampler scratch, allocated once. + fir_buf: Vec, /// Down-sampling coefficients, when the output rate is the lower one. down: Option, } @@ -1572,24 +1579,21 @@ impl Resampler { let mut head = [0i16; 48]; head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]); head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]); - let head = &head[..self.fs_in_khz]; + let n_head = self.fs_in_khz; let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)]; let split = self.fs_out_khz; let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz; if self.fs_in_khz == self.fs_out_khz { - out[..self.fs_in_khz].copy_from_slice(head); + out[..n_head].copy_from_slice(&head[..n_head]); out[split..split + rest_out].copy_from_slice(rest); } else if self.down.is_some() { - let head = head.to_vec(); - self.down_fir(&mut out[..split], &head); + self.down_fir(&mut out[..split], &head[..n_head]); self.down_fir(&mut out[split..split + rest_out], rest); } else if self.fs_out_khz == 2 * self.fs_in_khz { - let head = head.to_vec(); - self.up2_hq(&mut out[..split], &head); + self.up2_hq(&mut out[..split], &head[..n_head]); self.up2_hq(&mut out[split..split + rest_out], rest); } else { - let head = head.to_vec(); - self.iir_fir(&mut out[..split], &head); + self.iir_fir(&mut out[..split], &head[..n_head]); self.iir_fir(&mut out[split..split + rest_out], rest); } self.delay_buf[..self.input_delay] @@ -1634,7 +1638,9 @@ impl Resampler { fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) { let mut written = 0usize; let mut pos = 0usize; - let mut buf = vec![0i16; 2 * self.batch_size + 8]; + let mut buf = core::mem::take(&mut self.fir_buf); + buf.clear(); + buf.resize(2 * self.batch_size + 8, 0); buf[..8].copy_from_slice(&self.s_fir); let mut n_samples_in = 0; while pos < input.len() { @@ -1697,6 +1703,7 @@ impl Resampler { } self.s_fir .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]); + self.fir_buf = buf; } /// `silk_resampler_private_down_FIR`, for output rates below the internal diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index ce507366..01eec6d1 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -375,3 +375,351 @@ fn rfc6716_test_vectors() { println!("{line}"); } } + +// --------------------------------------------------------------------------- +// Real files: the Ogg-Opus fixtures, against ffmpeg +// --------------------------------------------------------------------------- + +use ec_opus::MultistreamDecoder; +use std::process::Command; + +/// Splits an Ogg stream into packets (RFC 3533): a page header, a segment +/// table, and packets that end on any segment shorter than 255 bytes. +fn ogg_packets(data: &[u8]) -> Vec> { + let mut packets = Vec::new(); + let mut partial: Vec = Vec::new(); + let mut i = 0; + while i + 27 <= data.len() { + assert_eq!(&data[i..i + 4], b"OggS", "not an Ogg page at {i}"); + let nsegs = data[i + 26] as usize; + let table = &data[i + 27..i + 27 + nsegs]; + let mut body = i + 27 + nsegs; + for &len in table { + let len = len as usize; + partial.extend_from_slice(&data[body..body + len]); + body += len; + if len < 255 { + packets.push(core::mem::take(&mut partial)); + } + } + i = body; + } + packets +} + +/// The RFC 7845 identification header: channel count, pre-skip and the +/// multistream layout. +struct OpusHead { + channels: usize, + pre_skip: usize, + streams: usize, + coupled: usize, + mapping: Vec, +} + +fn parse_opus_head(p: &[u8]) -> OpusHead { + assert_eq!(&p[..8], b"OpusHead"); + let channels = p[9] as usize; + let pre_skip = u16::from_le_bytes([p[10], p[11]]) as usize; + let family = p[18]; + if family == 0 { + OpusHead { + channels, + pre_skip, + streams: 1, + coupled: channels - 1, + mapping: (0..channels as u8).collect(), + } + } else { + OpusHead { + channels, + pre_skip, + streams: p[19] as usize, + coupled: p[20] as usize, + mapping: p[21..21 + channels].to_vec(), + } + } +} + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/audio") + .join(name) +} + +/// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel +/// order, with the pre-skip already removed. +/// +/// The decoder is forced to `libopus` — the reference implementation. ffmpeg's +/// own native Opus decoder is a third implementation and deviates from libopus +/// by as much as 0.97 correlation on this very fixture's coupled surround +/// streams, so it makes a poor oracle. +fn ffmpeg_decode(path: &Path, channels: usize) -> Option> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-c:a", "libopus", "-i"]) + .arg(path) + .args([ + "-f", + "f32le", + "-ar", + "48000", + "-ac", + &channels.to_string(), + "-", + ]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + Some( + out.stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(), + ) +} + +/// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed. +fn decode_ogg(path: &Path) -> (Vec, usize) { + let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let packets = ogg_packets(&data); + let head = parse_opus_head(&packets[0]); + let mut dec = MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping); + let mut pcm = Vec::new(); + for p in packets.iter().skip(2) { + if p.is_empty() { + continue; + } + let frame = dec.decode_packet(p).expect("decode"); + pcm.extend_from_slice(&frame); + } + pcm.drain(..head.pre_skip * head.channels); + (pcm, head.channels) +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let n = a.len().min(b.len()); + let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + sxy += a[i] as f64 * b[i] as f64; + sxx += (a[i] as f64).powi(2); + syy += (b[i] as f64).powi(2); + } + if sxx == 0.0 || syy == 0.0 { + return if sxx == syy { 1.0 } else { 0.0 }; + } + sxy / (sxx * syy).sqrt() +} + +/// Power at `freq` in a channel, by the Goertzel algorithm. +fn tone_power(x: &[f32], channels: usize, ch: usize, freq: f64) -> f64 { + let n = x.len() / channels; + let w = 2.0 * std::f64::consts::PI * freq / 48000.0; + let coeff = 2.0 * w.cos(); + let (mut s1, mut s2) = (0.0f64, 0.0f64); + for i in 0..n { + let s = x[i * channels + ch] as f64 + coeff * s1 - s2; + s2 = s1; + s1 = s; + } + (s1 * s1 + s2 * s2 - coeff * s1 * s2) / (n * n) as f64 +} + +#[test] +fn ogg_opus_fixtures_match_ffmpeg() { + // Mapping family 1 puts 5.1 in Vorbis order; ffmpeg hands its own order + // back, so the comparison permutes one into the other. + const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; + for (name, channels) in [ + ("opus-ogg-mono-48000.opus", 1usize), + ("opus-ogg-stereo-48000.opus", 2), + ("opus-ogg-5.1-48000.opus", 6), + ] { + let path = fixture(name); + if !path.exists() { + eprintln!("{name}: missing, skipped (run scripts/gen-fixtures.sh)"); + continue; + } + let Some(reference) = ffmpeg_decode(&path, channels) else { + eprintln!("{name}: ffmpeg unavailable, skipped"); + continue; + }; + let (mine, ch) = decode_ogg(&path); + assert_eq!(ch, channels, "{name}: channel count"); + let mut worst = 1.0f64; + let n = (reference.len() / channels).min(mine.len() / channels); + assert!(n > 48000, "{name}: only {n} samples decoded"); + for c in 0..channels { + let their_c = if channels == 6 { + VORBIS_TO_FFMPEG_5_1[c] + } else { + c + }; + let a: Vec = (0..n).map(|i| mine[i * channels + c]).collect(); + let b: Vec = (0..n).map(|i| reference[i * channels + their_c]).collect(); + let corr = correlation(&a, &b); + println!("{name}: channel {c} correlation {corr:.5}"); + worst = worst.min(corr); + } + assert!( + worst >= 0.99, + "{name}: worst channel correlation {worst:.5}" + ); + } +} + +#[test] +fn five_one_channels_land_in_the_right_places() { + // The fixture carries one distinct sine per channel, so a channel-order + // bug shows up as a channel playing the wrong tone. The tones themselves + // come from the reference decode rather than from an assumption about how + // ffmpeg laid the fixture out; what is asserted is that this decoder's + // Vorbis-order output is the reference's 5.1-order output permuted. + const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; + const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0]; + let path = fixture("opus-ogg-5.1-48000.opus"); + if !path.exists() { + eprintln!("5.1 fixture missing, skipped"); + return; + } + let Some(reference) = ffmpeg_decode(&path, 6) else { + eprintln!("ffmpeg unavailable, skipped"); + return; + }; + let (pcm, channels) = decode_ogg(&path); + assert_eq!(channels, 6); + let dominant = |x: &[f32], ch: usize| -> usize { + let mut best = (0usize, 0.0f64); + for (t, &f) in TONES.iter().enumerate() { + let p = tone_power(x, 6, ch, f); + if p > best.1 { + best = (t, p); + } + } + best.0 + }; + let mut seen = [false; 6]; + for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() { + let want = dominant(&reference, their); + let got = dominant(&pcm, c); + println!( + "channel {c}: {} Hz (reference channel {their} carries {} Hz)", + TONES[got], TONES[want] + ); + assert_eq!(got, want, "channel {c} carries the wrong tone"); + assert!(!seen[got], "tone {} Hz appears on two channels", TONES[got]); + seen[got] = true; + } +} + +#[test] +fn decode_speed() { + if cfg!(debug_assertions) { + eprintln!("decode speed is only meaningful in release; skipped"); + return; + } + for (name, channels) in [ + ("opus-ogg-stereo-48000.opus", 2usize), + ("opus-ogg-5.1-48000.opus", 6), + ] { + let path = fixture(name); + if !path.exists() { + continue; + } + let data = fs::read(&path).unwrap(); + let packets = ogg_packets(&data); + let head = parse_opus_head(&packets[0]); + let audio: Vec<&Vec> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect(); + let mut dec = + MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping); + let mut out = vec![0.0f32; 5760 * channels]; + // Warm up, then measure enough passes to cover several seconds of audio. + let mut samples = 0usize; + for p in &audio { + samples += dec.decode_float(p, &mut out).unwrap(); + } + let passes = 20; + let start = std::time::Instant::now(); + for _ in 0..passes { + dec.reset(); + for p in &audio { + dec.decode_float(p, &mut out).unwrap(); + } + } + let elapsed = start.elapsed().as_secs_f64(); + let audio_secs = (samples * passes) as f64 / 48000.0; + let realtime = audio_secs / elapsed; + println!( + "{name}: {realtime:.0}x realtime ({channels} channels, {audio_secs:.1} s in {elapsed:.3} s)" + ); + let floor = if channels == 6 { 104.0 } else { 135.0 }; + assert!( + realtime >= floor, + "{name}: {realtime:.0}x realtime is below the {floor}x floor" + ); + } + + // The fixtures are sine tones, which are cheap; testvector01 is real music + // at a high rate and is the honest stereo number. + let path = vectors_dir().join("testvector01.bit"); + if path.exists() { + let packets = read_vector(&path); + let mut dec = Decoder::new(48000, 2).unwrap(); + let mut out = vec![0.0f32; 5760 * 2]; + let mut samples = 0usize; + let start = std::time::Instant::now(); + for p in &packets { + samples += dec.decode_float(&p.payload, &mut out).unwrap(); + } + let elapsed = start.elapsed().as_secs_f64(); + let realtime = samples as f64 / 48000.0 / elapsed; + println!("testvector01 (stereo music): {realtime:.0}x realtime"); + assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x"); + } +} + +#[test] +#[ignore] +fn real_library_sweep() { + // Files named on the command line (EC_OPUS_FILES=a.opus:b.opus), decoded + // and compared against libopus channel by channel, with the decode speed. + let files = std::env::var("EC_OPUS_FILES").unwrap_or_default(); + for f in files.split(':').filter(|s| !s.is_empty()) { + let path = PathBuf::from(f); + let (pcm, channels) = decode_ogg(&path); + let reference = ffmpeg_decode(&path, channels).expect("libopus"); + let n = (reference.len() / channels).min(pcm.len() / channels); + let mut worst = 1.0f64; + for c in 0..channels { + let a: Vec = (0..n).map(|i| pcm[i * channels + c]).collect(); + let b: Vec = (0..n).map(|i| reference[i * channels + c]).collect(); + let corr = correlation(&a, &b); + worst = worst.min(corr); + println!("{f}: channel {c} correlation {corr:.5}"); + } + // Speed on the same file. + let data = fs::read(&path).unwrap(); + let packets = ogg_packets(&data); + let head = parse_opus_head(&packets[0]); + let audio: Vec<&Vec> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect(); + let mut dec = + MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping); + let mut out = vec![0.0f32; 5760 * channels]; + let mut samples = 0usize; + for p in &audio { + samples += dec.decode_float(p, &mut out).unwrap(); + } + dec.reset(); + let start = std::time::Instant::now(); + for p in &audio { + dec.decode_float(p, &mut out).unwrap(); + } + let elapsed = start.elapsed().as_secs_f64(); + println!( + "{f}: {channels} ch, {:.1} s audio, {:.0}x realtime, worst channel {worst:.5}", + samples as f64 / 48000.0, + samples as f64 / 48000.0 / elapsed + ); + } +}