Merge branch 'simplify/u8' into simplify/w1b
Browse files at this commit20 changed files +72 -2015
- .config/nextest.toml +1 -5
- Cargo.lock +0 -35
- crates/ec-opus/Cargo.toml +1 -12
- crates/ec-opus/examples/bench.rs +0 -171
- crates/ec-opus/src/analysis.rs +1 -1
- crates/ec-opus/src/celt.rs +43 -318
- crates/ec-opus/src/encoder.rs +5 -61
- crates/ec-opus/src/lib.rs +2 -28
- crates/ec-opus/src/silk.rs +1 -6
- crates/ec-opus/src/silk_flp/api.rs +1 -1
- crates/ec-opus/src/silk_flp/encode.rs +1 -1
- crates/ec-opus/src/silk_flp/nlsf.rs +1 -1
- crates/ec-opus/src/silk_flp/nsq.rs +1 -1
- crates/ec-opus/src/silk_flp/pitch.rs +1 -1
- crates/ec-opus/src/silk_flp/pred.rs +1 -1
- crates/ec-opus/src/silk_flp/stereo.rs +1 -1
- crates/ec-opus/src/stack_budget.rs +0 -864
- crates/ec-opus/tests/conformance.rs +11 -270
- crates/ec-opus/tests/plc.rs +0 -121
- crates/ec-opus/tests/snr_floor.rs +0 -116
.config/nextest.tomlmodified+1 -5
| @@ -1,10 +1,6 @@ | ||
| 1 | 1 | # Keep wall-clock performance assertions from sharing CPUs with other nextest jobs. |
| 2 | 2 | # These tests are regression tripwires, not throughput benchmarks under load. |
| 3 | 3 | |
| 4 | -[[profile.default.overrides]] | |
| 5 | -filter = 'package(ec-opus) & (test(decode_speed) | test(encode_speed))' | |
| 6 | -threads-required = "num-test-threads" | |
| 7 | - | |
| 8 | 4 | [[profile.default.overrides]] |
| 9 | 5 | filter = 'package(ec-aac) & test(five_one_decodes_faster_than_realtime)' |
| 10 | 6 | threads-required = "num-test-threads" |
| @@ -37,7 +33,7 @@ not ((package(ec-av1) & (test(=decode::tests::odd_sizes_round_trip_bit_exact_aga | ||
| 37 | 33 | (package(ec-matroska) & (test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) | |
| 38 | 34 | (package(ec-mp3) & (test(/(^|::)decodes_every_fixture_like_ffmpeg$/) | test(/(^|::)encodes_above_the_incumbent_bar$/) | test(/(^|::)random_frames_match_ffmpeg$/))) | |
| 39 | 35 | (package(ec-mp4) & (test(/(^|::)every_fixture_demuxes_into_the_streams_ffprobe_reports$/) | test(/(^|::)every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with$/))) | |
| 40 | - (package(ec-opus) & (test(/(^|::)oracle_decodes_our_packets_across_the_rate_table$/) | test(/(^|::)rfc6716_test_vectors$/) | test(/(^|::)rfc8251_test_vectors$/))) | | |
| 36 | + (package(ec-opus) & (test(/(^|::)oracle_decodes_our_packets_across_the_rate_table$/) | test(/(^|::)rfc8251_test_vectors$/))) | | |
| 41 | 37 | (package(ec-pcm-ext) & (test(/(^|::)every_format_is_bit_exact_against_ffmpeg$/))) | |
| 42 | 38 | (package(ec-vorbis) & (test(/(^|::)xiph_vectors_decode_like_ffmpeg$/) | test(/(^|::)onset_after_silence_has_no_pre_echo$/))) | |
| 43 | 39 | (package(ec-vp9) & (test(/(^|::)libvpx_vectors_match_per_frame_md5$/)))) |
Cargo.lockmodified+0 -35
| @@ -274,16 +274,6 @@ version = "0.10.3" | ||
| 274 | 274 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 275 | 275 | checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" |
| 276 | 276 | |
| 277 | -[[package]] | |
| 278 | -name = "cpu-time" | |
| 279 | -version = "1.0.0" | |
| 280 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 281 | -checksum = "e9e393a7668fe1fad3075085b86c781883000b4ede868f43627b34a87c8b7ded" | |
| 282 | -dependencies = [ | |
| 283 | - "libc", | |
| 284 | - "winapi", | |
| 285 | -] | |
| 286 | - | |
| 287 | 277 | [[package]] |
| 288 | 278 | name = "cpufeatures" |
| 289 | 279 | version = "0.3.1" |
| @@ -699,14 +689,11 @@ dependencies = [ | ||
| 699 | 689 | name = "ec-opus" |
| 700 | 690 | version = "0.1.0" |
| 701 | 691 | dependencies = [ |
| 702 | - "cpu-time", | |
| 703 | 692 | "ec-core", |
| 704 | 693 | "ec-dsp", |
| 705 | 694 | "ec-ogg", |
| 706 | 695 | "ec-testkit", |
| 707 | 696 | "rustfft", |
| 708 | - "tracking-allocator", | |
| 709 | - "wide", | |
| 710 | 697 | ] |
| 711 | 698 | |
| 712 | 699 | [[package]] |
| @@ -1984,28 +1971,6 @@ dependencies = [ | ||
| 1984 | 1971 | "safe_arch", |
| 1985 | 1972 | ] |
| 1986 | 1973 | |
| 1987 | -[[package]] | |
| 1988 | -name = "winapi" | |
| 1989 | -version = "0.3.9" | |
| 1990 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1991 | -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" | |
| 1992 | -dependencies = [ | |
| 1993 | - "winapi-i686-pc-windows-gnu", | |
| 1994 | - "winapi-x86_64-pc-windows-gnu", | |
| 1995 | -] | |
| 1996 | - | |
| 1997 | -[[package]] | |
| 1998 | -name = "winapi-i686-pc-windows-gnu" | |
| 1999 | -version = "0.4.0" | |
| 2000 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2001 | -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" | |
| 2002 | - | |
| 2003 | -[[package]] | |
| 2004 | -name = "winapi-x86_64-pc-windows-gnu" | |
| 2005 | -version = "0.4.0" | |
| 2006 | -source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2007 | -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" | |
| 2008 | - | |
| 2009 | 1974 | [[package]] |
| 2010 | 1975 | name = "winarm-cpufeatures" |
| 2011 | 1976 | version = "0.1.2" |
crates/ec-opus/Cargo.tomlmodified+1 -12
| @@ -8,20 +8,9 @@ authors.workspace = true | ||
| 8 | 8 | |
| 9 | 9 | [dependencies] |
| 10 | 10 | ec-core.workspace = true |
| 11 | -ec-dsp.workspace = true | |
| 12 | -wide.workspace = true | |
| 13 | -# Optional FFT backend (pure Rust, runtime-detected AVX kernels, no C): the | |
| 14 | -# family stays dependency-free without it (`--no-default-features`); the | |
| 15 | -# speed bench pulls it in behind `fft-rustfft`. | |
| 16 | -rustfft = { version = "6", optional = true, default-features = false } | |
| 11 | +rustfft = { version = "6", default-features = false } | |
| 17 | 12 | |
| 18 | 13 | [dev-dependencies] |
| 19 | 14 | ec-testkit.workspace = true |
| 20 | 15 | ec-dsp.workspace = true |
| 21 | 16 | ec-ogg.workspace = true |
| 22 | -cpu-time = "1.0.0" | |
| 23 | -tracking-allocator = "0.4.0" | |
| 24 | - | |
| 25 | -[features] | |
| 26 | -default = ["fft-rustfft"] | |
| 27 | -fft-rustfft = ["dep:rustfft"] |
crates/ec-opus/examples/bench.rsdeleted+0 -171
| @@ -1,171 +0,0 @@ | ||
| 1 | -//! bench: Opus decode and encode throughput for lanes/bench.md ("lane benchaudio"). | |
| 2 | -//! | |
| 3 | -//! usage: | |
| 4 | -//! bench dec <in.ogg> <out.f32le> [reps] | |
| 5 | -//! bench enc <in.f32le> <channels> <kbps> <out.ogg> [reps] | |
| 6 | -//! | |
| 7 | -//! `dec` demuxes an Ogg Opus file with `OggDemuxer` (the OpusHead and OpusTags packets are not | |
| 8 | -//! audio packets) and decodes every packet with `Decoder` at 48 kHz, `reps` times (default 5), | |
| 9 | -//! keeping the best wall time. The decoded interleaved f32 PCM of the last run, before the | |
| 10 | -//! pre-skip trim, is written to `out.f32le`. | |
| 11 | -//! `enc` encodes raw interleaved 48 kHz f32le PCM with `Encoder` (Application::Audio, CBR at | |
| 12 | -//! `kbps`, 20 ms frames) and muxes it to Ogg Opus, best of `reps` encode runs. | |
| 13 | -use std::fs::File; | |
| 14 | -use std::hint::black_box; | |
| 15 | -use std::io::BufReader; | |
| 16 | -use std::time::Instant; | |
| 17 | - | |
| 18 | -use ec_core::{CodecId, Demuxer, Packet as CorePacket, StreamInfo, TimeBase, Muxer}; | |
| 19 | -use ec_ogg::OggDemuxer; | |
| 20 | -use ec_opus::{Application, Decoder, Encoder, ogg::opus_head, Packet as OpusPacket}; | |
| 21 | - | |
| 22 | -const RATE: u32 = 48_000; | |
| 23 | -/// 20 ms at 48 kHz, per channel. | |
| 24 | -const FRAME: usize = 960; | |
| 25 | - | |
| 26 | -/// The audio packets of the first Opus stream, and its channel count from OpusHead. | |
| 27 | -fn read_packets(path: &str) -> (usize, Vec<Vec<u8>>) { | |
| 28 | - let mut demuxer = OggDemuxer::open(BufReader::new(File::open(path).expect("open"))).expect("ogg"); | |
| 29 | - let stream = demuxer | |
| 30 | - .streams() | |
| 31 | - .iter() | |
| 32 | - .find(|s| s.params.codec == CodecId::Opus) | |
| 33 | - .expect("an Opus stream") | |
| 34 | - .clone(); | |
| 35 | - let head = stream.params.extradata.clone().expect("OpusHead"); | |
| 36 | - let channels = usize::from(head[9]); | |
| 37 | - let mut packets = Vec::new(); | |
| 38 | - loop { | |
| 39 | - match demuxer.next_packet() { | |
| 40 | - Ok(p) if p.stream == stream.index => packets.push(p.data.to_vec()), | |
| 41 | - Ok(_) => {} | |
| 42 | - Err(e) if e.is_eof() => break, | |
| 43 | - Err(e) => panic!("demux: {e}"), | |
| 44 | - } | |
| 45 | - } | |
| 46 | - (channels, packets) | |
| 47 | -} | |
| 48 | - | |
| 49 | -/// Decode every packet once: (interleaved samples, packets that failed). | |
| 50 | -fn decode_once(packets: &[Vec<u8>], channels: usize) -> (Vec<f32>, usize) { | |
| 51 | - let mut decoder = Decoder::new(RATE, channels).expect("decoder"); | |
| 52 | - let mut out = Vec::new(); | |
| 53 | - let mut buf = vec![0f32; 5760 * channels]; | |
| 54 | - let mut failed = 0usize; | |
| 55 | - for p in packets { | |
| 56 | - match decoder.decode_float(p, &mut buf) { | |
| 57 | - Ok(n) => out.extend_from_slice(&buf[..n * channels]), | |
| 58 | - Err(_) => failed += 1, | |
| 59 | - } | |
| 60 | - } | |
| 61 | - (out, failed) | |
| 62 | -} | |
| 63 | - | |
| 64 | -fn le_f32(bytes: &[u8]) -> Vec<f32> { | |
| 65 | - bytes | |
| 66 | - .as_chunks::<4>().0.iter() | |
| 67 | - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| 68 | - .collect() | |
| 69 | -} | |
| 70 | - | |
| 71 | -/// Encode interleaved 48 kHz PCM into (Opus packets, pre-skip) with 20 ms frames. | |
| 72 | -fn encode_once(pcm: &[f32], channels: usize, kbps: u32) -> (Vec<Vec<u8>>, usize) { | |
| 73 | - let mut encoder = Encoder::new(RATE, channels, Application::Audio).expect("encoder"); | |
| 74 | - encoder.set_bitrate(kbps * 1000); | |
| 75 | - encoder.set_vbr_constrained(false); | |
| 76 | - let pre_skip = encoder.look_ahead(FRAME); | |
| 77 | - let frames = (pcm.len() / channels).div_ceil(FRAME); | |
| 78 | - let mut packets = Vec::with_capacity(frames); | |
| 79 | - let mut frame = vec![0f32; FRAME * channels]; | |
| 80 | - let mut out = vec![0u8; 1500]; | |
| 81 | - for f in 0..frames { | |
| 82 | - frame.fill(0.0); | |
| 83 | - let start = f * FRAME * channels; | |
| 84 | - let end = (start + FRAME * channels).min(pcm.len()); | |
| 85 | - frame[..end - start].copy_from_slice(&pcm[start..end]); | |
| 86 | - let n = encoder.encode_float(&frame, FRAME, &mut out).expect("encode"); | |
| 87 | - packets.push(out[..n].to_vec()); | |
| 88 | - } | |
| 89 | - (packets, pre_skip) | |
| 90 | -} | |
| 91 | - | |
| 92 | -/// Mux the packets into Ogg Opus. The last packet's duration ends at the true input length. | |
| 93 | -fn write_ogg(path: &str, packets: &[Vec<u8>], channels: usize, total: usize, pre_skip: usize) { | |
| 94 | - let file = std::io::BufWriter::new(File::create(path).expect("create")); | |
| 95 | - let mut mux = ec_ogg::OggMuxer::new(file); | |
| 96 | - let tb = TimeBase::from_rate(RATE); | |
| 97 | - let mut params = ec_core::CodecParameters::new(CodecId::Opus); | |
| 98 | - params.extradata = Some(opus_head(channels as u8, pre_skip as u16, RATE, 0, None).into()); | |
| 99 | - if let ec_core::MediaParameters::Audio(a) = &mut params.media { | |
| 100 | - a.sample_rate = RATE; | |
| 101 | - a.layout = ec_core::ChannelLayout::from_count(channels); | |
| 102 | - } | |
| 103 | - mux.add_stream(StreamInfo::new(0, tb, params)).expect("stream"); | |
| 104 | - let mut pts = 0i64; | |
| 105 | - for (idx, p) in packets.iter().enumerate() { | |
| 106 | - let dur = OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; | |
| 107 | - let dur = if idx == packets.len() - 1 { | |
| 108 | - total as i64 + pre_skip as i64 - pts | |
| 109 | - } else { | |
| 110 | - dur | |
| 111 | - }; | |
| 112 | - let pkt = CorePacket::new(0, tb, p.clone()).with_pts(pts).with_duration(dur); | |
| 113 | - mux.write_packet(&pkt).expect("write"); | |
| 114 | - pts += OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; | |
| 115 | - } | |
| 116 | - mux.finish().expect("finish"); | |
| 117 | -} | |
| 118 | - | |
| 119 | -fn main() { | |
| 120 | - let args: Vec<String> = std::env::args().collect(); | |
| 121 | - match args.get(1).map(String::as_str) { | |
| 122 | - Some("dec") if args.len() >= 4 => { | |
| 123 | - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); | |
| 124 | - let (channels, packets) = read_packets(&args[2]); | |
| 125 | - let (pcm, failed) = decode_once(&packets, channels); | |
| 126 | - let mut best = f64::MAX; | |
| 127 | - for _ in 0..reps { | |
| 128 | - let t = Instant::now(); | |
| 129 | - black_box(decode_once(black_box(&packets), channels).0.len()); | |
| 130 | - best = best.min(t.elapsed().as_secs_f64()); | |
| 131 | - } | |
| 132 | - let mut bytes = Vec::with_capacity(pcm.len() * 4); | |
| 133 | - for v in &pcm { | |
| 134 | - bytes.extend_from_slice(&v.to_le_bytes()); | |
| 135 | - } | |
| 136 | - std::fs::write(&args[3], &bytes).expect("write output"); | |
| 137 | - println!( | |
| 138 | - "packets={} failed={failed} samples={} best_decode_s={best:.4} reps={reps}", | |
| 139 | - packets.len(), | |
| 140 | - pcm.len() / channels | |
| 141 | - ); | |
| 142 | - } | |
| 143 | - Some("enc") if args.len() >= 6 => { | |
| 144 | - let channels: usize = args[3].parse().expect("channels"); | |
| 145 | - let kbps: u32 = args[4].parse().expect("kbps"); | |
| 146 | - let reps: usize = args.get(6).map_or(5, |s| s.parse().expect("reps")); | |
| 147 | - let pcm = le_f32(&std::fs::read(&args[2]).expect("read input")); | |
| 148 | - let total = pcm.len() / channels; | |
| 149 | - let (packets, pre_skip) = encode_once(&pcm, channels, kbps); | |
| 150 | - let mut best = f64::MAX; | |
| 151 | - for _ in 0..reps { | |
| 152 | - let t = Instant::now(); | |
| 153 | - black_box(encode_once(black_box(&pcm), channels, kbps).0.len()); | |
| 154 | - best = best.min(t.elapsed().as_secs_f64()); | |
| 155 | - } | |
| 156 | - write_ogg(&args[5], &packets, channels, total, pre_skip); | |
| 157 | - let bytes: usize = packets.iter().map(Vec::len).sum(); | |
| 158 | - println!( | |
| 159 | - "packets={} bytes={bytes} best_encode_s={best:.4} reps={reps} audio_s={:.3}", | |
| 160 | - packets.len(), | |
| 161 | - total as f64 / f64::from(RATE) | |
| 162 | - ); | |
| 163 | - } | |
| 164 | - _ => { | |
| 165 | - eprintln!( | |
| 166 | - "usage: bench dec <in.ogg> <out.f32le> [reps]\n bench enc <in.f32le> <channels> <kbps> <out.ogg> [reps]" | |
| 167 | - ); | |
| 168 | - std::process::exit(2); | |
| 169 | - } | |
| 170 | - } | |
| 171 | -} |
crates/ec-opus/src/analysis.rsmodified+1 -1
| @@ -291,7 +291,7 @@ pub(crate) struct TonalityAnalysis { | ||
| 291 | 291 | downmix_state: [f32; 3], |
| 292 | 292 | info: Vec<AnalysisInfo>, |
| 293 | 293 | /// Per-frame scratch, sized once so the steady-state encode loop stays |
| 294 | - /// allocation-free (`steady_state_encode_loop_zero_alloc`). | |
| 294 | + /// allocation-free. | |
| 295 | 295 | dm_tmp: Vec<f32>, |
| 296 | 296 | dm_tmp3x: Vec<f32>, |
| 297 | 297 | chunk: Vec<f32>, |
crates/ec-opus/src/celt.rsmodified+43 -318
| @@ -23,6 +23,10 @@ | ||
| 23 | 23 | |
| 24 | 24 | use ec_core::{Error, Result}; |
| 25 | 25 | |
| 26 | +use std::sync::Arc; | |
| 27 | + | |
| 28 | +use rustfft::num_complex::Complex; | |
| 29 | + | |
| 26 | 30 | use crate::range::{RangeDecoder, RangeEncoder}; |
| 27 | 31 | |
| 28 | 32 | /// Bands in the 48 kHz mode. |
| @@ -301,236 +305,53 @@ pub(crate) fn overlap_window() -> Vec<f32> { | ||
| 301 | 305 | // --------------------------------------------------------------------------- |
| 302 | 306 | // The N/4 FFT and the inverse MDCT |
| 303 | 307 | // --------------------------------------------------------------------------- |
| 304 | - | |
| 305 | -/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`). | |
| 306 | -/// | |
| 307 | -/// Two backends behind one signature, selected at compile time: | |
| 308 | -/// | |
| 309 | -/// - default, the in-project shape: [`ec_dsp::Fft`] covers the `2^k` factor | |
| 310 | -/// and the factor of 15 is one extra decimation stage (3 x 5), so the whole | |
| 311 | -/// transform stays `O(n log n)` without a mixed-radix kernel in the DSP | |
| 312 | -/// crate; | |
| 313 | -/// - under the optional `fft-rustfft` feature, a rustfft plan plans the size | |
| 314 | -/// directly (pure Rust, runtime-detected AVX butterflies, no C). The | |
| 315 | -/// family's dependency-free build stays the default; the feature is the | |
| 316 | -/// measured speed option. | |
| 317 | -/// | |
| 318 | -/// Both deliver the same contract: an UNSCALED inverse transform, | |
| 319 | -/// `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers. | |
| 320 | -#[cfg(not(feature = "fft-rustfft"))] | |
| 321 | -mod fft15 { | |
| 322 | - use super::dft15; | |
| 323 | - use ec_dsp::Fft; | |
| 324 | - | |
| 325 | - #[derive(Clone, Debug)] | |
| 326 | - pub(crate) struct Fft15 { | |
| 327 | - n: usize, | |
| 328 | - /// Sub-transform of length `n/15`. | |
| 329 | - sub: Fft<f32>, | |
| 330 | - /// `exp(2 pi i * k1 * n2 / n)` twiddles, split. | |
| 331 | - tw_re: Vec<f32>, | |
| 332 | - tw_im: Vec<f32>, | |
| 333 | - scratch_re: Vec<f32>, | |
| 334 | - scratch_im: Vec<f32>, | |
| 335 | - } | |
| 336 | - | |
| 337 | - impl Fft15 { | |
| 338 | - pub(crate) fn new(n: usize) -> Fft15 { | |
| 339 | - assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); | |
| 340 | - let l = n / 15; | |
| 341 | - let mut tw_re = vec![0.0; n]; | |
| 342 | - let mut tw_im = vec![0.0; n]; | |
| 343 | - for k1 in 0..15 { | |
| 344 | - for n2 in 0..l { | |
| 345 | - let a = 2.0 * core::f64::consts::PI * (k1 * n2) as f64 / n as f64; | |
| 346 | - tw_re[k1 * l + n2] = a.cos() as f32; | |
| 347 | - tw_im[k1 * l + n2] = a.sin() as f32; | |
| 348 | - } | |
| 349 | - } | |
| 350 | - Fft15 { | |
| 351 | - n, | |
| 352 | - sub: Fft::new(l), | |
| 353 | - tw_re, | |
| 354 | - tw_im, | |
| 355 | - scratch_re: vec![0.0; n], | |
| 356 | - scratch_im: vec![0.0; n], | |
| 357 | - } | |
| 358 | - } | |
| 359 | - | |
| 360 | - /// Unscaled inverse transform. | |
| 361 | - pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { | |
| 362 | - let n = self.n; | |
| 363 | - let l = n / 15; | |
| 364 | - debug_assert_eq!(re.len(), n); | |
| 365 | - // Stage 1: 15-point DFTs over n1 at stride L, twiddled on the way | |
| 366 | - // out. | |
| 367 | - for n2 in 0..l { | |
| 368 | - let mut xr = [0.0f32; 15]; | |
| 369 | - let mut xi = [0.0f32; 15]; | |
| 370 | - for n1 in 0..15 { | |
| 371 | - xr[n1] = re[l * n1 + n2]; | |
| 372 | - xi[n1] = im[l * n1 + n2]; | |
| 373 | - } | |
| 374 | - let (yr, yi) = dft15(&xr, &xi); | |
| 375 | - for k1 in 0..15 { | |
| 376 | - let (tr, ti) = (self.tw_re[k1 * l + n2], self.tw_im[k1 * l + n2]); | |
| 377 | - self.scratch_re[k1 * l + n2] = yr[k1] * tr - yi[k1] * ti; | |
| 378 | - self.scratch_im[k1 * l + n2] = yr[k1] * ti + yi[k1] * tr; | |
| 379 | - } | |
| 380 | - } | |
| 381 | - // Stage 2: L-point transforms, one per k1, written out at stride | |
| 382 | - // 15. ec-dsp scales its inverse by 1/L; undo that to keep the | |
| 383 | - // transform unscaled, which is what the MDCT expects. | |
| 384 | - for k1 in 0..15 { | |
| 385 | - let rr = &mut self.scratch_re[k1 * l..(k1 + 1) * l]; | |
| 386 | - let ii = &mut self.scratch_im[k1 * l..(k1 + 1) * l]; | |
| 387 | - self.sub.inverse_split(rr, ii); | |
| 388 | - for (k2, (&r, &i)) in rr.iter().zip(ii.iter()).enumerate() { | |
| 389 | - re[k1 + 15 * k2] = r * l as f32; | |
| 390 | - im[k1 + 15 * k2] = i * l as f32; | |
| 391 | - } | |
| 392 | - } | |
| 393 | - } | |
| 394 | - } | |
| 308 | +/// A complex inverse FFT of the sizes CELT needs (`15 * 2^k`), planned by | |
| 309 | +/// rustfft (pure Rust, runtime-detected AVX butterflies). The transform is | |
| 310 | +/// UNSCALED, `X[k] = sum x[n] exp(+2 pi i n k / N)`, over split-complex buffers. | |
| 311 | +#[derive(Clone)] | |
| 312 | +pub(crate) struct Fft15 { | |
| 313 | + n: usize, | |
| 314 | + plan: Arc<dyn rustfft::Fft<f32>>, | |
| 315 | + cbuf: Vec<Complex<f32>>, | |
| 316 | + /// Preallocated once: `process` would allocate this per call, and the | |
| 317 | + /// encoder's steady-state loop is a zero-allocation contract. | |
| 318 | + scratch: Vec<Complex<f32>>, | |
| 395 | 319 | } |
| 396 | 320 | |
| 397 | -#[cfg(feature = "fft-rustfft")] | |
| 398 | -mod fft15 { | |
| 399 | - use rustfft::num_complex::Complex; | |
| 400 | - use std::sync::Arc; | |
| 401 | - | |
| 402 | - #[derive(Clone)] | |
| 403 | - pub(crate) struct Fft15 { | |
| 404 | - n: usize, | |
| 405 | - plan: Arc<dyn rustfft::Fft<f32>>, | |
| 406 | - cbuf: Vec<Complex<f32>>, | |
| 407 | - /// Preallocated once: `process` would allocate this per call, and the | |
| 408 | - /// encoder's steady-state loop is a zero-allocation contract. | |
| 409 | - scratch: Vec<Complex<f32>>, | |
| 321 | +impl core::fmt::Debug for Fft15 { | |
| 322 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | |
| 323 | + f.debug_struct("Fft15").field("n", &self.n).finish() | |
| 410 | 324 | } |
| 325 | +} | |
| 411 | 326 | |
| 412 | - impl core::fmt::Debug for Fft15 { | |
| 413 | - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | |
| 414 | - f.debug_struct("Fft15").field("n", &self.n).finish() | |
| 327 | +impl Fft15 { | |
| 328 | + pub(crate) fn new(n: usize) -> Fft15 { | |
| 329 | + assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); | |
| 330 | + let mut planner = rustfft::FftPlanner::<f32>::new(); | |
| 331 | + let plan = planner.plan_fft_inverse(n); | |
| 332 | + let cbuf = vec![Complex::ZERO; n]; | |
| 333 | + let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()]; | |
| 334 | + Fft15 { | |
| 335 | + n, | |
| 336 | + plan, | |
| 337 | + cbuf, | |
| 338 | + scratch, | |
| 415 | 339 | } |
| 416 | 340 | } |
| 417 | 341 | |
| 418 | - impl Fft15 { | |
| 419 | - pub(crate) fn new(n: usize) -> Fft15 { | |
| 420 | - assert!(n.is_multiple_of(15) && (n / 15).is_power_of_two()); | |
| 421 | - let mut planner = rustfft::FftPlanner::<f32>::new(); | |
| 422 | - let plan = planner.plan_fft_inverse(n); | |
| 423 | - let cbuf = vec![Complex::ZERO; n]; | |
| 424 | - let scratch = vec![Complex::ZERO; plan.get_inplace_scratch_len()]; | |
| 425 | - Fft15 { | |
| 426 | - n, | |
| 427 | - plan, | |
| 428 | - cbuf, | |
| 429 | - scratch, | |
| 430 | - } | |
| 342 | + pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { | |
| 343 | + for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) { | |
| 344 | + *c = Complex::new(*r, *i); | |
| 431 | 345 | } |
| 432 | - | |
| 433 | - /// Unscaled inverse transform. rustfft does not scale, which is | |
| 434 | - /// exactly the contract here. | |
| 435 | - pub(crate) fn inverse(&mut self, re: &mut [f32], im: &mut [f32]) { | |
| 436 | - for (c, (r, i)) in self.cbuf.iter_mut().zip(re.iter().zip(im.iter())) { | |
| 437 | - *c = Complex::new(*r, *i); | |
| 438 | - } | |
| 439 | - self.plan | |
| 440 | - .process_with_scratch(&mut self.cbuf, &mut self.scratch); | |
| 441 | - for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) { | |
| 442 | - *r = c.re; | |
| 443 | - *i = c.im; | |
| 444 | - } | |
| 346 | + self.plan | |
| 347 | + .process_with_scratch(&mut self.cbuf, &mut self.scratch); | |
| 348 | + for ((c, r), i) in self.cbuf.iter().zip(re.iter_mut()).zip(im.iter_mut()) { | |
| 349 | + *r = c.re; | |
| 350 | + *i = c.im; | |
| 445 | 351 | } |
| 446 | 352 | } |
| 447 | 353 | } |
| 448 | 354 | |
| 449 | -pub(crate) use fft15::Fft15; | |
| 450 | - | |
| 451 | -/// A 15-point DFT as 5 radix-3 stages then 3 radix-5 stages (Cooley-Tukey on | |
| 452 | -/// 15 = 3*5), which costs about a third of the direct evaluation. | |
| 453 | -#[cfg(not(feature = "fft-rustfft"))] | |
| 454 | -#[inline] | |
| 455 | -fn dft15(xr: &[f32; 15], xi: &[f32; 15]) -> ([f32; 15], [f32; 15]) { | |
| 456 | - // exp(+2 pi i / 3) and the two fifth-root cosines/sines. | |
| 457 | - const C3: f32 = -0.5; | |
| 458 | - const S3: f32 = 0.866_025_4; | |
| 459 | - const C5_1: f32 = 0.309_017; | |
| 460 | - const S5_1: f32 = 0.951_056_5; | |
| 461 | - const C5_2: f32 = -0.809_017; | |
| 462 | - const S5_2: f32 = 0.587_785_25; | |
| 463 | - // exp(+2 pi i * (n2*k1) / 15) for n2 in 0..5, k1 in 0..3. | |
| 464 | - const TW_RE: [[f32; 3]; 5] = [ | |
| 465 | - [1.0, 1.0, 1.0], | |
| 466 | - [1.0, 0.913_545_5, 0.669_130_6], | |
| 467 | - [1.0, 0.669_130_6, -0.104_528_46], | |
| 468 | - [1.0, 0.309_017, -0.809_017], | |
| 469 | - [1.0, -0.104_528_46, -0.978_147_6], | |
| 470 | - ]; | |
| 471 | - const TW_IM: [[f32; 3]; 5] = [ | |
| 472 | - [0.0, 0.0, 0.0], | |
| 473 | - [0.0, 0.406_736_65, 0.743_144_8], | |
| 474 | - [0.0, 0.743_144_8, 0.994_521_9], | |
| 475 | - [0.0, 0.951_056_5, 0.587_785_25], | |
| 476 | - [0.0, 0.994_521_9, -0.207_911_69], | |
| 477 | - ]; | |
| 478 | - // Radix-3 over n1 (stride 5), one per n2. | |
| 479 | - let mut ar = [[0.0f32; 3]; 5]; | |
| 480 | - let mut ai = [[0.0f32; 3]; 5]; | |
| 481 | - for n2 in 0..5 { | |
| 482 | - let (r0, i0) = (xr[n2], xi[n2]); | |
| 483 | - let (r1, i1) = (xr[5 + n2], xi[5 + n2]); | |
| 484 | - let (r2, i2) = (xr[10 + n2], xi[10 + n2]); | |
| 485 | - let (sr, si) = (r1 + r2, i1 + i2); | |
| 486 | - let (dr, di) = (r1 - r2, i1 - i2); | |
| 487 | - ar[n2][0] = r0 + sr; | |
| 488 | - ai[n2][0] = i0 + si; | |
| 489 | - let (tr, ti) = (r0 + C3 * sr, i0 + C3 * si); | |
| 490 | - // Multiplying (dr, di) by i gives (-di, dr). | |
| 491 | - ar[n2][1] = tr - S3 * di; | |
| 492 | - ai[n2][1] = ti + S3 * dr; | |
| 493 | - ar[n2][2] = tr + S3 * di; | |
| 494 | - ai[n2][2] = ti - S3 * dr; | |
| 495 | - // Twiddle by exp(+2 pi i n2 k1 / 15). | |
| 496 | - for k1 in 1..3 { | |
| 497 | - let (tr, ti) = (TW_RE[n2][k1], TW_IM[n2][k1]); | |
| 498 | - let (r, i) = (ar[n2][k1], ai[n2][k1]); | |
| 499 | - ar[n2][k1] = r * tr - i * ti; | |
| 500 | - ai[n2][k1] = r * ti + i * tr; | |
| 501 | - } | |
| 502 | - } | |
| 503 | - // Radix-5 over n2, one per k1; output index is k1 + 3*k2. | |
| 504 | - let mut yr = [0.0f32; 15]; | |
| 505 | - let mut yi = [0.0f32; 15]; | |
| 506 | - for k1 in 0..3 { | |
| 507 | - let (r0, i0) = (ar[0][k1], ai[0][k1]); | |
| 508 | - let (r1, i1) = (ar[1][k1], ai[1][k1]); | |
| 509 | - let (r2, i2) = (ar[2][k1], ai[2][k1]); | |
| 510 | - let (r3, i3) = (ar[3][k1], ai[3][k1]); | |
| 511 | - let (r4, i4) = (ar[4][k1], ai[4][k1]); | |
| 512 | - let (s1r, s1i) = (r1 + r4, i1 + i4); | |
| 513 | - let (d1r, d1i) = (r1 - r4, i1 - i4); | |
| 514 | - let (s2r, s2i) = (r2 + r3, i2 + i3); | |
| 515 | - let (d2r, d2i) = (r2 - r3, i2 - i3); | |
| 516 | - yr[k1] = r0 + s1r + s2r; | |
| 517 | - yi[k1] = i0 + s1i + s2i; | |
| 518 | - let (m1r, m1i) = (r0 + C5_1 * s1r + C5_2 * s2r, i0 + C5_1 * s1i + C5_2 * s2i); | |
| 519 | - let (n1r, n1i) = (S5_1 * d1r + S5_2 * d2r, S5_1 * d1i + S5_2 * d2i); | |
| 520 | - let (m2r, m2i) = (r0 + C5_2 * s1r + C5_1 * s2r, i0 + C5_2 * s1i + C5_1 * s2i); | |
| 521 | - let (n2r, n2i) = (S5_2 * d1r - S5_1 * d2r, S5_2 * d1i - S5_1 * d2i); | |
| 522 | - yr[k1 + 3] = m1r - n1i; | |
| 523 | - yi[k1 + 3] = m1i + n1r; | |
| 524 | - yr[k1 + 12] = m1r + n1i; | |
| 525 | - yi[k1 + 12] = m1i - n1r; | |
| 526 | - yr[k1 + 6] = m2r - n2i; | |
| 527 | - yi[k1 + 6] = m2i + n2r; | |
| 528 | - yr[k1 + 9] = m2r + n2i; | |
| 529 | - yi[k1 + 9] = m2i - n2r; | |
| 530 | - } | |
| 531 | - (yr, yi) | |
| 532 | -} | |
| 533 | - | |
| 534 | 355 | /// One inverse-MDCT plan: spectrum length `l = 15 * 2^k`, window `2*l`. |
| 535 | 356 | #[derive(Clone, Debug)] |
| 536 | 357 | struct ImdctPlan { |
| @@ -1257,52 +1078,11 @@ fn compute_allocation_shared( | ||
| 1257 | 1078 | } |
| 1258 | 1079 | } |
| 1259 | 1080 | |
| 1260 | -/// Facts about the last decoded frame, for diagnostics. | |
| 1261 | -#[derive(Clone, Debug)] | |
| 1262 | -pub struct CeltDecDiag { | |
| 1263 | - /// The frame was coded as CELT digital silence. | |
| 1264 | - pub silence: bool, | |
| 1265 | - /// Coarse energies used the intra-frame reset. | |
| 1266 | - pub intra: bool, | |
| 1267 | - /// Short-block (transient) frame as coded. | |
| 1268 | - pub transient: bool, | |
| 1269 | - /// Packet bits the range decoder saw for this frame. | |
| 1270 | - pub total_bits: i32, | |
| 1271 | - /// Decoded log2 band energies after fine bits, per channel (`2*NB_BANDS`). | |
| 1272 | - pub old_band_e: Vec<f32>, | |
| 1273 | - /// Time-frequency resolution change per band after `tf_select`. | |
| 1274 | - pub tf_res: Vec<i32>, | |
| 1275 | - /// Spreading decision as coded (0..3). | |
| 1276 | - pub spread: usize, | |
| 1277 | - /// Anti-collapse flag as coded. | |
| 1278 | - pub anti_collapse: bool, | |
| 1279 | - /// Allocation trim index as coded (0..10). | |
| 1280 | - pub alloc_trim: i32, | |
| 1281 | - /// Per-band allocated pulses after `compute_allocation`. | |
| 1282 | - pub pulses: Vec<i32>, | |
| 1283 | - /// Per-band fine-energy precision bits. | |
| 1284 | - pub fine_quant: Vec<i32>, | |
| 1285 | - /// Stereo intensity band (bands >= this collapse to mono). | |
| 1286 | - pub intensity: usize, | |
| 1287 | - /// Dual-stereo flag as coded. | |
| 1288 | - pub dual_stereo: bool, | |
| 1289 | - /// Highest band actually allocated pulses (`codedBands`). | |
| 1290 | - pub coded_bands: usize, | |
| 1291 | - /// Bit balance left after allocation, in 1/8-bit units. | |
| 1292 | - pub balance: i32, | |
| 1293 | - /// Decoded dynalloc band boosts (1/8-bit units). | |
| 1294 | - pub offsets: Vec<i32>, | |
| 1295 | -} | |
| 1296 | - | |
| 1297 | 1081 | /// A CELT layer decoder, one per Opus stream. |
| 1298 | 1082 | #[derive(Clone, Debug)] |
| 1299 | 1083 | pub struct CeltDecoder { |
| 1300 | 1084 | /// Channels this decoder outputs. |
| 1301 | 1085 | channels: usize, |
| 1302 | - /// Decode with the RFC 6716 reconstruction (no RFC 8251 Section 8 energy cap | |
| 1303 | - /// and no Section 9 hybrid folding). Off by default: RFC 8251 Section 11 | |
| 1304 | - /// makes the new behaviour the reference. | |
| 1305 | - legacy_rfc6716: bool, | |
| 1306 | 1086 | /// Output decimation: 1 at 48 kHz, 2 at 24 kHz, and so on. |
| 1307 | 1087 | downsample: usize, |
| 1308 | 1088 | window: Vec<f32>, |
| @@ -1340,7 +1120,6 @@ pub struct CeltDecoder { | ||
| 1340 | 1120 | collapse_masks: [u8; 2 * NB_BANDS], |
| 1341 | 1121 | iy: Vec<i32>, |
| 1342 | 1122 | mdct_buf: Vec<f32>, |
| 1343 | - diag: CeltDecDiag, | |
| 1344 | 1123 | plc: Plc, |
| 1345 | 1124 | } |
| 1346 | 1125 | |
| @@ -1362,7 +1141,6 @@ impl CeltDecoder { | ||
| 1362 | 1141 | let max_n = SHORT_MDCT * 8; |
| 1363 | 1142 | CeltDecoder { |
| 1364 | 1143 | channels, |
| 1365 | - legacy_rfc6716: false, | |
| 1366 | 1144 | downsample, |
| 1367 | 1145 | window: overlap_window(), |
| 1368 | 1146 | plans: (0..4).map(|lm| ImdctPlan::new(SHORT_MDCT << lm)).collect(), |
| @@ -1404,34 +1182,9 @@ impl CeltDecoder { | ||
| 1404 | 1182 | start: 0, |
| 1405 | 1183 | end: NB_BANDS, |
| 1406 | 1184 | }, |
| 1407 | - diag: CeltDecDiag { | |
| 1408 | - silence: false, | |
| 1409 | - intra: false, | |
| 1410 | - transient: false, | |
| 1411 | - total_bits: 0, | |
| 1412 | - old_band_e: vec![0.0; 2 * NB_BANDS], | |
| 1413 | - tf_res: Vec::new(), | |
| 1414 | - spread: 0, | |
| 1415 | - anti_collapse: false, | |
| 1416 | - alloc_trim: 0, | |
| 1417 | - pulses: vec![0; NB_BANDS], | |
| 1418 | - fine_quant: vec![0; NB_BANDS], | |
| 1419 | - intensity: 0, | |
| 1420 | - dual_stereo: false, | |
| 1421 | - coded_bands: 0, | |
| 1422 | - balance: 0, | |
| 1423 | - offsets: vec![0; NB_BANDS], | |
| 1424 | - }, | |
| 1425 | 1185 | } |
| 1426 | 1186 | } |
| 1427 | 1187 | |
| 1428 | - /// Selects the RFC 6716 reconstruction (`true`) or the RFC 8251 one (`false`, | |
| 1429 | - /// the default). The two differ on some hybrid and high-energy frames, so each | |
| 1430 | - /// vector set is decoded with the behaviour its reference was made with. | |
| 1431 | - pub fn set_legacy_rfc6716(&mut self, on: bool) { | |
| 1432 | - self.legacy_rfc6716 = on; | |
| 1433 | - } | |
| 1434 | - | |
| 1435 | 1188 | /// Drops all inter-frame state (after a seek, or on a mode switch). |
| 1436 | 1189 | pub fn reset(&mut self) { |
| 1437 | 1190 | self.decode_mem.fill(0.0); |
| @@ -1456,11 +1209,6 @@ impl CeltDecoder { | ||
| 1456 | 1209 | self.rng |
| 1457 | 1210 | } |
| 1458 | 1211 | |
| 1459 | - /// Facts from the last decoded frame (diagnostic). | |
| 1460 | - pub fn last_diag(&self) -> &CeltDecDiag { | |
| 1461 | - &self.diag | |
| 1462 | - } | |
| 1463 | - | |
| 1464 | 1212 | /// Decodes one CELT frame. |
| 1465 | 1213 | /// |
| 1466 | 1214 | /// `frame_size` is in 48 kHz samples; `start`/`end` bound the coded bands |
| @@ -1664,11 +1412,7 @@ impl CeltDecoder { | ||
| 1664 | 1412 | // RFC 8251 Section 8: cap the log2 energy at 32 so the amplitude |
| 1665 | 1413 | // stays finite (libopus `log2Amp`, `MIN32(QCONST32(32.f, 16), lg)`). |
| 1666 | 1414 | let lg = (self.old_band_e[ch * NB_BANDS + i] + mean) as f64; |
| 1667 | - let lg = if self.legacy_rfc6716 { | |
| 1668 | - lg | |
| 1669 | - } else { | |
| 1670 | - lg.min(32.0) | |
| 1671 | - }; | |
| 1415 | + let lg = lg.min(32.0); | |
| 1672 | 1416 | lg.exp2() as f32 |
| 1673 | 1417 | }; |
| 1674 | 1418 | } |
| @@ -1769,24 +1513,6 @@ impl CeltDecoder { | ||
| 1769 | 1513 | self.old_log_e2[ch * NB_BANDS + i] = -28.0; |
| 1770 | 1514 | } |
| 1771 | 1515 | } |
| 1772 | - self.diag = CeltDecDiag { | |
| 1773 | - silence, | |
| 1774 | - intra, | |
| 1775 | - transient, | |
| 1776 | - total_bits, | |
| 1777 | - old_band_e: self.old_band_e.clone(), | |
| 1778 | - tf_res: self.tf_res.to_vec(), | |
| 1779 | - spread, | |
| 1780 | - anti_collapse: anti_collapse_on, | |
| 1781 | - alloc_trim, | |
| 1782 | - pulses: self.pulses.to_vec(), | |
| 1783 | - fine_quant: self.fine_quant.to_vec(), | |
| 1784 | - intensity, | |
| 1785 | - dual_stereo, | |
| 1786 | - coded_bands, | |
| 1787 | - balance, | |
| 1788 | - offsets: self.offsets.to_vec(), | |
| 1789 | - }; | |
| 1790 | 1516 | self.rng = dec.range(); |
| 1791 | 1517 | |
| 1792 | 1518 | self.deemphasis(out, n, cc); |
| @@ -1951,13 +1677,12 @@ impl CeltDecoder { | ||
| 1951 | 1677 | |
| 1952 | 1678 | // RFC 8251 Section 9: the second band may take the first band as its |
| 1953 | 1679 | // lowband even when the first band is narrower than it. |
| 1954 | - let rfc8251 = !self.legacy_rfc6716; | |
| 1955 | - if (m * E_BANDS[i] >= m * E_BANDS[start] + n_band || (rfc8251 && i == start + 1)) | |
| 1680 | + if (m * E_BANDS[i] >= m * E_BANDS[start] + n_band || i == start + 1) | |
| 1956 | 1681 | && (update_lowband || lowband_offset == 0) |
| 1957 | 1682 | { |
| 1958 | 1683 | lowband_offset = i; |
| 1959 | 1684 | } |
| 1960 | - if rfc8251 && i == start + 1 && start + 2 <= NB_BANDS { | |
| 1685 | + if i == start + 1 && start + 2 <= NB_BANDS { | |
| 1961 | 1686 | // RFC 8251 Section 9: repeat part of band `start` so band `i` can |
| 1962 | 1687 | // fold onto it. Copies nothing when band `i` is not wider than it. |
| 1963 | 1688 | let n1 = m * (E_BANDS[start + 1] - E_BANDS[start]); |
| @@ -1993,7 +1718,7 @@ impl CeltDecoder { | ||
| 1993 | 1718 | let mut fold_end = lowband_offset - 1; |
| 1994 | 1719 | loop { |
| 1995 | 1720 | fold_end += 1; |
| 1996 | - if (rfc8251 && fold_end >= i) || m * E_BANDS[fold_end] >= low + n_band { | |
| 1721 | + if fold_end >= i || m * E_BANDS[fold_end] >= low + n_band { | |
| 1997 | 1722 | break; |
| 1998 | 1723 | } |
| 1999 | 1724 | } |
crates/ec-opus/src/encoder.rsmodified+5 -61
| @@ -54,8 +54,7 @@ enum Prefill { | ||
| 54 | 54 | } |
| 55 | 55 | |
| 56 | 56 | /// One MDCT overlap: the CELT layer's delay without libopus's input |
| 57 | -/// alignment ([`Encoder::set_libopus_input_alignment`]), which adds | |
| 58 | -/// `delay_compensation = Fs/250` (192 at 48 kHz) on top. | |
| 57 | +/// alignment, which adds `delay_compensation = Fs/250` (192 at 48 kHz) on top. | |
| 59 | 58 | const CELT_OVERLAP_48K: usize = 120; |
| 60 | 59 | /// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`. |
| 61 | 60 | const CELT_DELAY_COMP_48K: usize = 192; |
| @@ -285,17 +284,15 @@ pub struct Encoder { | ||
| 285 | 284 | /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the |
| 286 | 285 | /// application and bitrate; `Some` forces one. |
| 287 | 286 | mode: Option<Mode>, |
| 288 | - /// The SILK layer, created on first use (boxed: `crate::stack_budget`). | |
| 287 | + /// The SILK layer, created on first use. | |
| 289 | 288 | silk: Option<Box<SilkLayer>>, |
| 290 | 289 | /// Scratch space for the SILK packet payload, sized once so the steady-state |
| 291 | - /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. | |
| 290 | + /// loop doesn't allocate. | |
| 292 | 291 | /// |
| 293 | 292 | /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is |
| 294 | 293 | /// 4088 bytes, and an inline array that size is a third of the whole |
| 295 | 294 | /// budget on the `Encoder` that a caller holds by value. |
| 296 | 295 | silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>, |
| 297 | - /// [`Encoder::set_libopus_input_alignment`]. | |
| 298 | - align_input: bool, | |
| 299 | 296 | filter: InputFilter, |
| 300 | 297 | /// Scratch space for the filter's output, sized once. |
| 301 | 298 | hp_buf: Vec<f32>, |
| @@ -441,7 +438,6 @@ impl Encoder { | ||
| 441 | 438 | mode: None, |
| 442 | 439 | silk: None, |
| 443 | 440 | silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]), |
| 444 | - align_input: application != Application::LowDelay, | |
| 445 | 441 | filter: InputFilter::new(), |
| 446 | 442 | hp_buf: Vec::new(), |
| 447 | 443 | delay_buffer: vec![0.0; encoder_buffer(sample_rate) * channels], |
| @@ -516,65 +512,13 @@ impl Encoder { | ||
| 516 | 512 | /// libopus's `delay_compensation` when the alignment is on. |
| 517 | 513 | fn celt_look_ahead_48k(&self) -> usize { |
| 518 | 514 | CELT_OVERLAP_48K |
| 519 | - + if self.align_input { | |
| 515 | + + if self.application != Application::LowDelay { | |
| 520 | 516 | CELT_DELAY_COMP_48K |
| 521 | 517 | } else { |
| 522 | 518 | 0 |
| 523 | 519 | } |
| 524 | 520 | } |
| 525 | 521 | |
| 526 | - /// On by default except for [`Application::LowDelay`], as in libopus: the | |
| 527 | - /// SILK layer's own delay is 312 samples, and only an aligned CELT layer | |
| 528 | - /// keeps CELT, SILK and hybrid frames of one stream at the same delay. | |
| 529 | - /// | |
| 530 | - /// Puts our CELT analysis window exactly where libopus's is: the layer is | |
| 531 | - /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at | |
| 532 | - /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through | |
| 533 | - /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell | |
| 534 | - /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band | |
| 535 | - /// log-energies become | |
| 536 | - /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against | |
| 537 | - /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight | |
| 538 | - /// within .0006 (the unaligned encoder is .06-.21 apart). | |
| 539 | - /// | |
| 540 | - /// It ships OFF because the 12-row library gate rejects it, and because | |
| 541 | - /// re-tuning the constants that were fitted on the misaligned spectrum | |
| 542 | - /// does not rescue it. Against the shipped rows | |
| 543 | - /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio: | |
| 544 | - /// | |
| 545 | - /// | arm | better | worse (blocking) | | |
| 546 | - /// |---|---|---| | |
| 547 | - /// | 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 | | |
| 548 | - /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 | | |
| 549 | - /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) | | |
| 550 | - /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows | | |
| 551 | - /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 | | |
| 552 | - /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 | | |
| 553 | - /// | + 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 | | |
| 554 | - /// | + 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 | | |
| 555 | - /// | |
| 556 | - /// The best aligned arm on the KEEP rule is the delay alone without | |
| 557 | - /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a | |
| 558 | - /// in the blocking set too. | |
| 559 | - /// | |
| 560 | - /// The last row is the one that was expected to rescue this: libopus's | |
| 561 | - /// actual operating point is the aligned spectrum *with* `analysis->valid` | |
| 562 | - /// true, and running the real analysis (`crates/ec-opus/src/analysis.rs`, | |
| 563 | - /// `music_prob` matching a patched-libopus trace to .001) moves reell@64 | |
| 564 | - /// 2.697→1.865, reell@96 4.499→3.986, reelo@64 1.510→1.123 and her@64 | |
| 565 | - /// 1.103→.952 — the largest movement any arm has produced on those rows — | |
| 566 | - /// and still leaves the same seven rows worse. | |
| 567 | - /// | |
| 568 | - /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and | |
| 569 | - /// no arm moves any of those rows back towards its shipped value, so the | |
| 570 | - /// misfit is not one of the swept constants. Turning this on also costs | |
| 571 | - /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame | |
| 572 | - /// becomes 312, not 120, and the Ogg pre-skip must follow it. | |
| 573 | - pub fn set_libopus_input_alignment(&mut self, on: bool) { | |
| 574 | - self.align_input = on; | |
| 575 | - self.filter = InputFilter::new(); | |
| 576 | - } | |
| 577 | - | |
| 578 | 522 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the |
| 579 | 523 | /// bitrate, the application and the input's Nyquist. |
| 580 | 524 | pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) { |
| @@ -1929,7 +1873,7 @@ impl Encoder { | ||
| 1929 | 1873 | } |
| 1930 | 1874 | |
| 1931 | 1875 | fn total_buffer(&self) -> usize { |
| 1932 | - if self.align_input { | |
| 1876 | + if self.application != Application::LowDelay { | |
| 1933 | 1877 | self.sample_rate as usize / 250 |
| 1934 | 1878 | } else { |
| 1935 | 1879 | 0 |
crates/ec-opus/src/lib.rsmodified+2 -28
| @@ -76,7 +76,7 @@ pub mod range; | ||
| 76 | 76 | pub mod silk; |
| 77 | 77 | pub(crate) mod silk_fix; |
| 78 | 78 | pub(crate) mod silk_flp; |
| 79 | -mod stack_budget; | |
| 79 | +pub(crate) mod silk_tables; | |
| 80 | 80 | |
| 81 | 81 | pub use celt::CeltDecoder; |
| 82 | 82 | pub use encoder::{Application, Encoder}; |
| @@ -103,7 +103,6 @@ pub struct Decoder { | ||
| 103 | 103 | /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder` |
| 104 | 104 | /// costs a caller taking one BY VALUE from `Decoder::new`. It is the |
| 105 | 105 | /// decoder's largest field and its only large one; `celt` is 1448. |
| 106 | - /// `Stack`: crate::stack_budget. | |
| 107 | 106 | silk: Box<SilkDecoder>, |
| 108 | 107 | /// The CELT overlap window, reused for redundancy cross-fades. |
| 109 | 108 | celt_window: Vec<f32>, |
| @@ -120,30 +119,9 @@ pub struct Decoder { | ||
| 120 | 119 | range_final: u32, |
| 121 | 120 | /// Samples per channel of the last packet, the default concealment length. |
| 122 | 121 | last_packet_size: usize, |
| 123 | - /// Test hook: drop the (CELT, SILK) layer's output before the sum. | |
| 124 | - debug_mute: (bool, bool), | |
| 125 | 122 | } |
| 126 | 123 | |
| 127 | 124 | impl Decoder { |
| 128 | - /// Test hook, not for production use: silences the CELT and/or SILK | |
| 129 | - /// layer's contribution to the output (the decoder state still advances) | |
| 130 | - /// so a hybrid packet's two layers can be measured one at a time. | |
| 131 | - #[doc(hidden)] | |
| 132 | - pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) { | |
| 133 | - self.debug_mute = (celt, silk); | |
| 134 | - } | |
| 135 | - | |
| 136 | - /// Decodes with the RFC 6716 reconstruction instead of the RFC 8251 one | |
| 137 | - /// (the default). Needed only to reproduce the RFC 6716 reference vectors. | |
| 138 | - pub fn set_legacy_rfc6716(&mut self, on: bool) { | |
| 139 | - self.celt.set_legacy_rfc6716(on); | |
| 140 | - } | |
| 141 | - | |
| 142 | - /// Facts from the last decoded frame's CELT layer (diagnostic). | |
| 143 | - pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag { | |
| 144 | - self.celt.last_diag() | |
| 145 | - } | |
| 146 | - | |
| 147 | 125 | /// A decoder for `channels` channels at `sample_rate`, which must be one of |
| 148 | 126 | /// 8000, 12000, 16000, 24000 or 48000 Hz. |
| 149 | 127 | pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> { |
| @@ -181,7 +159,6 @@ impl Decoder { | ||
| 181 | 159 | prev_redundancy: false, |
| 182 | 160 | range_final: 0, |
| 183 | 161 | last_packet_size: 960 / downsample, |
| 184 | - debug_mute: (false, false), | |
| 185 | 162 | }) |
| 186 | 163 | } |
| 187 | 164 | |
| @@ -515,10 +492,7 @@ impl Decoder { | ||
| 515 | 492 | } |
| 516 | 493 | |
| 517 | 494 | // Sum the two layers. |
| 518 | - if self.debug_mute.0 { | |
| 519 | - out.fill(0.0); | |
| 520 | - } | |
| 521 | - if mode != Mode::Celt && !self.debug_mute.1 { | |
| 495 | + if mode != Mode::Celt { | |
| 522 | 496 | for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { |
| 523 | 497 | *o += *s as f32 * (1.0 / 32768.0); |
| 524 | 498 | } |
crates/ec-opus/src/silk.rsmodified+1 -6
| @@ -27,12 +27,7 @@ use ec_core::Result; | ||
| 27 | 27 | use crate::range::RangeDecoder; |
| 28 | 28 | pub(crate) use crate::silk_fix::*; |
| 29 | 29 | |
| 30 | -pub(crate) mod tables { | |
| 31 | - #![allow(clippy::all)] | |
| 32 | - include!("silk_tables.rs"); | |
| 33 | -} | |
| 34 | - | |
| 35 | -use tables::*; | |
| 30 | +use crate::silk_tables::*; | |
| 36 | 31 | |
| 37 | 32 | pub(crate) const MAX_LPC_ORDER: usize = 16; |
| 38 | 33 | pub(crate) const LTP_ORDER: usize = 5; |
crates/ec-opus/src/silk_flp/api.rsmodified+1 -1
| @@ -10,7 +10,7 @@ use super::stereo::{StereoEncState, stereo_encode_mid_only, stereo_encode_pred, | ||
| 10 | 10 | use super::vad::vad_init; |
| 11 | 11 | use super::*; |
| 12 | 12 | use crate::range::RangeEncoder; |
| 13 | -use crate::silk::tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10}; | |
| 13 | +use crate::silk_tables::{LBRR_FLAGS_2_ICDF, LBRR_FLAGS_3_ICDF, QUANTIZATION_OFFSETS_Q10}; | |
| 14 | 14 | use crate::silk_fix::{lin2log, rshift_round, sat16, smlawb, smulwb}; |
| 15 | 15 | |
| 16 | 16 | macro_rules! fix_const { |
crates/ec-opus/src/silk_flp/encode.rsmodified+1 -1
| @@ -8,7 +8,7 @@ use super::shape::noise_shape_analysis; | ||
| 8 | 8 | use super::vad::vad_get_sa_q8; |
| 9 | 9 | use super::*; |
| 10 | 10 | use crate::range::RangeEncoder; |
| 11 | -use crate::silk::tables::*; | |
| 11 | +use crate::silk_tables::*; | |
| 12 | 12 | use crate::silk::{gains_dequant, nlsf_cb, nlsf_unpack}; |
| 13 | 13 | use crate::silk_fix::*; |
| 14 | 14 |
crates/ec-opus/src/silk_flp/nlsf.rsmodified+1 -1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | //! `silk/NLSF_del_dec_quant.c`, `silk/interpolate.c`, NLSF parts of `wrappers_FLP.c`. |
| 3 | 3 | |
| 4 | 4 | use super::*; |
| 5 | -use crate::silk::tables::LSFCOSTAB_FIX_Q12; | |
| 5 | +use crate::silk_tables::LSFCOSTAB_FIX_Q12; | |
| 6 | 6 | use crate::silk::{ |
| 7 | 7 | NlsfCodebook, nlsf_cb, nlsf_decode, nlsf_stabilize, nlsf_unpack, nlsf_vq_weights_laroia, nlsf2a, |
| 8 | 8 | }; |
crates/ec-opus/src/silk_flp/nsq.rsmodified+1 -1
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | //! `silk/NSQ.c`, `silk/NSQ_del_dec.c`, `silk_NSQ_wrapper_FLP` from `wrappers_FLP.c`. |
| 2 | 2 | |
| 3 | 3 | use super::*; |
| 4 | -use crate::silk::tables::{LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10}; | |
| 4 | +use crate::silk_tables::{LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10}; | |
| 5 | 5 | use crate::silk_fix::*; |
| 6 | 6 | |
| 7 | 7 | const QUANT_LEVEL_ADJUST_Q10: i32 = 80; |
crates/ec-opus/src/silk_flp/pitch.rsmodified+1 -1
| @@ -5,7 +5,7 @@ use super::sigproc::{ | ||
| 5 | 5 | lpc_analysis_filter, schur, silk_log2, |
| 6 | 6 | }; |
| 7 | 7 | use super::*; |
| 8 | -use crate::silk::tables::{ | |
| 8 | +use crate::silk_tables::{ | |
| 9 | 9 | CB_LAGS_STAGE2, CB_LAGS_STAGE2_10_MS, CB_LAGS_STAGE3, CB_LAGS_STAGE3_10_MS, |
| 10 | 10 | }; |
| 11 | 11 | use crate::silk_fix::{rshift_round, sat16, smlawb, smulbb, smulwb}; |
crates/ec-opus/src/silk_flp/pred.rsmodified+1 -1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | use super::nlsf::{a2nlsf_flp, interpolate, nlsf2a_flp, process_nlsfs_flp}; |
| 4 | 4 | use super::sigproc::{energy, inner_product, lpc_analysis_filter}; |
| 5 | 5 | use super::*; |
| 6 | -use crate::silk::tables::{ | |
| 6 | +use crate::silk_tables::{ | |
| 7 | 7 | LTP_GAIN_VQ_0, LTP_GAIN_VQ_1, LTP_GAIN_VQ_2, LTPSCALES_TABLE_Q14, QUANTIZATION_OFFSETS_Q10, |
| 8 | 8 | }; |
| 9 | 9 | use crate::silk_fix::{add_pos_sat32, lin2log, log2lin, smlawb, smulbb, smulwb}; |
crates/ec-opus/src/silk_flp/stereo.rsmodified+1 -1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | |
| 4 | 4 | use super::*; |
| 5 | 5 | use crate::range::RangeEncoder; |
| 6 | -use crate::silk::tables::{ | |
| 6 | +use crate::silk_tables::{ | |
| 7 | 7 | STEREO_ONLY_CODE_MID_ICDF, STEREO_PRED_JOINT_ICDF, STEREO_PRED_QUANT_Q13, UNIFORM3_ICDF, |
| 8 | 8 | UNIFORM5_ICDF, |
| 9 | 9 | }; |
crates/ec-opus/src/stack_budget.rsdeleted+0 -864
| @@ -1,864 +0,0 @@ | ||
| 1 | -#![cfg(test)] | |
| 2 | -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. | |
| 3 | -//! | |
| 4 | -//! # The class | |
| 5 | -//! | |
| 6 | -//! A large struct returned BY VALUE from a public constructor is a stack cost, | |
| 7 | -//! not a heap cost, and the cost is paid by the CALLER. `Encoder` is the | |
| 8 | -//! workspace's largest live instance of this class: it was **87,024 bytes** by | |
| 9 | -//! value -- ten and a half times the budget below -- because six | |
| 10 | -//! SILK encoder slots (79,176 bytes together) and a 3,831-byte SILK packet scratch buffer | |
| 11 | -//! (`MAX_SILK_PACKET_BYTES = 1 + 1 + 2 * 2 + 3 * 1275`) sat INLINE on a type | |
| 12 | -//! `Encoder::new` hands back by value. `Decoder` was 7,576, 92.5% of the | |
| 13 | -//! budget, with a 6,304-byte `SilkDecoder` inline. | |
| 14 | -//! | |
| 15 | -//! Both are boxed now (82,952 bytes moved off the stack onto the heap: the | |
| 16 | -//! `Box`ed SILK layer, `silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>`, and | |
| 17 | -//! `Decoder::silk: Box<SilkDecoder>`), and this module is what stops the | |
| 18 | -//! numbers from walking back. | |
| 19 | -//! | |
| 20 | -//! # Why this module exists | |
| 21 | -//! | |
| 22 | -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every type in this crate a public | |
| 23 | -//! `fn` can return or take by value, with a measured `size_of` recorded as | |
| 24 | -//! of this commit. [`the_measured_inventory_is_accurate`] fails if a size | |
| 25 | -//! moves, so the table cannot rot into a list of stale small numbers. | |
| 26 | -//! 2. [`STACK_BUDGET`] is the bound, and | |
| 27 | -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for | |
| 28 | -//! every budgeted row, so a regression reds naming the type that caused it. | |
| 29 | -//! 3. [`the_crate_private_silk_encoders_stay_behind_a_box`] pins the three | |
| 30 | -//! `Box` spellings that moved the 87 KB off the stack, with a negative | |
| 31 | -//! control so the scan cannot be matching a doc comment. | |
| 32 | -//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the | |
| 33 | -//! capability arm: it really constructs `Encoder::new` and `Decoder::new` on | |
| 34 | -//! a deliberately tight thread, so the old layout ABORTS THE PROCESS rather | |
| 35 | -//! than quietly costing margin. Red/green in milliseconds. | |
| 36 | -//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's | |
| 37 | -//! teeth against NEW types: a source scan re-derives the set of by-value | |
| 38 | -//! public returns from the crate source, so a lane that adds a 40 KB struct | |
| 39 | -//! to a `pub fn` return reds here until it is measured and listed. | |
| 40 | -//! [`the_inventory_scan_is_not_vacuous`] is its control, and | |
| 41 | -//! [`every_by_value_module_is_scanned`] keeps the scan's file list from | |
| 42 | -//! falling behind a new `mod` in `lib.rs`. | |
| 43 | -//! | |
| 44 | -//! # The bound, and why this number | |
| 45 | -//! | |
| 46 | -//! [`STACK_BUDGET`] = 8192 bytes (8 KiB), the same number ec-av1's identical | |
| 47 | -//! sweep uses, and it is bounded from BOTH sides by measurement: | |
| 48 | -//! | |
| 49 | -//! * **The smallest stack a caller can hand this crate is 2 MiB** -- libtest's | |
| 50 | -//! default test thread, and what `std::thread::Builder::new()` gives a | |
| 51 | -//! caller who does not ask for a size. This workspace's | |
| 52 | -//! `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, which hides | |
| 53 | -//! the problem from its own runs; a library consumer gets no | |
| 54 | -//! `.cargo/config.toml` and no such cover. | |
| 55 | -//! * **The deepest PUBLIC by-value chain is 2** | |
| 56 | -//! ([`DEEPEST_PUBLIC_CHAIN`]): `MultistreamDecoder::with_rate` -> | |
| 57 | -//! `MultistreamDecoder::try_with_rate` (`multistream.rs:47` -> `:63`), both | |
| 58 | -//! handing back a `MultistreamDecoder` by value, so both frames hold a | |
| 59 | -//! return slot at once. `Encoder::new` (`encoder.rs:166`) and `Decoder::new` | |
| 60 | -//! (`lib.rs:136`) are ONE level each -- neither delegates to an inner | |
| 61 | -//! constructor of its own type, they build the struct literal inline -- so | |
| 62 | -//! the worst live set of by-value return slots is two frames, and the test | |
| 63 | -//! asserts `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB`. | |
| 64 | -//! * **The budget applies to types a public `fn` returns by value.** The | |
| 65 | -//! `Box`ed payloads are listed with `public: false` and measured, but not | |
| 66 | -//! budgeted, because the budget's job is to bound what a CALLER can be made | |
| 67 | -//! to own and none of them is reachable that way any more -- every field | |
| 68 | -//! that holds one is a `Box`, which | |
| 69 | -//! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. | |
| 70 | -//! | |
| 71 | -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 2,936 | |
| 72 | -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 2936 = 5,872` bytes -- | |
| 73 | -//! **0.28%** of a 2 MiB thread -- and the budget sits 2.79x above the | |
| 74 | -//! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the | |
| 75 | -//! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect | |
| 76 | -//! and the near-miss both red by a factor rather than by a hair. | |
| 77 | -//! | |
| 78 | -//! **What it does not claim.** `size_of` is layout, not stack depth: the | |
| 79 | -//! measured stack/size ratio on a by-value constructor here is several times | |
| 80 | -//! over, because the constructor's own frames add on top of the return slot. | |
| 81 | -//! That residual is why | |
| 82 | -//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for | |
| 83 | -//! real instead of trusting the arithmetic. | |
| 84 | - | |
| 85 | -use crate::Decoder; | |
| 86 | -use crate::encoder::Encoder; | |
| 87 | - | |
| 88 | -/// The per-type ceiling for a type a CALLER can be made to hold by value, in | |
| 89 | -/// bytes. See the module docs for the derivation; it is two-sided, and both | |
| 90 | -/// sides are measured. | |
| 91 | -pub(crate) const STACK_BUDGET: usize = 8192; | |
| 92 | - | |
| 93 | -/// The deepest PUBLIC by-value constructor chain in this crate, counted from | |
| 94 | -/// the source: `MultistreamDecoder::with_rate` -> `MultistreamDecoder:: | |
| 95 | -/// try_with_rate` is two, both returning the same type by value so both frames | |
| 96 | -/// hold a `MultistreamDecoder` return slot at once. `Encoder::new` and | |
| 97 | -/// `Decoder::new` are one level each -- neither delegates to an inner | |
| 98 | -/// constructor of its own type. The budget is checked against two, the worse | |
| 99 | -/// of the chains. | |
| 100 | -const DEEPEST_PUBLIC_CHAIN: usize = 2; | |
| 101 | - | |
| 102 | -/// Every type in this crate a public `fn` can hand back BY VALUE (or take by | |
| 103 | -/// value in a public signature), with the `size_of` measured at the commit | |
| 104 | -/// that wrote this table. `None` means "not yet measured", which | |
| 105 | -/// [`the_measured_inventory_is_accurate`] rejects. | |
| 106 | -/// | |
| 107 | -/// The third column names the return path, so a reader can see why a type is | |
| 108 | -/// here rather than a coincidence of the type system. `false` in that column | |
| 109 | -/// means the type is NOT budgeted: it is a `Box`ed payload, reachable only | |
| 110 | -/// through a pointer now, and the pin that keeps it that way is | |
| 111 | -/// [`the_crate_private_silk_encoders_stay_behind_a_box`]. | |
| 112 | -pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |
| 113 | - // -- lib.rs ----------------------------------------------------------- | |
| 114 | - ( | |
| 115 | - "Decoder", | |
| 116 | - Some(1568), | |
| 117 | - true, | |
| 118 | - "Decoder::new -> Result<Decoder>. Was 7576, 92.5% of the budget, \ | |
| 119 | - because a 6304-byte SilkDecoder sat inline; that field is now a Box", | |
| 120 | - ), | |
| 121 | - // -- encoder.rs ------------------------------------------------------- | |
| 122 | - ( | |
| 123 | - "Encoder", | |
| 124 | - Some(2936), | |
| 125 | - true, | |
| 126 | - "Encoder::new -> Result<Encoder>. Was 87024, 10.62x the budget: six \ | |
| 127 | - inline SILK encoder slots (79176 together) and an inline 3831-byte \ | |
| 128 | - silk_buf", | |
| 129 | - ), | |
| 130 | - ( | |
| 131 | - "Application", | |
| 132 | - Some(1), | |
| 133 | - true, | |
| 134 | - "Encoder::new(.., application: Application) takes it by value and \ | |
| 135 | - stores it inline in every Encoder", | |
| 136 | - ), | |
| 137 | - // -- celt.rs ---------------------------------------------------------- | |
| 138 | - ( | |
| 139 | - "CeltDecoder", | |
| 140 | - Some(1440), | |
| 141 | - true, | |
| 142 | - "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ | |
| 143 | - value into Decoder::celt", | |
| 144 | - ), | |
| 145 | - // -- multistream.rs / multistream_enc.rs ------------------------------ | |
| 146 | - ( | |
| 147 | - "MultistreamDecoder", | |
| 148 | - Some(120), | |
| 149 | - true, | |
| 150 | - "MultistreamDecoder::with_rate / try_with_rate, the crate's deepest \ | |
| 151 | - public by-value chain: with_rate -> try_with_rate -> Result<..>", | |
| 152 | - ), | |
| 153 | - ( | |
| 154 | - "MultistreamEncoder", | |
| 155 | - Some(88), | |
| 156 | - true, | |
| 157 | - "MultistreamEncoder::surround_5_1 -> Result<MultistreamEncoder>", | |
| 158 | - ), | |
| 159 | - // -- packet.rs -------------------------------------------------------- | |
| 160 | - ( | |
| 161 | - "Packet", | |
| 162 | - Some(40), | |
| 163 | - true, | |
| 164 | - "Packet::parse -> Result<Packet<'a>>", | |
| 165 | - ), | |
| 166 | - ("Toc", Some(3), true, "Toc::new(byte: u8) -> Toc"), | |
| 167 | - ( | |
| 168 | - "Mode", | |
| 169 | - Some(1), | |
| 170 | - true, | |
| 171 | - "Toc::mode(self) -> Mode; also stored inline in Decoder::prev_mode", | |
| 172 | - ), | |
| 173 | - ( | |
| 174 | - "Bandwidth", | |
| 175 | - Some(1), | |
| 176 | - true, | |
| 177 | - "Toc::bandwidth(self) -> Bandwidth; also stored inline in \ | |
| 178 | - Encoder::bandwidth", | |
| 179 | - ), | |
| 180 | - // -- range.rs --------------------------------------------------------- | |
| 181 | - ( | |
| 182 | - "RangeEncoder", | |
| 183 | - Some(80), | |
| 184 | - true, | |
| 185 | - "RangeEncoder::new() -> Self; stored inline in Encoder::range", | |
| 186 | - ), | |
| 187 | - ( | |
| 188 | - "RangeDecoder", | |
| 189 | - Some(56), | |
| 190 | - true, | |
| 191 | - "RangeDecoder::new(buf) -> RangeDecoder<'a>", | |
| 192 | - ), | |
| 193 | - ( | |
| 194 | - "EncSnapshot", | |
| 195 | - Some(48), | |
| 196 | - true, | |
| 197 | - "RangeEncoder::snapshot(&self) -> EncSnapshot", | |
| 198 | - ), | |
| 199 | - // -- silk.rs ---------------------------------------------------------- | |
| 200 | - ( | |
| 201 | - "SilkDecoder", | |
| 202 | - Some(6512), | |
| 203 | - true, | |
| 204 | - "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \ | |
| 205 | - root, so 6512 bytes is a caller's by-value cost TODAY even though \ | |
| 206 | - Decoder::new moves it straight into a Box. At 77% of the budget it \ | |
| 207 | - is the LARGEST budgeted row in the table, and the one that says how \ | |
| 208 | - little headroom the budget would have left if it had stayed inline", | |
| 209 | - ), | |
| 210 | - ( | |
| 211 | - "SilkDecIndices", | |
| 212 | - Some(104), | |
| 213 | - true, | |
| 214 | - "SilkDecoder::last_indices(&self) -> SilkDecIndices", | |
| 215 | - ), | |
| 216 | - // -- analysis.rs (crate-private) -------------------------------------- | |
| 217 | - ( | |
| 218 | - "TonalityAnalysis", | |
| 219 | - Some(2096), | |
| 220 | - false, | |
| 221 | - "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ | |
| 222 | - INLINE in Encoder::analysis. 2096 is inside the budget and the field \ | |
| 223 | - is reached only through an Encoder that is itself budgeted, so it is \ | |
| 224 | - measured here rather than pinned behind a Box", | |
| 225 | - ), | |
| 226 | - ( | |
| 227 | - "AnalysisInfo", | |
| 228 | - Some(60), | |
| 229 | - false, | |
| 230 | - "analysis::AnalysisInfo::default() -> Self, stored inline in \ | |
| 231 | - Encoder::info", | |
| 232 | - ), | |
| 233 | -]; | |
| 234 | - | |
| 235 | -/// The live `size_of` for every inventoried type, keyed BY NAME. | |
| 236 | -/// | |
| 237 | -/// Keyed rather than positional on purpose: `Mode`, `Bandwidth` and | |
| 238 | -/// `Application` are all 1 byte, and a row inserted into [`BY_VALUE_TYPES`] | |
| 239 | -/// without a matching insert here would zip cleanly and assert the wrong | |
| 240 | -/// type's size against the wrong recorded one. A name key makes that mistake | |
| 241 | -/// loud instead. | |
| 242 | -fn measured_by_name() -> Vec<(&'static str, usize)> { | |
| 243 | - vec![ | |
| 244 | - ("Decoder", std::mem::size_of::<Decoder>()), | |
| 245 | - ("Encoder", std::mem::size_of::<Encoder>()), | |
| 246 | - ( | |
| 247 | - "Application", | |
| 248 | - std::mem::size_of::<crate::encoder::Application>(), | |
| 249 | - ), | |
| 250 | - ( | |
| 251 | - "CeltDecoder", | |
| 252 | - std::mem::size_of::<crate::celt::CeltDecoder>(), | |
| 253 | - ), | |
| 254 | - ( | |
| 255 | - "MultistreamDecoder", | |
| 256 | - std::mem::size_of::<crate::multistream::MultistreamDecoder>(), | |
| 257 | - ), | |
| 258 | - ( | |
| 259 | - "MultistreamEncoder", | |
| 260 | - std::mem::size_of::<crate::multistream_enc::MultistreamEncoder>(), | |
| 261 | - ), | |
| 262 | - ( | |
| 263 | - "Packet", | |
| 264 | - std::mem::size_of::<crate::packet::Packet<'static>>(), | |
| 265 | - ), | |
| 266 | - ("Toc", std::mem::size_of::<crate::packet::Toc>()), | |
| 267 | - ("Mode", std::mem::size_of::<crate::packet::Mode>()), | |
| 268 | - ("Bandwidth", std::mem::size_of::<crate::packet::Bandwidth>()), | |
| 269 | - ( | |
| 270 | - "RangeEncoder", | |
| 271 | - std::mem::size_of::<crate::range::RangeEncoder>(), | |
| 272 | - ), | |
| 273 | - ( | |
| 274 | - "RangeDecoder", | |
| 275 | - std::mem::size_of::<crate::range::RangeDecoder<'static>>(), | |
| 276 | - ), | |
| 277 | - ( | |
| 278 | - "EncSnapshot", | |
| 279 | - std::mem::size_of::<crate::range::EncSnapshot>(), | |
| 280 | - ), | |
| 281 | - ( | |
| 282 | - "SilkDecoder", | |
| 283 | - std::mem::size_of::<crate::silk::SilkDecoder>(), | |
| 284 | - ), | |
| 285 | - ( | |
| 286 | - "SilkDecIndices", | |
| 287 | - std::mem::size_of::<crate::silk::SilkDecIndices>(), | |
| 288 | - ), | |
| 289 | - ( | |
| 290 | - "TonalityAnalysis", | |
| 291 | - std::mem::size_of::<crate::analysis::TonalityAnalysis>(), | |
| 292 | - ), | |
| 293 | - ( | |
| 294 | - "AnalysisInfo", | |
| 295 | - std::mem::size_of::<crate::analysis::AnalysisInfo>(), | |
| 296 | - ), | |
| 297 | - ] | |
| 298 | -} | |
| 299 | - | |
| 300 | -/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] | |
| 301 | -/// constructs on. | |
| 302 | -/// | |
| 303 | -/// 256 KiB: an eighth of what an unconfigured caller gives this crate, and | |
| 304 | -/// **5.3x** the deepest need measured in a debug build on the current layout | |
| 305 | -/// (the constructors complete at 48 KiB and abort at 32 KiB) while sitting | |
| 306 | -/// **2.1x below** the pre-fix layout's own threshold, which completes at | |
| 307 | -/// 544 KiB and aborts at 528 KiB. That gap is what makes this a capability | |
| 308 | -/// arm rather than a formality: at 256 KiB the layout this crate used to | |
| 309 | -/// ship ABORTS THE PROCESS. The sweep is reproducible with | |
| 310 | -/// `EC_OPUS_TIGHT_STACK_BYTES`. | |
| 311 | -const TIGHT_STACK: usize = 256 * 1024; | |
| 312 | - | |
| 313 | -#[cfg(test)] | |
| 314 | -mod tests { | |
| 315 | - use super::{ | |
| 316 | - BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, | |
| 317 | - }; | |
| 318 | - use crate::Decoder; | |
| 319 | - use crate::encoder::Encoder; | |
| 320 | - | |
| 321 | - /// Return types that are not a by-value copy of anything the caller has to | |
| 322 | - /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the | |
| 323 | - /// stack), or a primitive. `Self` is a by-value copy of the impl's type, | |
| 324 | - /// which the inventory rows already cover, so it is exempt from the scan | |
| 325 | - /// and not from the table. | |
| 326 | - const THIN: &[&str] = &[ | |
| 327 | - "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", | |
| 328 | - "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", | |
| 329 | - "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", | |
| 330 | - ]; | |
| 331 | - | |
| 332 | - /// The type name a `pub fn` line returns BY VALUE, or `None` when the line | |
| 333 | - /// returns a pointer, a `Vec`, a primitive, or nothing. | |
| 334 | - /// | |
| 335 | - /// One function, shared by the sweep and its control, so the control | |
| 336 | - /// cannot pass while the sweep's copy of the logic rotted. | |
| 337 | - fn by_value_return_name(line: &str) -> Option<String> { | |
| 338 | - let trimmed = line.trim_start(); | |
| 339 | - if !trimmed.starts_with("pub fn ") { | |
| 340 | - return None; | |
| 341 | - } | |
| 342 | - let arrow = line.find("->")?; | |
| 343 | - let rest = &line[arrow + 2..]; | |
| 344 | - let end = rest.find('{').unwrap_or(rest.len()); | |
| 345 | - let ret = rest[..end].trim(); | |
| 346 | - if ret.is_empty() { | |
| 347 | - return None; | |
| 348 | - } | |
| 349 | - // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is | |
| 350 | - // not a shape this crate uses, and flagging one as uninventoried is | |
| 351 | - // the safe direction to be wrong in. | |
| 352 | - let inner = { | |
| 353 | - let t = ret | |
| 354 | - .strip_prefix("Result<") | |
| 355 | - .or_else(|| ret.strip_prefix("Option<")) | |
| 356 | - .unwrap_or(ret); | |
| 357 | - t.split('>').next().unwrap_or(t) | |
| 358 | - }; | |
| 359 | - // Drop the error type and any lifetime or generic argument: | |
| 360 | - // `Result<Decoder, Error>`, `RangeDecoder<'a>` and `Packet<'a>` are | |
| 361 | - // all the bare name for this purpose. Splitting on the comma is | |
| 362 | - // load-bearing: a matcher that cut only at `>` would read | |
| 363 | - // `Result<Decoder, Error>` as the name "Decoder, Error". | |
| 364 | - // `the_inventory_scan_is_not_vacuous` covers exactly that, which is | |
| 365 | - // why the control is not optional. | |
| 366 | - let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); | |
| 367 | - if name.is_empty() || THIN.contains(&name) { | |
| 368 | - return None; | |
| 369 | - } | |
| 370 | - // A generic parameter, not a concrete type. | |
| 371 | - if !name.chars().next().is_some_and(char::is_uppercase) { | |
| 372 | - return None; | |
| 373 | - } | |
| 374 | - Some(name.to_string()) | |
| 375 | - } | |
| 376 | - | |
| 377 | - /// The source files the by-value scan reads. Every module `lib.rs` | |
| 378 | - /// declares, plus `lib.rs` itself (which is where `Decoder` and | |
| 379 | - /// `Encoder::new`'s crate-root sibling live) and this module. | |
| 380 | - const FILES: &[(&str, &str)] = &[ | |
| 381 | - ("analysis.rs", include_str!("analysis.rs")), | |
| 382 | - ("celt.rs", include_str!("celt.rs")), | |
| 383 | - ("celt_flp/bands.rs", include_str!("celt_flp/bands.rs")), | |
| 384 | - ("celt_flp/enc.rs", include_str!("celt_flp/enc.rs")), | |
| 385 | - ("celt_flp/enc_an.rs", include_str!("celt_flp/enc_an.rs")), | |
| 386 | - ("celt_flp/fft.rs", include_str!("celt_flp/fft.rs")), | |
| 387 | - ("celt_flp/mod.rs", include_str!("celt_flp/mod.rs")), | |
| 388 | - ("celt_flp/pitch.rs", include_str!("celt_flp/pitch.rs")), | |
| 389 | - ( | |
| 390 | - "celt_flp/quant_bands.rs", | |
| 391 | - include_str!("celt_flp/quant_bands.rs"), | |
| 392 | - ), | |
| 393 | - ("celt_flp/tables.rs", include_str!("celt_flp/tables.rs")), | |
| 394 | - ("celt_flp/vq.rs", include_str!("celt_flp/vq.rs")), | |
| 395 | - ("encoder.rs", include_str!("encoder.rs")), | |
| 396 | - ("lib.rs", include_str!("lib.rs")), | |
| 397 | - ("multistream.rs", include_str!("multistream.rs")), | |
| 398 | - ("multistream_enc.rs", include_str!("multistream_enc.rs")), | |
| 399 | - ("ogg.rs", include_str!("ogg.rs")), | |
| 400 | - ("packet.rs", include_str!("packet.rs")), | |
| 401 | - ("range.rs", include_str!("range.rs")), | |
| 402 | - ("silk.rs", include_str!("silk.rs")), | |
| 403 | - ("silk_fix.rs", include_str!("silk_fix.rs")), | |
| 404 | - ("silk_flp/api.rs", include_str!("silk_flp/api.rs")), | |
| 405 | - ("silk_flp/encode.rs", include_str!("silk_flp/encode.rs")), | |
| 406 | - ("silk_flp/mod.rs", include_str!("silk_flp/mod.rs")), | |
| 407 | - ("silk_flp/nlsf.rs", include_str!("silk_flp/nlsf.rs")), | |
| 408 | - ("silk_flp/nsq.rs", include_str!("silk_flp/nsq.rs")), | |
| 409 | - ("silk_flp/opus.rs", include_str!("silk_flp/opus.rs")), | |
| 410 | - ("silk_flp/pitch.rs", include_str!("silk_flp/pitch.rs")), | |
| 411 | - ("silk_flp/pred.rs", include_str!("silk_flp/pred.rs")), | |
| 412 | - ( | |
| 413 | - "silk_flp/resampler.rs", | |
| 414 | - include_str!("silk_flp/resampler.rs"), | |
| 415 | - ), | |
| 416 | - ("silk_flp/shape.rs", include_str!("silk_flp/shape.rs")), | |
| 417 | - ("silk_flp/sigproc.rs", include_str!("silk_flp/sigproc.rs")), | |
| 418 | - ("silk_flp/stereo.rs", include_str!("silk_flp/stereo.rs")), | |
| 419 | - ("silk_flp/vad.rs", include_str!("silk_flp/vad.rs")), | |
| 420 | - ("stack_budget.rs", include_str!("stack_budget.rs")), | |
| 421 | - ]; | |
| 422 | - | |
| 423 | - /// Every module `lib.rs` declares, so the scan's file list cannot silently | |
| 424 | - /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` | |
| 425 | - /// that the scan never reads is exactly the hole this class would come | |
| 426 | - /// back through, so the list is derived, not curated. | |
| 427 | - /// | |
| 428 | - /// `pub(crate) mod foo;` is a module too, and ec-opus has several of them | |
| 429 | - /// (`analysis`, `silk_fix`, `silk_flp`), so the derivation strips the | |
| 430 | - /// visibility parenthesised form as well as the bare `pub`. | |
| 431 | - #[test] | |
| 432 | - fn every_by_value_module_is_scanned() { | |
| 433 | - let lib = include_str!("lib.rs"); | |
| 434 | - let mut declared: Vec<&str> = Vec::new(); | |
| 435 | - for line in lib.lines() { | |
| 436 | - let t = line.trim(); | |
| 437 | - let after_pub = if let Some(rest) = t.strip_prefix("pub(") { | |
| 438 | - // `pub(crate) mod foo;` / `pub(super) mod foo;` | |
| 439 | - rest.split_once(')') | |
| 440 | - .map(|(_, after)| after.trim_start()) | |
| 441 | - .unwrap_or("") | |
| 442 | - } else { | |
| 443 | - t.strip_prefix("pub ").unwrap_or(t) | |
| 444 | - }; | |
| 445 | - let Some(rest) = after_pub.strip_prefix("mod ") else { | |
| 446 | - continue; | |
| 447 | - }; | |
| 448 | - let name = rest.split([';', ' ']).next().unwrap_or(""); | |
| 449 | - if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { | |
| 450 | - declared.push(name); | |
| 451 | - } | |
| 452 | - } | |
| 453 | - assert!( | |
| 454 | - declared.len() > 8, | |
| 455 | - "only {} module declarations parsed out of lib.rs, so the \ | |
| 456 | - derived file list is broken rather than small", | |
| 457 | - declared.len() | |
| 458 | - ); | |
| 459 | - let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect(); | |
| 460 | - let mut missing: Vec<String> = declared | |
| 461 | - .iter() | |
| 462 | - .filter(|d| { | |
| 463 | - !scanned | |
| 464 | - .iter() | |
| 465 | - .any(|s| *s == format!("{d}.rs") || s.starts_with(&format!("{d}/"))) | |
| 466 | - }) | |
| 467 | - .map(|d| (*d).to_string()) | |
| 468 | - .collect(); | |
| 469 | - missing.sort(); | |
| 470 | - assert!( | |
| 471 | - missing.is_empty(), | |
| 472 | - "lib.rs declares modules the by-value scan never reads: {:?}. Add \ | |
| 473 | - them to FILES, or the sweep cannot see a new by-value return that \ | |
| 474 | - lands in one of them.", | |
| 475 | - missing | |
| 476 | - ); | |
| 477 | - } | |
| 478 | - | |
| 479 | - /// The inventory, printed as a sorted table, and checked against the | |
| 480 | - /// types' real sizes. | |
| 481 | - /// | |
| 482 | - /// The print is the instrument: one command reproduces the whole table, | |
| 483 | - /// biggest first, so "what is the largest by-value type in this crate" | |
| 484 | - /// has an answer that is a measurement rather than a grep. | |
| 485 | - /// | |
| 486 | - /// `cargo test -p ec-opus --lib -- stack_budget -- --nocapture` is the | |
| 487 | - /// command, with one wrinkle in THIS repo: `.cargo/config.toml` wraps | |
| 488 | - /// every test binary in `scripts/memguard-runner.sh`, which buffers a | |
| 489 | - /// green run's stdout and prints nothing. The table appears on a failing | |
| 490 | - /// run, or by invoking the built binary directly | |
| 491 | - /// (`target/debug/deps/ec_opus-* stack_budget --nocapture`). | |
| 492 | - /// | |
| 493 | - /// The check reds on ANY change with both numbers. That is deliberate: a | |
| 494 | - /// by-value type that grew raises the question of whether it should have | |
| 495 | - /// been boxed instead, and auto-accepting the new number would answer | |
| 496 | - /// that question by default. | |
| 497 | - #[test] | |
| 498 | - fn the_measured_inventory_is_accurate() { | |
| 499 | - let live = measured_by_name(); | |
| 500 | - assert_eq!( | |
| 501 | - BY_VALUE_TYPES.len(), | |
| 502 | - live.len(), | |
| 503 | - "the inventory names {} types but {} are measured; every row needs \ | |
| 504 | - a measured size or the sweep is a list of hopes", | |
| 505 | - BY_VALUE_TYPES.len(), | |
| 506 | - live.len() | |
| 507 | - ); | |
| 508 | - let mut rows: Vec<(&str, usize)> = live.clone(); | |
| 509 | - rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); | |
| 510 | - eprintln!( | |
| 511 | - "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", | |
| 512 | - rows.len(), | |
| 513 | - STACK_BUDGET / 1024 | |
| 514 | - ); | |
| 515 | - eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET"); | |
| 516 | - for (name, size) in &rows { | |
| 517 | - eprintln!( | |
| 518 | - "{size:>8} {:>6.1}% {name}", | |
| 519 | - *size as f64 * 100.0 / STACK_BUDGET as f64 | |
| 520 | - ); | |
| 521 | - } | |
| 522 | - for (name, recorded, _public, _path) in BY_VALUE_TYPES { | |
| 523 | - let recorded = recorded.expect("every inventory row carries a measured size"); | |
| 524 | - let actual = live | |
| 525 | - .iter() | |
| 526 | - .find(|(n, _)| n == name) | |
| 527 | - .map(|(_, size)| *size) | |
| 528 | - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); | |
| 529 | - assert_eq!( | |
| 530 | - recorded, actual, | |
| 531 | - "{name} is {actual} bytes, the inventory records {recorded}; \ | |
| 532 | - update the table deliberately -- a by-value type that changed \ | |
| 533 | - is a stack cost every caller of its constructor now pays" | |
| 534 | - ); | |
| 535 | - } | |
| 536 | - } | |
| 537 | - | |
| 538 | - /// The bound, asserted BY NAME. A regression in any inventoried type reds | |
| 539 | - /// here naming the type, not "some type is too big". | |
| 540 | - #[test] | |
| 541 | - fn every_by_value_type_fits_the_stack_budget() { | |
| 542 | - let live = measured_by_name(); | |
| 543 | - let mut checked = 0usize; | |
| 544 | - for (name, _, public, path) in BY_VALUE_TYPES { | |
| 545 | - if !public { | |
| 546 | - continue; | |
| 547 | - } | |
| 548 | - checked += 1; | |
| 549 | - let size = live | |
| 550 | - .iter() | |
| 551 | - .find(|(n, _)| n == name) | |
| 552 | - .map(|(_, size)| *size) | |
| 553 | - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); | |
| 554 | - assert!( | |
| 555 | - size <= STACK_BUDGET, | |
| 556 | - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ | |
| 557 | - stack budget ({:.2}x). It is returned by value from {path}, so \ | |
| 558 | - every caller pays it on its own stack, and the constructors \ | |
| 559 | - nest -- one value's size is the multiplier, not the cost. \ | |
| 560 | - Box the large field: Encoder's six SILK slots and silk_buf, \ | |
| 561 | - and Decoder::silk, are Boxed for exactly this reason and \ | |
| 562 | - took Encoder from 87024 bytes to this one.", | |
| 563 | - size as f64 / STACK_BUDGET as f64 | |
| 564 | - ); | |
| 565 | - } | |
| 566 | - assert!( | |
| 567 | - checked >= 10, | |
| 568 | - "only {checked} rows were bound-checked; the budget must apply to \ | |
| 569 | - every type a caller can be made to hold by value" | |
| 570 | - ); | |
| 571 | - // The other half of the derivation, asserted so it cannot rot: the | |
| 572 | - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. | |
| 573 | - let worst = live | |
| 574 | - .iter() | |
| 575 | - .filter(|(n, _)| { | |
| 576 | - BY_VALUE_TYPES | |
| 577 | - .iter() | |
| 578 | - .any(|(row, _, public, _)| row == n && *public) | |
| 579 | - }) | |
| 580 | - .map(|(_, size)| *size) | |
| 581 | - .max() | |
| 582 | - .expect("at least one public row"); | |
| 583 | - assert!( | |
| 584 | - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, | |
| 585 | - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ | |
| 586 | - public by-value return ({worst} B) is {} B, over an eighth of the \ | |
| 587 | - 2 MiB stack an unconfigured caller hands this crate; re-derive \ | |
| 588 | - STACK_BUDGET", | |
| 589 | - DEEPEST_PUBLIC_CHAIN * worst | |
| 590 | - ); | |
| 591 | - } | |
| 592 | - | |
| 593 | - /// The SILK encoders and the SILK packet buffer stay BEHIND A BOX. | |
| 594 | - /// | |
| 595 | - /// The SILK layer, the SILK packet buffer and `Decoder::silk` stay BEHIND | |
| 596 | - /// A BOX. Every field holding one is a `Box`, so no caller can reach them | |
| 597 | - /// by value. What keeps them off the stack is those exact `Box` spellings, | |
| 598 | - /// and THIS is the pin for that -- a source scan over the declarations, | |
| 599 | - /// with a negative control so it cannot be matching a doc comment. | |
| 600 | - /// | |
| 601 | - /// It earned its place, measured: unboxing `silk_buf` takes `Encoder` from | |
| 602 | - /// 4,072 to **7,896** bytes and reds this pin naming | |
| 603 | - /// `encoder.rs::Encoder::silk_buf` and | |
| 604 | - /// [`the_measured_inventory_is_accurate`] naming `Encoder`. Unboxing the | |
| 605 | - /// SILK layer is far larger -- `Encoder` was 87,024 bytes before the | |
| 606 | - /// boxing, 10.62x the budget. | |
| 607 | - #[test] | |
| 608 | - fn the_crate_private_silk_encoders_stay_behind_a_box() { | |
| 609 | - const PINS: &[(&str, &str, &str)] = &[ | |
| 610 | - ( | |
| 611 | - "encoder.rs", | |
| 612 | - "Encoder::silk", | |
| 613 | - "silk: Option<Box<SilkLayer>>", | |
| 614 | - ), | |
| 615 | - ( | |
| 616 | - "encoder.rs", | |
| 617 | - "Encoder::silk_buf", | |
| 618 | - "silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>", | |
| 619 | - ), | |
| 620 | - ("lib.rs", "Decoder::silk", "silk: Box<SilkDecoder>"), | |
| 621 | - ]; | |
| 622 | - const SCANNED: &[(&str, &str)] = &[ | |
| 623 | - ("encoder.rs", include_str!("encoder.rs")), | |
| 624 | - ("lib.rs", include_str!("lib.rs")), | |
| 625 | - ]; | |
| 626 | - for (file, field, spelling) in PINS { | |
| 627 | - let src = SCANNED | |
| 628 | - .iter() | |
| 629 | - .find(|(name, _)| name == file) | |
| 630 | - .map(|(_, src)| *src) | |
| 631 | - .unwrap_or_else(|| panic!("no source pinned for {file}")); | |
| 632 | - let where_ = format!("{file}::{field}"); | |
| 633 | - assert!( | |
| 634 | - src.contains(spelling), | |
| 635 | - "{where_} is no longer declared `{spelling}`. An inline SILK \ | |
| 636 | - encoder or scratch buffer there puts {field}'s bytes back on \ | |
| 637 | - every caller's stack -- that is how Encoder was 87024 bytes \ | |
| 638 | - and Decoder 7576 before the boxing, 10.62x the by-value budget \ | |
| 639 | - on the type Encoder::new hands back by value." | |
| 640 | - ); | |
| 641 | - } | |
| 642 | - // And the negative control: the UNBOXED spellings must be ABSENT, or | |
| 643 | - // the scan above could be matching a doc comment instead of the live | |
| 644 | - // declaration. The unboxed forms are what this lane removed, so their | |
| 645 | - // absence is the proof the pin is reading the code. | |
| 646 | - const UNBOXED: &[(&str, &str, &str)] = &[ | |
| 647 | - ("encoder.rs", "Encoder::silk", "silk: Option<SilkLayer>,"), | |
| 648 | - ( | |
| 649 | - "encoder.rs", | |
| 650 | - "Encoder::silk_buf", | |
| 651 | - "silk_buf: [u8; MAX_SILK_PACKET_BYTES],", | |
| 652 | - ), | |
| 653 | - ("lib.rs", "Decoder::silk", "silk: SilkDecoder,"), | |
| 654 | - ]; | |
| 655 | - for (file, field, spelling) in UNBOXED { | |
| 656 | - let src = SCANNED | |
| 657 | - .iter() | |
| 658 | - .find(|(name, _)| name == file) | |
| 659 | - .map(|(_, src)| *src) | |
| 660 | - .unwrap_or_else(|| panic!("no source pinned for {file}")); | |
| 661 | - assert!( | |
| 662 | - !src.contains(spelling), | |
| 663 | - "{file}::{field} is declared unboxed as `{spelling}`. The box pin is \ | |
| 664 | - matching a spelling that is not the live declaration, and \ | |
| 665 | - {field}'s bytes are back on every caller's stack." | |
| 666 | - ); | |
| 667 | - } | |
| 668 | - } | |
| 669 | - | |
| 670 | - /// CAPABILITY: really construct the heavy types on a tight stack, so a | |
| 671 | - /// regression ABORTS THE PROCESS instead of costing invisible margin. | |
| 672 | - /// | |
| 673 | - /// Both arms are the crate's by-value constructors: `Encoder::new`, the | |
| 674 | - /// type that was 87,024 bytes, and `Decoder::new`, 7,576 -- plus a real | |
| 675 | - /// 20 ms SILK packet decoded through the `Decoder` that arm built, so the | |
| 676 | - /// decoder is proved live on this thread rather than merely constructed. | |
| 677 | - /// | |
| 678 | - /// Measured stack need, **debug** build, one process per point so a | |
| 679 | - /// SIGABRT cannot truncate the sweep: | |
| 680 | - /// | |
| 681 | - /// | stack | pre-fix layout (inline SILK slots) | current layout | | |
| 682 | - /// |---|---|---| | |
| 683 | - /// | 32768 | overflow | **overflow** | | |
| 684 | - /// | 49152 | overflow | **ok** | | |
| 685 | - /// | 131072 | overflow | ok | | |
| 686 | - /// | 262144 (**the gate**) | **overflow** | **ok** | | |
| 687 | - /// | 524288 | **overflow** | ok | | |
| 688 | - /// | 557056 | ok | ok | | |
| 689 | - /// | 786432 | ok | ok | | |
| 690 | - /// | 1048576 | ok | ok | | |
| 691 | - /// | |
| 692 | - /// The gate sits at 256 KiB, **5.3x** the measured need of the current | |
| 693 | - /// layout and **2.1x** below the pre-fix layout's own threshold. Note | |
| 694 | - /// what the upper rows say: the pre-fix layout SURVIVED 1 MiB and 2 MiB, | |
| 695 | - /// so a gate set at 1 MiB would have been a formality -- a test that | |
| 696 | - /// passes for the old layout proves nothing. `EC_OPUS_TIGHT_STACK_BYTES` | |
| 697 | - /// overrides the size, which is how the table is reproduced. | |
| 698 | - /// | |
| 699 | - /// The results are checked, not just the absence of a crash: an `Encoder` | |
| 700 | - /// that constructed but came back with the wrong channel count, or a | |
| 701 | - /// `Decoder` that decoded a packet to silence, would both pass a | |
| 702 | - /// "did not overflow" assertion. | |
| 703 | - #[test] | |
| 704 | - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { | |
| 705 | - use crate::encoder::Application; | |
| 706 | - let stack: usize = std::env::var("EC_OPUS_TIGHT_STACK_BYTES") | |
| 707 | - .ok() | |
| 708 | - .and_then(|v| v.parse().ok()) | |
| 709 | - .unwrap_or(TIGHT_STACK); | |
| 710 | - let handle = std::thread::Builder::new() | |
| 711 | - .stack_size(stack) | |
| 712 | - .spawn(move || { | |
| 713 | - // Arm 1: the by-value constructor that was 10.62x the budget. | |
| 714 | - let encoder = Encoder::new(48000, 1, Application::Audio) | |
| 715 | - .expect("Encoder::new(48000, 1, Audio)"); | |
| 716 | - let channels = encoder.channels(); | |
| 717 | - let rate = encoder.sample_rate(); | |
| 718 | - drop(encoder); | |
| 719 | - let mut decoder = Decoder::new(48000, 1).expect("Decoder::new(48000, 1)"); | |
| 720 | - // A real packet, so the decoder is proved live on this thread | |
| 721 | - // rather than merely constructed: the SILK-only 20 ms packet | |
| 722 | - // below decodes through the same by-value Decoder. | |
| 723 | - let mut out = vec![0.0f32; 5760]; | |
| 724 | - let written = decoder | |
| 725 | - .decode_float(SILK_ONLY_PACKET, &mut out) | |
| 726 | - .expect("decode_float on the tight-stack thread"); | |
| 727 | - let peak = out[..written].iter().fold(0.0f32, |m, s| m.max(s.abs())); | |
| 728 | - (channels, rate, written, peak) | |
| 729 | - }) | |
| 730 | - .expect("spawn tight-stack thread"); | |
| 731 | - let (channels, rate, pcm_len, peak) = handle.join().unwrap_or_else(|_| { | |
| 732 | - panic!( | |
| 733 | - "a by-value constructor overflowed a {stack}-byte stack; \ | |
| 734 | - EC_OPUS_TIGHT_STACK_BYTES reproduces the threshold sweep" | |
| 735 | - ) | |
| 736 | - }); | |
| 737 | - assert_eq!(channels, 1, "Encoder::new lost its channel count"); | |
| 738 | - assert_eq!(rate, 48000, "Encoder::new lost its sample rate"); | |
| 739 | - assert_eq!( | |
| 740 | - pcm_len, 960, | |
| 741 | - "Decoder::decode_float returned {pcm_len} samples, not the 960 one \ | |
| 742 | - 20 ms mono frame at 48 kHz holds; the tight-stack thread built a \ | |
| 743 | - Decoder that cannot decode" | |
| 744 | - ); | |
| 745 | - assert!( | |
| 746 | - peak > 0.0, | |
| 747 | - "Decoder::decode_float returned silence (peak {peak}) on the \ | |
| 748 | - tight-stack thread" | |
| 749 | - ); | |
| 750 | - eprintln!( | |
| 751 | - "TIGHTSTACK {stack} bytes: Encoder={} Decoder={} SilkDecoder={} \ | |
| 752 | - bytes, both constructors returned and decoded 960 samples", | |
| 753 | - std::mem::size_of::<Encoder>(), | |
| 754 | - std::mem::size_of::<Decoder>(), | |
| 755 | - std::mem::size_of::<crate::silk::SilkDecoder>(), | |
| 756 | - ); | |
| 757 | - } | |
| 758 | - | |
| 759 | - /// A SILK-only 20 ms Opus packet: TOC byte `0x48` (config 9 = SILK | |
| 760 | - /// wideband 20 ms, stereo bit 0, code 0 = SILK only) followed by a frame | |
| 761 | - /// count byte `0x00` (one frame) and a 100-byte payload. Config 9 is | |
| 762 | - /// SILK-only, so decoding it exercises `SilkDecoder`'s state rather than | |
| 763 | - /// CELT's, and the crate decodes it to exactly 960 samples at 48 kHz. | |
| 764 | - const SILK_ONLY_PACKET: &[u8] = &[ | |
| 765 | - 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 766 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 767 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 768 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 769 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 770 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 771 | - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | |
| 772 | - ]; | |
| 773 | - | |
| 774 | - /// The sweep's teeth against a NEW by-value return: re-derive the set from | |
| 775 | - /// the crate source and require every name to be inventoried. | |
| 776 | - /// | |
| 777 | - /// Without this the inventory is a list of what someone remembered to | |
| 778 | - /// measure, and a lane that adds `pub fn make() -> HugeThing` where | |
| 779 | - /// `HugeThing` is 200 KB of inline tables passes every other test here. | |
| 780 | - #[test] | |
| 781 | - fn every_by_value_public_return_is_in_the_inventory() { | |
| 782 | - let mut found: Vec<(String, String)> = Vec::new(); | |
| 783 | - for (file, src) in FILES { | |
| 784 | - for (n, line) in src.lines().enumerate() { | |
| 785 | - if let Some(name) = by_value_return_name(line) { | |
| 786 | - found.push((name, format!("{file}:{}", n + 1))); | |
| 787 | - } | |
| 788 | - } | |
| 789 | - } | |
| 790 | - found.sort(); | |
| 791 | - found.dedup(); | |
| 792 | - assert!( | |
| 793 | - found.len() > 5, | |
| 794 | - "the by-value return scan found {} names across {} files, which is \ | |
| 795 | - too few to be a real sweep -- the matcher, not the crate, is broken", | |
| 796 | - found.len(), | |
| 797 | - FILES.len() | |
| 798 | - ); | |
| 799 | - | |
| 800 | - let mut missing = Vec::new(); | |
| 801 | - for (name, site) in &found { | |
| 802 | - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { | |
| 803 | - missing.push(format!("{name} ({site})")); | |
| 804 | - } | |
| 805 | - } | |
| 806 | - assert!( | |
| 807 | - missing.is_empty(), | |
| 808 | - "these types are returned BY VALUE from a public fn and are not in \ | |
| 809 | - the inventory: {}. Either they are thin enough not to be a stack \ | |
| 810 | - cost -- say so by adding a row with its measured size -- or they \ | |
| 811 | - are the next instance of the class this module exists for.", | |
| 812 | - missing.join(", ") | |
| 813 | - ); | |
| 814 | - } | |
| 815 | - | |
| 816 | - /// The control for the scan above, on synthetic text rather than by | |
| 817 | - /// trusting the live tree to happen to contain a case. | |
| 818 | - /// | |
| 819 | - /// If the matcher silently stopped recognising a shape, the sweep would | |
| 820 | - /// pass everything and this would still be asserting nothing. So: every | |
| 821 | - /// by-value spelling the crate uses must yield its type name, and every | |
| 822 | - /// pointer/Vec/primitive/`Self` spelling must yield nothing. | |
| 823 | - #[test] | |
| 824 | - fn the_inventory_scan_is_not_vacuous() { | |
| 825 | - for synthetic in [ | |
| 826 | - "pub fn zz_a() -> ZzNotInventoried { todo!() }", | |
| 827 | - "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }", | |
| 828 | - "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }", | |
| 829 | - "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }", | |
| 830 | - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", | |
| 831 | - ] { | |
| 832 | - let name = by_value_return_name(synthetic) | |
| 833 | - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); | |
| 834 | - assert_eq!( | |
| 835 | - name, "ZzNotInventoried", | |
| 836 | - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ | |
| 837 | - cannot see a new by-value return and its green is vacuous" | |
| 838 | - ); | |
| 839 | - assert!( | |
| 840 | - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), | |
| 841 | - "the synthetic control name is in the inventory, so the control \ | |
| 842 | - proves nothing" | |
| 843 | - ); | |
| 844 | - } | |
| 845 | - for thin in [ | |
| 846 | - "pub fn zz_t() -> Box<Decoder> { todo!() }", | |
| 847 | - "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }", | |
| 848 | - "pub fn zz_v() -> Option<&Path> { todo!() }", | |
| 849 | - "pub fn zz_w() -> usize { todo!() }", | |
| 850 | - "pub fn zz_x() -> Self { todo!() }", | |
| 851 | - "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }", | |
| 852 | - "pub fn zz_z() { todo!() }", | |
| 853 | - "fn zz_private() -> ZzNotInventoried { todo!() }", | |
| 854 | - ] { | |
| 855 | - assert_eq!( | |
| 856 | - by_value_return_name(thin), | |
| 857 | - None, | |
| 858 | - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ | |
| 859 | - above already cover, or not a `pub fn` -- the matcher must not \ | |
| 860 | - read it as an uninventoried by-value return" | |
| 861 | - ); | |
| 862 | - } | |
| 863 | - } | |
| 864 | -} |
crates/ec-opus/tests/conformance.rsmodified+11 -270
| @@ -9,61 +9,6 @@ use std::path::{Path, PathBuf}; | ||
| 9 | 9 | |
| 10 | 10 | use ec_opus::Decoder; |
| 11 | 11 | |
| 12 | -// --------------------------------------------------------------------------- | |
| 13 | -// Counting allocator: proves the steady-state encode loop allocates nothing. | |
| 14 | -// Lives in the test binary only — the shipped crate has no allocator games. | |
| 15 | -// Same pattern as ec-h264's proof: only the thread that armed the counter is | |
| 16 | -// counted, so parallel tests (and ffmpeg child plumbing) allocate freely. | |
| 17 | -// --------------------------------------------------------------------------- | |
| 18 | - | |
| 19 | -use std::alloc::System; | |
| 20 | -use std::sync::Once; | |
| 21 | - | |
| 22 | -use std::cell::Cell; | |
| 23 | -use std::sync::atomic::{AtomicU64, Ordering}; | |
| 24 | -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; | |
| 25 | - | |
| 26 | -struct CountingAlloc; | |
| 27 | - | |
| 28 | -static ALLOCS: AtomicU64 = AtomicU64::new(0); | |
| 29 | - | |
| 30 | -std::thread_local! { | |
| 31 | - static COUNTING_HERE: Cell<bool> = const { Cell::new(false) }; | |
| 32 | -} | |
| 33 | - | |
| 34 | -fn counting_here() -> bool { | |
| 35 | - COUNTING_HERE.try_with(Cell::get).unwrap_or(false) | |
| 36 | -} | |
| 37 | - | |
| 38 | -impl AllocationTracker for CountingAlloc { | |
| 39 | - fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { | |
| 40 | - if counting_here() { | |
| 41 | - ALLOCS.fetch_add(1, Ordering::Relaxed); | |
| 42 | - } | |
| 43 | - } | |
| 44 | - fn deallocated( | |
| 45 | - &self, | |
| 46 | - _addr: usize, | |
| 47 | - _object_size: usize, | |
| 48 | - _wrapped: usize, | |
| 49 | - _source: AllocationGroupId, | |
| 50 | - _current: AllocationGroupId, | |
| 51 | - ) { | |
| 52 | - } | |
| 53 | -} | |
| 54 | - | |
| 55 | -#[global_allocator] | |
| 56 | -static A: Allocator<System> = Allocator::system(); | |
| 57 | - | |
| 58 | -/// Installs the tracker once; every test that arms the counter calls this first. | |
| 59 | -fn install_counter() { | |
| 60 | - static ONCE: Once = Once::new(); | |
| 61 | - ONCE.call_once(|| { | |
| 62 | - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); | |
| 63 | - AllocationRegistry::enable_tracking(); | |
| 64 | - }); | |
| 65 | -} | |
| 66 | - | |
| 67 | 12 | /// One packet of an `opus_demo` test vector file. |
| 68 | 13 | struct VectorPacket { |
| 69 | 14 | payload: Vec<u8>, |
| @@ -93,33 +38,18 @@ fn read_vector(path: &Path) -> Vec<VectorPacket> { | ||
| 93 | 38 | out |
| 94 | 39 | } |
| 95 | 40 | |
| 96 | -fn vectors_dir() -> PathBuf { | |
| 97 | - ec_testkit::root().join("vectors/opus-rfc6716/opus_testvectors") | |
| 98 | -} | |
| 99 | - | |
| 100 | 41 | /// Decodes a vector at 48 kHz stereo, returning the samples and how many |
| 101 | 42 | /// packets ended with the reference range state. |
| 102 | 43 | fn decode_vector(packets: &[VectorPacket]) -> (Vec<f32>, usize, usize) { |
| 103 | - decode_vector_ch(packets, 2, true) | |
| 104 | -} | |
| 105 | - | |
| 106 | -/// Decodes a vector at 48 kHz with `channels` output channels (1 or 2), with the | |
| 107 | -/// RFC 6716 reconstruction when `legacy` and the RFC 8251 one otherwise. | |
| 108 | -fn decode_vector_ch( | |
| 109 | - packets: &[VectorPacket], | |
| 110 | - channels: usize, | |
| 111 | - legacy: bool, | |
| 112 | -) -> (Vec<f32>, usize, usize) { | |
| 113 | - let mut dec = Decoder::new(48000, channels).unwrap(); | |
| 114 | - dec.set_legacy_rfc6716(legacy); | |
| 44 | + let mut dec = Decoder::new(48000, 2).unwrap(); | |
| 115 | 45 | let mut pcm = Vec::new(); |
| 116 | - let mut buf = vec![0.0f32; 5760 * channels]; | |
| 46 | + let mut buf = vec![0.0f32; 5760 * 2]; | |
| 117 | 47 | let mut matched = 0; |
| 118 | 48 | let mut decoded = 0; |
| 119 | 49 | for p in packets { |
| 120 | 50 | match dec.decode_float(&p.payload, &mut buf) { |
| 121 | 51 | Ok(n) => { |
| 122 | - pcm.extend_from_slice(&buf[..n * channels]); | |
| 52 | + pcm.extend_from_slice(&buf[..n * 2]); | |
| 123 | 53 | decoded += 1; |
| 124 | 54 | if dec.final_range() == p.final_range { |
| 125 | 55 | matched += 1; |
| @@ -429,7 +359,7 @@ fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) { | ||
| 429 | 359 | let dir = vectors_dir_8251(); |
| 430 | 360 | let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit")); |
| 431 | 361 | let packets = read_vector(&bit); |
| 432 | - let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false); | |
| 362 | + let (pcm, matched, decoded) = decode_vector(&packets); | |
| 433 | 363 | let refs = read_i16(&dir.join(reference)); |
| 434 | 364 | let mine = to_i16(&pcm); |
| 435 | 365 | assert_eq!( |
| @@ -485,47 +415,6 @@ const VECTORS: [&str; 12] = [ | ||
| 485 | 415 | "testvector12", |
| 486 | 416 | ]; |
| 487 | 417 | |
| 488 | -/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's | |
| 489 | -/// range coder state MUST match the reference on every packet, and the output | |
| 490 | -/// MUST stay within the `opus_compare` threshold (quality >= 0). | |
| 491 | -#[test] | |
| 492 | -fn rfc6716_test_vectors() { | |
| 493 | - let mut table = Vec::new(); | |
| 494 | - for name in VECTORS { | |
| 495 | - let path = | |
| 496 | - ec_testkit::fixture(&format!("vectors/opus-rfc6716/opus_testvectors/{name}.bit")); | |
| 497 | - let packets = read_vector(&path); | |
| 498 | - let (pcm, matched, decoded) = decode_vector(&packets); | |
| 499 | - let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); | |
| 500 | - let mine = to_i16(&pcm); | |
| 501 | - assert_eq!( | |
| 502 | - reference.len(), | |
| 503 | - mine.len(), | |
| 504 | - "{name}: decoded {} samples, reference has {}", | |
| 505 | - mine.len() / 2, | |
| 506 | - reference.len() / 2 | |
| 507 | - ); | |
| 508 | - let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count(); | |
| 509 | - let quality = opus_compare(&reference, &mine, 2); | |
| 510 | - table.push(format!( | |
| 511 | - "{name}: {matched}/{decoded} packets range-exact, \ | |
| 512 | - {:.4} % samples identical, quality {quality:.2} %", | |
| 513 | - 100.0 * identical as f64 / reference.len() as f64 | |
| 514 | - )); | |
| 515 | - assert_eq!( | |
| 516 | - matched, decoded, | |
| 517 | - "{name}: range coder state diverged from the reference" | |
| 518 | - ); | |
| 519 | - assert!( | |
| 520 | - quality >= 0.0, | |
| 521 | - "{name}: opus_compare quality {quality:.2} %" | |
| 522 | - ); | |
| 523 | - } | |
| 524 | - for line in table { | |
| 525 | - println!("{line}"); | |
| 526 | - } | |
| 527 | -} | |
| 528 | - | |
| 529 | 418 | // --------------------------------------------------------------------------- |
| 530 | 419 | // Real files: the Ogg-Opus fixtures, against ffmpeg |
| 531 | 420 | // --------------------------------------------------------------------------- |
| @@ -857,35 +746,6 @@ fn encoder_roundtrips_at_every_rate() { | ||
| 857 | 746 | } |
| 858 | 747 | } |
| 859 | 748 | |
| 860 | -/// The libopus input alignment ([`Encoder::set_libopus_input_alignment`]): | |
| 861 | -/// with it on the CELT layer's advertised delay grows by libopus's | |
| 862 | -/// `delay_compensation`, and the decoded signal tracks the source at exactly | |
| 863 | -/// that lag and not at the old one — the knob is usable, not just present. | |
| 864 | -/// It is on by default except for `Application::LowDelay`, as in libopus. | |
| 865 | -#[test] | |
| 866 | -fn libopus_input_alignment_delays_and_still_decodes() { | |
| 867 | - let pcm = test_signal(2, 1.0); | |
| 868 | - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); | |
| 869 | - enc.set_bitrate(128_000); | |
| 870 | - assert_eq!( | |
| 871 | - enc.look_ahead(960), | |
| 872 | - 312, | |
| 873 | - "default: overlap + delay_compensation" | |
| 874 | - ); | |
| 875 | - enc.set_libopus_input_alignment(false); | |
| 876 | - assert_eq!(enc.look_ahead(960), 120, "off: one MDCT overlap"); | |
| 877 | - enc.set_libopus_input_alignment(true); | |
| 878 | - let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, 960); | |
| 879 | - let aligned = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); | |
| 880 | - let old = delayed_corr(&pcm, &decoded, 2, 120); | |
| 881 | - println!("aligned: corr at 312 {aligned:.4}, at 120 {old:.4}"); | |
| 882 | - assert!(aligned >= 0.85, "aligned round trip corr {aligned:.4}"); | |
| 883 | - assert!( | |
| 884 | - aligned > old, | |
| 885 | - "advertised delay 312 correlates {aligned:.4}, worse than the old 120 ({old:.4})" | |
| 886 | - ); | |
| 887 | -} | |
| 888 | - | |
| 889 | 749 | #[test] |
| 890 | 750 | // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the |
| 891 | 751 | // voice/music bandwidth tables blended by voice_est) since lane opus-mode; |
| @@ -1587,63 +1447,6 @@ fn ogg_opus_round_trip_duration_is_exact() { | ||
| 1587 | 1447 | let _ = fs::remove_file(&path); |
| 1588 | 1448 | } |
| 1589 | 1449 | |
| 1590 | -/// The steady-state encode loop allocates nothing: every buffer — MDCT | |
| 1591 | -/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder | |
| 1592 | -/// and sized on the first frame (the decoder discipline, applied to the | |
| 1593 | -/// encoder). | |
| 1594 | -#[test] | |
| 1595 | -fn steady_state_encode_loop_zero_alloc() { | |
| 1596 | - install_counter(); | |
| 1597 | - let pcm = test_signal(2, 0.5); | |
| 1598 | - let pcm6 = { | |
| 1599 | - let mono = test_signal(1, 0.5); | |
| 1600 | - let mut v = Vec::with_capacity(mono.len() * 6); | |
| 1601 | - for &s in &mono { | |
| 1602 | - for c in 0..6 { | |
| 1603 | - v.push(s * (1.0 + c as f32 * 0.01)); | |
| 1604 | - } | |
| 1605 | - } | |
| 1606 | - v | |
| 1607 | - }; | |
| 1608 | - // Stereo elementary encoder. | |
| 1609 | - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); | |
| 1610 | - enc.set_bitrate(256_000); | |
| 1611 | - let mut out = vec![0u8; 1500]; | |
| 1612 | - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { | |
| 1613 | - enc.encode_float(block, 960, &mut out).unwrap(); | |
| 1614 | - } | |
| 1615 | - ALLOCS.store(0, Ordering::SeqCst); | |
| 1616 | - COUNTING_HERE.with(|c| c.set(true)); | |
| 1617 | - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { | |
| 1618 | - enc.encode_float(block, 960, &mut out).unwrap(); | |
| 1619 | - } | |
| 1620 | - COUNTING_HERE.with(|c| c.set(false)); | |
| 1621 | - let n = ALLOCS.load(Ordering::SeqCst); | |
| 1622 | - assert_eq!(n, 0, "stereo encode allocated {n} times in steady state"); | |
| 1623 | - | |
| 1624 | - // 5.1 multistream. | |
| 1625 | - let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap(); | |
| 1626 | - ms.set_bitrate(384_000); | |
| 1627 | - let mut out6 = vec![0u8; 8 * 1500]; | |
| 1628 | - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { | |
| 1629 | - ms.encode_float(block, 960, &mut out6).unwrap(); | |
| 1630 | - } | |
| 1631 | - ALLOCS.store(0, Ordering::SeqCst); | |
| 1632 | - COUNTING_HERE.with(|c| c.set(true)); | |
| 1633 | - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { | |
| 1634 | - ms.encode_float(block, 960, &mut out6).unwrap(); | |
| 1635 | - } | |
| 1636 | - COUNTING_HERE.with(|c| c.set(false)); | |
| 1637 | - let n = ALLOCS.load(Ordering::SeqCst); | |
| 1638 | - assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state"); | |
| 1639 | - | |
| 1640 | - // Mono SILK (Voip, 12 kbps) is NOT asserted zero-alloc here: fixing | |
| 1641 | - // `Encoder::zero_stuff_mono` to reuse a scratch buffer removed its | |
| 1642 | - // per-frame Vec, but the SILK encode path itself (NLSF/LPC | |
| 1643 | - // analysis, pitch search) allocates well beyond that one site — sweeping | |
| 1644 | - // those is a separate, much larger effort than this defect's scope. | |
| 1645 | -} | |
| 1646 | - | |
| 1647 | 1450 | /// Malformed input must come back as an error, never a panic: the decoders |
| 1648 | 1451 | /// index tables with values the bitstream chooses, so this throws well-formed |
| 1649 | 1452 | /// TOC bytes at random payloads to make sure every mode is actually entered. |
| @@ -2219,21 +2022,18 @@ fn silk_packets_track_encoder_bitrate() { | ||
| 2219 | 2022 | // Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream). |
| 2220 | 2023 | |
| 2221 | 2024 | /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our |
| 2222 | -/// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts | |
| 2223 | -/// range-state parity packet for packet. Returns (decoded, packets). | |
| 2025 | +/// decoder; asserts range-state parity packet for packet. Returns (decoded, packets). | |
| 2224 | 2026 | fn hybrid_roundtrip( |
| 2225 | 2027 | pcm: &[f32], |
| 2226 | 2028 | bps: u32, |
| 2227 | 2029 | bandwidth: Option<Bandwidth>, |
| 2228 | 2030 | mode: Option<Mode>, |
| 2229 | - mute: (bool, bool), | |
| 2230 | 2031 | ) -> (Vec<f32>, Vec<Vec<u8>>) { |
| 2231 | 2032 | let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 2232 | 2033 | enc.set_bitrate(bps); |
| 2233 | 2034 | enc.set_bandwidth(bandwidth); |
| 2234 | 2035 | enc.set_mode(mode); |
| 2235 | 2036 | let mut dec = Decoder::new(48000, 1).unwrap(); |
| 2236 | - dec.debug_mute_layers(mute.0, mute.1); | |
| 2237 | 2037 | let mut out = vec![0u8; 1500]; |
| 2238 | 2038 | let mut buf = vec![0f32; 5760]; |
| 2239 | 2039 | let (mut decoded, mut packets) = (Vec::new(), Vec::new()); |
| @@ -2254,9 +2054,6 @@ fn hybrid_roundtrip( | ||
| 2254 | 2054 | (decoded, packets) |
| 2255 | 2055 | } |
| 2256 | 2056 | |
| 2257 | -/// The two layers of a hybrid packet reach the decoder's output at the same | |
| 2258 | -/// delay: a click's low-band-only and high-band-only peaks coincide at the | |
| 2259 | -/// encoder's documented look-ahead. | |
| 2260 | 2057 | /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame — |
| 2261 | 2058 | /// [`Encoder::look_ahead`] of that same configuration, so the lag assertions |
| 2262 | 2059 | /// track the layer's real delay instead of a constant. |
| @@ -2266,71 +2063,22 @@ fn hybrid_delay(bps: u32) -> usize { | ||
| 2266 | 2063 | enc.look_ahead(960) |
| 2267 | 2064 | } |
| 2268 | 2065 | |
| 2269 | -#[test] | |
| 2270 | -fn hybrid_layers_align() { | |
| 2271 | - let mut click = vec![0f32; 48000]; | |
| 2272 | - // Well inside the stream so both layers' predictors are running. | |
| 2273 | - let at = 960 * 10 + 300; | |
| 2274 | - click[at] = 0.9; | |
| 2275 | - let peak = |x: &[f32]| { | |
| 2276 | - x.iter() | |
| 2277 | - .enumerate() | |
| 2278 | - .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) | |
| 2279 | - .unwrap() | |
| 2280 | - .0 | |
| 2281 | - }; | |
| 2282 | - let (lb, _) = hybrid_roundtrip(&click, 32_000, None, None, (true, false)); | |
| 2283 | - let (hb, _) = hybrid_roundtrip(&click, 32_000, None, None, (false, true)); | |
| 2284 | - let delay = hybrid_delay(32_000) as i64; | |
| 2285 | - let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); | |
| 2286 | - eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {delay}"); | |
| 2287 | - // A fullband CELT click lands at exactly the encoder's advertised delay | |
| 2288 | - // (`celt_click_peak_offset`); the band-limited HB layer's main lobe sits | |
| 2289 | - // up to 2 samples early once transient frames keep their short blocks, | |
| 2290 | - // and SILK lands one sample late. | |
| 2291 | - assert!( | |
| 2292 | - (plb - phb).abs() <= 3, | |
| 2293 | - "layers misaligned: LB +{plb} vs HB +{phb}" | |
| 2294 | - ); | |
| 2295 | - assert!( | |
| 2296 | - (phb - delay).abs() <= 2, | |
| 2297 | - "HB peak +{phb}, look_ahead {delay}" | |
| 2298 | - ); | |
| 2299 | -} | |
| 2300 | - | |
| 2301 | 2066 | /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks |
| 2302 | -/// the input full-band and in the SILK layer's band alone, and the reference | |
| 2303 | -/// oracle decodes the packets to the same signal. | |
| 2067 | +/// the input full-band, and the reference oracle decodes the packets to the | |
| 2068 | +/// same signal. | |
| 2304 | 2069 | /// |
| 2305 | 2070 | /// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is |
| 2306 | 2071 | /// [`Encoder::look_ahead`] of that same configuration, never a constant. |
| 2307 | 2072 | #[test] |
| 2308 | 2073 | fn hybrid_fb_roundtrip() { |
| 2309 | 2074 | for (name, pcm) in silk_sources() { |
| 2310 | - let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, None, (false, false)); | |
| 2075 | + let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, None); | |
| 2311 | 2076 | let toc = ec_opus::Toc::new(packets[0][0]); |
| 2312 | 2077 | assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config); |
| 2313 | 2078 | let (corr, lag) = aligned_corr(&pcm, &decoded, 400); |
| 2314 | - let (lb_only, lb_packets) = hybrid_roundtrip( | |
| 2315 | - &pcm, | |
| 2316 | - 32_000, | |
| 2317 | - Some(Bandwidth::Full), | |
| 2318 | - Some(Mode::Hybrid), | |
| 2319 | - (true, false), | |
| 2320 | - ); | |
| 2321 | - assert!( | |
| 2322 | - lb_packets | |
| 2323 | - .iter() | |
| 2324 | - .all(|p| ec_opus::Toc::new(p[0]).config == 15), | |
| 2325 | - "{name}: forced-FB run left hybrid" | |
| 2326 | - ); | |
| 2327 | - let lb_ref = lowpass(&pcm, 7000.0); | |
| 2328 | - let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); | |
| 2329 | 2079 | let bytes: usize = packets.iter().map(Vec::len).sum(); |
| 2330 | 2080 | let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); |
| 2331 | - eprintln!( | |
| 2332 | - "hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps" | |
| 2333 | - ); | |
| 2081 | + eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, {kbps:.1} kbps"); | |
| 2334 | 2082 | assert!(corr >= 0.9, "{name}: full-band corr {corr:.4}"); |
| 2335 | 2083 | let delay = hybrid_delay(32_000); |
| 2336 | 2084 | let libopus = libopus_untrimmed(&format!("hybrid-lag-{name}"), &pcm); |
| @@ -2339,7 +2087,6 @@ fn hybrid_fb_roundtrip() { | ||
| 2339 | 2087 | lag.abs_diff(libopus_lag) <= 6, |
| 2340 | 2088 | "{name}: aligned at lag {lag}, libopus at {libopus_lag}" |
| 2341 | 2089 | ); |
| 2342 | - assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); | |
| 2343 | 2090 | assert!( |
| 2344 | 2091 | (28.0..=36.0).contains(&kbps), |
| 2345 | 2092 | "{name}: {kbps:.1} kbps for a 32 kbps CBR target" |
| @@ -2353,16 +2100,10 @@ fn hybrid_fb_roundtrip() { | ||
| 2353 | 2100 | // SWB when asked for it, and the rest of the automatic hybrid range |
| 2354 | 2101 | // (SILK's share leaves CELT least at the bottom of it). |
| 2355 | 2102 | let speech = speech_like(); |
| 2356 | - let (_, packets) = hybrid_roundtrip( | |
| 2357 | - &speech, | |
| 2358 | - 24_000, | |
| 2359 | - Some(Bandwidth::SuperWide), | |
| 2360 | - None, | |
| 2361 | - (false, false), | |
| 2362 | - ); | |
| 2103 | + let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), None); | |
| 2363 | 2104 | assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); |
| 2364 | 2105 | for bps in [20_000u32, 24_000, 39_000] { |
| 2365 | - let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, None, (false, false)); | |
| 2106 | + let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, None); | |
| 2366 | 2107 | let (corr, _) = aligned_corr(&speech, &decoded, 400); |
| 2367 | 2108 | let kbps = packets.iter().map(Vec::len).sum::<usize>() as f64 * 8.0 |
| 2368 | 2109 | / (packets.len() as f64 * 20.0); |
crates/ec-opus/tests/plc.rsdeleted+0 -121
| @@ -1,121 +0,0 @@ | ||
| 1 | -use ec_opus::{Application, Decoder, Encoder, Mode}; | |
| 2 | - | |
| 3 | -const FRAME: usize = 960; | |
| 4 | - | |
| 5 | -fn voice(frames: usize) -> Vec<f32> { | |
| 6 | - (0..frames * FRAME) | |
| 7 | - .map(|i| { | |
| 8 | - let t = i as f32 / 48000.0; | |
| 9 | - let f0 = 140.0 + 10.0 * (2.0 * std::f32::consts::PI * 0.7 * t).sin(); | |
| 10 | - (1..12) | |
| 11 | - .map(|h| (2.0 * std::f32::consts::PI * f0 * h as f32 * t).sin() * 0.25 / h as f32) | |
| 12 | - .sum() | |
| 13 | - }) | |
| 14 | - .collect() | |
| 15 | -} | |
| 16 | - | |
| 17 | -fn corr(a: &[f32], b: &[f32]) -> f32 { | |
| 18 | - let ab: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); | |
| 19 | - let aa: f32 = a.iter().map(|x| x * x).sum(); | |
| 20 | - let bb: f32 = b.iter().map(|x| x * x).sum(); | |
| 21 | - ab / (aa * bb).sqrt().max(1e-9) | |
| 22 | -} | |
| 23 | - | |
| 24 | -fn rms(a: &[f32]) -> f32 { | |
| 25 | - (a.iter().map(|x| x * x).sum::<f32>() / a.len() as f32).sqrt() | |
| 26 | -} | |
| 27 | - | |
| 28 | -#[test] | |
| 29 | -fn concealment_tracks_and_recovers() { | |
| 30 | - let pcm = voice(60); | |
| 31 | - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | |
| 32 | - enc.set_bitrate(32000); | |
| 33 | - enc.set_mode(Some(Mode::Celt)); | |
| 34 | - let mut pkt = vec![0u8; 1500]; | |
| 35 | - let packets: Vec<Vec<u8>> = pcm | |
| 36 | - .chunks_exact(FRAME) | |
| 37 | - .map(|f| { | |
| 38 | - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | |
| 39 | - pkt[..n].to_vec() | |
| 40 | - }) | |
| 41 | - .collect(); | |
| 42 | - let lost = [20usize, 40, 41, 42, 43, 44, 45, 46, 47]; | |
| 43 | - let mut clean = Decoder::new(48000, 1).unwrap(); | |
| 44 | - let mut lossy = Decoder::new(48000, 1).unwrap(); | |
| 45 | - let mut buf = vec![0f32; 5760]; | |
| 46 | - let (mut a, mut b) = (Vec::new(), Vec::new()); | |
| 47 | - for (i, p) in packets.iter().enumerate() { | |
| 48 | - let k = clean.decode_float(p, &mut buf).unwrap(); | |
| 49 | - a.extend_from_slice(&buf[..k]); | |
| 50 | - let k = if lost.contains(&i) { | |
| 51 | - lossy.decode_float(&[], &mut buf).unwrap() | |
| 52 | - } else { | |
| 53 | - lossy.decode_float(p, &mut buf).unwrap() | |
| 54 | - }; | |
| 55 | - b.extend_from_slice(&buf[..k]); | |
| 56 | - } | |
| 57 | - let f = |i: usize| i * FRAME..(i + 1) * FRAME; | |
| 58 | - let c20 = corr(&a[f(20)], &b[f(20)]); | |
| 59 | - let r20 = rms(&b[f(20)]) / rms(&a[f(20)]); | |
| 60 | - let c22 = corr(&a[f(22)], &b[f(22)]); | |
| 61 | - let r47 = rms(&b[f(47)]) / rms(&a[f(47)]); | |
| 62 | - let c50 = corr(&a[f(50)], &b[f(50)]); | |
| 63 | - let jump = b | |
| 64 | - .windows(2) | |
| 65 | - .map(|w| (w[1] - w[0]).abs()) | |
| 66 | - .fold(0.0f32, f32::max); | |
| 67 | - let jump_ref = a | |
| 68 | - .windows(2) | |
| 69 | - .map(|w| (w[1] - w[0]).abs()) | |
| 70 | - .fold(0.0f32, f32::max); | |
| 71 | - eprintln!( | |
| 72 | - "c20 {c20:.3} r20 {r20:.3} c22 {c22:.3} r47 {r47:.3} c50 {c50:.3} jump {jump:.4} ref {jump_ref:.4}" | |
| 73 | - ); | |
| 74 | - assert!(c20 > 0.5 && (0.5..1.5).contains(&r20)); | |
| 75 | - assert!(c22 > 0.9); | |
| 76 | - assert!(r47 < 0.5); | |
| 77 | - assert!(c50 > 0.9); | |
| 78 | - assert!(jump < 2.0 * jump_ref); | |
| 79 | -} | |
| 80 | - | |
| 81 | -#[test] | |
| 82 | -fn inband_fec_recovers_a_lost_frame() { | |
| 83 | - let pcm = voice(40); | |
| 84 | - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | |
| 85 | - enc.set_bitrate(48000); | |
| 86 | - enc.set_bandwidth(Some(ec_opus::Bandwidth::Full)); | |
| 87 | - enc.set_inband_fec(true); | |
| 88 | - enc.set_packet_loss_perc(15); | |
| 89 | - let mut pkt = vec![0u8; 1500]; | |
| 90 | - let packets: Vec<Vec<u8>> = pcm | |
| 91 | - .chunks_exact(FRAME) | |
| 92 | - .map(|f| { | |
| 93 | - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | |
| 94 | - pkt[..n].to_vec() | |
| 95 | - }) | |
| 96 | - .collect(); | |
| 97 | - let mut clean = Decoder::new(48000, 1).unwrap(); | |
| 98 | - let mut lossy = Decoder::new(48000, 1).unwrap(); | |
| 99 | - let mut buf = vec![0f32; 5760]; | |
| 100 | - let (mut a, mut b) = (Vec::new(), Vec::new()); | |
| 101 | - for (i, p) in packets.iter().enumerate() { | |
| 102 | - let k = clean.decode_float(p, &mut buf).unwrap(); | |
| 103 | - a.extend_from_slice(&buf[..k]); | |
| 104 | - let k = if i == 20 { | |
| 105 | - lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() | |
| 106 | - } else if i == 30 { | |
| 107 | - lossy.conceal(FRAME, &mut buf).unwrap() | |
| 108 | - } else { | |
| 109 | - lossy.decode_float(p, &mut buf).unwrap() | |
| 110 | - }; | |
| 111 | - b.extend_from_slice(&buf[..k]); | |
| 112 | - } | |
| 113 | - let f = |i: usize| i * FRAME..(i + 1) * FRAME; | |
| 114 | - let c20 = corr(&a[f(20)], &b[f(20)]); | |
| 115 | - let c22 = corr(&a[f(22)], &b[f(22)]); | |
| 116 | - let c30 = corr(&a[f(30)], &b[f(30)]); | |
| 117 | - eprintln!("fec c20 {c20:.3} c22 {c22:.3} plc c30 {c30:.3}"); | |
| 118 | - assert!(c30 > 0.3); | |
| 119 | - assert!(c20 > 0.7); | |
| 120 | - assert!(c22 > 0.95); | |
| 121 | -} |
crates/ec-opus/tests/snr_floor.rsdeleted+0 -116
| @@ -1,116 +0,0 @@ | ||
| 1 | -//! Encoder quality floor (lane opusq): a music-like signal (chords, noise, transients) must | |
| 2 | -//! round-trip through the encoder and the decoder above a per-bitrate SNR floor. The floors sit | |
| 3 | -//! about 0.1-0.5 dB under what the encoder measures after the continuous allocation trim and the | |
| 4 | -//! analysis-driven leak boost; libopus (CELT, restricted-lowdelay, CBR) measures within ~1 dB | |
| 5 | -//! above these on the same signal shape, so a regression of the allocation shows here. | |
| 6 | -use ec_opus::{Application, Decoder, Encoder, MultistreamDecoder, MultistreamEncoder}; | |
| 7 | - | |
| 8 | -const FRAME: usize = 960; | |
| 9 | - | |
| 10 | -/// Hides a constant chunk size from clippy's `as_chunks` lint. | |
| 11 | -fn channels_of(n: usize) -> usize { | |
| 12 | - std::hint::black_box(n) | |
| 13 | -} | |
| 14 | - | |
| 15 | -struct Lcg(u64); | |
| 16 | -impl Lcg { | |
| 17 | - fn next(&mut self) -> f32 { | |
| 18 | - self.0 = self | |
| 19 | - .0 | |
| 20 | - .wrapping_mul(6364136223846793005) | |
| 21 | - .wrapping_add(1442695040888963407); | |
| 22 | - ((self.0 >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0 | |
| 23 | - } | |
| 24 | -} | |
| 25 | - | |
| 26 | -/// `channels` interleaved channels, `secs` seconds at 48 kHz. | |
| 27 | -fn music(channels: usize, secs: f32, seed: u64) -> Vec<f32> { | |
| 28 | - let n = (48000.0 * secs) as usize; | |
| 29 | - let mut rng = Lcg(seed); | |
| 30 | - let notes = [220.0f32, 277.2, 329.6, 440.0, 554.4, 659.3]; | |
| 31 | - let mut out = vec![0f32; n * channels]; | |
| 32 | - for c in 0..channels { | |
| 33 | - let phases: Vec<f32> = notes.iter().map(|_| rng.next() * 3.0).collect(); | |
| 34 | - for t in 0..n { | |
| 35 | - let tt = t as f32 / 48000.0; | |
| 36 | - let f0 = [1.0f32, 1.122, 1.26, 1.5][(tt as usize) % 4]; | |
| 37 | - let mut v = 0.0; | |
| 38 | - for (k, f) in notes.iter().enumerate() { | |
| 39 | - for h in 1..=5 { | |
| 40 | - v += 0.08 / h as f32 | |
| 41 | - * (2.0 * core::f32::consts::PI * f * f0 * h as f32 * tt + phases[k]).sin(); | |
| 42 | - } | |
| 43 | - } | |
| 44 | - v += 0.004 * rng.next(); | |
| 45 | - let since = t % 12000; | |
| 46 | - if since < 3000 { | |
| 47 | - v += 0.15 * rng.next() * (-(since as f32) / 500.0).exp(); | |
| 48 | - } | |
| 49 | - out[t * channels + c] = v * 0.6; | |
| 50 | - } | |
| 51 | - } | |
| 52 | - out | |
| 53 | -} | |
| 54 | - | |
| 55 | -fn snr_db(reference: &[f32], decoded: &[f32], channels: usize) -> f32 { | |
| 56 | - let n = reference.len().min(decoded.len()) / channels; | |
| 57 | - let (lo, hi) = (2000 * channels, n.saturating_sub(2000) * channels); | |
| 58 | - let (mut s, mut e) = (0f64, 0f64); | |
| 59 | - for i in lo..hi { | |
| 60 | - s += f64::from(reference[i]).powi(2); | |
| 61 | - e += f64::from(reference[i] - decoded[i]).powi(2); | |
| 62 | - } | |
| 63 | - (10.0 * (s / e).log10()) as f32 | |
| 64 | -} | |
| 65 | - | |
| 66 | -fn stereo_snr(kbps: u32) -> f32 { | |
| 67 | - let mono = music(1, 1.5, 3); | |
| 68 | - let mut pcm = music(2, 1.5, 7); | |
| 69 | - // Correlated channels (a common part plus a private part), as in a real mix. | |
| 70 | - for (t, f) in pcm.chunks_exact_mut(channels_of(2)).enumerate() { | |
| 71 | - let (a, b) = (f[0], f[1]); | |
| 72 | - f[0] = 0.8 * mono[t] + 0.2 * a; | |
| 73 | - f[1] = 0.6 * mono[t] + 0.4 * b; | |
| 74 | - } | |
| 75 | - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); | |
| 76 | - enc.set_bitrate(kbps * 1000); | |
| 77 | - enc.set_vbr_constrained(false); | |
| 78 | - let skip = enc.look_ahead(FRAME); | |
| 79 | - let mut dec = Decoder::new(48000, 2).unwrap(); | |
| 80 | - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 2], vec![0u8; 1500]); | |
| 81 | - for f in pcm.chunks_exact(channels_of(FRAME * 2)) { | |
| 82 | - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | |
| 83 | - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); | |
| 84 | - out.extend_from_slice(&buf[..k * 2]); | |
| 85 | - } | |
| 86 | - snr_db(&pcm, &out[skip * 2..], 2) | |
| 87 | -} | |
| 88 | - | |
| 89 | -#[test] | |
| 90 | -fn stereo_snr_floor() { | |
| 91 | - for (kbps, floor) in [(64, 17.0), (96, 19.3), (128, 22.0), (256, 26.7)] { | |
| 92 | - let snr = stereo_snr(kbps); | |
| 93 | - eprintln!("stereo {kbps}k snr {snr:.2}"); | |
| 94 | - assert!(snr >= floor, "{kbps} kbit/s: {snr:.2} dB < floor {floor}"); | |
| 95 | - } | |
| 96 | -} | |
| 97 | - | |
| 98 | -#[test] | |
| 99 | -fn surround_5_1_snr_floor() { | |
| 100 | - let pcm = music(6, 0.8, 11); | |
| 101 | - let mut enc = MultistreamEncoder::surround(48000, 6, Application::Audio).unwrap(); | |
| 102 | - enc.set_bitrate(256_000); | |
| 103 | - enc.set_vbr_constrained(false); | |
| 104 | - let skip = enc.look_ahead(FRAME); | |
| 105 | - let table = ec_opus::ogg::default_mapping(6).unwrap().3; | |
| 106 | - let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &table); | |
| 107 | - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 6], vec![0u8; 4000]); | |
| 108 | - for f in pcm.chunks_exact(channels_of(FRAME * 6)) { | |
| 109 | - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); | |
| 110 | - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); | |
| 111 | - out.extend_from_slice(&buf[..k * 6]); | |
| 112 | - } | |
| 113 | - let snr = snr_db(&pcm, &out[skip * 6..], 6); | |
| 114 | - eprintln!("5.1 256k snr {snr:.2}"); | |
| 115 | - assert!(snr >= 15.0, "5.1 256 kbit/s: {snr:.2} dB"); | |
| 116 | -} |