forge
Explore
Log in

Don't you dare go Hollow

Multistream decoding, 5.1 and 7.1

Browse files at this commit

8bd3b2b22e43cf27f6d3df157a4bcdad30a3fa63Ahmet Kaan GümüşParent: 1325107
  • feat
    • multistream decoding, 5.1 and 7.1
Show full message
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.rsmodified+109 -37
@@ -306,9 +306,6 @@ struct Fft15 {
306306 /// `exp(2 pi i * k1 * n2 / n)` twiddles, split.
307307 tw_re: Vec<f32>,
308308 tw_im: Vec<f32>,
309- /// 15-point DFT twiddles.
310- w15_re: [f32; 15],
311- w15_im: [f32; 15],
312309 scratch_re: Vec<f32>,
313310 scratch_im: Vec<f32>,
314311 }
@@ -326,20 +323,11 @@ impl Fft15 {
326323 tw_im[k1 * l + n2] = a.sin() as f32;
327324 }
328325 }
329- let mut w15_re = [0.0f32; 15];
330- let mut w15_im = [0.0f32; 15];
331- for (j, (re, im)) in w15_re.iter_mut().zip(w15_im.iter_mut()).enumerate() {
332- let a = 2.0 * core::f64::consts::PI * j as f64 / 15.0;
333- *re = a.cos() as f32;
334- *im = a.sin() as f32;
335- }
336326 Fft15 {
337327 n,
338328 sub: Fft::new(l),
339329 tw_re,
340330 tw_im,
341- w15_re,
342- w15_im,
343331 scratch_re: vec![0.0; n],
344332 scratch_im: vec![0.0; n],
345333 }
@@ -350,7 +338,7 @@ impl Fft15 {
350338 let n = self.n;
351339 let l = n / 15;
352340 debug_assert_eq!(re.len(), n);
353- // Stage 1: 15-point DFTs over n1, input stride L.
341+ // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way out.
354342 for n2 in 0..l {
355343 let mut xr = [0.0f32; 15];
356344 let mut xi = [0.0f32; 15];
@@ -358,21 +346,14 @@ impl Fft15 {
358346 xr[n1] = re[l * n1 + n2];
359347 xi[n1] = im[l * n1 + n2];
360348 }
349+ let (yr, yi) = dft15(&xr, &xi);
361350 for k1 in 0..15 {
362- let (mut sr, mut si) = (0.0f32, 0.0f32);
363- for n1 in 0..15 {
364- let w = (k1 * n1) % 15;
365- let (wr, wi) = (self.w15_re[w], self.w15_im[w]);
366- sr += xr[n1] * wr - xi[n1] * wi;
367- si += xr[n1] * wi + xi[n1] * wr;
368- }
369- // Stage 2 twiddle, folded in here to avoid another pass.
370351 let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]);
371- self.scratch_re[k1 * l + n2] = sr * tr - si * ti;
372- self.scratch_im[k1 * l + n2] = sr * ti + si * tr;
352+ self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti;
353+ self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr;
373354 }
374355 }
375- // Stage 3: L-point transforms, one per k1, written out at stride 15.
356+ // Stage 2: L-point transforms, one per k1, written out at stride 15.
376357 for k1 in 0..15 {
377358 let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l];
378359 let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l];
@@ -387,6 +368,88 @@ impl Fft15 {
387368 }
388369 }
389370
371+/// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on
372+/// 15 = 3*5), which costs about a third of the direct evaluation.
373+#[inline]
374+fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) {
375+ // exp(+2 pi i / 3) and the two fifth-root cosines/sines.
376+ const C3: f32 = -0.5;
377+ const S3: f32 = 0.866_025_4;
378+ const C5_1: f32 = 0.309_017;
379+ const S5_1: f32 = 0.951_056_5;
380+ const C5_2: f32 = -0.809_017;
381+ const S5_2: f32 = 0.587_785_25;
382+ // exp(+2 pi i * (n2*k1) / 15) for n2 in 0..5, k1 in 0..3.
383+ const TW_RE: [[f32; 3]; 5] = [
384+ [1.0, 1.0, 1.0],
385+ [1.0, 0.913_545_5, 0.669_130_6],
386+ [1.0, 0.669_130_6, -0.104_528_46],
387+ [1.0, 0.309_017, -0.809_017],
388+ [1.0, -0.104_528_46, -0.978_147_6],
389+ ];
390+ const TW_IM: [[f32; 3]; 5] = [
391+ [0.0, 0.0, 0.0],
392+ [0.0, 0.406_736_65, 0.743_144_8],
393+ [0.0, 0.743_144_8, 0.994_521_9],
394+ [0.0, 0.951_056_5, 0.587_785_25],
395+ [0.0, 0.994_521_9, -0.207_911_69],
396+ ];
397+ // Radix-3 over n1 (stride 5), one per n2.
398+ let mut ar = [[0.0f32; 3]; 5];
399+ let mut ai = [[0.0f32; 3]; 5];
400+ for n2 in 0..5 {
401+ let (r0, i0) = (xr[n2], xi[n2]);
402+ let (r1, i1) = (xr[5 + n2], xi[5 + n2]);
403+ let (r2, i2) = (xr[10 + n2], xi[10 + n2]);
404+ let (sr, si) = (r1 + r2, i1 + i2);
405+ let (dr, di) = (r1 - r2, i1 - i2);
406+ ar[n2][0] = r0 + sr;
407+ ai[n2][0] = i0 + si;
408+ let (tr, ti) = (r0 + C3 * sr, i0 + C3 * si);
409+ // Multiplying (dr, di) by i gives (-di, dr).
410+ ar[n2][1] = tr - S3 * di;
411+ ai[n2][1] = ti + S3 * dr;
412+ ar[n2][2] = tr + S3 * di;
413+ ai[n2][2] = ti - S3 * dr;
414+ // Twiddle by exp(+2 pi i n2 k1 / 15).
415+ for k1 in 1..3 {
416+ let (tr, ti) = (TW_RE[n2][k1], TW_IM[n2][k1]);
417+ let (r, i) = (ar[n2][k1], ai[n2][k1]);
418+ ar[n2][k1] = r * tr - i * ti;
419+ ai[n2][k1] = r * ti + i * tr;
420+ }
421+ }
422+ // Radix-5 over n2, one per k1; output index is k1 + 3*k2.
423+ let mut yr = [0.0f32; 15];
424+ let mut yi = [0.0f32; 15];
425+ for k1 in 0..3 {
426+ let (r0, i0) = (ar[0][k1], ai[0][k1]);
427+ let (r1, i1) = (ar[1][k1], ai[1][k1]);
428+ let (r2, i2) = (ar[2][k1], ai[2][k1]);
429+ let (r3, i3) = (ar[3][k1], ai[3][k1]);
430+ let (r4, i4) = (ar[4][k1], ai[4][k1]);
431+ let (s1r, s1i) = (r1 + r4, i1 + i4);
432+ let (d1r, d1i) = (r1 - r4, i1 - i4);
433+ let (s2r, s2i) = (r2 + r3, i2 + i3);
434+ let (d2r, d2i) = (r2 - r3, i2 - i3);
435+ yr[k1] = r0 + s1r + s2r;
436+ yi[k1] = i0 + s1i + s2i;
437+ let (m1r, m1i) = (r0 + C5_1 * s1r + C5_2 * s2r, i0 + C5_1 * s1i + C5_2 * s2i);
438+ let (n1r, n1i) = (S5_1 * d1r + S5_2 * d2r, S5_1 * d1i + S5_2 * d2i);
439+ let (m2r, m2i) = (r0 + C5_2 * s1r + C5_1 * s2r, i0 + C5_2 * s1i + C5_1 * s2i);
440+ let (n2r, n2i) = (S5_2 * d1r - S5_1 * d2r, S5_2 * d1i - S5_1 * d2i);
441+ yr[k1 + 3] = m1r - n1i;
442+ yi[k1 + 3] = m1i + n1r;
443+ yr[k1 + 12] = m1r + n1i;
444+ yi[k1 + 12] = m1i - n1r;
445+ yr[k1 + 6] = m2r - n2i;
446+ yi[k1 + 6] = m2i + n2r;
447+ yr[k1 + 9] = m2r + n2i;
448+ yi[k1 + 9] = m2i - n2r;
449+ }
450+ (yr, yi)
451+}
452+
390453 /// One inverse-MDCT plan: spectrum length `l = 15 * 2^k`, window `2*l`.
391454 #[derive(Clone, Debug)]
392455 struct ImdctPlan {
@@ -654,6 +717,7 @@ pub struct CeltDecoder {
654717 freq: Vec<f32>,
655718 norm: Vec<f32>,
656719 lowband_scratch: Vec<f32>,
720+ hadamard_tmp: Vec<f32>,
657721 band_e: Vec<f32>,
658722 pulses: [i32; NB_BANDS],
659723 fine_quant: [i32; NB_BANDS],
@@ -695,6 +759,7 @@ impl CeltDecoder {
695759 freq: vec![0.0; 2 * max_n],
696760 norm: vec![0.0; 2 * max_n],
697761 lowband_scratch: vec![0.0; max_n],
762+ hadamard_tmp: vec![0.0; max_n],
698763 band_e: vec![0.0; 2 * NB_BANDS],
699764 pulses: [0; NB_BANDS],
700765 fine_quant: [0; NB_BANDS],
@@ -1711,17 +1776,23 @@ impl CeltDecoder {
17111776 if b0 > 1 {
17121777 deinterleave_hadamard(
17131778 &mut self.x[x..x + n],
1779+ &mut self.hadamard_tmp,
17141780 n_b >> recombine,
17151781 b0 << recombine,
17161782 long_blocks,
17171783 );
1718- if let Some(l) = self.lowband_mut(lowband) {
1719- deinterleave_hadamard(
1720- &mut l[..n],
1721- n_b >> recombine,
1722- b0 << recombine,
1723- long_blocks,
1724- );
1784+ if lowband != Lowband::None {
1785+ let mut tmp = core::mem::take(&mut self.hadamard_tmp);
1786+ if let Some(l) = self.lowband_mut(lowband) {
1787+ deinterleave_hadamard(
1788+ &mut l[..n],
1789+ tmp.as_mut_slice(),
1790+ n_b >> recombine,
1791+ b0 << recombine,
1792+ long_blocks,
1793+ );
1794+ }
1795+ self.hadamard_tmp = tmp;
17251796 }
17261797 }
17271798 }
@@ -2026,6 +2097,7 @@ impl CeltDecoder {
20262097 if b0 > 1 {
20272098 interleave_hadamard(
20282099 &mut self.x[x..x + n0],
2100+ &mut self.hadamard_tmp,
20292101 n_b >> recombine,
20302102 b0 << recombine,
20312103 long_blocks,
@@ -2403,9 +2475,9 @@ fn haar1(x: &mut [f32], n0: usize, stride: usize) {
24032475 }
24042476 }
24052477
2406-fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) {
2478+fn deinterleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) {
24072479 let n = n0 * stride;
2408- let mut tmp = vec![0.0f32; n];
2480+ let tmp = &mut tmp[..n];
24092481 if hadamard {
24102482 let order = &ORDERY[stride - 2..];
24112483 for i in 0..stride {
@@ -2420,12 +2492,12 @@ fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool
24202492 }
24212493 }
24222494 }
2423- x[..n].copy_from_slice(&tmp);
2495+ x[..n].copy_from_slice(tmp);
24242496 }
24252497
2426-fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) {
2498+fn interleave_hadamard(x: &mut [f32], tmp: &mut [f32], n0: usize, stride: usize, hadamard: bool) {
24272499 let n = n0 * stride;
2428- let mut tmp = vec![0.0f32; n];
2500+ let tmp = &mut tmp[..n];
24292501 if hadamard {
24302502 let order = &ORDERY[stride - 2..];
24312503 for i in 0..stride {
@@ -2440,7 +2512,7 @@ fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool)
24402512 }
24412513 }
24422514 }
2443- x[..n].copy_from_slice(&tmp);
2515+ x[..n].copy_from_slice(tmp);
24442516 }
24452517
24462518 /// Scales a vector to `gain` in the L2 sense.
crates/ec-opus/src/lib.rsmodified+16 -2
@@ -27,11 +27,13 @@
2727 #![warn(missing_docs)]
2828
2929 pub mod celt;
30+pub mod multistream;
3031 pub mod packet;
3132 pub mod range;
3233 pub mod silk;
3334
3435 pub use celt::CeltDecoder;
36+pub use multistream::MultistreamDecoder;
3537 pub use packet::{Bandwidth, Mode, Packet, Toc};
3638 pub use range::RangeDecoder;
3739 pub use silk::SilkDecoder;
@@ -53,6 +55,10 @@ pub struct Decoder {
5355 silk: SilkDecoder,
5456 /// The CELT overlap window, reused for redundancy cross-fades.
5557 celt_window: Vec<f32>,
58+ /// Per-frame scratch, allocated once: the SILK layer's output and the
59+ /// redundancy frame.
60+ silk_pcm: Vec<i16>,
61+ redundant: Vec<f32>,
5662 prev_mode: Option<Mode>,
5763 prev_redundancy: bool,
5864 range_final: u32,
@@ -88,6 +94,8 @@ impl Decoder {
8894 celt: CeltDecoder::new(channels, downsample),
8995 silk: SilkDecoder::new(sample_rate, channels),
9096 celt_window: celt::overlap_window(),
97+ silk_pcm: vec![0; 5760 * channels],
98+ redundant: vec![0.0; 240 * channels],
9199 prev_mode: None,
92100 prev_redundancy: false,
93101 range_final: 0,
@@ -197,7 +205,9 @@ impl Decoder {
197205 let f2_5 = 120 / self.downsample;
198206
199207 // --- SILK layer -----------------------------------------------------
200- let mut silk_pcm = vec![0i16; frame_out * self.channels];
208+ let mut silk_pcm = core::mem::take(&mut self.silk_pcm);
209+ silk_pcm.clear();
210+ silk_pcm.resize(frame_out * self.channels, 0);
201211 if mode != Mode::Celt {
202212 if self.prev_mode == Some(Mode::Celt) {
203213 self.silk.reset();
@@ -267,7 +277,9 @@ impl Decoder {
267277
268278 let end_band = toc.bandwidth().celt_end_band();
269279 let start_band = if mode == Mode::Celt { 0 } else { 17 };
270- let mut redundant = vec![0.0f32; f5 * self.channels];
280+ let mut redundant = core::mem::take(&mut self.redundant);
281+ redundant.clear();
282+ redundant.resize(f5 * self.channels, 0.0);
271283
272284 // A redundancy frame that precedes the main one is decoded first.
273285 let mut redundant_rng = 0u32;
@@ -355,6 +367,8 @@ impl Decoder {
355367
356368 self.prev_mode = Some(mode);
357369 self.prev_redundancy = redundancy && !celt_to_silk;
370+ self.silk_pcm = silk_pcm;
371+ self.redundant = redundant;
358372 Ok(dec.range() ^ redundant_rng)
359373 }
360374 }
crates/ec-opus/src/multistream.rsadded+245 -0
@@ -0,0 +1,245 @@
1+//! Multichannel Opus: several elementary streams in one packet.
2+//!
3+//! A multistream packet is just the ordinary packets of each stream laid end to
4+//! end. All but the last use the self-delimiting framing of RFC 6716
5+//! Appendix B, which carries one extra length so the boundary can be found
6+//! without a container; the last uses the ordinary framing, so it takes
7+//! whatever is left. That is the whole of the format — everything else is the
8+//! channel mapping table, which says where each stream's channels land.
9+//!
10+//! Streams come in two kinds: the first `coupled` streams are stereo, the rest
11+//! mono. `mapping[c]` names the coded channel that output channel `c` reads
12+//! from: values below `2*coupled` are a coupled stream's left (even) or right
13+//! (odd) channel, values above index the mono streams, and 255 means the
14+//! channel is silent.
15+//!
16+//! Channel *order* is the mapping's, not this decoder's: for RFC 7845 mapping
17+//! family 1 — what a 5.1 or 7.1 film track uses — that is Vorbis order
18+//! (left, centre, right, back left, back right, LFE for 5.1), and a caller that
19+//! wants the product's FL/FR/FC/LFE/BL/BR order permutes it.
20+
21+use ec_core::{Error, Result};
22+
23+use crate::Decoder;
24+
25+/// A decoder for a multichannel Opus stream, mono through 255 channels.
26+#[derive(Debug)]
27+pub struct MultistreamDecoder {
28+ streams: Vec<Decoder>,
29+ coupled: usize,
30+ mapping: Vec<u8>,
31+ channels: usize,
32+ sample_rate: u32,
33+ /// Scratch for one stream's output.
34+ buf: Vec<f32>,
35+}
36+
37+impl MultistreamDecoder {
38+ /// A decoder for `streams` elementary streams of which the first `coupled`
39+ /// are stereo, with `mapping` naming the coded channel each output channel
40+ /// comes from.
41+ ///
42+ /// # Panics
43+ /// On a layout that breaks the RFC's limits — more coupled streams than
44+ /// streams, a mapping entry naming a channel no stream codes, an
45+ /// unsupported rate. The layout comes from a container header, so callers
46+ /// that read one from a file should check it (or use
47+ /// [`MultistreamDecoder::try_with_rate`]) rather than pass it straight in.
48+ pub fn with_rate(
49+ sample_rate: u32,
50+ streams: usize,
51+ coupled: usize,
52+ mapping: &[u8],
53+ ) -> MultistreamDecoder {
54+ match Self::try_with_rate(sample_rate, streams, coupled, mapping) {
55+ Ok(d) => d,
56+ Err(e) => panic!("invalid Opus multistream layout: {e}"),
57+ }
58+ }
59+
60+ /// [`MultistreamDecoder::with_rate`] with the layout checked instead of
61+ /// asserted.
62+ pub fn try_with_rate(
63+ sample_rate: u32,
64+ streams: usize,
65+ coupled: usize,
66+ mapping: &[u8],
67+ ) -> Result<MultistreamDecoder> {
68+ if streams == 0 || streams > 255 || coupled > streams {
69+ return Err(Error::corrupt(format!(
70+ "opus multistream: {streams} streams of which {coupled} coupled"
71+ )));
72+ }
73+ let coded = coupled + streams;
74+ if mapping.is_empty() || mapping.len() > 255 {
75+ return Err(Error::corrupt(format!(
76+ "opus multistream: {} output channels",
77+ mapping.len()
78+ )));
79+ }
80+ if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
81+ return Err(Error::corrupt(format!(
82+ "opus multistream: mapping entry {bad} names a channel of {coded}"
83+ )));
84+ }
85+ let mut decoders = Vec::with_capacity(streams);
86+ for s in 0..streams {
87+ let ch = if s < coupled { 2 } else { 1 };
88+ decoders.push(Decoder::new(sample_rate, ch)?);
89+ }
90+ Ok(MultistreamDecoder {
91+ streams: decoders,
92+ coupled,
93+ mapping: mapping.to_vec(),
94+ channels: mapping.len(),
95+ sample_rate,
96+ buf: vec![0.0; 2 * 5760],
97+ })
98+ }
99+
100+ /// Output channels.
101+ pub fn channels(&self) -> usize {
102+ self.channels
103+ }
104+
105+ /// Output sample rate.
106+ pub fn sample_rate(&self) -> u32 {
107+ self.sample_rate
108+ }
109+
110+ /// Drops all inter-packet state in every stream; call after a seek.
111+ pub fn reset(&mut self) {
112+ for s in self.streams.iter_mut() {
113+ s.reset();
114+ }
115+ }
116+
117+ /// The range coder states of all streams, combined the way RFC 6716
118+ /// Section 6 combines them for conformance checking.
119+ pub fn final_range(&self) -> u32 {
120+ self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
121+ }
122+
123+ /// Decodes one multistream packet into a fresh interleaved buffer.
124+ ///
125+ /// This is the shape the product's decoder loop uses; [`decode_float`] is
126+ /// the same work without the allocation.
127+ ///
128+ /// [`decode_float`]: MultistreamDecoder::decode_float
129+ pub fn decode_packet(&mut self, data: &[u8]) -> Result<Vec<f32>> {
130+ // A packet is at most 120 ms, and the sample rate at most 48 kHz.
131+ let mut out = vec![0.0; 5760 * self.channels * self.sample_rate as usize / 48000];
132+ let n = self.decode_float(data, &mut out)?;
133+ out.truncate(n * self.channels);
134+ Ok(out)
135+ }
136+
137+ /// Decodes one multistream packet into `out`, returning samples per
138+ /// channel.
139+ pub fn decode_float(&mut self, data: &[u8], out: &mut [f32]) -> Result<usize> {
140+ // Every stream but the last needs at least a TOC and a length byte.
141+ if data.len() < 2 * self.streams.len() - 1 {
142+ return Err(Error::corrupt(format!(
143+ "opus multistream: {} bytes for {} streams",
144+ data.len(),
145+ self.streams.len()
146+ )));
147+ }
148+ let mut rest = data;
149+ let mut frame_size = 0usize;
150+ let nb_streams = self.streams.len();
151+ for s in 0..nb_streams {
152+ let last = s == nb_streams - 1;
153+ let stream_channels = if s < self.coupled { 2 } else { 1 };
154+ let need = 5760 * stream_channels;
155+ if self.buf.len() < need {
156+ self.buf.resize(need, 0.0);
157+ }
158+ let (n, consumed) = if last {
159+ (
160+ self.streams[s].decode_float(rest, &mut self.buf)?,
161+ rest.len(),
162+ )
163+ } else {
164+ self.streams[s].decode_self_delimited(rest, &mut self.buf)?
165+ };
166+ rest = &rest[consumed.min(rest.len())..];
167+ if s == 0 {
168+ frame_size = n;
169+ if out.len() < n * self.channels {
170+ return Err(Error::corrupt(format!(
171+ "opus multistream: output buffer holds {} samples, packet needs {}",
172+ out.len(),
173+ n * self.channels
174+ )));
175+ }
176+ } else if n != frame_size {
177+ return Err(Error::corrupt(format!(
178+ "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"
179+ )));
180+ }
181+ // Route this stream's channels to the outputs that name them.
182+ for (c, &m) in self.mapping.iter().enumerate() {
183+ if m == 255 {
184+ continue;
185+ }
186+ let m = m as usize;
187+ let src = if s < self.coupled {
188+ if m == 2 * s {
189+ Some(0)
190+ } else if m == 2 * s + 1 {
191+ Some(1)
192+ } else {
193+ None
194+ }
195+ } else if m == s + self.coupled {
196+ Some(0)
197+ } else {
198+ None
199+ };
200+ if let Some(off) = src {
201+ for i in 0..frame_size {
202+ out[self.channels * i + c] = self.buf[stream_channels * i + off];
203+ }
204+ }
205+ }
206+ }
207+ // Channels the mapping leaves unassigned are silent.
208+ for (c, &m) in self.mapping.iter().enumerate() {
209+ if m == 255 {
210+ for i in 0..frame_size {
211+ out[self.channels * i + c] = 0.0;
212+ }
213+ }
214+ }
215+ Ok(frame_size)
216+ }
217+}
218+
219+#[cfg(test)]
220+mod tests {
221+ use super::*;
222+
223+ #[test]
224+ fn layouts_are_checked() {
225+ // RFC 7845 mapping family 1, 5.1: four streams, two of them coupled.
226+ assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]).is_ok());
227+ // More coupled streams than streams.
228+ assert!(MultistreamDecoder::try_with_rate(48000, 2, 3, &[0, 1]).is_err());
229+ // A mapping entry naming a channel no stream codes: 4 streams with 2
230+ // coupled code 6 channels, so 6 is out of range.
231+ assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 6]).is_err());
232+ // 255 is the silent channel and is always allowed.
233+ assert!(MultistreamDecoder::try_with_rate(48000, 1, 0, &[0, 255]).is_ok());
234+ assert!(MultistreamDecoder::try_with_rate(44100, 1, 0, &[0]).is_err());
235+ }
236+
237+ #[test]
238+ fn truncated_packets_are_errors_not_panics() {
239+ let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]);
240+ for n in 0..40usize {
241+ let data: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
242+ let _ = dec.decode_packet(&data);
243+ }
244+ }
245+}
crates/ec-opus/src/silk.rsmodified+18 -11
@@ -159,7 +159,6 @@ fn sqrt_approx(x: i32) -> i32 {
159159 smlawb(y, y, smulbb(213, frac))
160160 }
161161
162-
163162 fn log2lin(log_q7: i32) -> i32 {
164163 if log_q7 < 0 {
165164 return 0;
@@ -393,6 +392,8 @@ pub struct SilkDecoder {
393392 channels_api: usize,
394393 api_rate: u32,
395394 prev_decode_only_middle: bool,
395+ /// Resampler output for one channel, allocated once.
396+ resample_tmp: Vec<i16>,
396397 }
397398
398399 impl SilkDecoder {
@@ -405,6 +406,7 @@ impl SilkDecoder {
405406 channels_api,
406407 api_rate,
407408 prev_decode_only_middle: false,
409+ resample_tmp: vec![0; 5760],
408410 }
409411 }
410412
@@ -582,7 +584,9 @@ impl SilkDecoder {
582584 self.prev_decode_only_middle = decode_only_middle;
583585
584586 let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000);
585- let mut tmp = vec![0i16; out_len];
587+ let mut tmp = core::mem::take(&mut self.resample_tmp);
588+ tmp.clear();
589+ tmp.resize(out_len, 0);
586590 let chans = self.channels_api.min(channels_internal);
587591 for n in 0..chans {
588592 let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] };
@@ -596,6 +600,7 @@ impl SilkDecoder {
596600 out[..out_len].copy_from_slice(&tmp[..out_len]);
597601 }
598602 }
603+ self.resample_tmp = tmp;
599604 // A mono stream fed to a stereo output is duplicated.
600605 if self.channels_api == 2 && channels_internal == 1 {
601606 for i in 0..out_len {
@@ -1476,6 +1481,8 @@ struct Resampler {
14761481 /// FIR history.
14771482 s_fir: [i16; 8],
14781483 delay_buf: DelayBuf,
1484+ /// Upsampler scratch, allocated once.
1485+ fir_buf: Vec<i16>,
14791486 /// Down-sampling coefficients, when the output rate is the lower one.
14801487 down: Option<DownFir>,
14811488 }
@@ -1572,24 +1579,21 @@ impl Resampler {
15721579 let mut head = [0i16; 48];
15731580 head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]);
15741581 head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]);
1575- let head = &head[..self.fs_in_khz];
1582+ let n_head = self.fs_in_khz;
15761583 let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)];
15771584 let split = self.fs_out_khz;
15781585 let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz;
15791586 if self.fs_in_khz == self.fs_out_khz {
1580- out[..self.fs_in_khz].copy_from_slice(head);
1587+ out[..n_head].copy_from_slice(&head[..n_head]);
15811588 out[split..split + rest_out].copy_from_slice(rest);
15821589 } else if self.down.is_some() {
1583- let head = head.to_vec();
1584- self.down_fir(&mut out[..split], &head);
1590+ self.down_fir(&mut out[..split], &head[..n_head]);
15851591 self.down_fir(&mut out[split..split + rest_out], rest);
15861592 } else if self.fs_out_khz == 2 * self.fs_in_khz {
1587- let head = head.to_vec();
1588- self.up2_hq(&mut out[..split], &head);
1593+ self.up2_hq(&mut out[..split], &head[..n_head]);
15891594 self.up2_hq(&mut out[split..split + rest_out], rest);
15901595 } else {
1591- let head = head.to_vec();
1592- self.iir_fir(&mut out[..split], &head);
1596+ self.iir_fir(&mut out[..split], &head[..n_head]);
15931597 self.iir_fir(&mut out[split..split + rest_out], rest);
15941598 }
15951599 self.delay_buf[..self.input_delay]
@@ -1634,7 +1638,9 @@ impl Resampler {
16341638 fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) {
16351639 let mut written = 0usize;
16361640 let mut pos = 0usize;
1637- let mut buf = vec![0i16; 2 * self.batch_size + 8];
1641+ let mut buf = core::mem::take(&mut self.fir_buf);
1642+ buf.clear();
1643+ buf.resize(2 * self.batch_size + 8, 0);
16381644 buf[..8].copy_from_slice(&self.s_fir);
16391645 let mut n_samples_in = 0;
16401646 while pos < input.len() {
@@ -1697,6 +1703,7 @@ impl Resampler {
16971703 }
16981704 self.s_fir
16991705 .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]);
1706+ self.fir_buf = buf;
17001707 }
17011708
17021709 /// `silk_resampler_private_down_FIR`, for output rates below the internal
crates/ec-opus/tests/conformance.rsmodified+348 -0
@@ -375,3 +375,351 @@ fn rfc6716_test_vectors() {
375375 println!("{line}");
376376 }
377377 }
378+
379+// ---------------------------------------------------------------------------
380+// Real files: the Ogg-Opus fixtures, against ffmpeg
381+// ---------------------------------------------------------------------------
382+
383+use ec_opus::MultistreamDecoder;
384+use std::process::Command;
385+
386+/// Splits an Ogg stream into packets (RFC 3533): a page header, a segment
387+/// table, and packets that end on any segment shorter than 255 bytes.
388+fn ogg_packets(data: &[u8]) -> Vec<Vec<u8>> {
389+ let mut packets = Vec::new();
390+ let mut partial: Vec<u8> = Vec::new();
391+ let mut i = 0;
392+ while i + 27 <= data.len() {
393+ assert_eq!(&data[i..i + 4], b"OggS", "not an Ogg page at {i}");
394+ let nsegs = data[i + 26] as usize;
395+ let table = &data[i + 27..i + 27 + nsegs];
396+ let mut body = i + 27 + nsegs;
397+ for &len in table {
398+ let len = len as usize;
399+ partial.extend_from_slice(&data[body..body + len]);
400+ body += len;
401+ if len < 255 {
402+ packets.push(core::mem::take(&mut partial));
403+ }
404+ }
405+ i = body;
406+ }
407+ packets
408+}
409+
410+/// The RFC 7845 identification header: channel count, pre-skip and the
411+/// multistream layout.
412+struct OpusHead {
413+ channels: usize,
414+ pre_skip: usize,
415+ streams: usize,
416+ coupled: usize,
417+ mapping: Vec<u8>,
418+}
419+
420+fn parse_opus_head(p: &[u8]) -> OpusHead {
421+ assert_eq!(&p[..8], b"OpusHead");
422+ let channels = p[9] as usize;
423+ let pre_skip = u16::from_le_bytes([p[10], p[11]]) as usize;
424+ let family = p[18];
425+ if family == 0 {
426+ OpusHead {
427+ channels,
428+ pre_skip,
429+ streams: 1,
430+ coupled: channels - 1,
431+ mapping: (0..channels as u8).collect(),
432+ }
433+ } else {
434+ OpusHead {
435+ channels,
436+ pre_skip,
437+ streams: p[19] as usize,
438+ coupled: p[20] as usize,
439+ mapping: p[21..21 + channels].to_vec(),
440+ }
441+ }
442+}
443+
444+fn fixture(name: &str) -> PathBuf {
445+ Path::new(env!("CARGO_MANIFEST_DIR"))
446+ .join("../../fixtures/audio")
447+ .join(name)
448+}
449+
450+/// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel
451+/// order, with the pre-skip already removed.
452+///
453+/// The decoder is forced to `libopus` — the reference implementation. ffmpeg's
454+/// own native Opus decoder is a third implementation and deviates from libopus
455+/// by as much as 0.97 correlation on this very fixture's coupled surround
456+/// streams, so it makes a poor oracle.
457+fn ffmpeg_decode(path: &Path, channels: usize) -> Option<Vec<f32>> {
458+ let out = Command::new("ffmpeg")
459+ .args(["-v", "error", "-c:a", "libopus", "-i"])
460+ .arg(path)
461+ .args([
462+ "-f",
463+ "f32le",
464+ "-ar",
465+ "48000",
466+ "-ac",
467+ &channels.to_string(),
468+ "-",
469+ ])
470+ .output()
471+ .ok()?;
472+ if !out.status.success() {
473+ return None;
474+ }
475+ Some(
476+ out.stdout
477+ .chunks_exact(4)
478+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
479+ .collect(),
480+ )
481+}
482+
483+/// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed.
484+fn decode_ogg(path: &Path) -> (Vec<f32>, usize) {
485+ let data = fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
486+ let packets = ogg_packets(&data);
487+ let head = parse_opus_head(&packets[0]);
488+ let mut dec = MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
489+ let mut pcm = Vec::new();
490+ for p in packets.iter().skip(2) {
491+ if p.is_empty() {
492+ continue;
493+ }
494+ let frame = dec.decode_packet(p).expect("decode");
495+ pcm.extend_from_slice(&frame);
496+ }
497+ pcm.drain(..head.pre_skip * head.channels);
498+ (pcm, head.channels)
499+}
500+
501+fn correlation(a: &[f32], b: &[f32]) -> f64 {
502+ let n = a.len().min(b.len());
503+ let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
504+ for i in 0..n {
505+ sxy += a[i] as f64 * b[i] as f64;
506+ sxx += (a[i] as f64).powi(2);
507+ syy += (b[i] as f64).powi(2);
508+ }
509+ if sxx == 0.0 || syy == 0.0 {
510+ return if sxx == syy { 1.0 } else { 0.0 };
511+ }
512+ sxy / (sxx * syy).sqrt()
513+}
514+
515+/// Power at `freq` in a channel, by the Goertzel algorithm.
516+fn tone_power(x: &[f32], channels: usize, ch: usize, freq: f64) -> f64 {
517+ let n = x.len() / channels;
518+ let w = 2.0 * std::f64::consts::PI * freq / 48000.0;
519+ let coeff = 2.0 * w.cos();
520+ let (mut s1, mut s2) = (0.0f64, 0.0f64);
521+ for i in 0..n {
522+ let s = x[i * channels + ch] as f64 + coeff * s1 - s2;
523+ s2 = s1;
524+ s1 = s;
525+ }
526+ (s1 * s1 + s2 * s2 - coeff * s1 * s2) / (n * n) as f64
527+}
528+
529+#[test]
530+fn ogg_opus_fixtures_match_ffmpeg() {
531+ // Mapping family 1 puts 5.1 in Vorbis order; ffmpeg hands its own order
532+ // back, so the comparison permutes one into the other.
533+ const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
534+ for (name, channels) in [
535+ ("opus-ogg-mono-48000.opus", 1usize),
536+ ("opus-ogg-stereo-48000.opus", 2),
537+ ("opus-ogg-5.1-48000.opus", 6),
538+ ] {
539+ let path = fixture(name);
540+ if !path.exists() {
541+ eprintln!("{name}: missing, skipped (run scripts/gen-fixtures.sh)");
542+ continue;
543+ }
544+ let Some(reference) = ffmpeg_decode(&path, channels) else {
545+ eprintln!("{name}: ffmpeg unavailable, skipped");
546+ continue;
547+ };
548+ let (mine, ch) = decode_ogg(&path);
549+ assert_eq!(ch, channels, "{name}: channel count");
550+ let mut worst = 1.0f64;
551+ let n = (reference.len() / channels).min(mine.len() / channels);
552+ assert!(n > 48000, "{name}: only {n} samples decoded");
553+ for c in 0..channels {
554+ let their_c = if channels == 6 {
555+ VORBIS_TO_FFMPEG_5_1[c]
556+ } else {
557+ c
558+ };
559+ let a: Vec<f32> = (0..n).map(|i| mine[i * channels + c]).collect();
560+ let b: Vec<f32> = (0..n).map(|i| reference[i * channels + their_c]).collect();
561+ let corr = correlation(&a, &b);
562+ println!("{name}: channel {c} correlation {corr:.5}");
563+ worst = worst.min(corr);
564+ }
565+ assert!(
566+ worst >= 0.99,
567+ "{name}: worst channel correlation {worst:.5}"
568+ );
569+ }
570+}
571+
572+#[test]
573+fn five_one_channels_land_in_the_right_places() {
574+ // The fixture carries one distinct sine per channel, so a channel-order
575+ // bug shows up as a channel playing the wrong tone. The tones themselves
576+ // come from the reference decode rather than from an assumption about how
577+ // ffmpeg laid the fixture out; what is asserted is that this decoder's
578+ // Vorbis-order output is the reference's 5.1-order output permuted.
579+ const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
580+ const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];
581+ let path = fixture("opus-ogg-5.1-48000.opus");
582+ if !path.exists() {
583+ eprintln!("5.1 fixture missing, skipped");
584+ return;
585+ }
586+ let Some(reference) = ffmpeg_decode(&path, 6) else {
587+ eprintln!("ffmpeg unavailable, skipped");
588+ return;
589+ };
590+ let (pcm, channels) = decode_ogg(&path);
591+ assert_eq!(channels, 6);
592+ let dominant = |x: &[f32], ch: usize| -> usize {
593+ let mut best = (0usize, 0.0f64);
594+ for (t, &f) in TONES.iter().enumerate() {
595+ let p = tone_power(x, 6, ch, f);
596+ if p > best.1 {
597+ best = (t, p);
598+ }
599+ }
600+ best.0
601+ };
602+ let mut seen = [false; 6];
603+ for (c, &their) in VORBIS_TO_FFMPEG_5_1.iter().enumerate() {
604+ let want = dominant(&reference, their);
605+ let got = dominant(&pcm, c);
606+ println!(
607+ "channel {c}: {} Hz (reference channel {their} carries {} Hz)",
608+ TONES[got], TONES[want]
609+ );
610+ assert_eq!(got, want, "channel {c} carries the wrong tone");
611+ assert!(!seen[got], "tone {} Hz appears on two channels", TONES[got]);
612+ seen[got] = true;
613+ }
614+}
615+
616+#[test]
617+fn decode_speed() {
618+ if cfg!(debug_assertions) {
619+ eprintln!("decode speed is only meaningful in release; skipped");
620+ return;
621+ }
622+ for (name, channels) in [
623+ ("opus-ogg-stereo-48000.opus", 2usize),
624+ ("opus-ogg-5.1-48000.opus", 6),
625+ ] {
626+ let path = fixture(name);
627+ if !path.exists() {
628+ continue;
629+ }
630+ let data = fs::read(&path).unwrap();
631+ let packets = ogg_packets(&data);
632+ let head = parse_opus_head(&packets[0]);
633+ let audio: Vec<&Vec<u8>> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect();
634+ let mut dec =
635+ MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
636+ let mut out = vec![0.0f32; 5760 * channels];
637+ // Warm up, then measure enough passes to cover several seconds of audio.
638+ let mut samples = 0usize;
639+ for p in &audio {
640+ samples += dec.decode_float(p, &mut out).unwrap();
641+ }
642+ let passes = 20;
643+ let start = std::time::Instant::now();
644+ for _ in 0..passes {
645+ dec.reset();
646+ for p in &audio {
647+ dec.decode_float(p, &mut out).unwrap();
648+ }
649+ }
650+ let elapsed = start.elapsed().as_secs_f64();
651+ let audio_secs = (samples * passes) as f64 / 48000.0;
652+ let realtime = audio_secs / elapsed;
653+ println!(
654+ "{name}: {realtime:.0}x realtime ({channels} channels, {audio_secs:.1} s in {elapsed:.3} s)"
655+ );
656+ let floor = if channels == 6 { 104.0 } else { 135.0 };
657+ assert!(
658+ realtime >= floor,
659+ "{name}: {realtime:.0}x realtime is below the {floor}x floor"
660+ );
661+ }
662+
663+ // The fixtures are sine tones, which are cheap; testvector01 is real music
664+ // at a high rate and is the honest stereo number.
665+ let path = vectors_dir().join("testvector01.bit");
666+ if path.exists() {
667+ let packets = read_vector(&path);
668+ let mut dec = Decoder::new(48000, 2).unwrap();
669+ let mut out = vec![0.0f32; 5760 * 2];
670+ let mut samples = 0usize;
671+ let start = std::time::Instant::now();
672+ for p in &packets {
673+ samples += dec.decode_float(&p.payload, &mut out).unwrap();
674+ }
675+ let elapsed = start.elapsed().as_secs_f64();
676+ let realtime = samples as f64 / 48000.0 / elapsed;
677+ println!("testvector01 (stereo music): {realtime:.0}x realtime");
678+ assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x");
679+ }
680+}
681+
682+#[test]
683+#[ignore]
684+fn real_library_sweep() {
685+ // Files named on the command line (EC_OPUS_FILES=a.opus:b.opus), decoded
686+ // and compared against libopus channel by channel, with the decode speed.
687+ let files = std::env::var("EC_OPUS_FILES").unwrap_or_default();
688+ for f in files.split(':').filter(|s| !s.is_empty()) {
689+ let path = PathBuf::from(f);
690+ let (pcm, channels) = decode_ogg(&path);
691+ let reference = ffmpeg_decode(&path, channels).expect("libopus");
692+ let n = (reference.len() / channels).min(pcm.len() / channels);
693+ let mut worst = 1.0f64;
694+ for c in 0..channels {
695+ let a: Vec<f32> = (0..n).map(|i| pcm[i * channels + c]).collect();
696+ let b: Vec<f32> = (0..n).map(|i| reference[i * channels + c]).collect();
697+ let corr = correlation(&a, &b);
698+ worst = worst.min(corr);
699+ println!("{f}: channel {c} correlation {corr:.5}");
700+ }
701+ // Speed on the same file.
702+ let data = fs::read(&path).unwrap();
703+ let packets = ogg_packets(&data);
704+ let head = parse_opus_head(&packets[0]);
705+ let audio: Vec<&Vec<u8>> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect();
706+ let mut dec =
707+ MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
708+ let mut out = vec![0.0f32; 5760 * channels];
709+ let mut samples = 0usize;
710+ for p in &audio {
711+ samples += dec.decode_float(p, &mut out).unwrap();
712+ }
713+ dec.reset();
714+ let start = std::time::Instant::now();
715+ for p in &audio {
716+ dec.decode_float(p, &mut out).unwrap();
717+ }
718+ let elapsed = start.elapsed().as_secs_f64();
719+ println!(
720+ "{f}: {channels} ch, {:.1} s audio, {:.0}x realtime, worst channel {worst:.5}",
721+ samples as f64 / 48000.0,
722+ samples as f64 / 48000.0 / elapsed
723+ );
724+ }
725+}