Skip to main content

hang/catalog/audio/
layout.rs

1use std::str::FromStr;
2
3use derive_more::Display;
4
5/// What a rendition's decoded channels carry, beyond the codec's own channel order.
6///
7/// Absent means the codec's channel order. An unrecognized value decodes to
8/// [`AudioLayout::Unknown`] instead of failing, and a consumer treats it as absent.
9#[derive(Debug, Clone, PartialEq, Eq, Display)]
10#[non_exhaustive]
11pub enum AudioLayout {
12	/// Full-sphere ambisonics in AmbiX: ACN channel order with SN3D normalization.
13	///
14	/// The order follows from the channel count, `(order + 1)²`, so the count is a square of at least 4.
15	#[display("ambisonic")]
16	Ambisonic,
17
18	/// A layout this build does not recognize, preserved verbatim.
19	#[display("{_0}")]
20	Unknown(String),
21}
22
23impl AudioLayout {
24	/// Refuse a channel count this layout cannot carry.
25	pub(crate) fn check(&self, channel_count: u32) -> crate::Result<()> {
26		if *self == Self::Ambisonic {
27			let order = channel_count.isqrt();
28			if order < 2 || order * order != channel_count {
29				return Err(crate::Error::InvalidAmbisonicChannels(channel_count));
30			}
31		}
32		Ok(())
33	}
34}
35
36impl FromStr for AudioLayout {
37	type Err = crate::Error;
38
39	fn from_str(s: &str) -> Result<Self, Self::Err> {
40		Ok(match s {
41			"ambisonic" => Self::Ambisonic,
42			_ => Self::Unknown(s.to_string()),
43		})
44	}
45}
46
47#[cfg(test)]
48mod test {
49	use crate::catalog::{AudioCodec, AudioConfig};
50
51	use super::*;
52
53	#[test]
54	fn round_trips() {
55		for (layout, json) in [
56			(AudioLayout::Ambisonic, "ambisonic"),
57			(AudioLayout::Unknown("surround".to_string()), "surround"),
58		] {
59			let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 4);
60			config.layout = Some(layout.clone());
61			let encoded = serde_json::to_value(&config).unwrap();
62			assert_eq!(encoded["layout"], json);
63			assert_eq!(
64				serde_json::from_value::<AudioConfig>(encoded).unwrap().layout,
65				Some(layout)
66			);
67		}
68	}
69
70	#[test]
71	fn ambisonic_needs_a_square_channel_count() {
72		for channels in [4, 9, 16, 225] {
73			AudioLayout::Ambisonic.check(channels).unwrap();
74		}
75		for channels in [0, 1, 2, 6, 8] {
76			assert!(matches!(
77				AudioLayout::Ambisonic.check(channels),
78				Err(crate::Error::InvalidAmbisonicChannels(c)) if c == channels
79			));
80		}
81		// An unknown layout puts no constraint on the channel count.
82		AudioLayout::Unknown("surround".to_string()).check(6).unwrap();
83	}
84}