diff --git a/.config/nextest.toml b/.config/nextest.toml index 79c775e7..f02205bf 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,10 +1,6 @@ # Keep wall-clock performance assertions from sharing CPUs with other nextest jobs. # These tests are regression tripwires, not throughput benchmarks under load. -[[profile.default.overrides]] -filter = 'package(ec-opus) & (test(decode_speed) | test(encode_speed))' -threads-required = "num-test-threads" - [[profile.default.overrides]] filter = 'package(ec-aac) & test(five_one_decodes_faster_than_realtime)' threads-required = "num-test-threads" @@ -37,7 +33,7 @@ not ((package(ec-av1) & (test(=decode::tests::odd_sizes_round_trip_bit_exact_aga (package(ec-matroska) & (test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) | (package(ec-mp3) & (test(/(^|::)decodes_every_fixture_like_ffmpeg$/) | test(/(^|::)encodes_above_the_incumbent_bar$/) | test(/(^|::)random_frames_match_ffmpeg$/))) | (package(ec-mp4) & (test(/(^|::)every_fixture_demuxes_into_the_streams_ffprobe_reports$/) | test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) | - (package(ec-opus) & (test(/(^|::)oracle_decodes_our_packets_across_the_rate_table$/) | test(/(^|::)rfc6716_test_vectors$/) | test(/(^|::)rfc8251_test_vectors$/))) | + (package(ec-opus) & (test(/(^|::)oracle_decodes_our_packets_across_the_rate_table$/) | test(/(^|::)rfc8251_test_vectors$/))) | (package(ec-pcm-ext) & (test(/(^|::)every_format_is_bit_exact_against_ffmpeg$/))) | (package(ec-vorbis) & (test(/(^|::)xiph_vectors_decode_like_ffmpeg$/) | test(/(^|::)onset_after_silence_has_no_pre_echo$/))) | (package(ec-vp9) & (test(/(^|::)libvpx_vectors_match_per_frame_md5$/)))) diff --git a/Cargo.lock b/Cargo.lock index dafe65a7..c794d0af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,16 +274,6 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" -[[package]] -name = "cpu-time" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e393a7668fe1fad3075085b86c781883000b4ede868f43627b34a87c8b7ded" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "cpufeatures" version = "0.3.1" @@ -699,14 +689,11 @@ dependencies = [ name = "ec-opus" version = "0.1.0" dependencies = [ - "cpu-time", "ec-core", "ec-dsp", "ec-ogg", "ec-testkit", "rustfft", - "tracking-allocator", - "wide", ] [[package]] @@ -1984,28 +1971,6 @@ dependencies = [ "safe_arch", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "winarm-cpufeatures" version = "0.1.2" diff --git a/crates/ec-opus/Cargo.toml b/crates/ec-opus/Cargo.toml index 5c672854..3507b3a0 100644 --- a/crates/ec-opus/Cargo.toml +++ b/crates/ec-opus/Cargo.toml @@ -8,20 +8,9 @@ authors.workspace = true [dependencies] ec-core.workspace = true -ec-dsp.workspace = true -wide.workspace = true -# Optional FFT backend (pure Rust, runtime-detected AVX kernels, no C): the -# family stays dependency-free without it (`--no-default-features`); the -# speed bench pulls it in behind `fft-rustfft`. -rustfft = { version = "6", optional = true, default-features = false } +rustfft = { version = "6", default-features = false } [dev-dependencies] ec-testkit.workspace = true ec-dsp.workspace = true ec-ogg.workspace = true -cpu-time = "1.0.0" -tracking-allocator = "0.4.0" - -[features] -default = ["fft-rustfft"] -fft-rustfft = ["dep:rustfft"] diff --git a/crates/ec-opus/examples/bench.rs b/crates/ec-opus/examples/bench.rs deleted file mode 100644 index 6280fc92..00000000 --- a/crates/ec-opus/examples/bench.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! bench: Opus decode and encode throughput for lanes/bench.md ("lane benchaudio"). -//! -//! usage: -//! bench dec [reps] -//! bench enc [reps] -//! -//! `dec` demuxes an Ogg Opus file with `OggDemuxer` (the OpusHead and OpusTags packets are not -//! audio packets) and decodes every packet with `Decoder` at 48 kHz, `reps` times (default 5), -//! keeping the best wall time. The decoded interleaved f32 PCM of the last run, before the -//! pre-skip trim, is written to `out.f32le`. -//! `enc` encodes raw interleaved 48 kHz f32le PCM with `Encoder` (Application::Audio, CBR at -//! `kbps`, 20 ms frames) and muxes it to Ogg Opus, best of `reps` encode runs. -use std::fs::File; -use std::hint::black_box; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::{CodecId, Demuxer, Packet as CorePacket, StreamInfo, TimeBase, Muxer}; -use ec_ogg::OggDemuxer; -use ec_opus::{Application, Decoder, Encoder, ogg::opus_head, Packet as OpusPacket}; - -const RATE: u32 = 48_000; -/// 20 ms at 48 kHz, per channel. -const FRAME: usize = 960; - -/// The audio packets of the first Opus stream, and its channel count from OpusHead. -fn read_packets(path: &str) -> (usize, Vec>) { - let mut demuxer = OggDemuxer::open(BufReader::new(File::open(path).expect("open"))).expect("ogg"); - let stream = demuxer - .streams() - .iter() - .find(|s| s.params.codec == CodecId::Opus) - .expect("an Opus stream") - .clone(); - let head = stream.params.extradata.clone().expect("OpusHead"); - let channels = usize::from(head[9]); - let mut packets = Vec::new(); - loop { - match demuxer.next_packet() { - Ok(p) if p.stream == stream.index => packets.push(p.data.to_vec()), - Ok(_) => {} - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (channels, packets) -} - -/// Decode every packet once: (interleaved samples, packets that failed). -fn decode_once(packets: &[Vec], channels: usize) -> (Vec, usize) { - let mut decoder = Decoder::new(RATE, channels).expect("decoder"); - let mut out = Vec::new(); - let mut buf = vec![0f32; 5760 * channels]; - let mut failed = 0usize; - for p in packets { - match decoder.decode_float(p, &mut buf) { - Ok(n) => out.extend_from_slice(&buf[..n * channels]), - Err(_) => failed += 1, - } - } - (out, failed) -} - -fn le_f32(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -/// Encode interleaved 48 kHz PCM into (Opus packets, pre-skip) with 20 ms frames. -fn encode_once(pcm: &[f32], channels: usize, kbps: u32) -> (Vec>, usize) { - let mut encoder = Encoder::new(RATE, channels, Application::Audio).expect("encoder"); - encoder.set_bitrate(kbps * 1000); - encoder.set_vbr_constrained(false); - let pre_skip = encoder.look_ahead(FRAME); - let frames = (pcm.len() / channels).div_ceil(FRAME); - let mut packets = Vec::with_capacity(frames); - let mut frame = vec![0f32; FRAME * channels]; - let mut out = vec![0u8; 1500]; - for f in 0..frames { - frame.fill(0.0); - let start = f * FRAME * channels; - let end = (start + FRAME * channels).min(pcm.len()); - frame[..end - start].copy_from_slice(&pcm[start..end]); - let n = encoder.encode_float(&frame, FRAME, &mut out).expect("encode"); - packets.push(out[..n].to_vec()); - } - (packets, pre_skip) -} - -/// Mux the packets into Ogg Opus. The last packet's duration ends at the true input length. -fn write_ogg(path: &str, packets: &[Vec], channels: usize, total: usize, pre_skip: usize) { - let file = std::io::BufWriter::new(File::create(path).expect("create")); - let mut mux = ec_ogg::OggMuxer::new(file); - let tb = TimeBase::from_rate(RATE); - let mut params = ec_core::CodecParameters::new(CodecId::Opus); - params.extradata = Some(opus_head(channels as u8, pre_skip as u16, RATE, 0, None).into()); - if let ec_core::MediaParameters::Audio(a) = &mut params.media { - a.sample_rate = RATE; - a.layout = ec_core::ChannelLayout::from_count(channels); - } - mux.add_stream(StreamInfo::new(0, tb, params)).expect("stream"); - let mut pts = 0i64; - for (idx, p) in packets.iter().enumerate() { - let dur = OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; - let dur = if idx == packets.len() - 1 { - total as i64 + pre_skip as i64 - pts - } else { - dur - }; - let pkt = CorePacket::new(0, tb, p.clone()).with_pts(pts).with_duration(dur); - mux.write_packet(&pkt).expect("write"); - pts += OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; - } - mux.finish().expect("finish"); -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("dec") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - let (channels, packets) = read_packets(&args[2]); - let (pcm, failed) = decode_once(&packets, channels); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(decode_once(black_box(&packets), channels).0.len()); - best = best.min(t.elapsed().as_secs_f64()); - } - let mut bytes = Vec::with_capacity(pcm.len() * 4); - for v in &pcm { - bytes.extend_from_slice(&v.to_le_bytes()); - } - std::fs::write(&args[3], &bytes).expect("write output"); - println!( - "packets={} failed={failed} samples={} best_decode_s={best:.4} reps={reps}", - packets.len(), - pcm.len() / channels - ); - } - Some("enc") if args.len() >= 6 => { - let channels: usize = args[3].parse().expect("channels"); - let kbps: u32 = args[4].parse().expect("kbps"); - let reps: usize = args.get(6).map_or(5, |s| s.parse().expect("reps")); - let pcm = le_f32(&std::fs::read(&args[2]).expect("read input")); - let total = pcm.len() / channels; - let (packets, pre_skip) = encode_once(&pcm, channels, kbps); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(encode_once(black_box(&pcm), channels, kbps).0.len()); - best = best.min(t.elapsed().as_secs_f64()); - } - write_ogg(&args[5], &packets, channels, total, pre_skip); - let bytes: usize = packets.iter().map(Vec::len).sum(); - println!( - "packets={} bytes={bytes} best_encode_s={best:.4} reps={reps} audio_s={:.3}", - packets.len(), - total as f64 / f64::from(RATE) - ); - } - _ => { - eprintln!( - "usage: bench dec [reps]\n bench enc [reps]" - ); - std::process::exit(2); - } - } -} diff --git a/crates/ec-opus/src/analysis.rs b/crates/ec-opus/src/analysis.rs index 3ebe4bf7..fa6bcdc7 100644 --- a/crates/ec-opus/src/analysis.rs +++ b/crates/ec-opus/src/analysis.rs @@ -291,7 +291,7 @@ pub(crate) struct TonalityAnalysis { downmix_state: [f32; 3], info: Vec, /// Per-frame scratch, sized once so the steady-state encode loop stays - /// allocation-free (`steady_state_encode_loop_zero_alloc`). + /// allocation-free. dm_tmp: Vec, dm_tmp3x: Vec, chunk: Vec, diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index b3040593..158c3a72 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -23,6 +23,10 @@ use ec_core::{Error, Result}; +use std::sync::Arc; + +use rustfft::num_complex::Complex; + use crate::range::{RangeDecoder, RangeEncoder}; /// Bands in the 48 kHz mode. @@ -301,236 +305,53 @@ pub(crate) fn overlap_window() -> Vec { // --------------------------------------------------------------------------- // The N/4 FFT and the inverse MDCT // --------------------------------------------------------------------------- - -/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`). -/// -/// Two backends behind one signature, selected at compile time: -/// -/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor -/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole -/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP -/// crate; -/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size -/// directly (pure Rust, runtime-detected AVX butterflies, no C). The -/// family's dependency-free build stays the default; the feature is the -/// measured speed option. -/// -/// Both deliver the same contract: an UNSCALED inverse transform, -/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers. -#[cfg(not(feature = "fft-rustfft"))] -mod fft15 { - use super::dft15; - use ec_dsp::Fft; - - #[derive(Clone, Debug)] - pub(crate) struct Fft15 { - n: usize, - /// Sub-transform of length `n/15`. - sub: Fft, - /// `exp(2 pi i * k1 * n2 / n)` twiddles, split. - tw_re: Vec, - tw_im: Vec, - scratch_re: Vec, - scratch_im: Vec, - } - - impl Fft15 { - pub(crate) fn new(n: usize) -> Fft15 { - assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); - let l = n / 15; - let mut tw_re = vec![0.0; n]; - let mut tw_im = vec![0.0; n]; - for k1 in 0..15 { - for n2 in 0..l { - let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64; - tw_re[k1 * l + n2] = a.cos() as f32; - tw_im[k1 * l + n2] = a.sin() as f32; - } - } - Fft15 { - n, - sub: Fft::new(l), - tw_re, - tw_im, - scratch_re: vec![0.0; n], - scratch_im: vec![0.0; n], - } - } - - /// Unscaled inverse transform. - pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { - let n = self.n; - let l = n / 15; - debug_assert_eq!(re.len(), n); - // 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]; - for n1 in 0..15 { - xr[n1] = re[l * n1 + n2]; - xi[n1] = im[l * n1 + n2]; - } - let (yr, yi) = dft15(&xr, &xi); - for k1 in 0..15 { - let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]); - 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 2: L-point transforms, one per k1, written out at stride - // 15. ec-dsp scales its inverse by 1/L; undo that to keep the - // transform unscaled, which is what the MDCT expects. - 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]; - self.sub.inverse_split(rr, ii); - for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() { - re[k1 + 15 * k2] = r * l as f32; - im[k1 + 15 * k2] = i * l as f32; - } - } - } - } +/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`), planned by +/// rustfft (pure Rust, runtime-detected AVX butterflies). The transform is +/// UNSCALED, `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers. +#[derive(Clone)] +pub(crate) struct Fft15 { + n: usize, + plan: Arc>, + cbuf: Vec>, + /// Preallocated once: `process` would allocate this per call, and the + /// encoder's steady-state loop is a zero-allocation contract. + scratch: Vec>, } -#[cfg(feature = "fft-rustfft")] -mod fft15 { - use rustfft::num_complex::Complex; - use std::sync::Arc; - - #[derive(Clone)] - pub(crate) struct Fft15 { - n: usize, - plan: Arc>, - cbuf: Vec>, - /// Preallocated once: `process` would allocate this per call, and the - /// encoder's steady-state loop is a zero-allocation contract. - scratch: Vec>, +impl core::fmt::Debug for Fft15 { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Fft15").field("n", &self.n).finish() } +} - impl core::fmt::Debug for Fft15 { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("Fft15").field("n", &self.n).finish() +impl Fft15 { + pub(crate) fn new(n: usize) -> Fft15 { + assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); + let mut planner = rustfft::FftPlanner::::new(); + let plan = planner.plan_fft_inverse(n); + let cbuf = vec![Complex::ZERO; n]; + let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()]; + Fft15 { + n, + plan, + cbuf, + scratch, } } - impl Fft15 { - pub(crate) fn new(n: usize) -> Fft15 { - assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); - let mut planner = rustfft::FftPlanner::::new(); - let plan = planner.plan_fft_inverse(n); - let cbuf = vec![Complex::ZERO; n]; - let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()]; - Fft15 { - n, - plan, - cbuf, - scratch, - } + pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { + for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) { + *c = Complex::new(*r, *i); } - - /// Unscaled inverse transform. rustfft does not scale, which is - /// exactly the contract here. - pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { - for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) { - *c = Complex::new(*r, *i); - } - self.plan - .process_with_scratch(&mut self.cbuf, &mut self.scratch); - for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) { - *r = c.re; - *i = c.im; - } + self.plan + .process_with_scratch(&mut self.cbuf, &mut self.scratch); + for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) { + *r = c.re; + *i = c.im; } } } -pub(crate) use fft15::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. -#[cfg(not(feature = "fft-rustfft"))] -#[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 { @@ -1257,52 +1078,11 @@ fn compute_allocation_shared( } } -/// Facts about the last decoded frame, for diagnostics. -#[derive(Clone, Debug)] -pub struct CeltDecDiag { - /// The frame was coded as CELT digital silence. - pub silence: bool, - /// Coarse energies used the intra-frame reset. - pub intra: bool, - /// Short-block (transient) frame as coded. - pub transient: bool, - /// Packet bits the range decoder saw for this frame. - pub total_bits: i32, - /// Decoded log2 band energies after fine bits, per channel (`2*NB_BANDS`). - pub old_band_e: Vec, - /// Time-frequency resolution change per band after `tf_select`. - pub tf_res: Vec, - /// Spreading decision as coded (0..3). - pub spread: usize, - /// Anti-collapse flag as coded. - pub anti_collapse: bool, - /// Allocation trim index as coded (0..10). - pub alloc_trim: i32, - /// Per-band allocated pulses after `compute_allocation`. - pub pulses: Vec, - /// Per-band fine-energy precision bits. - pub fine_quant: Vec, - /// Stereo intensity band (bands >= this collapse to mono). - pub intensity: usize, - /// Dual-stereo flag as coded. - pub dual_stereo: bool, - /// Highest band actually allocated pulses (`codedBands`). - pub coded_bands: usize, - /// Bit balance left after allocation, in 1/8-bit units. - pub balance: i32, - /// Decoded dynalloc band boosts (1/8-bit units). - pub offsets: Vec, -} - /// A CELT layer decoder, one per Opus stream. #[derive(Clone, Debug)] pub struct CeltDecoder { /// Channels this decoder outputs. channels: usize, - /// Decode with the RFC 6716 reconstruction (no RFC 8251 Section 8 energy cap - /// and no Section 9 hybrid folding). Off by default: RFC 8251 Section 11 - /// makes the new behaviour the reference. - legacy_rfc6716: bool, /// Output decimation: 1 at 48 kHz, 2 at 24 kHz, and so on. downsample: usize, window: Vec, @@ -1340,7 +1120,6 @@ pub struct CeltDecoder { collapse_masks: [u8; 2 * NB_BANDS], iy: Vec, mdct_buf: Vec, - diag: CeltDecDiag, plc: Plc, } @@ -1362,7 +1141,6 @@ impl CeltDecoder { let max_n = SHORT_MDCT * 8; CeltDecoder { channels, - legacy_rfc6716: false, downsample, window: overlap_window(), plans: (0..4).map(|lm| ImdctPlan::new(SHORT_MDCT << lm)).collect(), @@ -1404,34 +1182,9 @@ impl CeltDecoder { start: 0, end: NB_BANDS, }, - diag: CeltDecDiag { - silence: false, - intra: false, - transient: false, - total_bits: 0, - old_band_e: vec![0.0; 2 * NB_BANDS], - tf_res: Vec::new(), - spread: 0, - anti_collapse: false, - alloc_trim: 0, - pulses: vec![0; NB_BANDS], - fine_quant: vec![0; NB_BANDS], - intensity: 0, - dual_stereo: false, - coded_bands: 0, - balance: 0, - offsets: vec![0; NB_BANDS], - }, } } - /// Selects the RFC 6716 reconstruction (`true`) or the RFC 8251 one (`false`, - /// the default). The two differ on some hybrid and high-energy frames, so each - /// vector set is decoded with the behaviour its reference was made with. - pub fn set_legacy_rfc6716(&mut self, on: bool) { - self.legacy_rfc6716 = on; - } - /// Drops all inter-frame state (after a seek, or on a mode switch). pub fn reset(&mut self) { self.decode_mem.fill(0.0); @@ -1456,11 +1209,6 @@ impl CeltDecoder { self.rng } - /// Facts from the last decoded frame (diagnostic). - pub fn last_diag(&self) -> &CeltDecDiag { - &self.diag - } - /// Decodes one CELT frame. /// /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands @@ -1664,11 +1412,7 @@ impl CeltDecoder { // RFC 8251 Section 8: cap the log2 energy at 32 so the amplitude // stays finite (libopus `log2Amp`, `MIN32(QCONST32(32.f, 16), lg)`). let lg = (self.old_band_e[ch * NB_BANDS + i] + mean) as f64; - let lg = if self.legacy_rfc6716 { - lg - } else { - lg.min(32.0) - }; + let lg = lg.min(32.0); lg.exp2() as f32 }; } @@ -1769,24 +1513,6 @@ impl CeltDecoder { self.old_log_e2[ch * NB_BANDS + i] = -28.0; } } - self.diag = CeltDecDiag { - silence, - intra, - transient, - total_bits, - old_band_e: self.old_band_e.clone(), - tf_res: self.tf_res.to_vec(), - spread, - anti_collapse: anti_collapse_on, - alloc_trim, - pulses: self.pulses.to_vec(), - fine_quant: self.fine_quant.to_vec(), - intensity, - dual_stereo, - coded_bands, - balance, - offsets: self.offsets.to_vec(), - }; self.rng = dec.range(); self.deemphasis(out, n, cc); @@ -1951,13 +1677,12 @@ impl CeltDecoder { // RFC 8251 Section 9: the second band may take the first band as its // lowband even when the first band is narrower than it. - let rfc8251 = !self.legacy_rfc6716; - if (m * E_BANDS[i] >= m * E_BANDS[start] + n_band || (rfc8251 && i == start + 1)) + if (m * E_BANDS[i] >= m * E_BANDS[start] + n_band || i == start + 1) && (update_lowband || lowband_offset == 0) { lowband_offset = i; } - if rfc8251 && i == start + 1 && start + 2 <= NB_BANDS { + if i == start + 1 && start + 2 <= NB_BANDS { // RFC 8251 Section 9: repeat part of band `start` so band `i` can // fold onto it. Copies nothing when band `i` is not wider than it. let n1 = m * (E_BANDS[start + 1] - E_BANDS[start]); @@ -1993,7 +1718,7 @@ impl CeltDecoder { let mut fold_end = lowband_offset - 1; loop { fold_end += 1; - if (rfc8251 && fold_end >= i) || m * E_BANDS[fold_end] >= low + n_band { + if fold_end >= i || m * E_BANDS[fold_end] >= low + n_band { break; } } diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 68712986..496b4751 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -54,8 +54,7 @@ enum Prefill { } /// One MDCT overlap: the CELT layer's delay without libopus's input -/// alignment ([`Encoder::set_libopus_input_alignment`]), which adds -/// `delay_compensation = Fs/250` (192 at 48 kHz) on top. +/// alignment, which adds `delay_compensation = Fs/250` (192 at 48 kHz) on top. const CELT_OVERLAP_48K: usize = 120; /// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`. const CELT_DELAY_COMP_48K: usize = 192; @@ -285,17 +284,15 @@ pub struct Encoder { /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the /// application and bitrate; `Some` forces one. mode: Option, - /// The SILK layer, created on first use (boxed: `crate::stack_budget`). + /// The SILK layer, created on first use. silk: Option>, /// Scratch space for the SILK packet payload, sized once so the steady-state - /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. + /// loop doesn't allocate. /// /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is /// 4088 bytes, and an inline array that size is a third of the whole /// budget on the `Encoder` that a caller holds by value. silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>, - /// [`Encoder::set_libopus_input_alignment`]. - align_input: bool, filter: InputFilter, /// Scratch space for the filter's output, sized once. hp_buf: Vec, @@ -441,7 +438,6 @@ impl Encoder { mode: None, silk: None, silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]), - align_input: application != Application::LowDelay, filter: InputFilter::new(), hp_buf: Vec::new(), delay_buffer: vec![0.0; encoder_buffer(sample_rate) * channels], @@ -516,65 +512,13 @@ impl Encoder { /// libopus's `delay_compensation` when the alignment is on. fn celt_look_ahead_48k(&self) -> usize { CELT_OVERLAP_48K - + if self.align_input { + + if self.application != Application::LowDelay { CELT_DELAY_COMP_48K } else { 0 } } - /// On by default except for [`Application::LowDelay`], as in libopus: the - /// SILK layer's own delay is 312 samples, and only an aligned CELT layer - /// keeps CELT, SILK and hybrid frames of one stream at the same delay. - /// - /// Puts our CELT analysis window exactly where libopus's is: the layer is - /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at - /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through - /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell - /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band - /// log-energies become - /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against - /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight - /// within .0006 (the unaligned encoder is .06-.21 apart). - /// - /// It ships OFF because the 12-row library gate rejects it, and because - /// re-tuning the constants that were fitted on the misaligned spectrum - /// does not rescue it. Against the shipped rows - /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio: - /// - /// | arm | better | worse (blocking) | - /// |---|---|---| - /// | delay only (`opus-opusx-r1`) | 7 | nik@64 .708→.800, nik@96 .985→1.763, her@96 1.051→1.292, hein@64 .853→.980, hein@96 .528→1.602 | - /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 | - /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) | - /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows | - /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 | - /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 | - /// | + two-pass *and* k=1.25, the combined best (`-r7`) | 5 | same 7: nik@64 .773, nik@96 1.801, her@96 1.114, dl8a@64 1.181, dl8a@96 1.014, hein@64 .977, hein@96 1.398 | - /// | + the whole libopus tonality analysis and its `alloc_trim`/`compute_vbr` consumers (`opus-opustonal-r4`) | 5 | same 7: nik@64 1.014, nik@96 1.842, her@96 1.217, dl8a@64 1.162, dl8a@96 .988, hein@64 .971, hein@96 1.514 | - /// - /// The best aligned arm on the KEEP rule is the delay alone without - /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a - /// in the blocking set too. - /// - /// The last row is the one that was expected to rescue this: libopus's - /// actual operating point is the aligned spectrum *with* `analysis->valid` - /// true, and running the real analysis (`crates/ec-opus/src/analysis.rs`, - /// `music_prob` matching a patched-libopus trace to .001) moves reell@64 - /// 2.697→1.865, reell@96 4.499→3.986, reelo@64 1.510→1.123 and her@64 - /// 1.103→.952 — the largest movement any arm has produced on those rows — - /// and still leaves the same seven rows worse. - /// - /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and - /// no arm moves any of those rows back towards its shipped value, so the - /// misfit is not one of the swept constants. Turning this on also costs - /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame - /// becomes 312, not 120, and the Ogg pre-skip must follow it. - pub fn set_libopus_input_alignment(&mut self, on: bool) { - self.align_input = on; - self.filter = InputFilter::new(); - } - /// Forces the coded bandwidth; [`None`] (the default) picks it from the /// bitrate, the application and the input's Nyquist. pub fn set_bandwidth(&mut self, bandwidth: Option) { @@ -1929,7 +1873,7 @@ impl Encoder { } fn total_buffer(&self) -> usize { - if self.align_input { + if self.application != Application::LowDelay { self.sample_rate as usize / 250 } else { 0 diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 2289aaf4..3fa9a982 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -76,7 +76,7 @@ pub mod range; pub mod silk; pub(crate) mod silk_fix; pub(crate) mod silk_flp; -mod stack_budget; +pub(crate) mod silk_tables; pub use celt::CeltDecoder; pub use encoder::{Application, Encoder}; @@ -103,7 +103,6 @@ pub struct Decoder { /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder` /// costs a caller taking one BY VALUE from `Decoder::new`. It is the /// decoder's largest field and its only large one; `celt` is 1448. - /// `Stack`: crate::stack_budget. silk: Box, /// The CELT overlap window, reused for redundancy cross-fades. celt_window: Vec, @@ -120,30 +119,9 @@ pub struct Decoder { range_final: u32, /// Samples per channel of the last packet, the default concealment length. last_packet_size: usize, - /// Test hook: drop the (CELT, SILK) layer's output before the sum. - debug_mute: (bool, bool), } impl Decoder { - /// Test hook, not for production use: silences the CELT and/or SILK - /// layer's contribution to the output (the decoder state still advances) - /// so a hybrid packet's two layers can be measured one at a time. - #[doc(hidden)] - pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) { - self.debug_mute = (celt, silk); - } - - /// Decodes with the RFC 6716 reconstruction instead of the RFC 8251 one - /// (the default). Needed only to reproduce the RFC 6716 reference vectors. - pub fn set_legacy_rfc6716(&mut self, on: bool) { - self.celt.set_legacy_rfc6716(on); - } - - /// Facts from the last decoded frame's CELT layer (diagnostic). - pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag { - self.celt.last_diag() - } - /// A decoder for `channels` channels at `sample_rate`, which must be one of /// 8000, 12000, 16000, 24000 or 48000 Hz. pub fn new(sample_rate: u32, channels: usize) -> Result { @@ -181,7 +159,6 @@ impl Decoder { prev_redundancy: false, range_final: 0, last_packet_size: 960 / downsample, - debug_mute: (false, false), }) } @@ -515,10 +492,7 @@ impl Decoder { } // Sum the two layers. - if self.debug_mute.0 { - out.fill(0.0); - } - if mode != Mode::Celt && !self.debug_mute.1 { + if mode != Mode::Celt { for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { *o += *s as f32 * (1.0 / 32768.0); } diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs index 839fe47c..c07d262c 100644 --- a/crates/ec-opus/src/silk.rs +++ b/crates/ec-opus/src/silk.rs @@ -27,12 +27,7 @@ use ec_core::Result; use crate::range::RangeDecoder; pub(crate) use crate::silk_fix::*; -pub(crate) mod tables { - #![allow(clippy::all)] - include!("silk_tables.rs"); -} - -use tables::*; +use crate::silk_tables::*; pub(crate) const MAX_LPC_ORDER: usize = 16; pub(crate) const LTP_ORDER: usize = 5; diff --git a/crates/ec-opus/src/silk_flp/api.rs b/crates/ec-opus/src/silk_flp/api.rs index 273c4db4..ce45566f 100644 --- a/crates/ec-opus/src/silk_flp/api.rs +++ b/crates/ec-opus/src/silk_flp/api.rs @@ -10,7 +10,7 @@ use super::stereo::{StereoEncState, stereo_encode_mid_only, stereo_encode_pred, use super::vad::vad_init; use super::*; use crate::range::RangeEncoder; -use crate::silk::tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10}; +use crate::silk_tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10}; use crate::silk_fix::{lin2log, rshift_round, sat16, smlawb, smulwb}; macro_rules! fix_const { diff --git a/crates/ec-opus/src/silk_flp/encode.rs b/crates/ec-opus/src/silk_flp/encode.rs index 0b7665da..45416321 100644 --- a/crates/ec-opus/src/silk_flp/encode.rs +++ b/crates/ec-opus/src/silk_flp/encode.rs @@ -8,7 +8,7 @@ use super::shape::noise_shape_analysis; use super::vad::vad_get_sa_q8; use super::*; use crate::range::RangeEncoder; -use crate::silk::tables::*; +use crate::silk_tables::*; use crate::silk::{gains_dequant, nlsf_cb, nlsf_unpack}; use crate::silk_fix::*; diff --git a/crates/ec-opus/src/silk_flp/nlsf.rs b/crates/ec-opus/src/silk_flp/nlsf.rs index de99de8b..ea656a3d 100644 --- a/crates/ec-opus/src/silk_flp/nlsf.rs +++ b/crates/ec-opus/src/silk_flp/nlsf.rs @@ -2,7 +2,7 @@ //! `silk/NLSF_del_dec_quant.c`, `silk/interpolate.c`, NLSF parts of `wrappers_FLP.c`. use super::*; -use crate::silk::tables::LSFCOSTAB_FIX_Q12; +use crate::silk_tables::LSFCOSTAB_FIX_Q12; use crate::silk::{ NlsfCodebook, nlsf_cb, nlsf_decode, nlsf_stabilize, nlsf_unpack, nlsf_vq_weights_laroia, nlsf2a, }; diff --git a/crates/ec-opus/src/silk_flp/nsq.rs b/crates/ec-opus/src/silk_flp/nsq.rs index e39fd855..58080334 100644 --- a/crates/ec-opus/src/silk_flp/nsq.rs +++ b/crates/ec-opus/src/silk_flp/nsq.rs @@ -1,7 +1,7 @@ //! `silk/NSQ.c`, `silk/NSQ_del_dec.c`, `silk_NSQ_wrapper_FLP` from `wrappers_FLP.c`. use super::*; -use crate::silk::tables::{LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10}; +use crate::silk_tables::{LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10}; use crate::silk_fix::*; const QUANT_LEVEL_ADJUST_Q10: i32 = 80; diff --git a/crates/ec-opus/src/silk_flp/pitch.rs b/crates/ec-opus/src/silk_flp/pitch.rs index 516c3686..5cb173bc 100644 --- a/crates/ec-opus/src/silk_flp/pitch.rs +++ b/crates/ec-opus/src/silk_flp/pitch.rs @@ -5,7 +5,7 @@ use super::sigproc::{ lpc_analysis_filter, schur, silk_log2, }; use super::*; -use crate::silk::tables::{ +use crate::silk_tables::{ CB_LAGS_STAGE2, CB_LAGS_STAGE2_10_MS, CB_LAGS_STAGE3, CB_LAGS_STAGE3_10_MS, }; use crate::silk_fix::{rshift_round, sat16, smlawb, smulbb, smulwb}; diff --git a/crates/ec-opus/src/silk_flp/pred.rs b/crates/ec-opus/src/silk_flp/pred.rs index 5e48671c..c6a8663d 100644 --- a/crates/ec-opus/src/silk_flp/pred.rs +++ b/crates/ec-opus/src/silk_flp/pred.rs @@ -3,7 +3,7 @@ use super::nlsf::{a2nlsf_flp, interpolate, nlsf2a_flp, process_nlsfs_flp}; use super::sigproc::{energy, inner_product, lpc_analysis_filter}; use super::*; -use crate::silk::tables::{ +use crate::silk_tables::{ LTP_GAIN_VQ_0, LTP_GAIN_VQ_1, LTP_GAIN_VQ_2, LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10, }; use crate::silk_fix::{add_pos_sat32, lin2log, log2lin, smlawb, smulbb, smulwb}; diff --git a/crates/ec-opus/src/silk_flp/stereo.rs b/crates/ec-opus/src/silk_flp/stereo.rs index b4221e79..115b3ebc 100644 --- a/crates/ec-opus/src/silk_flp/stereo.rs +++ b/crates/ec-opus/src/silk_flp/stereo.rs @@ -3,7 +3,7 @@ use super::*; use crate::range::RangeEncoder; -use crate::silk::tables::{ +use crate::silk_tables::{ STEREO_ONLY_CODE_MID_ICDF, STEREO_PRED_JOINT_ICDF, STEREO_PRED_QUANT_Q13, UNIFORM3_ICDF, UNIFORM5_ICDF, }; diff --git a/crates/ec-opus/src/stack_budget.rs b/crates/ec-opus/src/stack_budget.rs deleted file mode 100755 index a0c275e3..00000000 --- a/crates/ec-opus/src/stack_budget.rs +++ /dev/null @@ -1,864 +0,0 @@ -#![cfg(test)] -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. -//! -//! # The class -//! -//! A large struct returned BY VALUE from a public constructor is a stack cost, -//! not a heap cost, and the cost is paid by the CALLER. `Encoder` is the -//! workspace's largest live instance of this class: it was **87,024 bytes** by -//! value -- ten and a half times the budget below -- because six -//! SILK encoder slots (79,176 bytes together) and a 3,831-byte SILK packet scratch buffer -//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type -//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the -//! budget, with a 6,304-byte `SilkDecoder` inline. -//! -//! Both are boxed now (82,952 bytes moved off the stack onto the heap: the -//! `Box`ed SILK layer, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and -//! `Decoder::silk: Box`), and this module is what stops the -//! numbers from walking back. -//! -//! # Why this module exists -//! -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public -//! `fn` can return or take by value, with a measured `size_of` recorded as -//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size -//! moves, so the table cannot rot into a list of stale small numbers. -//! 2. [`STACK_BUDGET`] is the bound, and -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for -//! every budgeted row, so a regression reds naming the type that caused it. -//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the three -//! `Box` spellings that moved the 87 KB off the stack, with a negative -//! control so the scan cannot be matching a doc comment. -//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the -//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on -//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather -//! than quietly costing margin. Red/green in milliseconds. -//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's -//! teeth against NEW types: a source scan re-derives the set of by-value -//! public returns from the crate source, so a lane that adds a 40 KB struct -//! to a `pub fn` return reds here until it is measured and listed. -//! [`the_inventory_scan_is_not_vacuous`] is its control, and -//! [`every_by_value_module_is_scanned`] keeps the scan's file list from -//! falling behind a new `mod` in `lib.rs`. -//! -//! # The bound, and why this number -//! -//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical -//! sweep uses, and it is bounded from BOTH sides by measurement: -//! -//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's -//! default test thread, and what `std::thread::Builder::new()` gives a -//! caller who does not ask for a size. This workspace's -//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides -//! the problem from its own runs; a library consumer gets no -//! `.cargo/config.toml` and no such cover. -//! * **The deepest PUBLIC by-value chain is 2** -//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` -> -//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both -//! handing back a `MultistreamDecoder` by value, so both frames hold a -//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new` -//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner -//! constructor of its own type, they build the struct literal inline -- so -//! the worst live set of by-value return slots is two frames, and the test -//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`. -//! * **The budget applies to types a public `fn` returns by value.** The -//! `Box`ed payloads are listed with `public: false` and measured, but not -//! budgeted, because the budget's job is to bound what a CALLER can be made -//! to own and none of them is reachable that way any more -- every field -//! that holds one is a `Box`, which -//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. -//! -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 2,936 -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 2936 = 5,872` bytes -- -//! **0.28%** of a 2 MiB thread -- and the budget sits 2.79x above the -//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the -//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect -//! and the near-miss both red by a factor rather than by a hair. -//! -//! **What it does not claim.** `size_of` is layout, not stack depth: the -//! measured stack/size ratio on a by-value constructor here is several times -//! over, because the constructor's own frames add on top of the return slot. -//! That residual is why -//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for -//! real instead of trusting the arithmetic. - -use crate::Decoder; -use crate::encoder::Encoder; - -/// The per-type ceiling for a type a CALLER can be made to hold by value, in -/// bytes. See the module docs for the derivation; it is two-sided, and both -/// sides are measured. -pub(crate) const STACK_BUDGET: usize = 8192; - -/// The deepest PUBLIC by-value constructor chain in this crate, counted from -/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder:: -/// try_with_rate` is two, both returning the same type by value so both frames -/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and -/// `Decoder::new` are one level each -- neither delegates to an inner -/// constructor of its own type. The budget is checked against two, the worse -/// of the chains. -const DEEPEST_PUBLIC_CHAIN: usize = 2; - -/// Every type in this crate a public `fn` can hand back BY VALUE (or take by -/// value in a public signature), with the `size_of` measured at the commit -/// that wrote this table. `None` means "not yet measured", which -/// [`the_measured_inventory_is_accurate`] rejects. -/// -/// The third column names the return path, so a reader can see why a type is -/// here rather than a coincidence of the type system. `false` in that column -/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only -/// through a pointer now, and the pin that keeps it that way is -/// [`the_crate_private_silk_encoders_stay_behind_a_box`]. -pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ - // -- lib.rs ----------------------------------------------------------- - ( - "Decoder", - Some(1568), - true, - "Decoder::new -> Result. Was 7576, 92.5% of the budget, \ - because a 6304-byte SilkDecoder sat inline; that field is now a Box", - ), - // -- encoder.rs ------------------------------------------------------- - ( - "Encoder", - Some(2936), - true, - "Encoder::new -> Result. Was 87024, 10.62x the budget: six \ - inline SILK encoder slots (79176 together) and an inline 3831-byte \ - silk_buf", - ), - ( - "Application", - Some(1), - true, - "Encoder::new(.., application: Application) takes it by value and \ - stores it inline in every Encoder", - ), - // -- celt.rs ---------------------------------------------------------- - ( - "CeltDecoder", - Some(1440), - true, - "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ - value into Decoder::celt", - ), - // -- multistream.rs / multistream_enc.rs ------------------------------ - ( - "MultistreamDecoder", - Some(120), - true, - "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \ - public by-value chain: with_rate -> try_with_rate -> Result<..>", - ), - ( - "MultistreamEncoder", - Some(88), - true, - "MultistreamEncoder::surround_5_1 -> Result", - ), - // -- packet.rs -------------------------------------------------------- - ( - "Packet", - Some(40), - true, - "Packet::parse -> Result>", - ), - ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"), - ( - "Mode", - Some(1), - true, - "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode", - ), - ( - "Bandwidth", - Some(1), - true, - "Toc::bandwidth(self) -> Bandwidth; also stored inline in \ - Encoder::bandwidth", - ), - // -- range.rs --------------------------------------------------------- - ( - "RangeEncoder", - Some(80), - true, - "RangeEncoder::new() -> Self; stored inline in Encoder::range", - ), - ( - "RangeDecoder", - Some(56), - true, - "RangeDecoder::new(buf) -> RangeDecoder<'a>", - ), - ( - "EncSnapshot", - Some(48), - true, - "RangeEncoder::snapshot(&self) -> EncSnapshot", - ), - // -- silk.rs ---------------------------------------------------------- - ( - "SilkDecoder", - Some(6512), - true, - "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \ - root, so 6512 bytes is a caller's by-value cost TODAY even though \ - Decoder::new moves it straight into a Box. At 77% of the budget it \ - is the LARGEST budgeted row in the table, and the one that says how \ - little headroom the budget would have left if it had stayed inline", - ), - ( - "SilkDecIndices", - Some(104), - true, - "SilkDecoder::last_indices(&self) -> SilkDecIndices", - ), - // -- analysis.rs (crate-private) -------------------------------------- - ( - "TonalityAnalysis", - Some(2096), - false, - "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ - INLINE in Encoder::analysis. 2096 is inside the budget and the field \ - is reached only through an Encoder that is itself budgeted, so it is \ - measured here rather than pinned behind a Box", - ), - ( - "AnalysisInfo", - Some(60), - false, - "analysis::AnalysisInfo::default() -> Self, stored inline in \ - Encoder::info", - ), -]; - -/// The live `size_of` for every inventoried type, keyed BY NAME. -/// -/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and -/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`] -/// without a matching insert here would zip cleanly and assert the wrong -/// type's size against the wrong recorded one. A name key makes that mistake -/// loud instead. -fn measured_by_name() -> Vec<(&'static str, usize)> { - vec![ - ("Decoder", std::mem::size_of::()), - ("Encoder", std::mem::size_of::()), - ( - "Application", - std::mem::size_of::(), - ), - ( - "CeltDecoder", - std::mem::size_of::(), - ), - ( - "MultistreamDecoder", - std::mem::size_of::(), - ), - ( - "MultistreamEncoder", - std::mem::size_of::(), - ), - ( - "Packet", - std::mem::size_of::>(), - ), - ("Toc", std::mem::size_of::()), - ("Mode", std::mem::size_of::()), - ("Bandwidth", std::mem::size_of::()), - ( - "RangeEncoder", - std::mem::size_of::(), - ), - ( - "RangeDecoder", - std::mem::size_of::>(), - ), - ( - "EncSnapshot", - std::mem::size_of::(), - ), - ( - "SilkDecoder", - std::mem::size_of::(), - ), - ( - "SilkDecIndices", - std::mem::size_of::(), - ), - ( - "TonalityAnalysis", - std::mem::size_of::(), - ), - ( - "AnalysisInfo", - std::mem::size_of::(), - ), - ] -} - -/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] -/// constructs on. -/// -/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and -/// **5.3x** the deepest need measured in a debug build on the current layout -/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting -/// **2.1x below** the pre-fix layout's own threshold, which completes at -/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability -/// arm rather than a formality: at 256 KiB the layout this crate used to -/// ship ABORTS THE PROCESS. The sweep is reproducible with -/// `EC_OPUS_TIGHT_STACK_BYTES`. -const TIGHT_STACK: usize = 256 * 1024; - -#[cfg(test)] -mod tests { - use super::{ - BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, - }; - use crate::Decoder; - use crate::encoder::Encoder; - - /// Return types that are not a by-value copy of anything the caller has to - /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the - /// stack), or a primitive. `Self` is a by-value copy of the impl's type, - /// which the inventory rows already cover, so it is exempt from the scan - /// and not from the table. - const THIN: &[&str] = &[ - "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", - "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", - "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", - ]; - - /// The type name a `pub fn` line returns BY VALUE, or `None` when the line - /// returns a pointer, a `Vec`, a primitive, or nothing. - /// - /// One function, shared by the sweep and its control, so the control - /// cannot pass while the sweep's copy of the logic rotted. - fn by_value_return_name(line: &str) -> Option { - let trimmed = line.trim_start(); - if !trimmed.starts_with("pub fn ") { - return None; - } - let arrow = line.find("->")?; - let rest = &line[arrow + 2..]; - let end = rest.find('{').unwrap_or(rest.len()); - let ret = rest[..end].trim(); - if ret.is_empty() { - return None; - } - // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is - // not a shape this crate uses, and flagging one as uninventoried is - // the safe direction to be wrong in. - let inner = { - let t = ret - .strip_prefix("Result<") - .or_else(|| ret.strip_prefix("Option<")) - .unwrap_or(ret); - t.split('>').next().unwrap_or(t) - }; - // Drop the error type and any lifetime or generic argument: - // `Result`, `RangeDecoder<'a>` and `Packet<'a>` are - // all the bare name for this purpose. Splitting on the comma is - // load-bearing: a matcher that cut only at `>` would read - // `Result` as the name "Decoder, Error". - // `the_inventory_scan_is_not_vacuous` covers exactly that, which is - // why the control is not optional. - let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); - if name.is_empty() || THIN.contains(&name) { - return None; - } - // A generic parameter, not a concrete type. - if !name.chars().next().is_some_and(char::is_uppercase) { - return None; - } - Some(name.to_string()) - } - - /// The source files the by-value scan reads. Every module `lib.rs` - /// declares, plus `lib.rs` itself (which is where `Decoder` and - /// `Encoder::new`'s crate-root sibling live) and this module. - const FILES: &[(&str, &str)] = &[ - ("analysis.rs", include_str!("analysis.rs")), - ("celt.rs", include_str!("celt.rs")), - ("celt_flp/bands.rs", include_str!("celt_flp/bands.rs")), - ("celt_flp/enc.rs", include_str!("celt_flp/enc.rs")), - ("celt_flp/enc_an.rs", include_str!("celt_flp/enc_an.rs")), - ("celt_flp/fft.rs", include_str!("celt_flp/fft.rs")), - ("celt_flp/mod.rs", include_str!("celt_flp/mod.rs")), - ("celt_flp/pitch.rs", include_str!("celt_flp/pitch.rs")), - ( - "celt_flp/quant_bands.rs", - include_str!("celt_flp/quant_bands.rs"), - ), - ("celt_flp/tables.rs", include_str!("celt_flp/tables.rs")), - ("celt_flp/vq.rs", include_str!("celt_flp/vq.rs")), - ("encoder.rs", include_str!("encoder.rs")), - ("lib.rs", include_str!("lib.rs")), - ("multistream.rs", include_str!("multistream.rs")), - ("multistream_enc.rs", include_str!("multistream_enc.rs")), - ("ogg.rs", include_str!("ogg.rs")), - ("packet.rs", include_str!("packet.rs")), - ("range.rs", include_str!("range.rs")), - ("silk.rs", include_str!("silk.rs")), - ("silk_fix.rs", include_str!("silk_fix.rs")), - ("silk_flp/api.rs", include_str!("silk_flp/api.rs")), - ("silk_flp/encode.rs", include_str!("silk_flp/encode.rs")), - ("silk_flp/mod.rs", include_str!("silk_flp/mod.rs")), - ("silk_flp/nlsf.rs", include_str!("silk_flp/nlsf.rs")), - ("silk_flp/nsq.rs", include_str!("silk_flp/nsq.rs")), - ("silk_flp/opus.rs", include_str!("silk_flp/opus.rs")), - ("silk_flp/pitch.rs", include_str!("silk_flp/pitch.rs")), - ("silk_flp/pred.rs", include_str!("silk_flp/pred.rs")), - ( - "silk_flp/resampler.rs", - include_str!("silk_flp/resampler.rs"), - ), - ("silk_flp/shape.rs", include_str!("silk_flp/shape.rs")), - ("silk_flp/sigproc.rs", include_str!("silk_flp/sigproc.rs")), - ("silk_flp/stereo.rs", include_str!("silk_flp/stereo.rs")), - ("silk_flp/vad.rs", include_str!("silk_flp/vad.rs")), - ("stack_budget.rs", include_str!("stack_budget.rs")), - ]; - - /// Every module `lib.rs` declares, so the scan's file list cannot silently - /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` - /// that the scan never reads is exactly the hole this class would come - /// back through, so the list is derived, not curated. - /// - /// `pub(crate) mod foo;` is a module too, and ec-opus has several of them - /// (`analysis`, `silk_fix`, `silk_flp`), so the derivation strips the - /// visibility parenthesised form as well as the bare `pub`. - #[test] - fn every_by_value_module_is_scanned() { - let lib = include_str!("lib.rs"); - let mut declared: Vec<&str> = Vec::new(); - for line in lib.lines() { - let t = line.trim(); - let after_pub = if let Some(rest) = t.strip_prefix("pub(") { - // `pub(crate) mod foo;` / `pub(super) mod foo;` - rest.split_once(')') - .map(|(_, after)| after.trim_start()) - .unwrap_or("") - } else { - t.strip_prefix("pub ").unwrap_or(t) - }; - let Some(rest) = after_pub.strip_prefix("mod ") else { - continue; - }; - let name = rest.split([';', ' ']).next().unwrap_or(""); - if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - declared.push(name); - } - } - assert!( - declared.len() > 8, - "only {} module declarations parsed out of lib.rs, so the \ - derived file list is broken rather than small", - declared.len() - ); - let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); - let mut missing: Vec = declared - .iter() - .filter(|d| { - !scanned - .iter() - .any(|s| *s == format!("{d}.rs") || s.starts_with(&format!("{d}/"))) - }) - .map(|d| (*d).to_string()) - .collect(); - missing.sort(); - assert!( - missing.is_empty(), - "lib.rs declares modules the by-value scan never reads: {:?}. Add \ - them to FILES, or the sweep cannot see a new by-value return that \ - lands in one of them.", - missing - ); - } - - /// The inventory, printed as a sorted table, and checked against the - /// types' real sizes. - /// - /// The print is the instrument: one command reproduces the whole table, - /// biggest first, so "what is the largest by-value type in this crate" - /// has an answer that is a measurement rather than a grep. - /// - /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the - /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps - /// every test binary in `scripts/memguard-runner.sh`, which buffers a - /// green run's stdout and prints nothing. The table appears on a failing - /// run, or by invoking the built binary directly - /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`). - /// - /// The check reds on ANY change with both numbers. That is deliberate: a - /// by-value type that grew raises the question of whether it should have - /// been boxed instead, and auto-accepting the new number would answer - /// that question by default. - #[test] - fn the_measured_inventory_is_accurate() { - let live = measured_by_name(); - assert_eq!( - BY_VALUE_TYPES.len(), - live.len(), - "the inventory names {} types but {} are measured; every row needs \ - a measured size or the sweep is a list of hopes", - BY_VALUE_TYPES.len(), - live.len() - ); - let mut rows: Vec<(&str, usize)> = live.clone(); - rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); - eprintln!( - "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", - rows.len(), - STACK_BUDGET / 1024 - ); - eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET"); - for (name, size) in &rows { - eprintln!( - "{size:>8} {:>6.1}% {name}", - *size as f64 * 100.0 / STACK_BUDGET as f64 - ); - } - for (name, recorded, _public, _path) in BY_VALUE_TYPES { - let recorded = recorded.expect("every inventory row carries a measured size"); - let actual = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert_eq!( - recorded, actual, - "{name} is {actual} bytes, the inventory records {recorded}; \ - update the table deliberately -- a by-value type that changed \ - is a stack cost every caller of its constructor now pays" - ); - } - } - - /// The bound, asserted BY NAME. A regression in any inventoried type reds - /// here naming the type, not "some type is too big". - #[test] - fn every_by_value_type_fits_the_stack_budget() { - let live = measured_by_name(); - let mut checked = 0usize; - for (name, _, public, path) in BY_VALUE_TYPES { - if !public { - continue; - } - checked += 1; - let size = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert!( - size <= STACK_BUDGET, - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ - stack budget ({:.2}x). It is returned by value from {path}, so \ - every caller pays it on its own stack, and the constructors \ - nest -- one value's size is the multiplier, not the cost. \ - Box the large field: Encoder's six SILK slots and silk_buf, \ - and Decoder::silk, are Boxed for exactly this reason and \ - took Encoder from 87024 bytes to this one.", - size as f64 / STACK_BUDGET as f64 - ); - } - assert!( - checked >= 10, - "only {checked} rows were bound-checked; the budget must apply to \ - every type a caller can be made to hold by value" - ); - // The other half of the derivation, asserted so it cannot rot: the - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. - let worst = live - .iter() - .filter(|(n, _)| { - BY_VALUE_TYPES - .iter() - .any(|(row, _, public, _)| row == n && *public) - }) - .map(|(_, size)| *size) - .max() - .expect("at least one public row"); - assert!( - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ - public by-value return ({worst} B) is {} B, over an eighth of the \ - 2 MiB stack an unconfigured caller hands this crate; re-derive \ - STACK_BUDGET", - DEEPEST_PUBLIC_CHAIN * worst - ); - } - - /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX. - /// - /// The SILK layer, the SILK packet buffer and `Decoder::silk` stay BEHIND - /// A BOX. Every field holding one is a `Box`, so no caller can reach them - /// by value. What keeps them off the stack is those exact `Box` spellings, - /// and THIS is the pin for that -- a source scan over the declarations, - /// with a negative control so it cannot be matching a doc comment. - /// - /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from - /// 4,072 to **7,896** bytes and reds this pin naming - /// `encoder.rs::Encoder::silk_buf` and - /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing the - /// SILK layer is far larger -- `Encoder` was 87,024 bytes before the - /// boxing, 10.62x the budget. - #[test] - fn the_crate_private_silk_encoders_stay_behind_a_box() { - const PINS: &[(&str, &str, &str)] = &[ - ( - "encoder.rs", - "Encoder::silk", - "silk: Option>", - ), - ( - "encoder.rs", - "Encoder::silk_buf", - "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>", - ), - ("lib.rs", "Decoder::silk", "silk: Box"), - ]; - const SCANNED: &[(&str, &str)] = &[ - ("encoder.rs", include_str!("encoder.rs")), - ("lib.rs", include_str!("lib.rs")), - ]; - for (file, field, spelling) in PINS { - let src = SCANNED - .iter() - .find(|(name, _)| name == file) - .map(|(_, src)| *src) - .unwrap_or_else(|| panic!("no source pinned for {file}")); - let where_ = format!("{file}::{field}"); - assert!( - src.contains(spelling), - "{where_} is no longer declared `{spelling}`. An inline SILK \ - encoder or scratch buffer there puts {field}'s bytes back on \ - every caller's stack -- that is how Encoder was 87024 bytes \ - and Decoder 7576 before the boxing, 10.62x the by-value budget \ - on the type Encoder::new hands back by value." - ); - } - // And the negative control: the UNBOXED spellings must be ABSENT, or - // the scan above could be matching a doc comment instead of the live - // declaration. The unboxed forms are what this lane removed, so their - // absence is the proof the pin is reading the code. - const UNBOXED: &[(&str, &str, &str)] = &[ - ("encoder.rs", "Encoder::silk", "silk: Option,"), - ( - "encoder.rs", - "Encoder::silk_buf", - "silk_buf: [u8; MAX_SILK_PACKET_BYTES],", - ), - ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"), - ]; - for (file, field, spelling) in UNBOXED { - let src = SCANNED - .iter() - .find(|(name, _)| name == file) - .map(|(_, src)| *src) - .unwrap_or_else(|| panic!("no source pinned for {file}")); - assert!( - !src.contains(spelling), - "{file}::{field} is declared unboxed as `{spelling}`. The box pin is \ - matching a spelling that is not the live declaration, and \ - {field}'s bytes are back on every caller's stack." - ); - } - } - - /// CAPABILITY: really construct the heavy types on a tight stack, so a - /// regression ABORTS THE PROCESS instead of costing invisible margin. - /// - /// Both arms are the crate's by-value constructors: `Encoder::new`, the - /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real - /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the - /// decoder is proved live on this thread rather than merely constructed. - /// - /// Measured stack need, **debug** build, one process per point so a - /// SIGABRT cannot truncate the sweep: - /// - /// | stack | pre-fix layout (inline SILK slots) | current layout | - /// |---|---|---| - /// | 32768 | overflow | **overflow** | - /// | 49152 | overflow | **ok** | - /// | 131072 | overflow | ok | - /// | 262144 (**the gate**) | **overflow** | **ok** | - /// | 524288 | **overflow** | ok | - /// | 557056 | ok | ok | - /// | 786432 | ok | ok | - /// | 1048576 | ok | ok | - /// - /// The gate sits at 256 KiB, **5.3x** the measured need of the current - /// layout and **2.1x** below the pre-fix layout's own threshold. Note - /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB, - /// so a gate set at 1 MiB would have been a formality -- a test that - /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES` - /// overrides the size, which is how the table is reproduced. - /// - /// The results are checked, not just the absence of a crash: an `Encoder` - /// that constructed but came back with the wrong channel count, or a - /// `Decoder` that decoded a packet to silence, would both pass a - /// "did not overflow" assertion. - #[test] - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { - use crate::encoder::Application; - let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(TIGHT_STACK); - let handle = std::thread::Builder::new() - .stack_size(stack) - .spawn(move || { - // Arm 1: the by-value constructor that was 10.62x the budget. - let encoder = Encoder::new(48000, 1, Application::Audio) - .expect("Encoder::new(48000, 1, Audio)"); - let channels = encoder.channels(); - let rate = encoder.sample_rate(); - drop(encoder); - let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)"); - // A real packet, so the decoder is proved live on this thread - // rather than merely constructed: the SILK-only 20 ms packet - // below decodes through the same by-value Decoder. - let mut out = vec![0.0f32; 5760]; - let written = decoder - .decode_float(SILK_ONLY_PACKET, &mut out) - .expect("decode_float on the tight-stack thread"); - let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs())); - (channels, rate, written, peak) - }) - .expect("spawn tight-stack thread"); - let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| { - panic!( - "a by-value constructor overflowed a {stack}-byte stack; \ - EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep" - ) - }); - assert_eq!(channels, 1, "Encoder::new lost its channel count"); - assert_eq!(rate, 48000, "Encoder::new lost its sample rate"); - assert_eq!( - pcm_len, 960, - "Decoder::decode_float returned {pcm_len} samples, not the 960 one \ - 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \ - Decoder that cannot decode" - ); - assert!( - peak > 0.0, - "Decoder::decode_float returned silence (peak {peak}) on the \ - tight-stack thread" - ); - eprintln!( - "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \ - bytes, both constructors returned and decoded 960 samples", - std::mem::size_of::(), - std::mem::size_of::(), - std::mem::size_of::(), - ); - } - - /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK - /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame - /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is - /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than - /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz. - const SILK_ONLY_PACKET: &[u8] = &[ - 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - ]; - - /// The sweep's teeth against a NEW by-value return: re-derive the set from - /// the crate source and require every name to be inventoried. - /// - /// Without this the inventory is a list of what someone remembered to - /// measure, and a lane that adds `pub fn make() -> HugeThing` where - /// `HugeThing` is 200 KB of inline tables passes every other test here. - #[test] - fn every_by_value_public_return_is_in_the_inventory() { - let mut found: Vec<(String, String)> = Vec::new(); - for (file, src) in FILES { - for (n, line) in src.lines().enumerate() { - if let Some(name) = by_value_return_name(line) { - found.push((name, format!("{file}:{}", n + 1))); - } - } - } - found.sort(); - found.dedup(); - assert!( - found.len() > 5, - "the by-value return scan found {} names across {} files, which is \ - too few to be a real sweep -- the matcher, not the crate, is broken", - found.len(), - FILES.len() - ); - - let mut missing = Vec::new(); - for (name, site) in &found { - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { - missing.push(format!("{name} ({site})")); - } - } - assert!( - missing.is_empty(), - "these types are returned BY VALUE from a public fn and are not in \ - the inventory: {}. Either they are thin enough not to be a stack \ - cost -- say so by adding a row with its measured size -- or they \ - are the next instance of the class this module exists for.", - missing.join(", ") - ); - } - - /// The control for the scan above, on synthetic text rather than by - /// trusting the live tree to happen to contain a case. - /// - /// If the matcher silently stopped recognising a shape, the sweep would - /// pass everything and this would still be asserting nothing. So: every - /// by-value spelling the crate uses must yield its type name, and every - /// pointer/Vec/primitive/`Self` spelling must yield nothing. - #[test] - fn the_inventory_scan_is_not_vacuous() { - for synthetic in [ - "pub fn zz_a() -> ZzNotInventoried { todo!() }", - "pub fn zz_b() -> Result { todo!() }", - "pub fn zz_c() -> Result { todo!() }", - "pub fn zz_d() -> Option { todo!() }", - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", - ] { - let name = by_value_return_name(synthetic) - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); - assert_eq!( - name, "ZzNotInventoried", - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ - cannot see a new by-value return and its green is vacuous" - ); - assert!( - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), - "the synthetic control name is in the inventory, so the control \ - proves nothing" - ); - } - for thin in [ - "pub fn zz_t() -> Box { todo!() }", - "pub fn zz_u() -> Result, Error> { todo!() }", - "pub fn zz_v() -> Option<&Path> { todo!() }", - "pub fn zz_w() -> usize { todo!() }", - "pub fn zz_x() -> Self { todo!() }", - "pub fn zz_y() -> Result, Error> { todo!() }", - "pub fn zz_z() { todo!() }", - "fn zz_private() -> ZzNotInventoried { todo!() }", - ] { - assert_eq!( - by_value_return_name(thin), - None, - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ - above already cover, or not a `pub fn` -- the matcher must not \ - read it as an uninventoried by-value return" - ); - } - } -} diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 5765c1cb..9468d83c 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -9,61 +9,6 @@ use std::path::{Path, PathBuf}; use ec_opus::Decoder; -// --------------------------------------------------------------------------- -// Counting allocator: proves the steady-state encode loop allocates nothing. -// Lives in the test binary only — the shipped crate has no allocator games. -// Same pattern as ec-h264's proof: only the thread that armed the counter is -// counted, so parallel tests (and ffmpeg child plumbing) allocate freely. -// --------------------------------------------------------------------------- - -use std::alloc::System; -use std::sync::Once; - -use std::cell::Cell; -use std::sync::atomic::{AtomicU64, Ordering}; -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; - -struct CountingAlloc; - -static ALLOCS: AtomicU64 = AtomicU64::new(0); - -std::thread_local! { - static COUNTING_HERE: Cell = const { Cell::new(false) }; -} - -fn counting_here() -> bool { - COUNTING_HERE.try_with(Cell::get).unwrap_or(false) -} - -impl AllocationTracker for CountingAlloc { - fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { - if counting_here() { - ALLOCS.fetch_add(1, Ordering::Relaxed); - } - } - fn deallocated( - &self, - _addr: usize, - _object_size: usize, - _wrapped: usize, - _source: AllocationGroupId, - _current: AllocationGroupId, - ) { - } -} - -#[global_allocator] -static A: Allocator = Allocator::system(); - -/// Installs the tracker once; every test that arms the counter calls this first. -fn install_counter() { - static ONCE: Once = Once::new(); - ONCE.call_once(|| { - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); - AllocationRegistry::enable_tracking(); - }); -} - /// One packet of an `opus_demo` test vector file. struct VectorPacket { payload: Vec, @@ -93,33 +38,18 @@ fn read_vector(path: &Path) -> Vec { out } -fn vectors_dir() -> PathBuf { - ec_testkit::root().join("vectors/opus-rfc6716/opus_testvectors") -} - /// Decodes a vector at 48 kHz stereo, returning the samples and how many /// packets ended with the reference range state. fn decode_vector(packets: &[VectorPacket]) -> (Vec, usize, usize) { - decode_vector_ch(packets, 2, true) -} - -/// Decodes a vector at 48 kHz with `channels` output channels (1 or 2), with the -/// RFC 6716 reconstruction when `legacy` and the RFC 8251 one otherwise. -fn decode_vector_ch( - packets: &[VectorPacket], - channels: usize, - legacy: bool, -) -> (Vec, usize, usize) { - let mut dec = Decoder::new(48000, channels).unwrap(); - dec.set_legacy_rfc6716(legacy); + let mut dec = Decoder::new(48000, 2).unwrap(); let mut pcm = Vec::new(); - let mut buf = vec![0.0f32; 5760 * channels]; + let mut buf = vec![0.0f32; 5760 * 2]; let mut matched = 0; let mut decoded = 0; for p in packets { match dec.decode_float(&p.payload, &mut buf) { Ok(n) => { - pcm.extend_from_slice(&buf[..n * channels]); + pcm.extend_from_slice(&buf[..n * 2]); decoded += 1; if dec.final_range() == p.final_range { matched += 1; @@ -429,7 +359,7 @@ fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) { let dir = vectors_dir_8251(); let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit")); let packets = read_vector(&bit); - let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false); + let (pcm, matched, decoded) = decode_vector(&packets); let refs = read_i16(&dir.join(reference)); let mine = to_i16(&pcm); assert_eq!( @@ -485,47 +415,6 @@ const VECTORS: [&str; 12] = [ "testvector12", ]; -/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's -/// range coder state MUST match the reference on every packet, and the output -/// MUST stay within the `opus_compare` threshold (quality >= 0). -#[test] -fn rfc6716_test_vectors() { - let mut table = Vec::new(); - for name in VECTORS { - let path = - ec_testkit::fixture(&format!("vectors/opus-rfc6716/opus_testvectors/{name}.bit")); - let packets = read_vector(&path); - let (pcm, matched, decoded) = decode_vector(&packets); - let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); - let mine = to_i16(&pcm); - assert_eq!( - reference.len(), - mine.len(), - "{name}: decoded {} samples, reference has {}", - mine.len() / 2, - reference.len() / 2 - ); - let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count(); - let quality = opus_compare(&reference, &mine, 2); - table.push(format!( - "{name}: {matched}/{decoded} packets range-exact, \ - {:.4} % samples identical, quality {quality:.2} %", - 100.0 * identical as f64 / reference.len() as f64 - )); - assert_eq!( - matched, decoded, - "{name}: range coder state diverged from the reference" - ); - assert!( - quality >= 0.0, - "{name}: opus_compare quality {quality:.2} %" - ); - } - for line in table { - println!("{line}"); - } -} - // --------------------------------------------------------------------------- // Real files: the Ogg-Opus fixtures, against ffmpeg // --------------------------------------------------------------------------- @@ -857,35 +746,6 @@ fn encoder_roundtrips_at_every_rate() { } } -/// The libopus input alignment ([`Encoder::set_libopus_input_alignment`]): -/// with it on the CELT layer's advertised delay grows by libopus's -/// `delay_compensation`, and the decoded signal tracks the source at exactly -/// that lag and not at the old one — the knob is usable, not just present. -/// It is on by default except for `Application::LowDelay`, as in libopus. -#[test] -fn libopus_input_alignment_delays_and_still_decodes() { - let pcm = test_signal(2, 1.0); - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(128_000); - assert_eq!( - enc.look_ahead(960), - 312, - "default: overlap + delay_compensation" - ); - enc.set_libopus_input_alignment(false); - assert_eq!(enc.look_ahead(960), 120, "off: one MDCT overlap"); - enc.set_libopus_input_alignment(true); - let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, 960); - let aligned = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); - let old = delayed_corr(&pcm, &decoded, 2, 120); - println!("aligned: corr at 312 {aligned:.4}, at 120 {old:.4}"); - assert!(aligned >= 0.85, "aligned round trip corr {aligned:.4}"); - assert!( - aligned > old, - "advertised delay 312 correlates {aligned:.4}, worse than the old 120 ({old:.4})" - ); -} - #[test] // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the // voice/music bandwidth tables blended by voice_est) since lane opus-mode; @@ -1587,63 +1447,6 @@ fn ogg_opus_round_trip_duration_is_exact() { let _ = fs::remove_file(&path); } -/// The steady-state encode loop allocates nothing: every buffer — MDCT -/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder -/// and sized on the first frame (the decoder discipline, applied to the -/// encoder). -#[test] -fn steady_state_encode_loop_zero_alloc() { - install_counter(); - let pcm = test_signal(2, 0.5); - let pcm6 = { - let mono = test_signal(1, 0.5); - let mut v = Vec::with_capacity(mono.len() * 6); - for &s in &mono { - for c in 0..6 { - v.push(s * (1.0 + c as f32 * 0.01)); - } - } - v - }; - // Stereo elementary encoder. - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(256_000); - let mut out = vec![0u8; 1500]; - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { - enc.encode_float(block, 960, &mut out).unwrap(); - } - ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { - enc.encode_float(block, 960, &mut out).unwrap(); - } - COUNTING_HERE.with(|c| c.set(false)); - let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(n, 0, "stereo encode allocated {n} times in steady state"); - - // 5.1 multistream. - let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap(); - ms.set_bitrate(384_000); - let mut out6 = vec![0u8; 8 * 1500]; - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { - ms.encode_float(block, 960, &mut out6).unwrap(); - } - ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { - ms.encode_float(block, 960, &mut out6).unwrap(); - } - COUNTING_HERE.with(|c| c.set(false)); - let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state"); - - // Mono SILK (Voip, 12 kbps) is NOT asserted zero-alloc here: fixing - // `Encoder::zero_stuff_mono` to reuse a scratch buffer removed its - // per-frame Vec, but the SILK encode path itself (NLSF/LPC - // analysis, pitch search) allocates well beyond that one site — sweeping - // those is a separate, much larger effort than this defect's scope. -} - /// Malformed input must come back as an error, never a panic: the decoders /// index tables with values the bitstream chooses, so this throws well-formed /// TOC bytes at random payloads to make sure every mode is actually entered. @@ -2219,21 +2022,18 @@ fn silk_packets_track_encoder_bitrate() { // Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream). /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our -/// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts -/// range-state parity packet for packet. Returns (decoded, packets). +/// decoder; asserts range-state parity packet for packet. Returns (decoded, packets). fn hybrid_roundtrip( pcm: &[f32], bps: u32, bandwidth: Option, mode: Option, - mute: (bool, bool), ) -> (Vec, Vec>) { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(bps); enc.set_bandwidth(bandwidth); enc.set_mode(mode); let mut dec = Decoder::new(48000, 1).unwrap(); - dec.debug_mute_layers(mute.0, mute.1); let mut out = vec![0u8; 1500]; let mut buf = vec![0f32; 5760]; let (mut decoded, mut packets) = (Vec::new(), Vec::new()); @@ -2254,9 +2054,6 @@ fn hybrid_roundtrip( (decoded, packets) } -/// The two layers of a hybrid packet reach the decoder's output at the same -/// delay: a click's low-band-only and high-band-only peaks coincide at the -/// encoder's documented look-ahead. /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame — /// [`Encoder::look_ahead`] of that same configuration, so the lag assertions /// track the layer's real delay instead of a constant. @@ -2266,71 +2063,22 @@ fn hybrid_delay(bps: u32) -> usize { enc.look_ahead(960) } -#[test] -fn hybrid_layers_align() { - let mut click = vec![0f32; 48000]; - // Well inside the stream so both layers' predictors are running. - let at = 960 * 10 + 300; - click[at] = 0.9; - let peak = |x: &[f32]| { - x.iter() - .enumerate() - .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) - .unwrap() - .0 - }; - let (lb, _) = hybrid_roundtrip(&click, 32_000, None, None, (true, false)); - let (hb, _) = hybrid_roundtrip(&click, 32_000, None, None, (false, true)); - let delay = hybrid_delay(32_000) as i64; - let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); - eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {delay}"); - // A fullband CELT click lands at exactly the encoder's advertised delay - // (`celt_click_peak_offset`); the band-limited HB layer's main lobe sits - // up to 2 samples early once transient frames keep their short blocks, - // and SILK lands one sample late. - assert!( - (plb - phb).abs() <= 3, - "layers misaligned: LB +{plb} vs HB +{phb}" - ); - assert!( - (phb - delay).abs() <= 2, - "HB peak +{phb}, look_ahead {delay}" - ); -} - /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks -/// the input full-band and in the SILK layer's band alone, and the reference -/// oracle decodes the packets to the same signal. +/// the input full-band, and the reference oracle decodes the packets to the +/// same signal. /// /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is /// [`Encoder::look_ahead`] of that same configuration, never a constant. #[test] fn hybrid_fb_roundtrip() { for (name, pcm) in silk_sources() { - let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, None, (false, false)); + let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, None); let toc = ec_opus::Toc::new(packets[0][0]); assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config); let (corr, lag) = aligned_corr(&pcm, &decoded, 400); - let (lb_only, lb_packets) = hybrid_roundtrip( - &pcm, - 32_000, - Some(Bandwidth::Full), - Some(Mode::Hybrid), - (true, false), - ); - assert!( - lb_packets - .iter() - .all(|p| ec_opus::Toc::new(p[0]).config == 15), - "{name}: forced-FB run left hybrid" - ); - let lb_ref = lowpass(&pcm, 7000.0); - let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); - eprintln!( - "hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps" - ); + eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, {kbps:.1} kbps"); assert!(corr >= 0.9, "{name}: full-band corr {corr:.4}"); let delay = hybrid_delay(32_000); let libopus = libopus_untrimmed(&format!("hybrid-lag-{name}"), &pcm); @@ -2339,7 +2087,6 @@ fn hybrid_fb_roundtrip() { lag.abs_diff(libopus_lag) <= 6, "{name}: aligned at lag {lag}, libopus at {libopus_lag}" ); - assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); assert!( (28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target" @@ -2353,16 +2100,10 @@ fn hybrid_fb_roundtrip() { // SWB when asked for it, and the rest of the automatic hybrid range // (SILK's share leaves CELT least at the bottom of it). let speech = speech_like(); - let (_, packets) = hybrid_roundtrip( - &speech, - 24_000, - Some(Bandwidth::SuperWide), - None, - (false, false), - ); + let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), None); assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); for bps in [20_000u32, 24_000, 39_000] { - let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, None, (false, false)); + let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, None); let (corr, _) = aligned_corr(&speech, &decoded, 400); let kbps = packets.iter().map(Vec::len).sum::() as f64 * 8.0 / (packets.len() as f64 * 20.0); diff --git a/crates/ec-opus/tests/plc.rs b/crates/ec-opus/tests/plc.rs deleted file mode 100644 index d8764947..00000000 --- a/crates/ec-opus/tests/plc.rs +++ /dev/null @@ -1,121 +0,0 @@ -use ec_opus::{Application, Decoder, Encoder, Mode}; - -const FRAME: usize = 960; - -fn voice(frames: usize) -> Vec { - (0..frames * FRAME) - .map(|i| { - let t = i as f32 / 48000.0; - let f0 = 140.0 + 10.0 * (2.0 * std::f32::consts::PI * 0.7 * t).sin(); - (1..12) - .map(|h| (2.0 * std::f32::consts::PI * f0 * h as f32 * t).sin() * 0.25 / h as f32) - .sum() - }) - .collect() -} - -fn corr(a: &[f32], b: &[f32]) -> f32 { - let ab: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); - let aa: f32 = a.iter().map(|x| x * x).sum(); - let bb: f32 = b.iter().map(|x| x * x).sum(); - ab / (aa * bb).sqrt().max(1e-9) -} - -fn rms(a: &[f32]) -> f32 { - (a.iter().map(|x| x * x).sum::() / a.len() as f32).sqrt() -} - -#[test] -fn concealment_tracks_and_recovers() { - let pcm = voice(60); - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); - enc.set_bitrate(32000); - enc.set_mode(Some(Mode::Celt)); - let mut pkt = vec![0u8; 1500]; - let packets: Vec> = pcm - .chunks_exact(FRAME) - .map(|f| { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - pkt[..n].to_vec() - }) - .collect(); - let lost = [20usize, 40, 41, 42, 43, 44, 45, 46, 47]; - let mut clean = Decoder::new(48000, 1).unwrap(); - let mut lossy = Decoder::new(48000, 1).unwrap(); - let mut buf = vec![0f32; 5760]; - let (mut a, mut b) = (Vec::new(), Vec::new()); - for (i, p) in packets.iter().enumerate() { - let k = clean.decode_float(p, &mut buf).unwrap(); - a.extend_from_slice(&buf[..k]); - let k = if lost.contains(&i) { - lossy.decode_float(&[], &mut buf).unwrap() - } else { - lossy.decode_float(p, &mut buf).unwrap() - }; - b.extend_from_slice(&buf[..k]); - } - let f = |i: usize| i * FRAME..(i + 1) * FRAME; - let c20 = corr(&a[f(20)], &b[f(20)]); - let r20 = rms(&b[f(20)]) / rms(&a[f(20)]); - let c22 = corr(&a[f(22)], &b[f(22)]); - let r47 = rms(&b[f(47)]) / rms(&a[f(47)]); - let c50 = corr(&a[f(50)], &b[f(50)]); - let jump = b - .windows(2) - .map(|w| (w[1] - w[0]).abs()) - .fold(0.0f32, f32::max); - let jump_ref = a - .windows(2) - .map(|w| (w[1] - w[0]).abs()) - .fold(0.0f32, f32::max); - eprintln!( - "c20 {c20:.3} r20 {r20:.3} c22 {c22:.3} r47 {r47:.3} c50 {c50:.3} jump {jump:.4} ref {jump_ref:.4}" - ); - assert!(c20 > 0.5 && (0.5..1.5).contains(&r20)); - assert!(c22 > 0.9); - assert!(r47 < 0.5); - assert!(c50 > 0.9); - assert!(jump < 2.0 * jump_ref); -} - -#[test] -fn inband_fec_recovers_a_lost_frame() { - let pcm = voice(40); - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); - enc.set_bitrate(48000); - enc.set_bandwidth(Some(ec_opus::Bandwidth::Full)); - enc.set_inband_fec(true); - enc.set_packet_loss_perc(15); - let mut pkt = vec![0u8; 1500]; - let packets: Vec> = pcm - .chunks_exact(FRAME) - .map(|f| { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - pkt[..n].to_vec() - }) - .collect(); - let mut clean = Decoder::new(48000, 1).unwrap(); - let mut lossy = Decoder::new(48000, 1).unwrap(); - let mut buf = vec![0f32; 5760]; - let (mut a, mut b) = (Vec::new(), Vec::new()); - for (i, p) in packets.iter().enumerate() { - let k = clean.decode_float(p, &mut buf).unwrap(); - a.extend_from_slice(&buf[..k]); - let k = if i == 20 { - lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() - } else if i == 30 { - lossy.conceal(FRAME, &mut buf).unwrap() - } else { - lossy.decode_float(p, &mut buf).unwrap() - }; - b.extend_from_slice(&buf[..k]); - } - let f = |i: usize| i * FRAME..(i + 1) * FRAME; - let c20 = corr(&a[f(20)], &b[f(20)]); - let c22 = corr(&a[f(22)], &b[f(22)]); - let c30 = corr(&a[f(30)], &b[f(30)]); - eprintln!("fec c20 {c20:.3} c22 {c22:.3} plc c30 {c30:.3}"); - assert!(c30 > 0.3); - assert!(c20 > 0.7); - assert!(c22 > 0.95); -} diff --git a/crates/ec-opus/tests/snr_floor.rs b/crates/ec-opus/tests/snr_floor.rs deleted file mode 100644 index f3e8977e..00000000 --- a/crates/ec-opus/tests/snr_floor.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Encoder quality floor (lane opusq): a music-like signal (chords, noise, transients) must -//! round-trip through the encoder and the decoder above a per-bitrate SNR floor. The floors sit -//! about 0.1-0.5 dB under what the encoder measures after the continuous allocation trim and the -//! analysis-driven leak boost; libopus (CELT, restricted-lowdelay, CBR) measures within ~1 dB -//! above these on the same signal shape, so a regression of the allocation shows here. -use ec_opus::{Application, Decoder, Encoder, MultistreamDecoder, MultistreamEncoder}; - -const FRAME: usize = 960; - -/// Hides a constant chunk size from clippy's `as_chunks` lint. -fn channels_of(n: usize) -> usize { - std::hint::black_box(n) -} - -struct Lcg(u64); -impl Lcg { - fn next(&mut self) -> f32 { - self.0 = self - .0 - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - ((self.0 >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0 - } -} - -/// `channels` interleaved channels, `secs` seconds at 48 kHz. -fn music(channels: usize, secs: f32, seed: u64) -> Vec { - let n = (48000.0 * secs) as usize; - let mut rng = Lcg(seed); - let notes = [220.0f32, 277.2, 329.6, 440.0, 554.4, 659.3]; - let mut out = vec![0f32; n * channels]; - for c in 0..channels { - let phases: Vec = notes.iter().map(|_| rng.next() * 3.0).collect(); - for t in 0..n { - let tt = t as f32 / 48000.0; - let f0 = [1.0f32, 1.122, 1.26, 1.5][(tt as usize) % 4]; - let mut v = 0.0; - for (k, f) in notes.iter().enumerate() { - for h in 1..=5 { - v += 0.08 / h as f32 - * (2.0 * core::f32::consts::PI * f * f0 * h as f32 * tt + phases[k]).sin(); - } - } - v += 0.004 * rng.next(); - let since = t % 12000; - if since < 3000 { - v += 0.15 * rng.next() * (-(since as f32) / 500.0).exp(); - } - out[t * channels + c] = v * 0.6; - } - } - out -} - -fn snr_db(reference: &[f32], decoded: &[f32], channels: usize) -> f32 { - let n = reference.len().min(decoded.len()) / channels; - let (lo, hi) = (2000 * channels, n.saturating_sub(2000) * channels); - let (mut s, mut e) = (0f64, 0f64); - for i in lo..hi { - s += f64::from(reference[i]).powi(2); - e += f64::from(reference[i] - decoded[i]).powi(2); - } - (10.0 * (s / e).log10()) as f32 -} - -fn stereo_snr(kbps: u32) -> f32 { - let mono = music(1, 1.5, 3); - let mut pcm = music(2, 1.5, 7); - // Correlated channels (a common part plus a private part), as in a real mix. - for (t, f) in pcm.chunks_exact_mut(channels_of(2)).enumerate() { - let (a, b) = (f[0], f[1]); - f[0] = 0.8 * mono[t] + 0.2 * a; - f[1] = 0.6 * mono[t] + 0.4 * b; - } - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(kbps * 1000); - enc.set_vbr_constrained(false); - let skip = enc.look_ahead(FRAME); - let mut dec = Decoder::new(48000, 2).unwrap(); - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 2], vec![0u8; 1500]); - for f in pcm.chunks_exact(channels_of(FRAME * 2)) { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); - out.extend_from_slice(&buf[..k * 2]); - } - snr_db(&pcm, &out[skip * 2..], 2) -} - -#[test] -fn stereo_snr_floor() { - for (kbps, floor) in [(64, 17.0), (96, 19.3), (128, 22.0), (256, 26.7)] { - let snr = stereo_snr(kbps); - eprintln!("stereo {kbps}k snr {snr:.2}"); - assert!(snr >= floor, "{kbps} kbit/s: {snr:.2} dB < floor {floor}"); - } -} - -#[test] -fn surround_5_1_snr_floor() { - let pcm = music(6, 0.8, 11); - let mut enc = MultistreamEncoder::surround(48000, 6, Application::Audio).unwrap(); - enc.set_bitrate(256_000); - enc.set_vbr_constrained(false); - let skip = enc.look_ahead(FRAME); - let table = ec_opus::ogg::default_mapping(6).unwrap().3; - let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &table); - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 6], vec![0u8; 4000]); - for f in pcm.chunks_exact(channels_of(FRAME * 6)) { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); - out.extend_from_slice(&buf[..k * 6]); - } - let snr = snr_db(&pcm, &out[skip * 6..], 6); - eprintln!("5.1 256k snr {snr:.2}"); - assert!(snr >= 15.0, "5.1 256 kbit/s: {snr:.2} dB"); -}