Skip to main content

moq_mux/codec/opus/
mapping.rs

1//! The OpusHead channel mapping table (RFC 7845 §5.1.1).
2
3use bytes::Buf;
4
5use super::{Error, Result};
6
7/// An OpusHead channel mapping table (RFC 7845 §5.1.1), present for every family but 0.
8#[derive(Clone, Copy, PartialEq, Eq)]
9pub struct Mapping {
10	family: u8,
11	streams: u8,
12	coupled: u8,
13	channels: u8,
14	// Sized for the most channels any family allows, so `opus::Config` stays `Copy`.
15	table: [u8; 255],
16}
17
18/// The fields of a channel mapping table, checked into a [`Mapping`] by [`Mapping::new`].
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct Config<'a> {
21	/// The channel mapping family; 0 has no table and is refused.
22	pub family: u8,
23	/// Number of Opus streams in each packet.
24	pub streams: u8,
25	/// How many of those streams are coupled (stereo); they come first.
26	pub coupled: u8,
27	/// The decoded channel feeding each output channel, 255 for silence.
28	pub table: &'a [u8],
29}
30
31/// The family 1 stream counts and table for 1 to 8 channels, as libopus and
32/// RFC 7845 §5.1.1.2 lay out the Vorbis channel orders.
33const VORBIS: [(u8, u8, &[u8]); 8] = [
34	(1, 0, &[0]),
35	(1, 1, &[0, 1]),
36	(2, 1, &[0, 2, 1]),
37	(2, 2, &[0, 1, 2, 3]),
38	(3, 2, &[0, 4, 1, 2, 3]),
39	(4, 2, &[0, 4, 1, 2, 3, 5]),
40	(4, 3, &[0, 4, 1, 2, 3, 5, 6]),
41	(5, 3, &[0, 6, 1, 2, 3, 4, 5, 7]),
42];
43
44impl Mapping {
45	/// The family 1 mapping a surround encoder uses for `channels` in Vorbis
46	/// order, for sources that name only a channel count.
47	pub(crate) fn vorbis(channels: u8) -> Result<Self> {
48		let (streams, coupled, table) = *channels
49			.checked_sub(1)
50			.and_then(|index| VORBIS.get(index as usize))
51			.ok_or(Error::UnsupportedChannelCount(channels as u32))?;
52		Self::new(Config {
53			family: 1,
54			streams,
55			coupled,
56			table,
57		})
58	}
59
60	/// Check `config` into a mapping with one output channel per table entry.
61	///
62	/// Refuses family 0, a channel count the family does not allow (family 2
63	/// allows only the 4, 9, 16, ... channels of first order ambisonics and up,
64	/// without RFC 8486's non-diegetic stereo pair), and a table
65	/// that names no streams, more coupled streams than streams, or a channel
66	/// past the decoded ones.
67	pub fn new(config: Config<'_>) -> Result<Self> {
68		let Config {
69			family,
70			streams,
71			coupled,
72			table,
73		} = config;
74		let max_channels = match family {
75			0 => return Err(Error::UnsupportedMappingFamily(0)),
76			1 => 8,
77			_ => 255,
78		};
79		if table.is_empty() || table.len() > max_channels {
80			return Err(Error::UnsupportedChannelCount(table.len() as u32));
81		}
82		// RFC 8486 §3.1 gives family 2 (1 + n)² ambisonic channels for n in 0..=14, plus 0 or 2
83		// non-diegetic stereo ones. The catalog's ambisonic layout carries neither zeroth order nor
84		// the stereo pair, so only first order and up without the pair is accepted.
85		let order = (table.len() as u32).isqrt();
86		if family == 2 && (order < 2 || order * order != table.len() as u32) {
87			return Err(Error::UnsupportedChannelCount(table.len() as u32));
88		}
89
90		let decoded = streams as u32 + coupled as u32;
91		if streams == 0 || coupled > streams || decoded > 255 {
92			return Err(Error::InvalidMappingTable);
93		}
94		if table.iter().any(|&entry| entry != 255 && entry as u32 >= decoded) {
95			return Err(Error::InvalidMappingTable);
96		}
97
98		let mut padded = [0u8; 255];
99		padded[..table.len()].copy_from_slice(table);
100		Ok(Self {
101			family,
102			streams,
103			coupled,
104			channels: table.len() as u8,
105			table: padded,
106		})
107	}
108
109	pub(super) fn parse<T: Buf>(buf: &mut T, family: u8, channels: u8) -> Result<Self> {
110		if buf.remaining() < 2 + channels as usize {
111			return Err(Error::MappingTableTooShort);
112		}
113		let streams = buf.get_u8();
114		let coupled = buf.get_u8();
115		let mut table = [0u8; 255];
116		buf.copy_to_slice(&mut table[..channels as usize]);
117		Self::new(Config {
118			family,
119			streams,
120			coupled,
121			table: &table[..channels as usize],
122		})
123	}
124
125	/// The channel mapping family: 1 is the Vorbis speaker order, 2 and 3 are
126	/// ambisonics, and 255 is channels with no declared position.
127	pub fn family(&self) -> u8 {
128		self.family
129	}
130
131	/// Number of Opus streams in each packet.
132	pub fn streams(&self) -> u8 {
133		self.streams
134	}
135
136	/// How many of those streams are coupled (stereo); they come first.
137	pub fn coupled(&self) -> u8 {
138		self.coupled
139	}
140
141	/// The decoded channel feeding each output channel, 255 for silence.
142	pub fn table(&self) -> &[u8] {
143		&self.table[..self.channels as usize]
144	}
145}
146
147impl std::fmt::Debug for Mapping {
148	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149		f.debug_struct("Mapping")
150			.field("family", &self.family)
151			.field("streams", &self.streams)
152			.field("coupled", &self.coupled)
153			.field("table", &self.table())
154			.finish()
155	}
156}
157
158#[cfg(test)]
159mod tests {
160	use super::*;
161
162	#[test]
163	fn new_validates_the_table() {
164		fn new(family: u8, streams: u8, coupled: u8, table: &[u8]) -> Result<Mapping> {
165			Mapping::new(Config {
166				family,
167				streams,
168				coupled,
169				table,
170			})
171		}
172
173		let mapping = new(255, 2, 0, &[0, 1, 255]).unwrap();
174		assert_eq!(mapping.family(), 255);
175		assert_eq!((mapping.streams(), mapping.coupled()), (2, 0));
176		assert_eq!(mapping.table(), &[0, 1, 255]);
177
178		assert!(matches!(new(0, 1, 1, &[0, 1]), Err(Error::UnsupportedMappingFamily(0))));
179		assert!(matches!(new(1, 1, 0, &[]), Err(Error::UnsupportedChannelCount(0))));
180		assert!(matches!(new(1, 9, 0, &[0; 9]), Err(Error::UnsupportedChannelCount(9))));
181		assert_eq!(new(2, 4, 0, &[0, 1, 2, 3]).unwrap().family(), 2);
182		assert_eq!(new(2, 9, 0, &[0, 1, 2, 3, 4, 5, 6, 7, 8]).unwrap().family(), 2);
183		// Zeroth order, first order with RFC 8486's non-diegetic stereo pair, and counts it forbids.
184		for channels in [1u8, 3, 6, 11, 2, 5, 8, 10] {
185			let table: Vec<u8> = (0..channels).collect();
186			assert!(
187				matches!(new(2, channels, 0, &table), Err(Error::UnsupportedChannelCount(c)) if c == channels as u32),
188				"{channels} channels"
189			);
190		}
191		for (streams, coupled, table) in [(0, 0, &[0][..]), (1, 2, &[0]), (1, 1, &[2]), (200, 100, &[0])] {
192			assert!(
193				matches!(new(1, streams, coupled, table), Err(Error::InvalidMappingTable)),
194				"{streams} streams, {coupled} coupled, {table:?}"
195			);
196		}
197	}
198}