Skip to main content

moq_mux/codec/opus/
mod.rs

1//! Opus.
2//!
3//! RFC 7845 OpusHead parse and encode lives in [`Config`]. [`Import`]
4//! publishes raw Opus frames (no Ogg framing) to a moq broadcast.
5
6mod 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
16/// The decoder pre-roll a joining Opus viewer discards, per RFC 7845 section 4.6.
17pub const WARMUP: std::time::Duration = std::time::Duration::from_millis(80);
18
19/// Opus parsing errors.
20#[derive(Debug, Clone, thiserror::Error)]
21#[non_exhaustive]
22pub enum Error {
23	/// The OpusHead packet was shorter than the 19-byte minimum (RFC 7845 §5.1).
24	#[error("OpusHead must be at least 19 bytes")]
25	HeadTooShort,
26
27	/// The packet did not start with the `OpusHead` magic signature.
28	#[error("invalid OpusHead signature")]
29	InvalidSignature,
30
31	/// The OpusHead major version (the upper four bits) is not one this parser
32	/// understands, so none of its fields can be trusted (RFC 7845 §5.1).
33	#[error("unsupported OpusHead version {0}")]
34	UnsupportedVersion(u8),
35
36	/// The channel count is zero, or one the channel mapping family does not allow:
37	/// family 0 covers mono/stereo, family 1 up to eight channels, and family 2 the
38	/// square counts of first order ambisonics and up.
39	#[error("channel mapping family does not allow {0} channels")]
40	UnsupportedChannelCount(u32),
41
42	/// A nonzero channel mapping family without its complete mapping table.
43	#[error("OpusHead channel mapping table is truncated")]
44	MappingTableTooShort,
45
46	/// The channel mapping table names no streams, more coupled streams than
47	/// streams, or a channel index past the decoded streams.
48	#[error("invalid OpusHead channel mapping table")]
49	InvalidMappingTable,
50
51	/// A channel mapping family the operation cannot carry: family 0 given to
52	/// [`Mapping::new`], which has no table, or a container with no room for
53	/// the mapping, such as family 3's demixing matrix in an fMP4 `dOps`.
54	#[error("unsupported channel mapping family {0}")]
55	UnsupportedMappingFamily(u8),
56}
57
58/// A result using this module's error type.
59pub type Result<T> = std::result::Result<T, Error>;
60
61/// Typed Opus configuration mirroring the parsed fields of an OpusHead packet.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct Config {
65	/// Original input sample rate in Hz, or 0 when unknown.
66	///
67	/// Metadata only: Opus always runs on a 48 kHz clock, and this need not be a
68	/// rate Opus can decode at (44.1 kHz is common).
69	pub sample_rate: u32,
70	/// Number of output channels.
71	pub channel_count: u32,
72	/// Number of decoded 48 kHz samples to discard at stream start.
73	pub pre_skip: u16,
74	/// Gain to apply to the decoded output, in Q7.8 dB.
75	pub output_gain: i16,
76	/// The channel mapping table, carrying its family; `None` is family 0.
77	pub mapping: Option<Mapping>,
78}
79
80impl Config {
81	/// Build a mono/stereo Opus config with no pre-skip or gain.
82	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	/// Set the number of decoded 48 kHz samples to discard at stream start.
93	pub fn with_pre_skip(mut self, pre_skip: u16) -> Self {
94		self.pre_skip = pre_skip;
95		self
96	}
97
98	/// Parse an OpusHead buffer (RFC 7845 §5.1).
99	///
100	/// Accepts any minor version and refuses a new major version. Reads the
101	/// channel mapping, refusing a channel count the family forbids or an
102	/// inconsistent mapping table. Bytes after the header are left in `buf`.
103	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	/// Encode an OpusHead packet (RFC 7845 §5.1), followed by the channel mapping
138	/// table when there is one.
139	///
140	/// The family byte is the mapping's, or 0 when there is none. Errors with
141	/// [`Error::UnsupportedChannelCount`] when `channel_count` is not 1 or 2
142	/// without a `mapping` (family 0 is only defined for mono/stereo), or is not
143	/// the mapping's own channel count.
144	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); // version
156		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
171/// Number of 48 kHz samples in an Opus packet, read from its TOC byte (RFC 6716 §3.1).
172///
173/// Opus timing is always reckoned at 48 kHz regardless of the encoder's internal bandwidth.
174/// Returns `None` for an empty packet, a code-3 packet missing its frame-count byte, or a
175/// packet outside the 1 frame and 120 ms RFC 6716 allows.
176pub 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		// Code 3: the frame count is the low 6 bits of the following byte.
182		_ => (packet.get(1)? & 0b0011_1111) as u32,
183	};
184	let samples = config_samples(toc >> 3) * frames;
185	// RFC 6716 §3.2.5: a packet holds at most 120 ms of audio.
186	(frames > 0 && samples <= 5_760).then_some(samples)
187}
188
189/// 48 kHz samples per frame for an Opus TOC config index (0..=31), per RFC 6716 Table 1.
190fn config_samples(config: u8) -> u32 {
191	match config {
192		// SILK NB/MB/WB: 10, 20, 40, 60 ms.
193		0 | 4 | 8 => 480,
194		1 | 5 | 9 => 960,
195		2 | 6 | 10 => 1920,
196		3 | 7 | 11 => 2880,
197		// Hybrid SWB/FB: 10, 20 ms.
198		12 | 14 => 480,
199		13 | 15 => 960,
200		// CELT NB/WB/SWB/FB: 2.5, 5, 10, 20 ms.
201		16 | 20 | 24 | 28 => 120,
202		17 | 21 | 25 | 29 => 240,
203		18 | 22 | 26 | 30 => 480,
204		// 19, 23, 27, 31 are the 20 ms CELT configs.
205		_ => 960,
206	}
207}
208
209#[cfg(test)]
210mod tests {
211	use super::*;
212
213	#[test]
214	fn packet_samples_reads_toc() {
215		// config 16 (CELT NB 2.5 ms = 120 samples), code 0 (1 frame).
216		assert_eq!(packet_samples(&[16 << 3]), Some(120));
217		// config 3 (SILK NB 60 ms = 2880), code 0.
218		assert_eq!(packet_samples(&[3 << 3]), Some(2880));
219		// config 1 (SILK NB 20 ms = 960), code 1 (2 frames) -> 1920.
220		assert_eq!(packet_samples(&[(1 << 3) | 1]), Some(1920));
221		// config 1, code 3 with 4 frames -> 3840.
222		assert_eq!(packet_samples(&[(1 << 3) | 3, 4]), Some(3840));
223		assert_eq!(packet_samples(&[]), None);
224		// Code 3 with zero frames, and with 63 frames of 60 ms.
225		assert_eq!(packet_samples(&[(1 << 3) | 3, 0]), None);
226		assert_eq!(packet_samples(&[(3 << 3) | 3, 63]), None);
227		// Two 60 ms frames is the 120 ms maximum.
228		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	/// A 19-byte head with the given version, channels, gain, and family.
257	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		// The gain survives a round trip.
278		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		// 5.1 in family 1: four streams, two coupled, Vorbis order.
296		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		// The table survives a re-encode.
311		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		// 5.1 is the table libopus and ffmpeg write.
329		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		// The channel count must agree with the table.
337		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		// Family 1 promising a table that is not there, or only half of it.
361		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			// No streams.
374			[0, 0, 0, 1],
375			// More coupled streams than streams.
376			[1, 2, 0, 1],
377			// A channel index past the two decoded channels.
378			[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		// 255 is a silent channel, not an index.
389		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}