forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2cccf17Tahinli3 months ago136 commits

encoder.rs340 lines, 12.3 KiBHistoryRawDownload
1//! The Opus packet encoder: CELT-only, 8 to 48 kHz in.
2//!
3//! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3)
4//! or the self-delimited variant of Appendix B that the multistream framing
5//! needs. Every configuration this encoder emits is a CELT one (TOC configs
6//! 16..31), which is what music encoding uses at every rate the product asks
7//! for; there is no SILK and no hybrid path — a speech-optimised mode below
8//! 16 kbps is out of scope, not silently approximated.
9//!
10//! Input below 48 kHz is zero-stuffed to CELT's native rate and the coded
11//! bandwidth is capped at the input's own Nyquist, so the images the stuffing
12//! puts there are never coded and the decoder's decimation drops them.
13//! [`Encoder::look_ahead`] reports the delay in *input* samples.
14//!
15//! Rate control is CBR by default — every packet the same size, derived from
16//! the bitrate — or constrained VBR, the reference's reservoir scheme, when
17//! [`Encoder::set_vbr_constrained`] is on.
18
19use ec_core::{Error, Result};
20
21use crate::celt_enc::CeltEncoder;
22use crate::packet::Bandwidth;
23use crate::range::RangeEncoder;
24
25/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
26const MAX_FRAME_BYTES: usize = 1275;
27
28/// What the caller is encoding. This encoder is CELT-only, so the setting
29/// biases the coded bandwidth rather than selecting a different layer.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Application {
32 /// Speech: one step narrower at a given rate, where the top octave costs
33 /// most and carries least.
34 Voip,
35 /// Music and general audio, the default.
36 Audio,
37 /// Lowest delay.
38 LowDelay,
39}
40
41/// One elementary Opus encoder: mono or stereo, CELT-only.
42#[derive(Clone, Debug)]
43pub struct Encoder {
44 celt: CeltEncoder,
45 range: RangeEncoder,
46 sample_rate: u32,
47 /// 48000 / `sample_rate`: the zero-stuffing factor into CELT.
48 upsample: usize,
49 channels: usize,
50 bitrate: u32,
51 vbr: bool,
52 application: Application,
53 bandwidth: Option<Bandwidth>,
54 final_range: u32,
55}
56
57impl Encoder {
58 /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which
59 /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates
60 /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the
61 /// input rate is (RFC 7845 Section 5.1).
62 pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> {
63 let upsample = match sample_rate {
64 48000 => 1,
65 24000 => 2,
66 16000 => 3,
67 12000 => 4,
68 8000 => 6,
69 _ => {
70 return Err(Error::unsupported(
71 format!("opus encode at {sample_rate} Hz"),
72 "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first",
73 ));
74 }
75 };
76 if !(1..=2).contains(&channels) {
77 return Err(Error::unsupported(
78 format!("{channels}-channel Opus stream"),
79 "one stream carries at most two channels; use MultistreamEncoder",
80 ));
81 }
82 Ok(Encoder {
83 celt: CeltEncoder::new(channels, upsample),
84 range: RangeEncoder::new(),
85 sample_rate,
86 upsample,
87 channels,
88 bitrate: 64_000 * channels as u32,
89 vbr: false,
90 application,
91 bandwidth: None,
92 final_range: 0,
93 })
94 }
95
96 /// Channels per frame of input.
97 pub fn channels(&self) -> usize {
98 self.channels
99 }
100
101 /// The rate the caller feeds.
102 pub fn sample_rate(&self) -> u32 {
103 self.sample_rate
104 }
105
106 /// Encoder delay in *input* samples: the decoded stream lags the input by
107 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
108 /// cancels it exactly. One MDCT overlap, 120 samples at 48 kHz.
109 pub fn look_ahead(&self) -> usize {
110 120 / self.upsample
111 }
112
113 /// Forces the coded bandwidth; [`None`] (the default) picks it from the
114 /// bitrate, the application and the input's Nyquist.
115 pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) {
116 self.bandwidth = bandwidth;
117 }
118
119 /// Target bitrate in bits per second for the whole packet stream,
120 /// including the packet headers. Clamped to 500..=510000.
121 pub fn set_bitrate(&mut self, bps: u32) {
122 self.bitrate = bps.clamp(500, 510_000);
123 }
124
125 /// Current target bitrate.
126 pub fn bitrate(&self) -> u32 {
127 self.bitrate
128 }
129
130 /// Switches between CBR (default, every packet the target size) and
131 /// constrained VBR (packets vary, a reservoir holds the average to the
132 /// target).
133 pub fn set_vbr_constrained(&mut self, vbr: bool) {
134 self.vbr = vbr;
135 }
136
137 /// The range coder state after the last packet — the same value RFC 6716
138 /// test vectors carry, and what a conformant decoder's `final_range`
139 /// must equal after decoding that packet.
140 pub fn final_range(&self) -> u32 {
141 self.final_range
142 }
143
144 /// Drops all inter-frame state; the next packet starts like the first.
145 pub fn reset(&mut self) {
146 self.celt.reset();
147 self.final_range = 0;
148 }
149
150 /// The TOC byte, the frame size in 48 kHz samples and the CELT end band
151 /// for a frame of `frame_size` input samples per channel.
152 fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> {
153 let frame_48k = frame_size * self.upsample;
154 let fs_idx: u8 = match frame_48k {
155 120 => 0,
156 240 => 1,
157 480 => 2,
158 960 => 3,
159 _ => {
160 return Err(Error::unsupported(
161 format!(
162 "opus frame of {frame_size} samples at {} Hz",
163 self.sample_rate
164 ),
165 "CELT frames are 2.5, 5, 10 or 20 ms",
166 ));
167 }
168 };
169 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
170 let bw_idx: u8 = match bandwidth {
171 Bandwidth::Narrow => 0,
172 // CELT has no mediumband configuration; the next one up covers it.
173 Bandwidth::Medium | Bandwidth::Wide => 1,
174 Bandwidth::SuperWide => 2,
175 Bandwidth::Full => 3,
176 };
177 let config = 16 + 4 * bw_idx + fs_idx;
178 Ok((
179 (config << 3) | (u8::from(self.channels == 2) << 2),
180 frame_48k,
181 bandwidth.celt_end_band(),
182 ))
183 }
184
185 /// Bandwidth from the bitrate: coding 20 kHz at 24 kbps spends bits on air.
186 ///
187 /// The thresholds are on the mono-equivalent rate — a coupled stereo stream
188 /// needs about 1.6x a mono one for the same per-channel quality — and VoIP
189 /// asks for one step narrower. The input's own Nyquist bounds the result:
190 /// coding above it would code the images the zero-stuffing put there.
191 fn auto_bandwidth(&self) -> Bandwidth {
192 let equiv = if self.channels == 2 {
193 (self.bitrate as f32 * 0.62) as u32
194 } else {
195 self.bitrate
196 };
197 let equiv = if self.application == Application::Voip {
198 (equiv as f32 * 0.7) as u32
199 } else {
200 equiv
201 };
202 let ceiling = match self.sample_rate {
203 48000 => Bandwidth::Full,
204 24000 => Bandwidth::SuperWide,
205 16000 => Bandwidth::Wide,
206 _ => Bandwidth::Narrow,
207 };
208 let wanted = if equiv < 9000 {
209 Bandwidth::Narrow
210 } else if equiv < 13000 {
211 Bandwidth::Wide
212 } else if equiv < 20000 {
213 Bandwidth::SuperWide
214 } else {
215 Bandwidth::Full
216 };
217 wanted.min(ceiling)
218 }
219
220 /// Encodes one frame — `frame_size` samples per channel of interleaved
221 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
222 /// packet in `out`, returning the packet length.
223 pub fn encode_float(
224 &mut self,
225 pcm: &[f32],
226 frame_size: usize,
227 out: &mut [u8],
228 ) -> Result<usize> {
229 let (toc, frame_48k, end) = self.toc(frame_size)?;
230 let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?;
231 if out.len() < 1 + n {
232 return Err(Error::corrupt(format!(
233 "opus encode: packet needs {} bytes, buffer holds {}",
234 1 + n,
235 out.len()
236 )));
237 }
238 out[0] = toc;
239 out[1..1 + n].copy_from_slice(&self.range.data()[..n]);
240 Ok(1 + n)
241 }
242
243 /// [`Encoder::encode_float`] from 16-bit samples.
244 pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> {
245 let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect();
246 self.encode_float(&float, frame_size, out)
247 }
248
249 /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
250 /// Appendix B: TOC, an explicit frame length, then the frame. This is
251 /// what every stream but the last uses inside a multistream packet.
252 pub fn encode_self_delimited(
253 &mut self,
254 pcm: &[f32],
255 frame_size: usize,
256 out: &mut [u8],
257 ) -> Result<usize> {
258 let (toc, frame_48k, end) = self.toc(frame_size)?;
259 let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?;
260 let len_bytes = if n < 252 { 1 } else { 2 };
261 if out.len() < 1 + len_bytes + n {
262 return Err(Error::corrupt(format!(
263 "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
264 1 + len_bytes + n,
265 out.len()
266 )));
267 }
268 out[0] = toc;
269 if n < 252 {
270 out[1] = n as u8;
271 } else {
272 let b0 = 252 + ((n - 252) & 3);
273 out[1] = b0 as u8;
274 out[2] = ((n - b0) / 4) as u8;
275 }
276 out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]);
277 Ok(1 + len_bytes + n)
278 }
279
280 /// Encodes the CELT frame into the internal range coder and returns its
281 /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded
282 /// band, and `cap` bounds the frame (the caller's buffer minus headers).
283 fn encode_frame(
284 &mut self,
285 pcm: &[f32],
286 frame_size: usize,
287 end: usize,
288 cap: usize,
289 ) -> Result<usize> {
290 let cap = cap.min(MAX_FRAME_BYTES);
291 if cap < 2 {
292 return Err(Error::corrupt(
293 "opus encode: output buffer smaller than the minimum packet",
294 ));
295 }
296 // One byte per packet goes to the TOC; the CELT layer sees the rest.
297 let toc_bps = 8 * 48000 / frame_size as u32;
298 let (budget, vbr_rate) = if self.vbr {
299 (cap, self.bitrate.saturating_sub(toc_bps).max(500))
300 } else {
301 let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize;
302 (b.saturating_sub(1).clamp(2, cap), 0)
303 };
304 self.range.reset(budget);
305 let n = self
306 .celt
307 .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?;
308 self.final_range = self.range.range();
309 Ok(n)
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 /// The private half of the bandwidth decision: the thresholds themselves,
318 /// which the TOC config only reports.
319 #[test]
320 fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() {
321 let mut e = Encoder::new(48000, 1, Application::Audio).unwrap();
322 e.set_bitrate(64000);
323 assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
324 e.set_bitrate(16000);
325 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
326 e.set_bitrate(10000);
327 assert_eq!(e.auto_bandwidth(), Bandwidth::Wide);
328 e.set_bitrate(8000);
329 assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow);
330 // Speech asks for one step narrower at the same rate.
331 let mut v = Encoder::new(48000, 1, Application::Voip).unwrap();
332 v.set_bitrate(16000);
333 assert_eq!(v.auto_bandwidth(), Bandwidth::Wide);
334 // The input's own Nyquist bounds it whatever the rate says.
335 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
336 e.set_bitrate(256_000);
337 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
338 assert_eq!(e.look_ahead(), 60);
339 }
340}