forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB052d1d3Tahinli2 months ago3627 commits

lib.rs464 lines, 17.3 KiBHistoryRawDownload
1//! Compatibility shim: the `opus-rs` 0.1.26 surface edith consumes, served by
2//! [`ec_opus`].
3//!
4//! The incumbent this replaces encoded packets that only its own decoder read
5//! back above ~128-165 kbps (correlation 0.06 against the reference decoder at 256 kbps on
6//! the same signal that round-tripped internally at 0.999), and mono was
7//! broken at every rate. This shim serves the same three-call surface —
8//! `OpusEncoder::new(rate, channels, Application)`, the public `bitrate_bps`
9//! and `complexity` fields, `.encode(&pcm, frame_size, &mut out)` — from the
10//! `ec-opus` CELT encoder, which is range-exact against the family's
11//! RFC-vector-verified decoder and the reference decoder-verified at every rate up to
12//! 510 kbps, mono and stereo alike. The measured envelope that capped the
13//! incumbent (`OPUS_MAX_KBPS = 128`) is obsolete behind this crate.
14//!
15//! `complexity` is accepted for drop-in compatibility and ignored: this
16//! encoder has one (fast) analysis path, not a ladder.
17//!
18//! [`Application::Voip`] below 20 kbps, mono, 20 ms frames picks the SILK
19//! layer, as the reference does; every other combination stays CELT. Stereo
20//! SILK and SILK at other frame sizes fall back to CELT rather than
21//! silently approximating it.
22
23#![forbid(unsafe_code)]
24#![warn(missing_docs)]
25
26use std::fmt;
27
28/// What the encoded stream is optimised for. This CELT-only encoder spends the
29/// setting on the coded bandwidth, not on a different coding layer.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Application {
32 /// Speech-optimised (SILK in the reference decoder; served by CELT here).
33 Voip,
34 /// Music and general audio.
35 Audio,
36 /// Lowest-latency mode.
37 RestrictedLowdelay,
38}
39
40impl From<Application> for ec_opus::Application {
41 fn from(a: Application) -> ec_opus::Application {
42 match a {
43 Application::Voip => ec_opus::Application::Voip,
44 Application::Audio => ec_opus::Application::Audio,
45 Application::RestrictedLowdelay => ec_opus::Application::LowDelay,
46 }
47 }
48}
49
50/// Coded audio bandwidth, with the C API's discriminants.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Bandwidth {
53 /// Chosen from the bitrate, the application and the input rate.
54 Auto = -1000,
55 /// 4 kHz.
56 Narrowband = 1101,
57 /// 6 kHz. CELT has no mediumband configuration; this codes as wideband.
58 Mediumband = 1102,
59 /// 8 kHz.
60 Wideband = 1103,
61 /// 12 kHz.
62 SuperWideband = 1104,
63 /// 20 kHz.
64 Fullband = 1105,
65}
66
67/// The error type of this shim: a message, as the incumbent's was.
68#[derive(Debug, Clone)]
69pub struct OpusError(String);
70
71impl fmt::Display for OpusError {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 f.write_str(&self.0)
74 }
75}
76
77impl std::error::Error for OpusError {}
78
79/// An Opus encoder with the incumbent's field-configured surface.
80#[derive(Debug)]
81pub struct OpusEncoder {
82 /// Target bitrate in bits per second, applied at the next
83 /// [`OpusEncoder::encode`] call.
84 pub bitrate_bps: i32,
85 /// Accepted for compatibility; this encoder has a single analysis path.
86 pub complexity: i32,
87 /// Coded bandwidth; [`Bandwidth::Auto`] follows the bitrate.
88 pub bandwidth: Bandwidth,
89 /// Constrained VBR. Off by default, as the incumbent's was.
90 pub vbr: bool,
91 inner: ec_opus::Encoder,
92 channels: usize,
93 applied_bandwidth: Bandwidth,
94 applied_vbr: bool,
95}
96
97impl OpusEncoder {
98 /// An encoder at `sample_rate` (8000, 12000, 16000, 24000 or 48000) for
99 /// `channels` channels (1 or 2).
100 pub fn new(
101 sample_rate: i32,
102 channels: i32,
103 application: Application,
104 ) -> Result<OpusEncoder, OpusError> {
105 if sample_rate < 0 || channels < 0 {
106 return Err(OpusError(format!(
107 "invalid encoder arguments: {sample_rate} Hz, {channels} channels"
108 )));
109 }
110 let inner =
111 ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into())
112 .map_err(|e| OpusError(e.to_string()))?;
113 Ok(OpusEncoder {
114 bitrate_bps: 64_000 * channels,
115 complexity: 10,
116 bandwidth: Bandwidth::Auto,
117 vbr: false,
118 inner,
119 channels: channels as usize,
120 applied_bandwidth: Bandwidth::Auto,
121 applied_vbr: false,
122 })
123 }
124
125 /// Samples of encoder delay, at the input rate: the decoded stream lags
126 /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to
127 /// 48 kHz) cancels the lag exactly. Reported for the canonical 20 ms
128 /// frame (SILK and Hybrid, which shift the delay, only run at 20 ms
129 /// anyway) — like the incumbent's `OPUS_GET_LOOKAHEAD`, which doesn't
130 /// take a frame size either.
131 pub fn look_ahead(&self) -> usize {
132 self.inner.look_ahead(self.inner.sample_rate() as usize / 50)
133 }
134
135 /// The range coder state after the last packet — the RFC 6716 Section 6
136 /// conformance hook, which a conformant decoder reproduces exactly.
137 pub fn final_range(&self) -> u32 {
138 self.inner.final_range()
139 }
140
141 /// Encodes `frame_size` samples per channel of interleaved `f32` into
142 /// `out`, returning the packet length in bytes.
143 pub fn encode(
144 &mut self,
145 pcm: &[f32],
146 frame_size: usize,
147 out: &mut [u8],
148 ) -> Result<usize, OpusError> {
149 if pcm.len() < frame_size * self.channels {
150 return Err(OpusError(format!(
151 "{} samples is short of {} channels x {frame_size}",
152 pcm.len(),
153 self.channels
154 )));
155 }
156 self.sync_settings();
157 self.inner
158 .encode_float(pcm, frame_size, out)
159 .map_err(|e| OpusError(e.to_string()))
160 }
161
162 /// [`OpusEncoder::encode`] from 16-bit samples.
163 pub fn encode_i16(
164 &mut self,
165 pcm: &[i16],
166 frame_size: usize,
167 out: &mut [u8],
168 ) -> Result<usize, OpusError> {
169 if pcm.len() < frame_size * self.channels {
170 return Err(OpusError(format!(
171 "{} samples is short of {} channels x {frame_size}",
172 pcm.len(),
173 self.channels
174 )));
175 }
176 self.sync_settings();
177 self.inner
178 .encode(pcm, frame_size, out)
179 .map_err(|e| OpusError(e.to_string()))
180 }
181
182 /// Drops all inter-frame state; the next packet starts a fresh stream.
183 pub fn reset(&mut self) {
184 self.inner.reset();
185 }
186
187 /// Pushes the public fields into the encoder before a frame.
188 fn sync_settings(&mut self) {
189 self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
190 if self.bandwidth != self.applied_bandwidth {
191 self.inner.set_bandwidth(match self.bandwidth {
192 Bandwidth::Auto => None,
193 Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow),
194 Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide),
195 Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide),
196 Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full),
197 });
198 self.applied_bandwidth = self.bandwidth;
199 }
200 if self.vbr != self.applied_vbr {
201 self.inner.set_vbr_constrained(self.vbr);
202 self.applied_vbr = self.vbr;
203 }
204 }
205}
206
207/// An Opus decoder, mono or stereo.
208#[derive(Debug)]
209pub struct OpusDecoder {
210 inner: ec_opus::Decoder,
211}
212
213impl OpusDecoder {
214 /// A decoder for `channels` channels at `sample_rate` Hz.
215 pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> {
216 if sample_rate < 0 || channels < 0 {
217 return Err(OpusError(format!(
218 "invalid decoder arguments: {sample_rate} Hz, {channels} channels"
219 )));
220 }
221 Ok(OpusDecoder {
222 inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize)
223 .map_err(|e| OpusError(e.to_string()))?,
224 })
225 }
226
227 /// Decodes one packet into interleaved `f32`, returning samples per
228 /// channel. `frame_size` bounds the output, as the incumbent's did.
229 pub fn decode(
230 &mut self,
231 packet: &[u8],
232 frame_size: usize,
233 out: &mut [f32],
234 ) -> Result<usize, OpusError> {
235 let _ = frame_size;
236 self.inner
237 .decode_float(packet, out)
238 .map_err(|e| OpusError(e.to_string()))
239 }
240
241 /// The range coder state after the last packet.
242 pub fn final_range(&self) -> u32 {
243 self.inner.final_range()
244 }
245}
246
247/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not
248/// do at all — the replica's surround Opus path today is stereo only.
249#[derive(Debug)]
250pub struct MultistreamEncoder {
251 /// Target bitrate in bits per second, across all streams.
252 pub bitrate_bps: i32,
253 inner: ec_opus::MultistreamEncoder,
254 channels: usize,
255}
256
257impl MultistreamEncoder {
258 /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1
259 /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis
260 /// order: left, centre, right, back left, back right, LFE.
261 pub fn surround(
262 sample_rate: i32,
263 channels: usize,
264 application: Application,
265 ) -> Result<MultistreamEncoder, OpusError> {
266 if sample_rate < 0 {
267 return Err(OpusError(format!("invalid sample rate {sample_rate}")));
268 }
269 let inner =
270 ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into())
271 .map_err(|e| OpusError(e.to_string()))?;
272 Ok(MultistreamEncoder {
273 bitrate_bps: 96_000 * channels as i32 / 2,
274 inner,
275 channels,
276 })
277 }
278
279 /// The channel mapping table the `OpusHead` for this encoder needs.
280 pub fn mapping(&self) -> &[u8] {
281 self.inner.layout().2
282 }
283
284 /// Elementary streams, and how many of them are coupled.
285 pub fn stream_counts(&self) -> (usize, usize) {
286 let (streams, coupled, _) = self.inner.layout();
287 (streams, coupled)
288 }
289
290 /// Encodes one frame of interleaved `f32`, returning the packet length.
291 pub fn encode(
292 &mut self,
293 pcm: &[f32],
294 frame_size: usize,
295 out: &mut [u8],
296 ) -> Result<usize, OpusError> {
297 if pcm.len() < frame_size * self.channels {
298 return Err(OpusError(format!(
299 "{} samples is short of {} channels x {frame_size}",
300 pcm.len(),
301 self.channels
302 )));
303 }
304 self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
305 self.inner
306 .encode_float(pcm, frame_size, out)
307 .map_err(|e| OpusError(e.to_string()))
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 /// The exact call shape edith's export path uses (export.rs:1863-1896).
316 #[test]
317 fn edith_call_shape_compiles_and_encodes() {
318 let mut encoder = OpusEncoder::new(48000, 2, Application::Audio)
319 .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))
320 .unwrap();
321 encoder.bitrate_bps = 256_000;
322 encoder.complexity = 10;
323 let frame = vec![0.1f32; 960 * 2];
324 let mut out = vec![0u8; 1500];
325 let len = encoder
326 .encode(&frame, 960, &mut out)
327 .map_err(|e| format!("Opus encode failed: {e}"))
328 .unwrap();
329 assert!(len > 2 && len <= 1276);
330 // Mono — broken at every rate in the incumbent — encodes too.
331 let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap();
332 mono.bitrate_bps = 96_000;
333 let frame = vec![0.1f32; 960];
334 let len = mono.encode(&frame, 960, &mut out).unwrap();
335 assert!(len > 2);
336 }
337
338 fn tone(n: usize, channels: usize) -> Vec<f32> {
339 (0..n * channels)
340 .map(|i| {
341 let t = (i / channels) as f32;
342 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin()
343 })
344 .collect()
345 }
346
347 /// The decoder half of the surface, and the conformance hook that says the
348 /// two agree: the decoder's range state must equal the encoder's after
349 /// every packet.
350 #[test]
351 fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() {
352 const FRAME: usize = 960;
353 let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap();
354 enc.bitrate_bps = 256_000;
355 let mut dec = OpusDecoder::new(48_000, 2).unwrap();
356 let pcm = tone(FRAME * 8, 2);
357 let mut out = vec![0u8; 1500];
358 let mut back = vec![0.0f32; FRAME * 2];
359 let mut total = 0;
360 for block in pcm.chunks_exact(FRAME * 2) {
361 let len = enc.encode(block, FRAME, &mut out).unwrap();
362 assert!(len > 1 && len <= 1276, "packet of {len} bytes");
363 total += len;
364 assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
365 assert_eq!(dec.final_range(), enc.final_range());
366 }
367 // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is
368 // what this number exists to refute.
369 let want = 256_000 / 8 / 50 * 8;
370 assert!(
371 (total as f64 - want as f64).abs() < 0.2 * want as f64,
372 "{total} bytes vs {want} at 256 kbps"
373 );
374 }
375
376 /// Input below 48 kHz, which the shim used to refuse outright, and the
377 /// `look_ahead` that goes with it. 48/24 kHz VoIP at 32 kbps run
378 /// hybrid (SWB/FB), so the delay is CELT's 120-sample overlap, scaled;
379 /// 16 kHz and below cap the bandwidth at WB or narrower, where hybrid
380 /// does not exist, so dispatch takes SILK and the delay is the SILK
381 /// resampler look-ahead (WB 50 / MB 54 / NB 58 at 48 kHz), scaled.
382 #[test]
383 fn slower_input_rates_encode_and_report_their_own_delay() {
384 for &(rate, frame, look) in &[
385 (48_000i32, 960usize, 120usize),
386 (24_000, 480, 60),
387 (16_000, 320, 50 / 3),
388 (12_000, 240, 54 / 4),
389 (8_000, 160, 58 / 6),
390 ] {
391 let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap();
392 enc.bitrate_bps = 32_000;
393 assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead");
394 let pcm = tone(frame * 4, 1);
395 let mut out = vec![0u8; 1500];
396 // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in.
397 let mut dec = OpusDecoder::new(48_000, 1).unwrap();
398 let mut back = vec![0.0f32; 960];
399 for block in pcm.chunks_exact(frame) {
400 let len = enc.encode(block, frame, &mut out).unwrap();
401 assert!(len > 2, "{rate} Hz packet of {len} bytes");
402 assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960);
403 assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range");
404 }
405 }
406 assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err());
407 }
408
409 /// A narrower band is a smaller top-band cost, not a refusal: forcing the
410 /// bandwidth must still produce packets a decoder reads.
411 #[test]
412 fn forced_bandwidth_and_i16_input_round_trip() {
413 const FRAME: usize = 960;
414 let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap();
415 enc.bitrate_bps = 64_000;
416 enc.bandwidth = Bandwidth::Wideband;
417 enc.vbr = true;
418 let pcm: Vec<i16> = tone(FRAME * 4, 1)
419 .iter()
420 .map(|v| (v * 16_000.0) as i16)
421 .collect();
422 let mut out = vec![0u8; 1500];
423 let mut dec = OpusDecoder::new(48_000, 1).unwrap();
424 let mut back = vec![0.0f32; FRAME];
425 for block in pcm.chunks_exact(FRAME) {
426 let len = enc.encode_i16(block, FRAME, &mut out).unwrap();
427 // TOC config 20..23 is wideband CELT (RFC 6716 Table 2).
428 assert_eq!(out[0] >> 3, 23, "wideband CELT config");
429 assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
430 assert_eq!(dec.final_range(), enc.final_range());
431 }
432 }
433
434 /// 5.1, which the incumbent could not encode at all.
435 #[test]
436 fn surround_encodes_five_one() {
437 const FRAME: usize = 960;
438 let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap();
439 e.bitrate_bps = 384_000;
440 assert_eq!(e.stream_counts(), (4, 2));
441 assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]);
442 let pcm = tone(FRAME * 3, 6);
443 let mut out = vec![0u8; 8 * 1500];
444 for block in pcm.chunks_exact(FRAME * 6) {
445 assert!(e.encode(block, FRAME, &mut out).unwrap() > 8);
446 }
447 assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err());
448 }
449
450 /// `Application::Voip` under 20 kbps, mono, 20 ms frames reaches the
451 /// SILK layer through this shim's existing surface — no new API, just
452 /// the application and bitrate the incumbent already exposed. TOC
453 /// configs 0..=11 are SILK (RFC 6716 Table 2).
454 #[test]
455 fn voip_below_20kbps_reaches_silk() {
456 let mut enc = OpusEncoder::new(48_000, 1, Application::Voip).unwrap();
457 enc.bitrate_bps = 12_000;
458 let pcm = tone(960, 1);
459 let mut out = vec![0u8; 1500];
460 let len = enc.encode(&pcm, 960, &mut out).unwrap();
461 assert!(len > 1);
462 assert!(out[0] >> 3 <= 11, "TOC config {} is not SILK", out[0] >> 3);
463 }
464}