From 88bd9f95db22440d8a126a49d95e241ace65c4dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:34:36 +0300 Subject: [PATCH] U8: ec-opus delete bench example, plc and snr_floor test binaries (timing and diagnostic probes) --- crates/ec-opus/examples/bench.rs | 171 ------------------------------ crates/ec-opus/tests/plc.rs | 121 --------------------- crates/ec-opus/tests/snr_floor.rs | 116 -------------------- 3 files changed, 408 deletions(-) delete mode 100644 crates/ec-opus/examples/bench.rs delete mode 100644 crates/ec-opus/tests/plc.rs delete mode 100644 crates/ec-opus/tests/snr_floor.rs diff --git a/crates/ec-opus/examples/bench.rs b/crates/ec-opus/examples/bench.rs deleted file mode 100644 index 6280fc92..00000000 --- a/crates/ec-opus/examples/bench.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! bench: Opus decode and encode throughput for lanes/bench.md ("lane benchaudio"). -//! -//! usage: -//! bench dec [reps] -//! bench enc [reps] -//! -//! `dec` demuxes an Ogg Opus file with `OggDemuxer` (the OpusHead and OpusTags packets are not -//! audio packets) and decodes every packet with `Decoder` at 48 kHz, `reps` times (default 5), -//! keeping the best wall time. The decoded interleaved f32 PCM of the last run, before the -//! pre-skip trim, is written to `out.f32le`. -//! `enc` encodes raw interleaved 48 kHz f32le PCM with `Encoder` (Application::Audio, CBR at -//! `kbps`, 20 ms frames) and muxes it to Ogg Opus, best of `reps` encode runs. -use std::fs::File; -use std::hint::black_box; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::{CodecId, Demuxer, Packet as CorePacket, StreamInfo, TimeBase, Muxer}; -use ec_ogg::OggDemuxer; -use ec_opus::{Application, Decoder, Encoder, ogg::opus_head, Packet as OpusPacket}; - -const RATE: u32 = 48_000; -/// 20 ms at 48 kHz, per channel. -const FRAME: usize = 960; - -/// The audio packets of the first Opus stream, and its channel count from OpusHead. -fn read_packets(path: &str) -> (usize, Vec>) { - let mut demuxer = OggDemuxer::open(BufReader::new(File::open(path).expect("open"))).expect("ogg"); - let stream = demuxer - .streams() - .iter() - .find(|s| s.params.codec == CodecId::Opus) - .expect("an Opus stream") - .clone(); - let head = stream.params.extradata.clone().expect("OpusHead"); - let channels = usize::from(head[9]); - let mut packets = Vec::new(); - loop { - match demuxer.next_packet() { - Ok(p) if p.stream == stream.index => packets.push(p.data.to_vec()), - Ok(_) => {} - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (channels, packets) -} - -/// Decode every packet once: (interleaved samples, packets that failed). -fn decode_once(packets: &[Vec], channels: usize) -> (Vec, usize) { - let mut decoder = Decoder::new(RATE, channels).expect("decoder"); - let mut out = Vec::new(); - let mut buf = vec![0f32; 5760 * channels]; - let mut failed = 0usize; - for p in packets { - match decoder.decode_float(p, &mut buf) { - Ok(n) => out.extend_from_slice(&buf[..n * channels]), - Err(_) => failed += 1, - } - } - (out, failed) -} - -fn le_f32(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -/// Encode interleaved 48 kHz PCM into (Opus packets, pre-skip) with 20 ms frames. -fn encode_once(pcm: &[f32], channels: usize, kbps: u32) -> (Vec>, usize) { - let mut encoder = Encoder::new(RATE, channels, Application::Audio).expect("encoder"); - encoder.set_bitrate(kbps * 1000); - encoder.set_vbr_constrained(false); - let pre_skip = encoder.look_ahead(FRAME); - let frames = (pcm.len() / channels).div_ceil(FRAME); - let mut packets = Vec::with_capacity(frames); - let mut frame = vec![0f32; FRAME * channels]; - let mut out = vec![0u8; 1500]; - for f in 0..frames { - frame.fill(0.0); - let start = f * FRAME * channels; - let end = (start + FRAME * channels).min(pcm.len()); - frame[..end - start].copy_from_slice(&pcm[start..end]); - let n = encoder.encode_float(&frame, FRAME, &mut out).expect("encode"); - packets.push(out[..n].to_vec()); - } - (packets, pre_skip) -} - -/// Mux the packets into Ogg Opus. The last packet's duration ends at the true input length. -fn write_ogg(path: &str, packets: &[Vec], channels: usize, total: usize, pre_skip: usize) { - let file = std::io::BufWriter::new(File::create(path).expect("create")); - let mut mux = ec_ogg::OggMuxer::new(file); - let tb = TimeBase::from_rate(RATE); - let mut params = ec_core::CodecParameters::new(CodecId::Opus); - params.extradata = Some(opus_head(channels as u8, pre_skip as u16, RATE, 0, None).into()); - if let ec_core::MediaParameters::Audio(a) = &mut params.media { - a.sample_rate = RATE; - a.layout = ec_core::ChannelLayout::from_count(channels); - } - mux.add_stream(StreamInfo::new(0, tb, params)).expect("stream"); - let mut pts = 0i64; - for (idx, p) in packets.iter().enumerate() { - let dur = OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; - let dur = if idx == packets.len() - 1 { - total as i64 + pre_skip as i64 - pts - } else { - dur - }; - let pkt = CorePacket::new(0, tb, p.clone()).with_pts(pts).with_duration(dur); - mux.write_packet(&pkt).expect("write"); - pts += OpusPacket::parse(p, false).expect("packet").samples_48k() as i64; - } - mux.finish().expect("finish"); -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("dec") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - let (channels, packets) = read_packets(&args[2]); - let (pcm, failed) = decode_once(&packets, channels); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(decode_once(black_box(&packets), channels).0.len()); - best = best.min(t.elapsed().as_secs_f64()); - } - let mut bytes = Vec::with_capacity(pcm.len() * 4); - for v in &pcm { - bytes.extend_from_slice(&v.to_le_bytes()); - } - std::fs::write(&args[3], &bytes).expect("write output"); - println!( - "packets={} failed={failed} samples={} best_decode_s={best:.4} reps={reps}", - packets.len(), - pcm.len() / channels - ); - } - Some("enc") if args.len() >= 6 => { - let channels: usize = args[3].parse().expect("channels"); - let kbps: u32 = args[4].parse().expect("kbps"); - let reps: usize = args.get(6).map_or(5, |s| s.parse().expect("reps")); - let pcm = le_f32(&std::fs::read(&args[2]).expect("read input")); - let total = pcm.len() / channels; - let (packets, pre_skip) = encode_once(&pcm, channels, kbps); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(encode_once(black_box(&pcm), channels, kbps).0.len()); - best = best.min(t.elapsed().as_secs_f64()); - } - write_ogg(&args[5], &packets, channels, total, pre_skip); - let bytes: usize = packets.iter().map(Vec::len).sum(); - println!( - "packets={} bytes={bytes} best_encode_s={best:.4} reps={reps} audio_s={:.3}", - packets.len(), - total as f64 / f64::from(RATE) - ); - } - _ => { - eprintln!( - "usage: bench dec [reps]\n bench enc [reps]" - ); - std::process::exit(2); - } - } -} diff --git a/crates/ec-opus/tests/plc.rs b/crates/ec-opus/tests/plc.rs deleted file mode 100644 index d8764947..00000000 --- a/crates/ec-opus/tests/plc.rs +++ /dev/null @@ -1,121 +0,0 @@ -use ec_opus::{Application, Decoder, Encoder, Mode}; - -const FRAME: usize = 960; - -fn voice(frames: usize) -> Vec { - (0..frames * FRAME) - .map(|i| { - let t = i as f32 / 48000.0; - let f0 = 140.0 + 10.0 * (2.0 * std::f32::consts::PI * 0.7 * t).sin(); - (1..12) - .map(|h| (2.0 * std::f32::consts::PI * f0 * h as f32 * t).sin() * 0.25 / h as f32) - .sum() - }) - .collect() -} - -fn corr(a: &[f32], b: &[f32]) -> f32 { - let ab: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); - let aa: f32 = a.iter().map(|x| x * x).sum(); - let bb: f32 = b.iter().map(|x| x * x).sum(); - ab / (aa * bb).sqrt().max(1e-9) -} - -fn rms(a: &[f32]) -> f32 { - (a.iter().map(|x| x * x).sum::() / a.len() as f32).sqrt() -} - -#[test] -fn concealment_tracks_and_recovers() { - let pcm = voice(60); - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); - enc.set_bitrate(32000); - enc.set_mode(Some(Mode::Celt)); - let mut pkt = vec![0u8; 1500]; - let packets: Vec> = pcm - .chunks_exact(FRAME) - .map(|f| { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - pkt[..n].to_vec() - }) - .collect(); - let lost = [20usize, 40, 41, 42, 43, 44, 45, 46, 47]; - let mut clean = Decoder::new(48000, 1).unwrap(); - let mut lossy = Decoder::new(48000, 1).unwrap(); - let mut buf = vec![0f32; 5760]; - let (mut a, mut b) = (Vec::new(), Vec::new()); - for (i, p) in packets.iter().enumerate() { - let k = clean.decode_float(p, &mut buf).unwrap(); - a.extend_from_slice(&buf[..k]); - let k = if lost.contains(&i) { - lossy.decode_float(&[], &mut buf).unwrap() - } else { - lossy.decode_float(p, &mut buf).unwrap() - }; - b.extend_from_slice(&buf[..k]); - } - let f = |i: usize| i * FRAME..(i + 1) * FRAME; - let c20 = corr(&a[f(20)], &b[f(20)]); - let r20 = rms(&b[f(20)]) / rms(&a[f(20)]); - let c22 = corr(&a[f(22)], &b[f(22)]); - let r47 = rms(&b[f(47)]) / rms(&a[f(47)]); - let c50 = corr(&a[f(50)], &b[f(50)]); - let jump = b - .windows(2) - .map(|w| (w[1] - w[0]).abs()) - .fold(0.0f32, f32::max); - let jump_ref = a - .windows(2) - .map(|w| (w[1] - w[0]).abs()) - .fold(0.0f32, f32::max); - eprintln!( - "c20 {c20:.3} r20 {r20:.3} c22 {c22:.3} r47 {r47:.3} c50 {c50:.3} jump {jump:.4} ref {jump_ref:.4}" - ); - assert!(c20 > 0.5 && (0.5..1.5).contains(&r20)); - assert!(c22 > 0.9); - assert!(r47 < 0.5); - assert!(c50 > 0.9); - assert!(jump < 2.0 * jump_ref); -} - -#[test] -fn inband_fec_recovers_a_lost_frame() { - let pcm = voice(40); - let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); - enc.set_bitrate(48000); - enc.set_bandwidth(Some(ec_opus::Bandwidth::Full)); - enc.set_inband_fec(true); - enc.set_packet_loss_perc(15); - let mut pkt = vec![0u8; 1500]; - let packets: Vec> = pcm - .chunks_exact(FRAME) - .map(|f| { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - pkt[..n].to_vec() - }) - .collect(); - let mut clean = Decoder::new(48000, 1).unwrap(); - let mut lossy = Decoder::new(48000, 1).unwrap(); - let mut buf = vec![0f32; 5760]; - let (mut a, mut b) = (Vec::new(), Vec::new()); - for (i, p) in packets.iter().enumerate() { - let k = clean.decode_float(p, &mut buf).unwrap(); - a.extend_from_slice(&buf[..k]); - let k = if i == 20 { - lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() - } else if i == 30 { - lossy.conceal(FRAME, &mut buf).unwrap() - } else { - lossy.decode_float(p, &mut buf).unwrap() - }; - b.extend_from_slice(&buf[..k]); - } - let f = |i: usize| i * FRAME..(i + 1) * FRAME; - let c20 = corr(&a[f(20)], &b[f(20)]); - let c22 = corr(&a[f(22)], &b[f(22)]); - let c30 = corr(&a[f(30)], &b[f(30)]); - eprintln!("fec c20 {c20:.3} c22 {c22:.3} plc c30 {c30:.3}"); - assert!(c30 > 0.3); - assert!(c20 > 0.7); - assert!(c22 > 0.95); -} diff --git a/crates/ec-opus/tests/snr_floor.rs b/crates/ec-opus/tests/snr_floor.rs deleted file mode 100644 index f3e8977e..00000000 --- a/crates/ec-opus/tests/snr_floor.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Encoder quality floor (lane opusq): a music-like signal (chords, noise, transients) must -//! round-trip through the encoder and the decoder above a per-bitrate SNR floor. The floors sit -//! about 0.1-0.5 dB under what the encoder measures after the continuous allocation trim and the -//! analysis-driven leak boost; libopus (CELT, restricted-lowdelay, CBR) measures within ~1 dB -//! above these on the same signal shape, so a regression of the allocation shows here. -use ec_opus::{Application, Decoder, Encoder, MultistreamDecoder, MultistreamEncoder}; - -const FRAME: usize = 960; - -/// Hides a constant chunk size from clippy's `as_chunks` lint. -fn channels_of(n: usize) -> usize { - std::hint::black_box(n) -} - -struct Lcg(u64); -impl Lcg { - fn next(&mut self) -> f32 { - self.0 = self - .0 - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - ((self.0 >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0 - } -} - -/// `channels` interleaved channels, `secs` seconds at 48 kHz. -fn music(channels: usize, secs: f32, seed: u64) -> Vec { - let n = (48000.0 * secs) as usize; - let mut rng = Lcg(seed); - let notes = [220.0f32, 277.2, 329.6, 440.0, 554.4, 659.3]; - let mut out = vec![0f32; n * channels]; - for c in 0..channels { - let phases: Vec = notes.iter().map(|_| rng.next() * 3.0).collect(); - for t in 0..n { - let tt = t as f32 / 48000.0; - let f0 = [1.0f32, 1.122, 1.26, 1.5][(tt as usize) % 4]; - let mut v = 0.0; - for (k, f) in notes.iter().enumerate() { - for h in 1..=5 { - v += 0.08 / h as f32 - * (2.0 * core::f32::consts::PI * f * f0 * h as f32 * tt + phases[k]).sin(); - } - } - v += 0.004 * rng.next(); - let since = t % 12000; - if since < 3000 { - v += 0.15 * rng.next() * (-(since as f32) / 500.0).exp(); - } - out[t * channels + c] = v * 0.6; - } - } - out -} - -fn snr_db(reference: &[f32], decoded: &[f32], channels: usize) -> f32 { - let n = reference.len().min(decoded.len()) / channels; - let (lo, hi) = (2000 * channels, n.saturating_sub(2000) * channels); - let (mut s, mut e) = (0f64, 0f64); - for i in lo..hi { - s += f64::from(reference[i]).powi(2); - e += f64::from(reference[i] - decoded[i]).powi(2); - } - (10.0 * (s / e).log10()) as f32 -} - -fn stereo_snr(kbps: u32) -> f32 { - let mono = music(1, 1.5, 3); - let mut pcm = music(2, 1.5, 7); - // Correlated channels (a common part plus a private part), as in a real mix. - for (t, f) in pcm.chunks_exact_mut(channels_of(2)).enumerate() { - let (a, b) = (f[0], f[1]); - f[0] = 0.8 * mono[t] + 0.2 * a; - f[1] = 0.6 * mono[t] + 0.4 * b; - } - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(kbps * 1000); - enc.set_vbr_constrained(false); - let skip = enc.look_ahead(FRAME); - let mut dec = Decoder::new(48000, 2).unwrap(); - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 2], vec![0u8; 1500]); - for f in pcm.chunks_exact(channels_of(FRAME * 2)) { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); - out.extend_from_slice(&buf[..k * 2]); - } - snr_db(&pcm, &out[skip * 2..], 2) -} - -#[test] -fn stereo_snr_floor() { - for (kbps, floor) in [(64, 17.0), (96, 19.3), (128, 22.0), (256, 26.7)] { - let snr = stereo_snr(kbps); - eprintln!("stereo {kbps}k snr {snr:.2}"); - assert!(snr >= floor, "{kbps} kbit/s: {snr:.2} dB < floor {floor}"); - } -} - -#[test] -fn surround_5_1_snr_floor() { - let pcm = music(6, 0.8, 11); - let mut enc = MultistreamEncoder::surround(48000, 6, Application::Audio).unwrap(); - enc.set_bitrate(256_000); - enc.set_vbr_constrained(false); - let skip = enc.look_ahead(FRAME); - let table = ec_opus::ogg::default_mapping(6).unwrap().3; - let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &table); - let (mut out, mut buf, mut pkt) = (Vec::new(), vec![0f32; 5760 * 6], vec![0u8; 4000]); - for f in pcm.chunks_exact(channels_of(FRAME * 6)) { - let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); - let k = dec.decode_float(&pkt[..n], &mut buf).unwrap(); - out.extend_from_slice(&buf[..k * 6]); - } - let snr = snr_db(&pcm, &out[skip * 6..], 6); - eprintln!("5.1 256k snr {snr:.2}"); - assert!(snr >= 15.0, "5.1 256 kbit/s: {snr:.2} dB"); -}