1mod import;
7pub mod mapping;
8
9pub use import::*;
10pub use mapping::Mapping;
11
12use bytes::{Buf, Bytes};
13
14const OPUS_HEAD: u64 = u64::from_be_bytes(*b"OpusHead");
15
16pub const WARMUP: std::time::Duration = std::time::Duration::from_millis(80);
18
19#[derive(Debug, Clone, thiserror::Error)]
21#[non_exhaustive]
22pub enum Error {
23 #[error("OpusHead must be at least 19 bytes")]
25 HeadTooShort,
26
27 #[error("invalid OpusHead signature")]
29 InvalidSignature,
30
31 #[error("unsupported OpusHead version {0}")]
34 UnsupportedVersion(u8),
35
36 #[error("channel mapping family does not allow {0} channels")]
40 UnsupportedChannelCount(u32),
41
42 #[error("OpusHead channel mapping table is truncated")]
44 MappingTableTooShort,
45
46 #[error("invalid OpusHead channel mapping table")]
49 InvalidMappingTable,
50
51 #[error("unsupported channel mapping family {0}")]
55 UnsupportedMappingFamily(u8),
56}
57
58pub type Result<T> = std::result::Result<T, Error>;
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct Config {
65 pub sample_rate: u32,
70 pub channel_count: u32,
72 pub pre_skip: u16,
74 pub output_gain: i16,
76 pub mapping: Option<Mapping>,
78}
79
80impl Config {
81 pub fn new(sample_rate: u32, channel_count: u32) -> Self {
83 Self {
84 sample_rate,
85 channel_count,
86 pre_skip: 0,
87 output_gain: 0,
88 mapping: None,
89 }
90 }
91
92 pub fn with_pre_skip(mut self, pre_skip: u16) -> Self {
94 self.pre_skip = pre_skip;
95 self
96 }
97
98 pub fn parse<T: Buf>(buf: &mut T) -> Result<Self> {
104 if buf.remaining() < 19 {
105 return Err(Error::HeadTooShort);
106 }
107 let signature = buf.get_u64();
108 if signature != OPUS_HEAD {
109 return Err(Error::InvalidSignature);
110 }
111
112 let version = buf.get_u8();
113 if version > 15 {
114 return Err(Error::UnsupportedVersion(version));
115 }
116 let channel_count = buf.get_u8() as u32;
117 let pre_skip = buf.get_u16_le();
118 let sample_rate = buf.get_u32_le();
119 let output_gain = buf.get_i16_le();
120 let family = buf.get_u8();
121
122 let mapping = match family {
123 0 if (1..=2).contains(&channel_count) => None,
124 0 => return Err(Error::UnsupportedChannelCount(channel_count)),
125 other => Some(Mapping::parse(buf, other, channel_count as u8)?),
126 };
127
128 Ok(Self {
129 sample_rate,
130 channel_count,
131 pre_skip,
132 output_gain,
133 mapping,
134 })
135 }
136
137 pub fn encode(&self) -> Result<Bytes> {
145 let valid = match &self.mapping {
146 None => (1..=2).contains(&self.channel_count),
147 Some(mapping) => self.channel_count == mapping.table().len() as u32,
148 };
149 if !valid {
150 return Err(Error::UnsupportedChannelCount(self.channel_count));
151 }
152
153 let mut head = Vec::with_capacity(21 + self.channel_count as usize);
154 head.extend_from_slice(b"OpusHead");
155 head.push(1); head.push(self.channel_count as u8);
157 head.extend_from_slice(&self.pre_skip.to_le_bytes());
158 head.extend_from_slice(&self.sample_rate.to_le_bytes());
159 head.extend_from_slice(&self.output_gain.to_le_bytes());
160 match &self.mapping {
161 None => head.push(0),
162 Some(mapping) => {
163 head.extend_from_slice(&[mapping.family(), mapping.streams(), mapping.coupled()]);
164 head.extend_from_slice(mapping.table());
165 }
166 }
167 Ok(Bytes::from(head))
168 }
169}
170
171pub fn packet_samples(packet: &[u8]) -> Option<u32> {
177 let toc = *packet.first()?;
178 let frames = match toc & 0b11 {
179 0 => 1,
180 1 | 2 => 2,
181 _ => (packet.get(1)? & 0b0011_1111) as u32,
183 };
184 let samples = config_samples(toc >> 3) * frames;
185 (frames > 0 && samples <= 5_760).then_some(samples)
187}
188
189fn config_samples(config: u8) -> u32 {
191 match config {
192 0 | 4 | 8 => 480,
194 1 | 5 | 9 => 960,
195 2 | 6 | 10 => 1920,
196 3 | 7 | 11 => 2880,
197 12 | 14 => 480,
199 13 | 15 => 960,
200 16 | 20 | 24 | 28 => 120,
202 17 | 21 | 25 | 29 => 240,
203 18 | 22 | 26 | 30 => 480,
204 _ => 960,
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 #[test]
214 fn packet_samples_reads_toc() {
215 assert_eq!(packet_samples(&[16 << 3]), Some(120));
217 assert_eq!(packet_samples(&[3 << 3]), Some(2880));
219 assert_eq!(packet_samples(&[(1 << 3) | 1]), Some(1920));
221 assert_eq!(packet_samples(&[(1 << 3) | 3, 4]), Some(3840));
223 assert_eq!(packet_samples(&[]), None);
224 assert_eq!(packet_samples(&[(1 << 3) | 3, 0]), None);
226 assert_eq!(packet_samples(&[(3 << 3) | 3, 63]), None);
227 assert_eq!(packet_samples(&[(3 << 3) | 3, 2]), Some(5760));
229 }
230
231 #[test]
232 fn parses_valid_opus_head() {
233 let cfg = Config::new(48_000, 2).with_pre_skip(312);
234 let encoded = cfg.encode().unwrap();
235 assert_eq!(encoded.len(), 19);
236 let parsed = Config::parse(&mut encoded.as_ref()).unwrap();
237 assert_eq!(parsed.sample_rate, 48_000);
238 assert_eq!(parsed.channel_count, 2);
239 assert_eq!(parsed.pre_skip, 312);
240 assert_eq!(parsed, cfg);
241 }
242
243 #[test]
244 fn parse_rejects_invalid_signature() {
245 let mut bytes = Config::new(48_000, 1).encode().unwrap().to_vec();
246 bytes[0] = b'X';
247 assert!(Config::parse(&mut bytes.as_slice()).is_err());
248 }
249
250 #[test]
251 fn encode_rejects_multichannel() {
252 let err = Config::new(48_000, 6).encode().unwrap_err();
253 assert!(matches!(err, Error::UnsupportedChannelCount(6)));
254 }
255
256 fn head(version: u8, channels: u8, gain: i16, family: u8) -> Vec<u8> {
258 let mut head = b"OpusHead".to_vec();
259 head.push(version);
260 head.push(channels);
261 head.extend_from_slice(&312u16.to_le_bytes());
262 head.extend_from_slice(&44_100u32.to_le_bytes());
263 head.extend_from_slice(&gain.to_le_bytes());
264 head.push(family);
265 head
266 }
267
268 #[test]
269 fn parses_gain_and_input_rate() {
270 let bytes = head(1, 2, -1536, 0);
271 let parsed = Config::parse(&mut bytes.as_slice()).unwrap();
272 assert_eq!(parsed.sample_rate, 44_100);
273 assert_eq!(parsed.pre_skip, 312);
274 assert_eq!(parsed.output_gain, -1536);
275 assert!(parsed.mapping.is_none());
276
277 let encoded = parsed.encode().unwrap();
279 assert_eq!(encoded.as_ref(), bytes.as_slice());
280 }
281
282 #[test]
283 fn parse_accepts_minor_versions_only() {
284 for version in [0, 1, 15] {
285 assert!(Config::parse(&mut head(version, 2, 0, 0).as_slice()).is_ok());
286 }
287 assert!(matches!(
288 Config::parse(&mut head(16, 2, 0, 0).as_slice()),
289 Err(Error::UnsupportedVersion(16))
290 ));
291 }
292
293 #[test]
294 fn parses_a_mapping_table() {
295 let mut bytes = head(1, 6, 0, 1);
297 bytes.extend_from_slice(&[4, 2, 0, 4, 1, 2, 3, 5]);
298 let trailing = [bytes.as_slice(), b"trailing"].concat();
299 let mut buf = trailing.as_slice();
300 let parsed = Config::parse(&mut buf).unwrap();
301 assert_eq!(buf, b"trailing");
302 assert_eq!(parsed.channel_count, 6);
303
304 let mapping = parsed.mapping.unwrap();
305 assert_eq!(mapping.family(), 1);
306 assert_eq!(mapping.streams(), 4);
307 assert_eq!(mapping.coupled(), 2);
308 assert_eq!(mapping.table(), &[0, 4, 1, 2, 3, 5]);
309
310 assert_eq!(parsed.encode().unwrap(), bytes);
312 }
313
314 #[test]
315 fn encodes_the_vorbis_mappings() {
316 for channels in 1..=8u8 {
317 let mut config = Config::new(48_000, channels as u32);
318 config.mapping = Some(Mapping::vorbis(channels).unwrap());
319 let head = config.encode().unwrap();
320 assert_eq!(head.len(), 21 + channels as usize, "{channels} channels");
321 assert_eq!(
322 Config::parse(&mut head.as_ref()).unwrap(),
323 config,
324 "{channels} channels"
325 );
326 }
327
328 let five_one = Mapping::vorbis(6).unwrap();
330 assert_eq!((five_one.streams(), five_one.coupled()), (4, 2));
331 assert_eq!(five_one.table(), &[0, 4, 1, 2, 3, 5]);
332
333 assert!(matches!(Mapping::vorbis(0), Err(Error::UnsupportedChannelCount(0))));
334 assert!(matches!(Mapping::vorbis(9), Err(Error::UnsupportedChannelCount(9))));
335
336 let mut config = Config::new(48_000, 5);
338 config.mapping = Some(five_one);
339 assert!(matches!(config.encode(), Err(Error::UnsupportedChannelCount(5))));
340 }
341
342 #[test]
343 fn parse_rejects_channel_counts_the_family_does_not_allow() {
344 for (channels, family) in [(0, 0), (3, 0), (0, 1), (9, 1), (0, 255)] {
345 let mut bytes = head(1, channels, 0, family);
346 bytes.extend_from_slice(&[1, 0]);
347 bytes.extend(std::iter::repeat_n(0, channels as usize));
348 assert!(
349 matches!(
350 Config::parse(&mut bytes.as_slice()),
351 Err(Error::UnsupportedChannelCount(_))
352 ),
353 "{channels} channels in family {family}"
354 );
355 }
356 }
357
358 #[test]
359 fn parse_rejects_a_bad_mapping_table() {
360 assert!(matches!(
362 Config::parse(&mut head(1, 2, 0, 1).as_slice()),
363 Err(Error::MappingTableTooShort)
364 ));
365 let mut short = head(1, 2, 0, 1);
366 short.extend_from_slice(&[1, 1, 0]);
367 assert!(matches!(
368 Config::parse(&mut short.as_slice()),
369 Err(Error::MappingTableTooShort)
370 ));
371
372 for table in [
373 [0, 0, 0, 1],
375 [1, 2, 0, 1],
377 [1, 1, 0, 2],
379 ] {
380 let mut bytes = head(1, 2, 0, 1);
381 bytes.extend_from_slice(&table);
382 assert!(
383 matches!(Config::parse(&mut bytes.as_slice()), Err(Error::InvalidMappingTable)),
384 "{table:?}"
385 );
386 }
387
388 let mut silent = head(1, 2, 0, 1);
390 silent.extend_from_slice(&[1, 0, 0, 255]);
391 assert_eq!(
392 Config::parse(&mut silent.as_slice()).unwrap().mapping.unwrap().table(),
393 &[0, 255]
394 );
395 }
396}