Skip to main content

hang/catalog/audio/
mod.rs

1mod aac;
2mod codec;
3mod layout;
4
5pub use aac::*;
6pub use codec::*;
7pub use layout::*;
8
9use std::collections::{BTreeMap, btree_map};
10
11use bytes::Bytes;
12
13use serde::{Deserialize, Serialize};
14use serde_with::DisplayFromStr;
15
16use crate::catalog::Container;
17use crate::catalog::hex::Hex;
18use crate::catalog::millis::MillisCeil;
19
20/// Information about an audio track in the catalog.
21///
22/// This struct contains a map of renditions (different quality/codec options)
23///
24/// Marked `#[non_exhaustive]` so additional optional fields can be added without
25/// bumping the major version. External callers start from [`Audio::default`] and
26/// fill in what they need ([`insert`](Self::insert) for renditions); struct-literal
27/// construction (with or without `..base`) is not available outside this crate.
28#[serde_with::serde_as]
29#[serde_with::skip_serializing_none]
30#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
31#[serde(rename_all = "camelCase")]
32#[non_exhaustive]
33pub struct Audio {
34	/// A map of track name to rendition configuration.
35	/// This is not an array so it will work with JSON Merge Patch.
36	/// We use a BTreeMap so keys are sorted alphabetically for *some* deterministic behavior.
37	///
38	/// A malformed rendition refuses the whole catalog when decoding.
39	#[serde(
40		deserialize_with = "crate::catalog::deserialize_entries",
41		serialize_with = "crate::catalog::serialize_entries"
42	)]
43	pub renditions: BTreeMap<String, AudioConfig>,
44}
45
46impl Audio {
47	/// Insert a track config, returning an error if the name already exists.
48	pub fn insert(&mut self, name: &str, config: AudioConfig) -> crate::Result<()> {
49		let btree_map::Entry::Vacant(entry) = self.renditions.entry(name.to_string()) else {
50			return Err(crate::Error::Duplicate(name.to_string()));
51		};
52		entry.insert(config);
53		Ok(())
54	}
55
56	/// Remove the track from the catalog and return the configuration if found.
57	pub fn remove(&mut self, name: &str) -> Option<AudioConfig> {
58		self.renditions.remove(name)
59	}
60
61	/// True when there are no renditions, so the section can be omitted from the catalog.
62	pub fn is_empty(&self) -> bool {
63		self.renditions.is_empty()
64	}
65
66	/// Iterate enabled renditions in quality order.
67	pub fn enabled(&self) -> impl Iterator<Item = (&String, &AudioConfig)> {
68		self.ranked().filter(|(_, config)| config.enabled)
69	}
70
71	/// Iterate the renditions best first: enabled, then highest bitrate, then sample rate, then channel count.
72	///
73	/// A consumer that carries one rendition takes the first it supports, so the
74	/// choice doesn't depend on how the tracks are named. An unknown bitrate ranks
75	/// below a known one, and exact ties keep name order.
76	pub fn ranked(&self) -> impl Iterator<Item = (&String, &AudioConfig)> {
77		let mut ranked: Vec<_> = self.renditions.iter().collect();
78		ranked.sort_by_key(|(_, config)| {
79			std::cmp::Reverse((config.enabled, config.bitrate, config.sample_rate, config.channel_count))
80		});
81		ranked.into_iter()
82	}
83}
84
85/// Audio decoder configuration based on WebCodecs AudioDecoderConfig.
86///
87/// This struct contains all the information needed to initialize an audio decoder,
88/// including codec-specific parameters, sample rate, and channel configuration.
89///
90/// Reference: <https://www.w3.org/TR/webcodecs/#audio-decoder-config>
91///
92/// Marked `#[non_exhaustive]` so additional optional fields can be added
93/// without bumping the major version. External callers build a config with
94/// [`AudioConfig::new`] and then assign whichever optional fields they need;
95/// struct-literal construction (with or without `..base`) is not available
96/// outside this crate.
97#[serde_with::serde_as]
98#[serde_with::skip_serializing_none]
99#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
100#[serde(rename_all = "camelCase")]
101#[non_exhaustive]
102pub struct AudioConfig {
103	/// Optional reference to another broadcast that publishes this track, expressed
104	/// relative to the broadcast that served this catalog (e.g. `./source`). If unset,
105	/// the track lives in the same broadcast as the catalog.
106	///
107	/// Resolve it with [`Path::resolve`](moq_net::Path::resolve): a reference that walks
108	/// above the root names no broadcast, so the catalog is rejected.
109	#[serde(default)]
110	#[serde_as(as = "crate::catalog::NotNull")]
111	pub broadcast: Option<moq_net::path::Relative>,
112
113	/// The track's name in its broadcast, when it differs from this entry's ID: its key in the
114	/// catalog. Absent means the ID is the track name, as in every catalog before this field.
115	///
116	/// Set it only when the ID can't be the name, such as two renditions of same-named tracks
117	/// from different broadcasts. Readers resolve the name with
118	/// [`Reference::track`](crate::catalog::Reference::track); one that predates the
119	/// field subscribes to the ID instead.
120	#[serde(default)]
121	#[serde_as(as = "crate::catalog::NotNull")]
122	pub track: Option<String>,
123
124	/// Human-readable rendition name for track pickers.
125	#[serde(default)]
126	#[serde_as(as = "crate::catalog::NotNull")]
127	pub label: Option<String>,
128
129	/// The codec, see the registry for details:
130	/// <https://w3c.github.io/webcodecs/codec_registry.html>
131	#[serde_as(as = "DisplayFromStr")]
132	pub codec: AudioCodec,
133
134	/// The sample rate of the audio in Hz, never zero.
135	pub sample_rate: u32,
136
137	/// The number of channels in the audio, never zero.
138	#[serde(rename = "numberOfChannels")]
139	pub channel_count: u32,
140
141	/// What the decoded channels carry, or the codec's own channel order when absent.
142	///
143	/// Live state, like video `color`.
144	#[serde(default)]
145	#[serde_as(as = "crate::catalog::NotNull<DisplayFromStr>")]
146	pub layout: Option<AudioLayout>,
147
148	/// The maximum bitrate of the audio track in bits per second, at most 2^53 - 1.
149	#[serde(default)]
150	#[serde_as(as = "crate::catalog::NotNull<crate::snapshot::Number>")]
151	pub bitrate: Option<u64>,
152
153	/// Whether this rendition may be selected. When false, no frames are coming and a consumer
154	/// must not select it. Only written when false.
155	#[serde(
156		default = "crate::catalog::enabled_default",
157		skip_serializing_if = "crate::catalog::enabled_skip"
158	)]
159	pub enabled: bool,
160
161	/// Some codecs include a description so the decoder can be initialized without extra data.
162	/// If not provided, there may be in-band metadata (marginally higher overhead).
163	#[serde(default)]
164	#[serde_as(as = "crate::catalog::NotNull<Hex>")]
165	pub description: Option<Bytes>,
166
167	/// Container format for frame encoding.
168	/// Defaults to "legacy" for backward compatibility.
169	#[serde(default)]
170	pub container: Container,
171
172	/// The largest media span the publisher hands to the transport behind a frame's presentation
173	/// timestamp: the reorder delay of a frame presented after frames decoded behind it, or the span
174	/// of a batch written together, such as a run of audio packets between video packets in TS. A
175	/// consumer's jitter buffer should be at least this large. Absent when the publisher measured
176	/// none.
177	///
178	/// Measured from media timestamps alone, so a frame written in presentation order adds nothing,
179	/// whatever the frame rate; encoder latency and the network don't count. It only ever grows
180	/// over the life of a stream.
181	///
182	/// Serialized as a whole number of milliseconds, rounded up, so an upper bound never
183	/// rounds down into a promise the publisher can't keep.
184	#[serde_as(as = "MillisCeil")]
185	#[serde(default)]
186	pub jitter: Option<std::time::Duration>,
187
188	/// After a non-continuous join, decode from the group start, present at start plus warmup, and join that much earlier.
189	/// Serialized as whole milliseconds, rounded up so presentation never starts early.
190	#[serde_as(as = "crate::catalog::NotNull<MillisCeil>")]
191	#[serde(default)]
192	pub warmup: Option<std::time::Duration>,
193
194	/// How far this rendition's frames reach the transport behind the broadcast's other
195	/// renditions: a constant offset, either supplied by the publisher or measured as the least
196	/// its frames trailed the others' over a window of a second of media, keeping the largest
197	/// window. Lateness only some frames have, such as B-frame reorder, is left out, since a
198	/// consumer measures it. Absent on a rendition that trails nothing, and on any rendition the
199	/// publisher neither supplied nor measured.
200	///
201	/// A consumer adds a frame duration on top, so a publisher that knows its frames trail by no
202	/// more than their own duration, such as an encoder configured not to reorder or queue, states
203	/// `Some(Duration::ZERO)`. It is never measured, and is omitted on the
204	/// wire like an absent value, which means the same to a consumer. `None` leaves it to
205	/// measurement.
206	///
207	/// A consumer holds `delay + jitter` for this rendition and MUST NOT subtract one rendition's
208	/// `delay` from another's: each is taken against whichever rendition was ahead, so two need not
209	/// share an origin. It only ever grows over the life of a stream, and is serialized like
210	/// [`jitter`](Self::jitter).
211	#[serde_as(as = "MillisCeil")]
212	#[serde(default, skip_serializing_if = "crate::catalog::millis::no_delay")]
213	pub delay: Option<std::time::Duration>,
214}
215
216impl AudioConfig {
217	/// Construct a config with the required fields set and every optional
218	/// field cleared. `container` defaults to [`Container::default`]. Fields
219	/// are `pub`, so callers set whatever they need by assignment afterwards.
220	///
221	/// This is the only path external crates have to build an `AudioConfig`
222	/// since the type is `#[non_exhaustive]`.
223	pub fn new(codec: impl Into<AudioCodec>, sample_rate: u32, channel_count: u32) -> Self {
224		Self {
225			broadcast: None,
226			track: None,
227			label: None,
228			codec: codec.into(),
229			sample_rate,
230			channel_count,
231			layout: None,
232			bitrate: None,
233			enabled: true,
234			description: None,
235			container: Container::default(),
236			jitter: None,
237			warmup: None,
238			delay: None,
239		}
240	}
241
242	/// Whether `other` keeps this config's track identity: the fields a consumer cannot change
243	/// without reinitializing its decoder or demuxer (`codec`, `description`, `container`,
244	/// `sample_rate`, and `channel_count`).
245	///
246	/// A track name always means the same content, so a publisher that changes any of them
247	/// publishes under a new name; every other field may update in place. See the draft's
248	/// [Track Identity](https://github.com/moq-dev/moq/blob/main/drafts/draft-lcurley-moq-hang.md#identity).
249	pub fn same_identity(&self, other: &Self) -> bool {
250		self.codec == other.codec
251			&& self.description == other.description
252			&& self.container == other.container
253			&& self.sample_rate == other.sample_rate
254			&& self.channel_count == other.channel_count
255	}
256}
257
258impl crate::catalog::Entry for AudioConfig {
259	fn check(&self) -> crate::Result<()> {
260		if self.sample_rate == 0 {
261			return Err(crate::Error::Zero("sampleRate"));
262		}
263		if self.channel_count == 0 {
264			return Err(crate::Error::Zero("numberOfChannels"));
265		}
266		if let Some(layout) = &self.layout {
267			layout.check(self.channel_count)?;
268		}
269		Ok(())
270	}
271
272	fn version(&self, id: &str) -> Option<u64> {
273		crate::catalog::renamed_version(self, id)
274	}
275}
276
277#[cfg(test)]
278mod test {
279	use super::*;
280
281	#[test]
282	fn warmup_round_trips() {
283		let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
284		assert!(serde_json::to_value(&config).unwrap().get("warmup").is_none());
285		for millis in [0, 80, 1_000] {
286			config.warmup = Some(std::time::Duration::from_millis(millis));
287			let encoded = serde_json::to_value(&config).unwrap();
288			assert_eq!(encoded["warmup"], millis);
289			let decoded: AudioConfig = serde_json::from_value(encoded).unwrap();
290			assert_eq!(decoded.warmup, config.warmup);
291		}
292	}
293
294	#[test]
295	fn warmup_rounds_up() {
296		let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
297		for (nanos, millis) in [(1, 1), (499_999, 1), (333_200_000, 334)] {
298			config.warmup = Some(std::time::Duration::from_nanos(nanos));
299			let encoded = serde_json::to_value(&config).unwrap();
300			assert_eq!(encoded["warmup"], millis);
301			let decoded: AudioConfig = serde_json::from_value(encoded).unwrap();
302			assert_eq!(decoded.warmup, Some(std::time::Duration::from_millis(millis)));
303		}
304	}
305
306	#[test]
307	fn ranked_orders_by_enabled_then_bitrate_then_rate_then_channels() {
308		fn rendition(sample_rate: u32, channels: u32, bitrate: Option<u64>) -> AudioConfig {
309			let mut config = AudioConfig::new(AudioCodec::Opus, sample_rate, channels);
310			config.bitrate = bitrate;
311			config
312		}
313
314		let mut audio = Audio::default();
315		// Names sort the weaker renditions first, so name order alone would pick the wrong one.
316		audio.insert("a", rendition(48_000, 2, None)).unwrap();
317		audio.insert("b", rendition(48_000, 1, Some(64_000))).unwrap();
318		audio.insert("c", rendition(16_000, 1, Some(128_000))).unwrap();
319		audio.insert("d", rendition(48_000, 2, Some(64_000))).unwrap();
320		audio.insert("e", rendition(48_000, 2, Some(64_000))).unwrap();
321		audio.insert("f", rendition(44_100, 2, Some(64_000))).unwrap();
322		audio.insert("g", rendition(16_000, 1, None)).unwrap();
323
324		let names: Vec<_> = audio.ranked().map(|(name, _)| name.as_str()).collect();
325		assert_eq!(names, ["c", "d", "e", "b", "f", "a", "g"]);
326
327		// Disabled renditions rank last, so catalog transforms can retain their metadata.
328		audio.renditions.get_mut("c").unwrap().enabled = false;
329		let names: Vec<_> = audio.ranked().map(|(name, _)| name.as_str()).collect();
330		assert_eq!(names, ["d", "e", "b", "f", "a", "g", "c"]);
331		let names: Vec<_> = audio.enabled().map(|(name, _)| name.as_str()).collect();
332		assert_eq!(names, ["d", "e", "b", "f", "a", "g"]);
333	}
334
335	#[test]
336	fn disabled_renditions_are_ineligible_until_reenabled() {
337		let mut catalog = Audio::default();
338		let config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
339		catalog.renditions.insert("track".into(), config);
340		assert_eq!(catalog.enabled().count(), 1);
341		catalog.renditions.get_mut("track").unwrap().enabled = false;
342		assert_eq!(catalog.enabled().count(), 0);
343		assert_eq!(catalog.ranked().count(), 1);
344		catalog.renditions.get_mut("track").unwrap().enabled = true;
345		assert_eq!(catalog.enabled().count(), 1);
346	}
347
348	#[test]
349	fn enabled_is_written_only_when_false() {
350		let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
351		assert!(serde_json::to_value(&config).unwrap().get("enabled").is_none());
352
353		config.enabled = false;
354		let encoded = serde_json::to_value(&config).expect("failed to encode");
355		assert_eq!(encoded["enabled"], false);
356		let decoded: AudioConfig = serde_json::from_value(encoded).expect("failed to decode");
357		assert!(!decoded.enabled);
358	}
359}