Skip to main content

moq_mux/
select.rs

1//! Track selection.
2//!
3//! [`Broadcast`] picks which renditions of a broadcast to keep. It is purely
4//! additive: a default [`Broadcast`] selects *nothing*, and you opt a role in with
5//! [`video`](Broadcast::video) / [`audio`](Broadcast::audio). Within an opted-in
6//! role, an empty field matches everything; listing values keeps renditions matching
7//! any one of them (a union within a field, intersected across fields). Per the hang spec, a
8//! disabled rendition (catalog `enabled: false`) and one whose container `kind` this build does
9//! not recognize are never selected. Selection runs on every snapshot, so a rendition that
10//! re-enables is selected again.
11//!
12//! The same [`Broadcast`] drives selection at either end of the pipeline: narrowing
13//! a published catalog on the consume side (see [`catalog::Select`](crate::catalog::Select)),
14//! or choosing which tracks to publish on the import side.
15
16use hang::catalog::{AudioCodecKind, AudioConfig, VideoCodecKind, VideoConfig};
17
18use crate::catalog::hang::{Catalog, CatalogExt, supported};
19
20/// Which renditions of a broadcast to keep.
21///
22/// Defaults to selecting nothing. Opt a role in with [`video`](Self::video) /
23/// [`audio`](Self::audio); an unselected role is dropped entirely.
24#[derive(Clone, Debug, Default)]
25pub struct Broadcast {
26	video: Option<Video>,
27	audio: Option<Audio>,
28}
29
30impl Broadcast {
31	/// Select video, narrowed by `video`. A default [`Video`] keeps every video rendition.
32	pub fn video(mut self, video: Video) -> Self {
33		self.video = Some(video);
34		self
35	}
36
37	/// Select audio, narrowed by `audio`. A default [`Audio`] keeps every audio rendition.
38	pub fn audio(mut self, audio: Audio) -> Self {
39		self.audio = Some(audio);
40		self
41	}
42
43	/// Whether any video is selected.
44	pub fn has_video(&self) -> bool {
45		self.video.is_some()
46	}
47
48	/// Whether any audio is selected.
49	pub fn has_audio(&self) -> bool {
50		self.audio.is_some()
51	}
52
53	/// Drop every rendition from `catalog` that isn't selected.
54	pub fn retain<E: CatalogExt>(&self, catalog: &mut Catalog<E>) {
55		match &self.video {
56			Some(video) => catalog
57				.video
58				.renditions
59				.retain(|name, config| video.matches(name, config)),
60			None => catalog.video.renditions.clear(),
61		}
62		match &self.audio {
63			Some(audio) => catalog
64				.audio
65				.renditions
66				.retain(|name, config| audio.matches(name, config)),
67			None => catalog.audio.renditions.clear(),
68		}
69	}
70}
71
72/// Video rendition criteria. An empty field matches every rendition.
73#[derive(Clone, Debug, Default)]
74pub struct Video {
75	name: Vec<String>,
76	codec: Vec<VideoCodecKind>,
77}
78
79impl Video {
80	/// Also accept the rendition with this exact name. Repeatable; empty = any name.
81	pub fn name(mut self, name: impl Into<String>) -> Self {
82		self.name.push(name.into());
83		self
84	}
85
86	/// Also accept renditions of this codec. Repeatable; empty = any codec.
87	pub fn codec(mut self, codec: VideoCodecKind) -> Self {
88		self.codec.push(codec);
89		self
90	}
91
92	fn matches(&self, name: &str, config: &VideoConfig) -> bool {
93		config.enabled
94			&& supported(name, &config.container)
95			&& (self.name.is_empty() || self.name.iter().any(|n| n == name))
96			&& (self.codec.is_empty() || self.codec.contains(&config.codec.kind()))
97	}
98}
99
100/// Audio rendition criteria. An empty field matches every rendition.
101#[derive(Clone, Debug, Default)]
102pub struct Audio {
103	name: Vec<String>,
104	codec: Vec<AudioCodecKind>,
105}
106
107impl Audio {
108	/// Also accept the rendition with this exact name. Repeatable; empty = any name.
109	pub fn name(mut self, name: impl Into<String>) -> Self {
110		self.name.push(name.into());
111		self
112	}
113
114	/// Also accept renditions of this codec. Repeatable; empty = any codec.
115	pub fn codec(mut self, codec: AudioCodecKind) -> Self {
116		self.codec.push(codec);
117		self
118	}
119
120	fn matches(&self, name: &str, config: &AudioConfig) -> bool {
121		config.enabled
122			&& supported(name, &config.container)
123			&& (self.name.is_empty() || self.name.iter().any(|n| n == name))
124			&& (self.codec.is_empty() || self.codec.contains(&config.codec.kind()))
125	}
126}
127
128#[cfg(test)]
129mod tests {
130	use std::collections::BTreeMap;
131
132	use hang::catalog::{AudioCodec, AudioConfig, Container, H264, VP9, VideoConfig};
133
134	use super::*;
135
136	fn h264(name: &str) -> (String, VideoConfig) {
137		let mut config = VideoConfig::new(H264 {
138			profile: 0x42,
139			constraints: 0,
140			level: 0x1e,
141			inline: false,
142		});
143		config.container = Container::Legacy;
144		(name.to_string(), config)
145	}
146
147	fn vp9(name: &str) -> (String, VideoConfig) {
148		let mut config = VideoConfig::new(VP9 {
149			profile: 0,
150			level: 10,
151			bit_depth: 8,
152			chroma_subsampling: 1,
153			color_primaries: 1,
154			transfer_characteristics: 1,
155			matrix_coefficients: 1,
156			full_range: false,
157		});
158		config.container = Container::Legacy;
159		(name.to_string(), config)
160	}
161
162	fn opus(name: &str) -> (String, AudioConfig) {
163		let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
164		config.container = Container::Legacy;
165		(name.to_string(), config)
166	}
167
168	fn catalog(video: Vec<(String, VideoConfig)>, audio: Vec<(String, AudioConfig)>) -> Catalog {
169		let mut catalog = Catalog::default();
170		catalog.video.renditions = BTreeMap::from_iter(video);
171		catalog.audio.renditions = BTreeMap::from_iter(audio);
172		catalog
173	}
174
175	fn video_names(catalog: &Catalog) -> Vec<&str> {
176		catalog.video.renditions.keys().map(String::as_str).collect()
177	}
178
179	fn audio_names(catalog: &Catalog) -> Vec<&str> {
180		catalog.audio.renditions.keys().map(String::as_str).collect()
181	}
182
183	#[test]
184	fn default_selects_nothing() {
185		let mut catalog = catalog(vec![h264("v")], vec![opus("a")]);
186		Broadcast::default().retain(&mut catalog);
187		assert!(catalog.video.renditions.is_empty());
188		assert!(catalog.audio.renditions.is_empty());
189	}
190
191	#[test]
192	fn empty_axis_keeps_everything() {
193		let mut catalog = catalog(vec![h264("lo"), h264("hi")], vec![opus("a")]);
194		Broadcast::default().video(Video::default()).retain(&mut catalog);
195		assert_eq!(video_names(&catalog), vec!["hi", "lo"]);
196		// Audio was never selected, so it's dropped.
197		assert!(catalog.audio.renditions.is_empty());
198	}
199
200	#[test]
201	fn name_matches_exact() {
202		let mut catalog = catalog(vec![h264("lo"), h264("hi")], vec![]);
203		Broadcast::default()
204			.video(Video::default().name("hi"))
205			.retain(&mut catalog);
206		assert_eq!(video_names(&catalog), vec!["hi"]);
207	}
208
209	#[test]
210	fn names_union_within_field() {
211		let mut catalog = catalog(vec![], vec![opus("en"), opus("es"), opus("fr")]);
212		Broadcast::default()
213			.audio(Audio::default().name("en").name("es"))
214			.retain(&mut catalog);
215		assert_eq!(audio_names(&catalog), vec!["en", "es"]);
216	}
217
218	#[test]
219	fn codec_filters_within_selected_axis() {
220		let mut catalog = catalog(vec![h264("a"), vp9("b"), h264("c")], vec![]);
221		Broadcast::default()
222			.video(Video::default().codec(VideoCodecKind::H264))
223			.retain(&mut catalog);
224		assert_eq!(video_names(&catalog), vec!["a", "c"]);
225	}
226
227	#[test]
228	fn codecs_union_within_field() {
229		let mut catalog = catalog(vec![h264("a"), vp9("b")], vec![]);
230		Broadcast::default()
231			.video(Video::default().codec(VideoCodecKind::H264).codec(VideoCodecKind::VP9))
232			.retain(&mut catalog);
233		assert_eq!(video_names(&catalog), vec!["a", "b"]);
234	}
235
236	#[test]
237	fn unknown_container_never_selected() {
238		let (name, mut future) = h264("future");
239		future.container = serde_json::from_str(r#"{"kind":"future"}"#).unwrap();
240
241		let mut catalog = catalog(vec![h264("known"), (name, future)], vec![]);
242		Broadcast::default().video(Video::default()).retain(&mut catalog);
243		assert_eq!(video_names(&catalog), vec!["known"]);
244	}
245
246	#[test]
247	fn disabled_never_selected() {
248		let (name, mut disabled) = h264("hi");
249		disabled.enabled = false;
250		let (audio, mut muted) = opus("a");
251		muted.enabled = false;
252
253		let mut catalog = catalog(vec![h264("lo"), (name, disabled)], vec![(audio, muted)]);
254		let selection = Broadcast::default().video(Video::default()).audio(Audio::default());
255		selection.retain(&mut catalog);
256		assert_eq!(video_names(&catalog), vec!["lo"]);
257		assert!(catalog.audio.renditions.is_empty());
258	}
259
260	#[test]
261	fn name_and_codec_intersect() {
262		let mut catalog = catalog(vec![h264("hi"), vp9("hi2"), h264("lo")], vec![]);
263		// name in {hi, hi2} AND codec H264 -> only "hi".
264		Broadcast::default()
265			.video(Video::default().name("hi").name("hi2").codec(VideoCodecKind::H264))
266			.retain(&mut catalog);
267		assert_eq!(video_names(&catalog), vec!["hi"]);
268	}
269}