Skip to main content

hang/catalog/
ext.rs

1use serde::{Deserialize, Serialize};
2
3/// An application's catalog extension: a plain serde struct of extra root sections that are
4/// serialized as a flat union with the base media sections.
5///
6/// Implement it (no methods) on a struct of your own sections, then publish/consume a
7/// [`Catalog<YourExt>`](super::Catalog):
8///
9/// ```
10/// use serde::{Deserialize, Serialize};
11///
12/// #[derive(Serialize, Deserialize, Clone, Default)]
13/// struct Scte35Ext {
14///     #[serde(skip_serializing_if = "Option::is_none")]
15///     scte35: Option<Scte35>,
16/// }
17///
18/// #[derive(Serialize, Deserialize, Clone, Default)]
19/// struct Scte35 {
20///     splice_id: u32,
21/// }
22///
23/// impl hang::catalog::CatalogExt for Scte35Ext {}
24/// ```
25///
26/// The unit type `()` is the no-extension case, so [`Catalog<()>`](super::Catalog) is just the base media catalog.
27///
28/// The same extension rides the MSF catalog track, so this requires [`moq_msf::CatalogExt`];
29/// that trait is blanket-implemented, so one `impl CatalogExt` is still all a caller writes.
30pub trait CatalogExt: moq_msf::CatalogExt {}
31
32impl CatalogExt for () {}
33
34/// The untyped catalog extension: arbitrary top-level JSON sections beyond the base
35/// `video`/`audio`/`text` media sections and shared `archive`, captured and republished verbatim.
36///
37/// This is the extension a caller reaches for when the section names aren't known at
38/// compile time, e.g. across the FFI/C boundary where a typed [`CatalogExt`] struct can't
39/// cross. Publish/consume a [`Catalog<Extra>`](super::Catalog) and use [`set`](Self::set)/[`get`](Self::get).
40/// The default extension stays `()` (unknown sections dropped); opt into `Extra` explicitly.
41///
42/// `version`, `video`, `audio`, `sync`, `text`, `archive`, `clock`, `media`, `json`, `binary`,
43/// `stats`, `echo`, `include`, and the retired `timeline` key are reserved, so decoding and
44/// [`set`](Self::set) reject them to keep the wire JSON free of duplicate or retired keys. The
45/// exceptions are a root `clock` and `media`, which each held the clock before `sync`: an older
46/// publisher's is dropped on decode, so its media still plays.
47#[derive(Serialize, Clone, Default, Debug, PartialEq)]
48#[serde(transparent)]
49pub struct Extra(serde_json::Map<String, serde_json::Value>);
50
51impl CatalogExt for Extra {}
52
53impl<'de> Deserialize<'de> for Extra {
54	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
55		let mut sections = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
56		sections.remove("clock");
57		sections.remove("media");
58		if let Some(name) = sections.keys().find(|name| reserved(name)) {
59			return Err(serde::de::Error::custom(format!("reserved catalog section: {name}")));
60		}
61		Ok(Self(sections))
62	}
63}
64
65// The root members a catalog defines, the keys it retired, and MSF's root members, since the same
66// sections ride both catalog tracks.
67fn reserved(name: &str) -> bool {
68	super::root::RESERVED.contains(&name)
69		|| matches!(name, "archive" | "clock" | "media" | "timeline")
70		|| moq_msf::reserved_root(name)
71}
72
73impl Extra {
74	/// Look up a section by name.
75	pub fn get(&self, name: &str) -> Option<&serde_json::Value> {
76		self.0.get(name)
77	}
78
79	/// Iterate over every section as `(name, value)` pairs, sorted by name.
80	pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
81		self.0.iter()
82	}
83
84	/// The number of sections.
85	pub fn len(&self) -> usize {
86		self.0.len()
87	}
88
89	/// Whether there are no sections.
90	pub fn is_empty(&self) -> bool {
91		self.0.is_empty()
92	}
93
94	/// Set (or replace) a section. Errors if `name` collides with a reserved member of either
95	/// catalog: hang's root `version` and base sections
96	/// (`video`/`audio`/`sync`/`text`/`archive`/`clock`/`media`/`json`/`binary`/`stats`/`echo`/`include`),
97	/// the retired `timeline` key that the wire format forbids beside `archive`, or a root member
98	/// MSF defines ([`moq_msf::reserved_root`]).
99	///
100	/// The same sections ride both catalog tracks, so a name reserved on either is refused on
101	/// both. Without the MSF half a colliding name reaches that track as a duplicate JSON key,
102	/// which serde emits without complaint.
103	pub fn set(&mut self, name: impl Into<String>, value: serde_json::Value) -> crate::Result<()> {
104		let name = name.into();
105		if reserved(&name) {
106			return Err(crate::Error::ReservedSection(name));
107		}
108		self.0.insert(name, value);
109		Ok(())
110	}
111
112	/// Remove a section, returning its previous value if present.
113	pub fn remove(&mut self, name: &str) -> Option<serde_json::Value> {
114		self.0.remove(name)
115	}
116}
117
118#[cfg(test)]
119mod test {
120	use crate::catalog::Catalog;
121
122	use super::*;
123
124	/// A section hang defines is hang's, whatever an application puts there: one with the wrong
125	/// shape refuses the catalog rather than passing to `Extra` or reading as empty.
126	#[test]
127	fn a_mis_shaped_text_section_refuses_the_catalog() {
128		let json = r#"{"text":{"overlay":"hi"},"scte35":{"spliceId":7}}"#;
129		serde_json::from_str::<Catalog<Extra>>(json).expect_err("a mis-shaped text section");
130
131		// Republishing drops the empty media sections an older payload carried.
132		let json = r#"{"video":{"renditions":{}},"audio":{"renditions":{}},"scte35":{"spliceId":7}}"#;
133		let catalog: Catalog<Extra> = serde_json::from_str(json).unwrap();
134		assert_eq!(serde_json::to_string(&catalog).unwrap(), r#"{"scte35":{"spliceId":7}}"#);
135	}
136
137	/// A publisher from before `sync` writes its clock at the root or under `media`: those keys are
138	/// dropped rather than refusing the catalog, and are never written back.
139	#[test]
140	fn an_older_clock_is_dropped() {
141		for older in [
142			r#""clock":{"wall":1000,"timescale":1000000}"#,
143			r#""media":{"clock":{"wall":1000},"join":{"interval":2000}}"#,
144		] {
145			let json = format!(r#"{{{older},"audio":{{"renditions":{{}}}},"scte35":{{"spliceId":7}}}}"#);
146			let catalog = serde_json::from_str::<Catalog<Extra>>(&json).expect(older);
147			assert_eq!(catalog.ext.get("clock"), None);
148			assert_eq!(catalog.ext.get("media"), None);
149			assert_eq!(catalog.sync, Default::default(), "an older clock is not read as sync's");
150			assert_eq!(serde_json::to_string(&catalog).unwrap(), r#"{"scte35":{"spliceId":7}}"#);
151		}
152	}
153
154	#[test]
155	fn retired_timeline_section_is_rejected() {
156		let json = r#"{"timeline":{"track":"timeline.json"}}"#;
157
158		let error = serde_json::from_str::<Catalog<Extra>>(json).expect_err("retired timeline section was accepted");
159		assert!(error.to_string().contains("reserved catalog section: timeline"));
160	}
161
162	#[test]
163	fn set_refuses_reserved_names() {
164		let mut extra = Extra::default();
165		extra
166			.set("transcript", serde_json::json!({ "track": "transcript.json" }))
167			.unwrap();
168		assert_eq!(
169			extra.get("transcript"),
170			Some(&serde_json::json!({ "track": "transcript.json" }))
171		);
172
173		// Every hang root, the retired keys, and every MSF root.
174		let hang = [
175			"version", "video", "audio", "sync", "text", "json", "binary", "stats", "echo", "include",
176		];
177		let retired = ["archive", "clock", "media", "timeline"];
178		let msf = ["generatedAt", "isComplete", "tracks", "initDataList"];
179		for name in hang.into_iter().chain(retired).chain(msf) {
180			assert!(
181				matches!(
182					extra.set(name, serde_json::json!({})),
183					Err(crate::Error::ReservedSection(_))
184				),
185				"{name} must be refused",
186			);
187		}
188		assert_eq!(extra.len(), 1);
189	}
190}