forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

lib.rs442 lines, 16.0 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 libopus 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 libopus-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//! One behaviour is genuinely narrower and is stated rather than hidden: this
19//! encoder is **CELT-only**, so [`Application::Voip`] selects a narrower
20//! bandwidth at a given rate but not the SILK layer the name implies. Speech
21//! below about 32 kbps is where that costs the most.
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 libopus; 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.
128 pub fn look_ahead(&self) -> usize {
129 self.inner.look_ahead()
130 }
131
132 /// The range coder state after the last packet — the RFC 6716 Section 6
133 /// conformance hook, which a conformant decoder reproduces exactly.
134 pub fn final_range(&self) -> u32 {
135 self.inner.final_range()
136 }
137
138 /// Encodes `frame_size` samples per channel of interleaved `f32` into
139 /// `out`, returning the packet length in bytes.
140 pub fn encode(
141 &mut self,
142 pcm: &[f32],
143 frame_size: usize,
144 out: &mut [u8],
145 ) -> Result<usize, OpusError> {
146 if pcm.len() < frame_size * self.channels {
147 return Err(OpusError(format!(
148 "{} samples is short of {} channels x {frame_size}",
149 pcm.len(),
150 self.channels
151 )));
152 }
153 self.sync_settings();
154 self.inner
155 .encode_float(pcm, frame_size, out)
156 .map_err(|e| OpusError(e.to_string()))
157 }
158
159 /// [`OpusEncoder::encode`] from 16-bit samples.
160 pub fn encode_i16(
161 &mut self,
162 pcm: &[i16],
163 frame_size: usize,
164 out: &mut [u8],
165 ) -> Result<usize, OpusError> {
166 if pcm.len() < frame_size * self.channels {
167 return Err(OpusError(format!(
168 "{} samples is short of {} channels x {frame_size}",
169 pcm.len(),
170 self.channels
171 )));
172 }
173 self.sync_settings();
174 self.inner
175 .encode(pcm, frame_size, out)
176 .map_err(|e| OpusError(e.to_string()))
177 }
178
179 /// Drops all inter-frame state; the next packet starts a fresh stream.
180 pub fn reset(&mut self) {
181 self.inner.reset();
182 }
183
184 /// Pushes the public fields into the encoder before a frame.
185 fn sync_settings(&mut self) {
186 self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
187 if self.bandwidth != self.applied_bandwidth {
188 self.inner.set_bandwidth(match self.bandwidth {
189 Bandwidth::Auto => None,
190 Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow),
191 Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide),
192 Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide),
193 Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full),
194 });
195 self.applied_bandwidth = self.bandwidth;
196 }
197 if self.vbr != self.applied_vbr {
198 self.inner.set_vbr_constrained(self.vbr);
199 self.applied_vbr = self.vbr;
200 }
201 }
202}
203
204/// An Opus decoder, mono or stereo.
205#[derive(Debug)]
206pub struct OpusDecoder {
207 inner: ec_opus::Decoder,
208}
209
210impl OpusDecoder {
211 /// A decoder for `channels` channels at `sample_rate` Hz.
212 pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> {
213 if sample_rate < 0 || channels < 0 {
214 return Err(OpusError(format!(
215 "invalid decoder arguments: {sample_rate} Hz, {channels} channels"
216 )));
217 }
218 Ok(OpusDecoder {
219 inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize)
220 .map_err(|e| OpusError(e.to_string()))?,
221 })
222 }
223
224 /// Decodes one packet into interleaved `f32`, returning samples per
225 /// channel. `frame_size` bounds the output, as the incumbent's did.
226 pub fn decode(
227 &mut self,
228 packet: &[u8],
229 frame_size: usize,
230 out: &mut [f32],
231 ) -> Result<usize, OpusError> {
232 let _ = frame_size;
233 self.inner
234 .decode_float(packet, out)
235 .map_err(|e| OpusError(e.to_string()))
236 }
237
238 /// The range coder state after the last packet.
239 pub fn final_range(&self) -> u32 {
240 self.inner.final_range()
241 }
242}
243
244/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not
245/// do at all — the replica's surround Opus path today is stereo only.
246#[derive(Debug)]
247pub struct MultistreamEncoder {
248 /// Target bitrate in bits per second, across all streams.
249 pub bitrate_bps: i32,
250 inner: ec_opus::MultistreamEncoder,
251 channels: usize,
252}
253
254impl MultistreamEncoder {
255 /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1
256 /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis
257 /// order: left, centre, right, back left, back right, LFE.
258 pub fn surround(
259 sample_rate: i32,
260 channels: usize,
261 application: Application,
262 ) -> Result<MultistreamEncoder, OpusError> {
263 if sample_rate < 0 {
264 return Err(OpusError(format!("invalid sample rate {sample_rate}")));
265 }
266 let inner =
267 ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into())
268 .map_err(|e| OpusError(e.to_string()))?;
269 Ok(MultistreamEncoder {
270 bitrate_bps: 96_000 * channels as i32 / 2,
271 inner,
272 channels,
273 })
274 }
275
276 /// The channel mapping table the `OpusHead` for this encoder needs.
277 pub fn mapping(&self) -> &[u8] {
278 self.inner.layout().2
279 }
280
281 /// Elementary streams, and how many of them are coupled.
282 pub fn stream_counts(&self) -> (usize, usize) {
283 let (streams, coupled, _) = self.inner.layout();
284 (streams, coupled)
285 }
286
287 /// Encodes one frame of interleaved `f32`, returning the packet length.
288 pub fn encode(
289 &mut self,
290 pcm: &[f32],
291 frame_size: usize,
292 out: &mut [u8],
293 ) -> Result<usize, OpusError> {
294 if pcm.len() < frame_size * self.channels {
295 return Err(OpusError(format!(
296 "{} samples is short of {} channels x {frame_size}",
297 pcm.len(),
298 self.channels
299 )));
300 }
301 self.inner.set_bitrate(self.bitrate_bps.max(0) as u32);
302 self.inner
303 .encode_float(pcm, frame_size, out)
304 .map_err(|e| OpusError(e.to_string()))
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 /// The exact call shape edith's export path uses (export.rs:1863-1896).
313 #[test]
314 fn edith_call_shape_compiles_and_encodes() {
315 let mut encoder = OpusEncoder::new(48000, 2, Application::Audio)
316 .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))
317 .unwrap();
318 encoder.bitrate_bps = 256_000;
319 encoder.complexity = 10;
320 let frame = vec![0.1f32; 960 * 2];
321 let mut out = vec![0u8; 1500];
322 let len = encoder
323 .encode(&frame, 960, &mut out)
324 .map_err(|e| format!("Opus encode failed: {e}"))
325 .unwrap();
326 assert!(len > 2 && len <= 1276);
327 // Mono — broken at every rate in the incumbent — encodes too.
328 let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap();
329 mono.bitrate_bps = 96_000;
330 let frame = vec![0.1f32; 960];
331 let len = mono.encode(&frame, 960, &mut out).unwrap();
332 assert!(len > 2);
333 }
334
335 fn tone(n: usize, channels: usize) -> Vec<f32> {
336 (0..n * channels)
337 .map(|i| {
338 let t = (i / channels) as f32;
339 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin()
340 })
341 .collect()
342 }
343
344 /// The decoder half of the surface, and the conformance hook that says the
345 /// two agree: the decoder's range state must equal the encoder's after
346 /// every packet.
347 #[test]
348 fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() {
349 const FRAME: usize = 960;
350 let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap();
351 enc.bitrate_bps = 256_000;
352 let mut dec = OpusDecoder::new(48_000, 2).unwrap();
353 let pcm = tone(FRAME * 8, 2);
354 let mut out = vec![0u8; 1500];
355 let mut back = vec![0.0f32; FRAME * 2];
356 let mut total = 0;
357 for block in pcm.chunks_exact(FRAME * 2) {
358 let len = enc.encode(block, FRAME, &mut out).unwrap();
359 assert!(len > 1 && len <= 1276, "packet of {len} bytes");
360 total += len;
361 assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
362 assert_eq!(dec.final_range(), enc.final_range());
363 }
364 // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is
365 // what this number exists to refute.
366 let want = 256_000 / 8 / 50 * 8;
367 assert!(
368 (total as f64 - want as f64).abs() < 0.2 * want as f64,
369 "{total} bytes vs {want} at 256 kbps"
370 );
371 }
372
373 /// Input below 48 kHz, which the shim used to refuse outright, and the
374 /// `look_ahead` that goes with it (120 samples at 48 kHz, scaled).
375 #[test]
376 fn slower_input_rates_encode_and_report_their_own_delay() {
377 for &(rate, frame, look) in &[
378 (48_000i32, 960usize, 120usize),
379 (24_000, 480, 60),
380 (16_000, 320, 40),
381 (12_000, 240, 30),
382 (8_000, 160, 20),
383 ] {
384 let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap();
385 enc.bitrate_bps = 32_000;
386 assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead");
387 let pcm = tone(frame * 4, 1);
388 let mut out = vec![0u8; 1500];
389 // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in.
390 let mut dec = OpusDecoder::new(48_000, 1).unwrap();
391 let mut back = vec![0.0f32; 960];
392 for block in pcm.chunks_exact(frame) {
393 let len = enc.encode(block, frame, &mut out).unwrap();
394 assert!(len > 2, "{rate} Hz packet of {len} bytes");
395 assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960);
396 assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range");
397 }
398 }
399 assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err());
400 }
401
402 /// A narrower band is a smaller top-band cost, not a refusal: forcing the
403 /// bandwidth must still produce packets a decoder reads.
404 #[test]
405 fn forced_bandwidth_and_i16_input_round_trip() {
406 const FRAME: usize = 960;
407 let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap();
408 enc.bitrate_bps = 64_000;
409 enc.bandwidth = Bandwidth::Wideband;
410 enc.vbr = true;
411 let pcm: Vec<i16> = tone(FRAME * 4, 1)
412 .iter()
413 .map(|v| (v * 16_000.0) as i16)
414 .collect();
415 let mut out = vec![0u8; 1500];
416 let mut dec = OpusDecoder::new(48_000, 1).unwrap();
417 let mut back = vec![0.0f32; FRAME];
418 for block in pcm.chunks_exact(FRAME) {
419 let len = enc.encode_i16(block, FRAME, &mut out).unwrap();
420 // TOC config 20..23 is wideband CELT (RFC 6716 Table 2).
421 assert_eq!(out[0] >> 3, 23, "wideband CELT config");
422 assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME);
423 assert_eq!(dec.final_range(), enc.final_range());
424 }
425 }
426
427 /// 5.1, which the incumbent could not encode at all.
428 #[test]
429 fn surround_encodes_five_one() {
430 const FRAME: usize = 960;
431 let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap();
432 e.bitrate_bps = 384_000;
433 assert_eq!(e.stream_counts(), (4, 2));
434 assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]);
435 let pcm = tone(FRAME * 3, 6);
436 let mut out = vec![0u8; 8 * 1500];
437 for block in pcm.chunks_exact(FRAME * 6) {
438 assert!(e.encode(block, FRAME, &mut out).unwrap() > 8);
439 }
440 assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err());
441 }
442}