forge
Explore
Log in

Don't you dare go Hollow

U8: ec-opus delete bench example, plc and snr_floor test binaries (timing and diagnostic probes)

Browse files at this commit

88bd9f95db22440d8a126a49d95e241ace65c4dcAhmet Kaan GümüşParent: d77ec3f
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/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-}