forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

packet.rs423 lines, 15.2 KiBHistoryRawDownload
1//! Opus packet framing: the TOC byte, codes 0-3, and the self-delimiting
2//! variant (RFC 6716, Section 3 and Appendix B).
3//!
4//! Every rule marked `[R1]`..`[R7]` in Section 3.4 is enforced here and reported as
5//! [`Error::Corrupt`] — a malformed packet is rejected at the framing layer, so
6//! nothing downstream ever sees a frame it cannot account for.
7//!
8//! The self-delimiting variant is what makes multichannel work: a multistream
9//! packet is several ordinary Opus packets concatenated, all but the last
10//! carrying their own length. [`Packet::parse`] with `self_delimited = true`
11//! reports how many bytes it consumed so the next stream can start there.
12
13use ec_core::{Error, Result};
14
15/// Which of the three operating modes a configuration selects.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Mode {
18 /// SILK only: NB/MB/WB speech, 10-60 ms.
19 Silk,
20 /// SILK below 8 kHz plus CELT above it: SWB/FB, 10 or 20 ms.
21 Hybrid,
22 /// CELT only: NB..FB, 2.5-20 ms.
23 Celt,
24}
25
26/// Audio bandwidth, in the RFC's names.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
28pub enum Bandwidth {
29 /// Narrowband, 4 kHz.
30 Narrow,
31 /// Mediumband, 6 kHz.
32 Medium,
33 /// Wideband, 8 kHz.
34 Wide,
35 /// Super-wideband, 12 kHz.
36 SuperWide,
37 /// Fullband, 20 kHz.
38 Full,
39}
40
41impl Bandwidth {
42 /// The CELT band count that covers this bandwidth (Section 4.3).
43 pub fn celt_end_band(self) -> usize {
44 match self {
45 Bandwidth::Narrow => 13,
46 Bandwidth::Medium | Bandwidth::Wide => 17,
47 Bandwidth::SuperWide => 19,
48 Bandwidth::Full => 21,
49 }
50 }
51}
52
53/// The parsed TOC byte (Section 3.1).
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub struct Toc {
56 /// Configuration number, 0..32.
57 pub config: u8,
58 /// True when the packet carries two channels.
59 pub stereo: bool,
60 /// Frame count code, 0..4.
61 pub code: u8,
62}
63
64impl Toc {
65 /// Splits a TOC byte into its fields.
66 pub fn new(byte: u8) -> Toc {
67 Toc {
68 config: byte >> 3,
69 stereo: byte & 0x4 != 0,
70 code: byte & 0x3,
71 }
72 }
73
74 /// Operating mode for this configuration.
75 pub fn mode(self) -> Mode {
76 match self.config {
77 0..=11 => Mode::Silk,
78 12..=15 => Mode::Hybrid,
79 _ => Mode::Celt,
80 }
81 }
82
83 /// Audio bandwidth for this configuration.
84 pub fn bandwidth(self) -> Bandwidth {
85 match self.config {
86 0..=3 => Bandwidth::Narrow,
87 4..=7 => Bandwidth::Medium,
88 8..=11 => Bandwidth::Wide,
89 12..=13 => Bandwidth::SuperWide,
90 14..=15 => Bandwidth::Full,
91 16..=19 => Bandwidth::Narrow,
92 20..=23 => Bandwidth::Wide,
93 24..=27 => Bandwidth::SuperWide,
94 _ => Bandwidth::Full,
95 }
96 }
97
98 /// Samples per frame at 48 kHz.
99 pub fn frame_size_48k(self) -> usize {
100 match self.config {
101 // SILK: 10, 20, 40, 60 ms.
102 0..=11 => [480, 960, 1920, 2880][(self.config & 0x3) as usize],
103 // Hybrid: 10, 20 ms.
104 12..=15 => [480, 960][(self.config & 0x1) as usize],
105 // CELT: 2.5, 5, 10, 20 ms.
106 _ => [120, 240, 480, 960][(self.config & 0x3) as usize],
107 }
108 }
109
110 /// Channel count signalled by the stereo flag.
111 pub fn channels(self) -> usize {
112 if self.stereo { 2 } else { 1 }
113 }
114}
115
116/// One parsed Opus packet: its TOC and the byte range of each Opus frame.
117#[derive(Clone, Debug)]
118pub struct Packet<'a> {
119 /// The table-of-contents byte.
120 pub toc: Toc,
121 /// Compressed frames, in order. A zero-length frame is DTX.
122 pub frames: Vec<&'a [u8]>,
123 /// Bytes of the input this packet occupied — the offset of the next
124 /// stream when parsing self-delimited packets.
125 pub consumed: usize,
126}
127
128/// Reads a one- or two-byte frame length (Section 3.2.1).
129fn frame_length(data: &[u8], pos: &mut usize) -> Result<usize> {
130 let b0 = *data
131 .get(*pos)
132 .ok_or_else(|| Error::corrupt("opus packet: truncated frame length"))?
133 as usize;
134 *pos += 1;
135 if b0 < 252 {
136 return Ok(b0);
137 }
138 let b1 = *data
139 .get(*pos)
140 .ok_or_else(|| Error::corrupt("opus packet: truncated two-byte frame length"))?
141 as usize;
142 *pos += 1;
143 Ok(b1 * 4 + b0)
144}
145
146impl<'a> Packet<'a> {
147 /// Parses one packet. `self_delimited` selects the Appendix B variant, in
148 /// which one extra length precedes the first frame's data.
149 ///
150 /// Rejects every malformed packet listed in Section 3.4 rather than
151 /// guessing at a repair.
152 pub fn parse(data: &'a [u8], self_delimited: bool) -> Result<Packet<'a>> {
153 // [R1] Packets are at least one byte.
154 if data.is_empty() {
155 return Err(Error::corrupt("opus packet: empty"));
156 }
157 let toc = Toc::new(data[0]);
158 let mut pos = 1usize;
159 let mut frames = Vec::new();
160 // Total duration cap of 120 ms [R5].
161 let max_frames = 5760 / toc.frame_size_48k();
162
163 match toc.code {
164 0 => {
165 let len = if self_delimited {
166 frame_length(data, &mut pos)?
167 } else {
168 data.len() - pos
169 };
170 push_frame(data, &mut pos, len, &mut frames)?;
171 }
172 1 => {
173 let len = if self_delimited {
174 frame_length(data, &mut pos)?
175 } else {
176 // [R3] the payload must split evenly in two.
177 let rest = data.len() - pos;
178 if !rest.is_multiple_of(2) {
179 return Err(Error::corrupt("opus packet: code 1 with odd payload"));
180 }
181 rest / 2
182 };
183 push_frame(data, &mut pos, len, &mut frames)?;
184 push_frame(data, &mut pos, len, &mut frames)?;
185 }
186 2 => {
187 // [R4] first length must fit in what remains.
188 let n1 = frame_length(data, &mut pos)?;
189 let n2 = if self_delimited {
190 frame_length(data, &mut pos)?
191 } else {
192 (data.len() - pos)
193 .checked_sub(n1)
194 .ok_or_else(|| Error::corrupt("opus packet: code 2 first frame overruns"))?
195 };
196 push_frame(data, &mut pos, n1, &mut frames)?;
197 push_frame(data, &mut pos, n2, &mut frames)?;
198 }
199 _ => {
200 // [R6,R7] code 3 needs the frame count byte.
201 let fc = *data
202 .get(pos)
203 .ok_or_else(|| Error::corrupt("opus packet: code 3 without frame count"))?;
204 pos += 1;
205 let vbr = fc & 0x80 != 0;
206 let padded = fc & 0x40 != 0;
207 let count = (fc & 0x3F) as usize;
208 // [R5] at least one frame, at most 120 ms of audio.
209 if count == 0 || count > max_frames {
210 return Err(Error::corrupt(format!(
211 "opus packet: code 3 frame count {count} (max {max_frames})"
212 )));
213 }
214 let mut padding = 0usize;
215 if padded {
216 loop {
217 let p = *data.get(pos).ok_or_else(|| {
218 Error::corrupt("opus packet: truncated padding length")
219 })?;
220 pos += 1;
221 padding += p as usize;
222 if p != 255 {
223 break;
224 }
225 padding -= 1;
226 }
227 }
228 // Padding bytes live at the very end of the packet. Where the
229 // packet end is only known from the frame lengths (Appendix B),
230 // they are skipped after the frames instead.
231 let body = if self_delimited {
232 data
233 } else {
234 let end = data
235 .len()
236 .checked_sub(padding)
237 .filter(|end| *end >= pos)
238 .ok_or_else(|| Error::corrupt("opus packet: padding larger than packet"))?;
239 &data[..end]
240 };
241 if vbr {
242 let mut lengths = Vec::with_capacity(count);
243 for _ in 0..count - 1 {
244 lengths.push(frame_length(body, &mut pos)?);
245 }
246 let last = if self_delimited {
247 frame_length(body, &mut pos)?
248 } else {
249 let used: usize = lengths.iter().sum();
250 (body.len() - pos).checked_sub(used).ok_or_else(|| {
251 Error::corrupt("opus packet: code 3 VBR lengths overrun")
252 })?
253 };
254 lengths.push(last);
255 for len in lengths {
256 push_frame(body, &mut pos, len, &mut frames)?;
257 }
258 } else {
259 let len = if self_delimited {
260 frame_length(body, &mut pos)?
261 } else {
262 // [R6] (N-2-P) must be a multiple of M.
263 let rest = body.len() - pos;
264 if !rest.is_multiple_of(count) {
265 return Err(Error::corrupt(
266 "opus packet: code 3 CBR payload not a multiple of the frame count",
267 ));
268 }
269 rest / count
270 };
271 for _ in 0..count {
272 push_frame(body, &mut pos, len, &mut frames)?;
273 }
274 }
275 pos += padding;
276 }
277 }
278
279 // [R2] no frame exceeds 1275 bytes.
280 if let Some(f) = frames.iter().find(|f| f.len() > 1275) {
281 return Err(Error::corrupt(format!(
282 "opus packet: frame of {} bytes exceeds 1275",
283 f.len()
284 )));
285 }
286 if !self_delimited && pos != data.len() {
287 return Err(Error::corrupt(format!(
288 "opus packet: {} trailing bytes",
289 data.len() - pos
290 )));
291 }
292 Ok(Packet {
293 toc,
294 frames,
295 consumed: pos,
296 })
297 }
298
299 /// Samples this packet decodes to at 48 kHz.
300 pub fn samples_48k(&self) -> usize {
301 self.frames.len() * self.toc.frame_size_48k()
302 }
303}
304
305fn push_frame<'a>(
306 data: &'a [u8],
307 pos: &mut usize,
308 len: usize,
309 frames: &mut Vec<&'a [u8]>,
310) -> Result<()> {
311 let end = pos
312 .checked_add(len)
313 .filter(|end| *end <= data.len())
314 .ok_or_else(|| Error::corrupt("opus packet: frame runs past the end of the packet"))?;
315 frames.push(&data[*pos..end]);
316 *pos = end;
317 Ok(())
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 #[test]
325 fn toc_table_2() {
326 // Spot-checks of Table 2, one per row plus the frame-size ordering.
327 assert_eq!(Toc::new(0).mode(), Mode::Silk);
328 assert_eq!(Toc::new(0).frame_size_48k(), 480);
329 assert_eq!(Toc::new(3 << 3).frame_size_48k(), 2880);
330 assert_eq!(Toc::new(4 << 3).bandwidth(), Bandwidth::Medium);
331 assert_eq!(Toc::new(12 << 3).mode(), Mode::Hybrid);
332 assert_eq!(Toc::new(12 << 3).bandwidth(), Bandwidth::SuperWide);
333 assert_eq!(Toc::new(13 << 3).frame_size_48k(), 960);
334 assert_eq!(Toc::new(15 << 3).bandwidth(), Bandwidth::Full);
335 assert_eq!(Toc::new(16 << 3).mode(), Mode::Celt);
336 assert_eq!(Toc::new(16 << 3).frame_size_48k(), 120);
337 assert_eq!(Toc::new(31 << 3).bandwidth(), Bandwidth::Full);
338 assert!(Toc::new((31 << 3) | 4).stereo);
339 assert_eq!(Toc::new((31 << 3) | 4 | 3).code, 3);
340 }
341
342 #[test]
343 fn code0_to_code3() {
344 // Code 0: everything after the TOC is one frame.
345 let p = Packet::parse(&[0, 0xaa, 0xbb], false).unwrap();
346 assert_eq!(p.frames, vec![&[0xaa, 0xbb][..]]);
347
348 // Code 1: two halves.
349 let p = Packet::parse(&[1, 1, 2, 3, 4], false).unwrap();
350 assert_eq!(p.frames, vec![&[1, 2][..], &[3, 4][..]]);
351 assert!(Packet::parse(&[1, 1, 2, 3], false).is_err(), "[R3]");
352
353 // Code 2: explicit first length.
354 let p = Packet::parse(&[2, 1, 0x11, 0x22, 0x33], false).unwrap();
355 assert_eq!(p.frames, vec![&[0x11][..], &[0x22, 0x33][..]]);
356 assert!(Packet::parse(&[2, 9, 0x11], false).is_err(), "[R4]");
357
358 // Code 3 CBR, 3 frames of 2 bytes.
359 let p = Packet::parse(&[3, 3, 1, 2, 3, 4, 5, 6], false).unwrap();
360 assert_eq!(p.frames.len(), 3);
361 assert_eq!(p.frames[2], &[5, 6][..]);
362 assert!(
363 Packet::parse(&[3, 3, 1, 2, 3, 4, 5], false).is_err(),
364 "[R6]"
365 );
366 assert!(Packet::parse(&[3, 0], false).is_err(), "[R5] zero frames");
367
368 // Code 3 VBR with padding: lengths 1 and 2, then 2 padding bytes.
369 let p = Packet::parse(
370 &[3, 0x80 | 0x40 | 3, 2, 1, 2, 0xa, 0xb, 0xc, 0xd, 0, 0],
371 false,
372 )
373 .unwrap();
374 assert_eq!(p.frames, vec![&[0xa][..], &[0xb, 0xc][..], &[0xd][..]]);
375
376 // [R1]
377 assert!(Packet::parse(&[], false).is_err());
378 }
379
380 #[test]
381 fn self_delimited_leaves_the_rest_for_the_next_stream() {
382 // Two self-delimited code 0 packets back to back, then an undelimited one.
383 let data = [0, 2, 0xa, 0xb, 0, 1, 0xc, 0, 0xd, 0xe];
384 let first = Packet::parse(&data, true).unwrap();
385 assert_eq!(first.frames, vec![&[0xa, 0xb][..]]);
386 assert_eq!(first.consumed, 4);
387 let second = Packet::parse(&data[first.consumed..], true).unwrap();
388 assert_eq!(second.frames, vec![&[0xc][..]]);
389 assert_eq!(second.consumed, 3);
390 let last = Packet::parse(&data[first.consumed + second.consumed..], false).unwrap();
391 assert_eq!(last.frames, vec![&[0xd, 0xe][..]]);
392
393 // Code 1 self-delimited: the length applies to both frames.
394 let p = Packet::parse(&[1, 2, 1, 2, 3, 4, 0xff], true).unwrap();
395 assert_eq!(p.frames, vec![&[1, 2][..], &[3, 4][..]]);
396 assert_eq!(p.consumed, 6);
397
398 // Code 2 self-delimited: both lengths explicit.
399 let p = Packet::parse(&[2, 1, 2, 0x11, 0x22, 0x33, 0xff], true).unwrap();
400 assert_eq!(p.frames, vec![&[0x11][..], &[0x22, 0x33][..]]);
401 assert_eq!(p.consumed, 6);
402 }
403
404 #[test]
405 fn malformed_input_is_an_error_not_a_panic() {
406 // Every prefix of a well-formed packet, and a fuzz of short buffers.
407 let good = [3u8, 0x80 | 0x40 | 3, 2, 1, 2, 0xa, 0xb, 0xc, 0xd, 0, 0];
408 for n in 0..good.len() {
409 let _ = Packet::parse(&good[..n], false);
410 let _ = Packet::parse(&good[..n], true);
411 }
412 let mut x = 1u32;
413 for _ in 0..5000 {
414 let mut buf = Vec::new();
415 for _ in 0..(x % 17) {
416 x = x.wrapping_mul(1664525).wrapping_add(1013904223);
417 buf.push((x >> 16) as u8);
418 }
419 let _ = Packet::parse(&buf, false);
420 let _ = Packet::parse(&buf, true);
421 }
422 }
423}