Skip to main content

hang/catalog/
root.rs

1//! This module contains the structs and functions for the MoQ catalog format
2use crate::Result;
3use crate::catalog::skipped::Probe;
4use crate::catalog::{Audio, Binary, Json, PRIORITY, Text, Video};
5use serde::de::DeserializeOwned;
6use std::str::FromStr;
7
8use serde::{Deserialize, Serialize};
9
10/// A catalog track, created by a broadcaster to describe the tracks available in a broadcast.
11///
12/// The base catalog carries the media sections (`video`, `audio`, `text`), the optional `sync`
13/// section (the broadcast's one wall-clock mapping and join interval), the data sections
14/// (`json`, `binary`) for application tracks that aren't media, plus `stats` naming the
15/// publisher's media snapshot track, `echo` soliciting viewer feedback under a relative broadcast
16/// prefix, and `include` naming whole broadcasts for explicit selection.
17/// Applications extend it with their own root sections (e.g. `com.example.scte35`, or moq-mux's
18/// `mpegts`) through `E`. The catalog
19/// does not deny unknown fields, so a base consumer ignores the extra sections and an extended
20/// catalog stays wire-compatible. See the `extension_roundtrip` test.
21///
22/// Every section this crate defines must have its shape when present, or decoding refuses the
23/// whole catalog: a section that silently read as empty would hide a publisher bug. An
24/// application's own root data goes under a namespaced key (`com.example.telemetry`) instead.
25///
26/// Marked `#[non_exhaustive]` so a future base section can be added without bumping the major
27/// version. External callers start from [`Catalog::default`] and fill in the sections they
28/// publish; struct-literal construction (with or without `..base`) is not available outside
29/// this crate.
30#[derive(Debug, Clone, PartialEq, Default)]
31#[non_exhaustive]
32pub struct Catalog<E = ()> {
33	/// Video track information with multiple renditions.
34	///
35	/// Contains a map of video track renditions that the viewer can choose from
36	/// based on their preferences (resolution, bitrate, codec, etc). Omitted from the
37	/// wire when it has no renditions.
38	pub video: Video,
39
40	/// Audio track information with multiple renditions.
41	///
42	/// Contains a map of audio track renditions that the viewer can choose from
43	/// based on their preferences (codec, bitrate, language, etc). Omitted from the
44	/// wire when it has no renditions.
45	pub audio: Audio,
46
47	/// The broadcast's timeline: its clock and join interval.
48	///
49	/// Omitted from the wire when it holds nothing. See [`Timeline`](crate::catalog::Timeline).
50	pub sync: crate::catalog::Timeline,
51
52	/// Text (caption/subtitle) track information with multiple renditions.
53	///
54	/// Contains a map of text track renditions that the viewer can choose from
55	/// based on their preferences (language, role). Omitted from the wire when empty, so a
56	/// broadcast without captions stays byte-identical to before this section existed.
57	pub text: Text,
58
59	/// JSON tracks: application data published as live JSON documents or logs.
60	///
61	/// Omitted from the wire when empty, so a media-only catalog is unchanged.
62	pub json: Json,
63
64	/// Binary tracks: application data published as opaque payloads.
65	///
66	/// Omitted from the wire when empty, so a media-only catalog is unchanged.
67	pub binary: Binary,
68
69	/// The publisher's optional media snapshot track.
70	pub stats: Option<crate::catalog::Stats>,
71
72	/// The optional prefix soliciting viewer feedback broadcasts.
73	pub echo: Option<crate::catalog::Echo>,
74
75	/// Whole broadcasts listed for explicit, lazy selection, keyed by include ID.
76	///
77	/// Each shares this catalog's PTS timeline and root settings, including `sync.clock` and
78	/// `sync.interval`; its own settings are ignored. Listing one subscribes to nothing;
79	/// see [`Include`](crate::catalog::Include). Omitted from the wire when empty.
80	pub include: std::collections::BTreeMap<String, crate::catalog::Include>,
81
82	/// Application-defined root sections, flattened alongside the base catalog sections.
83	///
84	/// The root `version` and every section name are reserved: serializing fails if the extension
85	/// names one.
86	pub ext: E,
87
88	/// The entries decoding skipped because a newer moq-hang draft defines them.
89	///
90	/// Filled when a catalog is decoded and never written.
91	pub skipped: crate::catalog::Skipped,
92}
93
94/// The wire shape of [`Catalog`]: its sections, without the root `version`.
95///
96/// The root `version` is the oldest moq-hang draft that reads the catalog correctly, absent while
97/// that is 3. [`Probe`] checks it before any section is decoded. No moq-hang-04 field reshapes the
98/// root, so this crate never writes it; a field one entry uses raises that entry's `version`.
99#[serde_with::serde_as]
100#[serde_with::skip_serializing_none]
101#[derive(Serialize, Deserialize)]
102// Field defaults rather than a container one: a remote container default would be a `Catalog`.
103#[serde(remote = "Catalog", rename_all = "camelCase")]
104#[serde(bound(serialize = "E: Serialize", deserialize = "E: DeserializeOwned + Default"))]
105struct Wire<E> {
106	#[serde(
107		default,
108		skip_serializing_if = "Video::is_empty",
109		deserialize_with = "crate::catalog::deserialize_object"
110	)]
111	video: Video,
112
113	#[serde(
114		default,
115		skip_serializing_if = "Audio::is_empty",
116		deserialize_with = "crate::catalog::deserialize_object"
117	)]
118	audio: Audio,
119
120	#[serde(
121		default,
122		skip_serializing_if = "crate::catalog::Timeline::is_empty",
123		deserialize_with = "crate::catalog::deserialize_object"
124	)]
125	sync: crate::catalog::Timeline,
126
127	#[serde(
128		default,
129		skip_serializing_if = "Text::is_empty",
130		deserialize_with = "crate::catalog::deserialize_object"
131	)]
132	text: Text,
133
134	#[serde(
135		default,
136		skip_serializing_if = "Json::is_empty",
137		deserialize_with = "crate::catalog::deserialize_object"
138	)]
139	json: Json,
140
141	#[serde(
142		default,
143		skip_serializing_if = "Binary::is_empty",
144		deserialize_with = "crate::catalog::deserialize_object"
145	)]
146	binary: Binary,
147
148	#[serde(default, deserialize_with = "crate::catalog::deserialize_some")]
149	stats: Option<crate::catalog::Stats>,
150
151	#[serde(default, deserialize_with = "crate::catalog::deserialize_some")]
152	echo: Option<crate::catalog::Echo>,
153
154	#[serde(
155		default,
156		skip_serializing_if = "std::collections::BTreeMap::is_empty",
157		deserialize_with = "crate::catalog::deserialize_entries",
158		serialize_with = "crate::catalog::serialize_entries"
159	)]
160	include: std::collections::BTreeMap<String, crate::catalog::Include>,
161
162	#[serde(flatten, serialize_with = "serialize_ext")]
163	ext: E,
164
165	// Filled from `Probe` by `Catalog::from_value`.
166	#[serde(skip)]
167	skipped: crate::catalog::Skipped,
168}
169
170/// The root members this specification defines: `version` and each [`Wire`] section.
171pub(crate) const RESERVED: [&str; 10] = [
172	"version", "video", "audio", "sync", "text", "json", "binary", "stats", "echo", "include",
173];
174
175/// Refuse an extension member the specification reserves. One beside a section would write a
176/// duplicate key that a reader resolves to either copy, and an extension `version` would claim a
177/// newer draft that a reader refuses.
178fn serialize_ext<E: Serialize, S: serde::Serializer>(ext: &E, serializer: S) -> std::result::Result<S::Ok, S::Error> {
179	use serde::ser::Error;
180
181	// Inspected as a `Value` but written from `ext` itself, which keeps its member order.
182	let value = serde_json::to_value(ext).map_err(S::Error::custom)?;
183	if let Some(key) = RESERVED.into_iter().find(|key| value.get(key).is_some()) {
184		return Err(S::Error::custom(format!(
185			"catalog extension must not name the reserved member `{key}`"
186		)));
187	}
188	ext.serialize(serializer)
189}
190
191// Exhaustive on both sides, so a `Catalog` field missing from `Wire` fails to compile.
192impl<E> From<Wire<E>> for Catalog<E> {
193	fn from(wire: Wire<E>) -> Self {
194		let Wire {
195			video,
196			audio,
197			sync,
198			text,
199			json,
200			binary,
201			stats,
202			echo,
203			include,
204			ext,
205			skipped,
206		} = wire;
207		Self {
208			video,
209			audio,
210			sync,
211			text,
212			json,
213			binary,
214			stats,
215			echo,
216			include,
217			ext,
218			skipped,
219		}
220	}
221}
222
223impl<E: Serialize> Serialize for Catalog<E> {
224	fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
225		Wire::serialize(self, serializer)
226	}
227}
228
229impl<'de, E: DeserializeOwned + Default> Deserialize<'de> for Catalog<E> {
230	/// Buffered, so every `version` is read before any section, which a newer draft may have
231	/// reshaped. An entry needing a newer draft is skipped and listed in [`skipped`](Self::skipped).
232	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
233		Self::from_value(Strict::deserialize(deserializer)?.0).map_err(serde::de::Error::custom)
234	}
235}
236
237/// A JSON value that refuses an object repeating a member, which a [`Value`](serde_json::Value)
238/// would silently collapse to its last. Without it, `{"version":5,"version":3}` would read as 3.
239struct Strict(serde_json::Value);
240
241impl<'de> Deserialize<'de> for Strict {
242	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
243		struct Visitor;
244
245		impl<'de> serde::de::Visitor<'de> for Visitor {
246			type Value = serde_json::Value;
247
248			fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
249				f.write_str("any JSON value")
250			}
251
252			fn visit_bool<E>(self, v: bool) -> std::result::Result<Self::Value, E> {
253				Ok(v.into())
254			}
255
256			fn visit_i64<E>(self, v: i64) -> std::result::Result<Self::Value, E> {
257				Ok(v.into())
258			}
259
260			fn visit_u64<E>(self, v: u64) -> std::result::Result<Self::Value, E> {
261				Ok(v.into())
262			}
263
264			fn visit_f64<E>(self, v: f64) -> std::result::Result<Self::Value, E> {
265				Ok(serde_json::Number::from_f64(v).map_or(serde_json::Value::Null, serde_json::Value::Number))
266			}
267
268			fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E> {
269				Ok(v.into())
270			}
271
272			fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E> {
273				Ok(v.into())
274			}
275
276			fn visit_none<E>(self) -> std::result::Result<Self::Value, E> {
277				Ok(serde_json::Value::Null)
278			}
279
280			fn visit_unit<E>(self) -> std::result::Result<Self::Value, E> {
281				Ok(serde_json::Value::Null)
282			}
283
284			fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error> {
285				let mut items = Vec::new();
286				while let Some(Strict(item)) = seq.next_element()? {
287					items.push(item);
288				}
289				Ok(items.into())
290			}
291
292			fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> std::result::Result<Self::Value, A::Error> {
293				let mut object = serde_json::Map::new();
294				while let Some((key, Strict(value))) = map.next_entry::<String, Strict>()? {
295					if object.insert(key.clone(), value).is_some() {
296						return Err(serde::de::Error::custom(format!("duplicate member `{key}`")));
297					}
298				}
299				Ok(object.into())
300			}
301		}
302
303		deserializer.deserialize_any(Visitor).map(Self)
304	}
305}
306
307impl Catalog<()> {
308	/// The default name for the catalog track.
309	pub const DEFAULT_NAME: &str = "catalog.json";
310
311	/// Track properties for creating the catalog track via
312	/// [`create_track`](moq_net::broadcast::Producer::create_track) at
313	/// [`DEFAULT_NAME`](Self::DEFAULT_NAME).
314	///
315	/// Timed in milliseconds, so snapshots share the broadcast clock with media, fresh for the media's
316	/// [`MAX_AGE`](crate::container::MAX_AGE), so a reader playing behind the live edge still
317	/// receives each update it holds until its timestamp, and
318	/// [compressed](moq_net::track::Info::compression), since catalog JSON is small and repetitive.
319	pub fn default_track_info() -> moq_net::track::Info {
320		moq_net::track::Info::default()
321			.with_timescale(moq_net::Timescale::MILLI)
322			.with_max_age(crate::container::MAX_AGE)
323			.with_priority(PRIORITY.catalog)
324			.with_compression(moq_net::track::Compression::Deflate)
325	}
326
327	/// The subscription preferences used for the catalog track (high priority so
328	/// it preempts media tracks).
329	pub fn default_subscription() -> moq_net::track::Subscription {
330		moq_net::track::Subscription::default()
331			.with_ranges([moq_net::track::Range::default().with_priority(PRIORITY.catalog)])
332	}
333}
334
335impl<E> Catalog<E> {
336	/// Refuse a catalog with an ID naming both a video and an audio rendition, or with a
337	/// rendition field out of range, such as a zero sample rate or a projection out of bounds.
338	///
339	/// Decoding already refuses an out-of-range rendition, so this catches a catalog built by hand.
340	pub fn check_renditions(&self) -> Result<()> {
341		use crate::catalog::Entry;
342
343		if let Some(id) = self
344			.video
345			.renditions
346			.keys()
347			.find(|id| self.audio.renditions.contains_key(*id))
348		{
349			return Err(crate::Error::DuplicateRendition(id.clone()));
350		}
351		for config in self.video.renditions.values() {
352			config.check()?;
353		}
354		for config in self.audio.renditions.values() {
355			config.check()?;
356		}
357		Ok(())
358	}
359
360	/// Copy every section into a catalog with no application extension.
361	pub fn without_ext(&self) -> Catalog<()> {
362		// Destructured without `..`, so a new field fails to compile until it is carried over.
363		let Catalog {
364			video,
365			audio,
366			sync,
367			text,
368			json,
369			binary,
370			stats,
371			echo,
372			include,
373			ext: _,
374			skipped,
375		} = self;
376		Catalog {
377			video: video.clone(),
378			audio: audio.clone(),
379			sync: *sync,
380			text: text.clone(),
381			json: json.clone(),
382			binary: binary.clone(),
383			stats: stats.clone(),
384			echo: echo.clone(),
385			include: include.clone(),
386			ext: (),
387			skipped: skipped.clone(),
388		}
389	}
390}
391
392impl<E: DeserializeOwned + Default> FromStr for Catalog<E> {
393	type Err = crate::Error;
394
395	/// Parse a catalog from a string.
396	///
397	/// Fails with [`Error::UnsupportedVersion`](crate::Error::UnsupportedVersion) if the catalog
398	/// needs a newer moq-hang draft than this crate reads.
399	fn from_str(s: &str) -> Result<Self> {
400		Self::from_slice(s.as_bytes())
401	}
402}
403
404impl<E: DeserializeOwned + Default> Catalog<E> {
405	/// Subscribe to catalog updates on a broadcast, reading only the newest.
406	///
407	/// For a reader that applies each update on arrival; one that holds updates until their
408	/// timestamp builds a [`Consumer`](super::Consumer) with its playout delay.
409	///
410	/// Fails here, not on the first read, when the catalog track is refused or missing.
411	#[cfg(feature = "async")]
412	pub async fn subscribe(broadcast: &moq_net::broadcast::Consumer) -> Result<super::Consumer<E>> {
413		let track = broadcast.track(Catalog::DEFAULT_NAME)?;
414		// Resolved on the consumer's own subscription, so a refusal fails here with no extra request.
415		let mut consumer = super::Consumer::new(track, std::time::Duration::ZERO);
416		consumer.info().await?;
417		Ok(consumer)
418	}
419
420	/// Parse a catalog from a slice of bytes.
421	///
422	/// Fails with [`Error::UnsupportedVersion`](crate::Error::UnsupportedVersion) if the catalog
423	/// needs a newer moq-hang draft than this crate reads.
424	pub fn from_slice(v: &[u8]) -> Result<Self> {
425		// Probed straight from the bytes first, so an unsupported root `version` is reported before
426		// any other fault; `Strict` then refuses a repeated member, which a `Value` would collapse.
427		serde_json::from_slice::<Probe>(v)?.check()?;
428		Self::from_value(serde_json::from_slice::<Strict>(v)?.0)
429	}
430
431	/// Parse a catalog from a reader.
432	///
433	/// Fails with [`Error::UnsupportedVersion`](crate::Error::UnsupportedVersion) if the catalog
434	/// needs a newer moq-hang draft than this crate reads.
435	pub fn from_reader(mut reader: impl std::io::Read) -> Result<Self> {
436		let mut buf = Vec::new();
437		reader.read_to_end(&mut buf).map_err(serde_json::Error::io)?;
438		Self::from_slice(&buf)
439	}
440
441	/// Parse a catalog from a JSON value.
442	///
443	/// Fails with [`Error::UnsupportedVersion`](crate::Error::UnsupportedVersion) if the catalog
444	/// needs a newer moq-hang draft than this crate reads. Every `version` is read before any
445	/// section, which the newer draft may have reshaped; an entry needing a newer draft is
446	/// skipped and reported in [`skipped`](Self::skipped).
447	pub(crate) fn from_value(mut value: serde_json::Value) -> Result<Self> {
448		let probe = Probe::deserialize(&value)?;
449		probe.check()?;
450		// Checked, so taken out of what an extension would otherwise receive.
451		if let Some(root) = value.as_object_mut() {
452			root.remove("version");
453		}
454		let mut catalog: Self = Wire::deserialize(value)?;
455		catalog.skipped = probe.skipped;
456		Ok(catalog)
457	}
458}
459
460impl<E: Serialize> Catalog<E> {
461	/// Serialize the catalog to a JSON string.
462	pub fn to_json(&self) -> Result<String> {
463		Ok(serde_json::to_string(self)?)
464	}
465
466	/// Serialize the catalog to a vector of bytes.
467	pub fn to_vec(&self) -> Result<Vec<u8>> {
468		Ok(serde_json::to_vec(self)?)
469	}
470
471	/// Serialize the catalog to a writer.
472	pub fn to_writer(&self, writer: impl std::io::Write) -> Result<()> {
473		Ok(serde_json::to_writer(writer, self)?)
474	}
475}
476
477#[cfg(test)]
478mod test {
479	use std::collections::BTreeMap;
480
481	use crate::catalog::{AudioCodec::Opus, AudioConfig, BinaryConfig, Container, H264, JsonConfig, Mode, VideoConfig};
482
483	use super::*;
484
485	#[derive(Deserialize)]
486	struct ParityCase {
487		name: String,
488		catalog: serde_json::Value,
489		#[serde(default)]
490		refused: bool,
491		#[serde(default)]
492		video: Vec<String>,
493		#[serde(default)]
494		audio: Vec<String>,
495		#[serde(default)]
496		text: Vec<String>,
497		#[serde(default)]
498		json: Vec<String>,
499		#[serde(default)]
500		binary: Vec<String>,
501		#[serde(default)]
502		include: Vec<String>,
503		#[serde(default)]
504		skipped: BTreeMap<String, BTreeMap<String, u64>>,
505	}
506
507	/// The corpus `js/hang` also loads: both languages accept the same catalogs and keep the same
508	/// rendition, data track, and include IDs, and skip the same newer entries, so a divergence
509	/// fails CI on whichever side drifts.
510	#[test]
511	fn shared_parity_fixtures() {
512		let cases: Vec<ParityCase> = serde_json::from_str(include_str!("../../fixtures/catalog-parity.json")).unwrap();
513		let mut failures = Vec::new();
514		for case in cases {
515			let parsed = Catalog::<()>::from_str(&case.catalog.to_string()).and_then(|catalog| {
516				catalog.check_renditions()?;
517				Ok(catalog)
518			});
519			match (parsed, case.refused) {
520				(Err(_), true) => {}
521				(Ok(catalog), true) => failures.push(format!("{}: accepted {catalog:?}", case.name)),
522				(Err(err), false) => failures.push(format!("{}: refused: {err}", case.name)),
523				(Ok(catalog), false) => {
524					let video: Vec<_> = catalog.video.renditions.keys().cloned().collect();
525					let audio: Vec<_> = catalog.audio.renditions.keys().cloned().collect();
526					let text: Vec<_> = catalog.text.renditions.keys().cloned().collect();
527					let json: Vec<_> = catalog.json.tracks.keys().cloned().collect();
528					let binary: Vec<_> = catalog.binary.tracks.keys().cloned().collect();
529					let include: Vec<_> = catalog.include.keys().cloned().collect();
530					if (&video, &audio, &text, &json, &binary, &include)
531						!= (
532							&case.video,
533							&case.audio,
534							&case.text,
535							&case.json,
536							&case.binary,
537							&case.include,
538						) {
539						failures.push(format!(
540							"{}: kept video {video:?} audio {audio:?} text {text:?} json {json:?} binary {binary:?} include {include:?}",
541							case.name
542						));
543					}
544					let skipped = &catalog.skipped;
545					let skipped: BTreeMap<String, BTreeMap<String, u64>> = [
546						("video", &skipped.video),
547						("audio", &skipped.audio),
548						("text", &skipped.text),
549						("json", &skipped.json),
550						("binary", &skipped.binary),
551						("include", &skipped.include),
552					]
553					.into_iter()
554					.filter(|(_, ids)| !ids.is_empty())
555					.map(|(section, ids)| (section.to_string(), ids.clone()))
556					.collect();
557					if skipped != case.skipped {
558						failures.push(format!("{}: skipped {skipped:?}", case.name));
559					}
560				}
561			}
562		}
563		assert!(failures.is_empty(), "{}", failures.join("\n"));
564	}
565
566	/// The rendition count is the publisher's to choose: a catalog listing many is accepted.
567	#[test]
568	fn many_renditions_are_accepted() {
569		let mut catalog = Catalog::<()>::default();
570		for i in 0..1000 {
571			catalog
572				.audio
573				.renditions
574				.insert(format!("audio{i}"), AudioConfig::new(Opus, 48_000, 2));
575		}
576		catalog.check_renditions().unwrap();
577		let decoded = Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap();
578		assert_eq!(decoded.audio.renditions.len(), 1000);
579	}
580
581	#[test]
582	fn track_name_defaults_to_the_id() {
583		use crate::catalog::Reference;
584
585		let catalog = Catalog::<()>::from_str(
586			r#"{
587				"video": {"renditions": {"hd": {"codec": "avc1.64001f", "container": {"kind": "legacy"}}}},
588				"audio": {"renditions": {"en": {"codec": "opus", "sampleRate": 48000, "numberOfChannels": 2, "container": {"kind": "legacy"}}}}
589			}"#,
590		)
591		.unwrap();
592		assert_eq!(catalog.video.renditions["hd"].track("hd"), "hd");
593		assert_eq!(catalog.audio.renditions["en"].track("en"), "en");
594		assert!(!catalog.to_json().unwrap().contains("\"track\""));
595	}
596
597	#[test]
598	fn one_track_name_in_two_broadcasts() {
599		use crate::catalog::Reference;
600
601		let encoded = r#"{
602			"video": {"renditions": {
603				"left": {"broadcast": "./left", "track": "video", "codec": "avc1.64001f", "container": {"kind": "legacy"}},
604				"right": {"broadcast": "./right", "track": "video", "codec": "avc1.64001f", "container": {"kind": "legacy"}}
605			}}
606		}"#;
607		let catalog = Catalog::<()>::from_str(encoded).unwrap();
608		assert!(catalog.check_renditions().is_ok());
609		for id in ["left", "right"] {
610			let config = &catalog.video.renditions[id];
611			assert_eq!(config.track(id), "video");
612			assert_eq!(config.broadcast().map(|b| b.as_str()), Some(id));
613		}
614		assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog);
615	}
616
617	/// An include round-trips, stays off the wire when none is listed, and a malformed entry
618	/// refuses the catalog rather than being dropped.
619	#[test]
620	fn includes_roundtrip_and_refuse_malformed_entries() {
621		let json = r#"{"include":{"alice":{"broadcast":"./alice.hang"}},"video":{"renditions":{"alice":{"codec":"avc1.64001f","container":{"kind":"legacy"}}}}}"#;
622		let catalog = Catalog::<()>::from_str(json).unwrap();
623		assert_eq!(
624			catalog.include["alice"],
625			crate::catalog::Include::new(moq_net::path::Relative::new("./alice.hang").unwrap())
626		);
627		// Include IDs are their own namespace, so one may share a rendition's ID.
628		assert!(catalog.check_renditions().is_ok());
629		assert!(catalog.video.renditions.contains_key("alice"));
630		assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog);
631		assert!(!Catalog::<()>::default().to_json().unwrap().contains("include"));
632
633		for bad in [
634			r#"{"include":[]}"#,
635			r#"{"include":{"alice":null}}"#,
636			r#"{"include":{"alice":{}}}"#,
637			r#"{"include":{"alice":{"broadcast":42}}}"#,
638		] {
639			assert!(Catalog::<()>::from_str(bad).is_err(), "{bad} must be refused");
640		}
641	}
642
643	#[test]
644	fn cross_kind_duplicate_id_is_refused() {
645		let catalog = Catalog::<()>::from_str(
646			r#"{
647				"video": {"renditions": {"main": {"codec": "avc1.64001f", "container": {"kind": "legacy"}}}},
648				"audio": {"renditions": {"main": {"codec": "opus", "sampleRate": 48000, "numberOfChannels": 2, "container": {"kind": "legacy"}}}}
649			}"#,
650		)
651		.unwrap();
652		assert!(matches!(
653			catalog.check_renditions(),
654			Err(crate::Error::DuplicateRendition(id)) if id == "main"
655		));
656	}
657
658	/// A publisher building the catalog by hand is caught before it writes a value every reader refuses.
659	#[test]
660	fn fields_out_of_range_are_refused() {
661		use crate::catalog::{AudioLayout, Projection, VideoCodec, VideoConfig};
662
663		let mut catalog = Catalog::<()>::default();
664		let mut amb = AudioConfig::new(Opus, 48_000, 6);
665		amb.layout = Some(AudioLayout::Ambisonic);
666		catalog.audio.insert("amb", amb).unwrap();
667		assert!(matches!(
668			catalog.check_renditions(),
669			Err(crate::Error::InvalidAmbisonicChannels(6))
670		));
671		catalog.audio.renditions.get_mut("amb").unwrap().channel_count = 4;
672		catalog.check_renditions().unwrap();
673
674		catalog.audio.renditions.get_mut("amb").unwrap().sample_rate = 0;
675		assert!(matches!(
676			catalog.check_renditions(),
677			Err(crate::Error::Zero("sampleRate"))
678		));
679		catalog.audio.renditions.get_mut("amb").unwrap().sample_rate = 48_000;
680
681		let mut config = VideoConfig::new(VideoCodec::VP8);
682		config.coded_width = Some(0);
683		catalog.video.insert("empty", config).unwrap();
684		assert!(matches!(
685			catalog.check_renditions(),
686			Err(crate::Error::Zero("codedWidth"))
687		));
688		catalog.video.remove("empty");
689
690		let mut config = VideoConfig::new(VideoCodec::VP8);
691		config.projection = Some(Projection::Equirectangular { fov: Some(400.0) });
692		catalog.video.insert("vr", config).unwrap();
693		assert!(matches!(
694			catalog.check_renditions(),
695			Err(crate::Error::InvalidFieldOfView(_))
696		));
697	}
698
699	#[test]
700	fn simple() {
701		let mut encoded = r#"{
702			"video": {
703				"renditions": {
704					"video": {
705						"codec": "avc1.64001f",
706						"codedWidth": 1280,
707						"codedHeight": 720,
708						"bitrate": 6000000,
709						"framerate": 30.0,
710						"container": {"kind": "legacy"}
711					}
712				}
713			},
714			"audio": {
715				"renditions": {
716					"audio": {
717						"codec": "opus",
718						"sampleRate": 48000,
719						"numberOfChannels": 2,
720						"bitrate": 128000,
721						"container": {"kind": "legacy"}
722					}
723				}
724			}
725		}"#
726		.to_string();
727
728		encoded.retain(|c| !c.is_whitespace());
729
730		let mut video_config = VideoConfig::new(H264 {
731			profile: 0x64,
732			constraints: 0x00,
733			level: 0x1f,
734			inline: false,
735		});
736		video_config.coded_width = Some(1280);
737		video_config.coded_height = Some(720);
738		video_config.bitrate = Some(6_000_000);
739		video_config.framerate = Some(30.0);
740		video_config.container = Container::Legacy;
741
742		let mut video_renditions = BTreeMap::new();
743		video_renditions.insert("video".to_string(), video_config);
744
745		let mut audio_config = AudioConfig::new(Opus, 48_000, 2);
746		audio_config.bitrate = Some(128_000);
747		audio_config.container = Container::Legacy;
748
749		let mut audio_renditions = BTreeMap::new();
750		audio_renditions.insert("audio".to_string(), audio_config);
751
752		let mut decoded = Catalog::<()>::default();
753		decoded.video.renditions = video_renditions;
754		decoded.audio.renditions = audio_renditions;
755
756		let output = Catalog::<()>::from_str(&encoded).expect("failed to decode");
757		assert_eq!(decoded, output, "wrong decoded output");
758
759		let output = decoded.to_json().expect("failed to encode");
760		assert_eq!(encoded, output, "wrong encoded output");
761	}
762
763	/// Lock in the on-wire shape of the jitter and delay fields: a bare integer number
764	/// of milliseconds. If `Option<Duration>` ever loses the `duration_millis`
765	/// serde adapter, this regresses to serde's default `{secs, nanos}` shape.
766	#[test]
767	fn jitter_and_delay_serialized_as_millis() {
768		let mut encoded = r#"{
769			"video": {
770				"renditions": {
771					"video": {
772						"codec": "avc1.64001f",
773						"container": {"kind": "legacy"},
774						"jitter": 100,
775						"delay": 200
776					}
777				}
778			},
779			"audio": {
780				"renditions": {
781					"audio": {
782						"codec": "opus",
783						"sampleRate": 48000,
784						"numberOfChannels": 2,
785						"container": {"kind": "legacy"},
786						"jitter": 40
787					}
788				}
789			}
790		}"#
791		.to_string();
792		encoded.retain(|c| !c.is_whitespace());
793
794		let mut video_renditions = BTreeMap::new();
795		video_renditions.insert(
796			"video".to_string(),
797			VideoConfig {
798				broadcast: None,
799				track: None,
800				label: None,
801				codec: H264 {
802					profile: 0x64,
803					constraints: 0x00,
804					level: 0x1f,
805					inline: false,
806				}
807				.into(),
808				description: None,
809				coded_width: None,
810				coded_height: None,
811				display_aspect_width: None,
812				display_aspect_height: None,
813				color: None,
814				projection: None,
815				stereo: None,
816				interlaced: false,
817				bitrate: None,
818				enabled: true,
819				preference: 0,
820				framerate: None,
821				reorder: None,
822				optimize_for_latency: None,
823				container: Container::Legacy,
824				jitter: Some(std::time::Duration::from_millis(100)),
825				delay: Some(std::time::Duration::from_millis(200)),
826			},
827		);
828
829		let mut audio_renditions = BTreeMap::new();
830		audio_renditions.insert(
831			"audio".to_string(),
832			AudioConfig {
833				broadcast: None,
834				track: None,
835				label: None,
836				codec: Opus,
837				sample_rate: 48_000,
838				channel_count: 2,
839				layout: None,
840				bitrate: None,
841				enabled: true,
842				description: None,
843				container: Container::Legacy,
844				warmup: None,
845				jitter: Some(std::time::Duration::from_millis(40)),
846				delay: None,
847			},
848		);
849
850		let mut catalog = Catalog::<()>::default();
851		catalog.video.renditions = video_renditions;
852		catalog.audio.renditions = audio_renditions;
853
854		let decoded = Catalog::<()>::from_str(&encoded).expect("failed to decode");
855		assert_eq!(catalog, decoded, "decode mismatch");
856
857		let output = catalog.to_json().expect("failed to encode");
858		assert_eq!(encoded, output, "encode mismatch");
859	}
860
861	#[test]
862	fn rendition_with_broadcast_override() {
863		// Decode a catalog where one rendition references a track in a sibling broadcast,
864		// and verify the `broadcast` field round-trips through serde.
865		let encoded = r#"{
866			"video": {
867				"renditions": {
868					"video": {
869						"broadcast": "./source",
870						"codec": "avc1.64001f",
871						"codedWidth": 1280,
872						"codedHeight": 720,
873						"container": {"kind": "legacy"}
874					}
875				}
876			}
877		}"#;
878
879		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
880		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
881		assert_eq!(
882			rendition.broadcast.as_ref().map(|p| p.as_str()),
883			Some("source"),
884			"broadcast field did not deserialize"
885		);
886
887		// Full encode -> decode -> equality, so the test catches any encoder regression
888		// (e.g. wrong key, double-emission, or `null` instead of skip).
889		let output = parsed.to_json().expect("failed to encode");
890		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
891		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
892	}
893
894	#[test]
895	fn rendition_without_broadcast_omits_field() {
896		// `broadcast: None` must NOT serialize as `"broadcast":null`, otherwise the wire
897		// format silently changes for every catalog that doesn't use cross-broadcast refs.
898		let mut video_config = VideoConfig::new(H264 {
899			profile: 0x64,
900			constraints: 0x00,
901			level: 0x1f,
902			inline: false,
903		});
904		video_config.container = Container::Legacy;
905
906		let mut renditions = BTreeMap::new();
907		renditions.insert("video".to_string(), video_config);
908
909		let catalog = Catalog::<()> {
910			video: Video {
911				renditions,
912				..Default::default()
913			},
914			..Default::default()
915		};
916
917		let output = catalog.to_json().expect("failed to encode");
918		assert!(
919			!output.contains("broadcast"),
920			"broadcast field leaked into JSON when None: {output}"
921		);
922	}
923
924	#[test]
925	fn rendition_with_empty_broadcast_normalizes() {
926		// An empty-string broadcast field should normalize to an empty `path::Relative` so the
927		// consumer can treat it identically to a missing field.
928		let encoded = r#"{
929			"video": {
930				"renditions": {
931					"video": {
932						"broadcast": "",
933						"codec": "avc1.64001f",
934						"container": {"kind": "legacy"}
935					}
936				}
937			}
938		}"#;
939
940		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
941		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
942		assert_eq!(
943			rendition.broadcast.as_ref().map(|p| p.is_empty()),
944			Some(true),
945			"empty broadcast should deserialize as Some(empty)"
946		);
947	}
948
949	#[test]
950	fn rendition_with_misspelled_broadcast_is_refused() {
951		// Spelled like a path, so an empty segment or a lone backslash makes the rendition malformed,
952		// which refuses the catalog. Mirrors the JS `rendition broadcast reference is parsed and normalized`.
953		for broadcast in ["./source/", "/source", "a//b", r"a\b"] {
954			let encoded = serde_json::json!({
955				"video": {"renditions": {"video": {
956					"broadcast": broadcast,
957					"codec": "avc1.64001f",
958					"container": {"kind": "legacy"}
959				}}}
960			})
961			.to_string();
962
963			Catalog::<()>::from_str(&encoded).expect_err(&format!("{broadcast:?} should be refused"));
964		}
965	}
966
967	#[test]
968	fn rendition_with_parent_broadcast_stays_distinct_from_empty() {
969		let encoded = r#"{
970			"video": {
971				"renditions": {
972					"video": {
973						"broadcast": ".",
974						"codec": "avc1.64001f",
975						"container": {"kind": "legacy"}
976					}
977				}
978			}
979		}"#;
980
981		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
982		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
983		assert_eq!(
984			rendition.broadcast.as_ref().map(|p| p.as_str()),
985			Some("."),
986			"parent reference should not normalize to empty"
987		);
988	}
989
990	#[test]
991	fn unknown_container_keeps_siblings() {
992		// A rendition using a future container must not take down the rest of the catalog.
993		let encoded = r#"{
994			"video": {
995				"renditions": {
996					"future": {
997						"codec": "avc1.64001f",
998						"container": {"kind": "future", "magic": 7}
999					},
1000					"legacy": {
1001						"codec": "avc1.64001f",
1002						"codedWidth": 1280,
1003						"codedHeight": 720,
1004						"container": {"kind": "legacy"}
1005					}
1006				}
1007			}
1008		}"#;
1009
1010		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
1011
1012		let known = parsed.video.renditions.get("legacy").expect("missing rendition");
1013		assert_eq!(known.container, Container::Legacy);
1014		assert_eq!(known.coded_width, Some(1280));
1015
1016		let future = parsed.video.renditions.get("future").expect("missing rendition");
1017		let Container::Unknown(unknown) = &future.container else {
1018			panic!("expected unknown container: {:?}", future.container);
1019		};
1020		assert_eq!(unknown.kind(), "future");
1021
1022		// The unknown rendition survives a republish intact.
1023		let output = parsed.to_json().expect("failed to encode");
1024		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
1025		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
1026		assert!(output.contains(r#""magic":7"#), "unknown fields dropped: {output}");
1027	}
1028
1029	#[test]
1030	fn empty_video_and_audio_sections_omitted() {
1031		// A data-only broadcast must not advertise media it does not have. An old publisher's
1032		// empty objects still decode, and a republish drops them.
1033		assert_eq!(Catalog::<()>::default().to_json().expect("failed to encode"), "{}");
1034
1035		let mut audio_only = Catalog::<()>::default();
1036		audio_only
1037			.audio
1038			.insert("audio", AudioConfig::new(Opus, 48_000, 2))
1039			.unwrap();
1040		let output = audio_only.to_json().expect("failed to encode");
1041		assert!(output.contains("\"audio\""), "audio section missing: {output}");
1042		assert!(!output.contains("\"video\""), "empty video section leaked: {output}");
1043
1044		let mut video_only = Catalog::<()>::default();
1045		video_only.video.display = Some(crate::catalog::Display { width: 16, height: 9 });
1046		assert_eq!(
1047			video_only.to_json().expect("failed to encode"),
1048			"{}",
1049			"display without a rendition must not keep an empty video section"
1050		);
1051
1052		let legacy = Catalog::<()>::from_str(r#"{"video":{"renditions":{}},"audio":{"renditions":{}}}"#)
1053			.expect("failed to decode");
1054		assert!(legacy.video.is_empty());
1055		assert!(legacy.audio.is_empty());
1056		assert_eq!(legacy.to_json().expect("failed to encode"), "{}");
1057	}
1058
1059	#[test]
1060	fn text_section_roundtrip() {
1061		use crate::catalog::{Text, TextConfig, TextFormat, TextRole};
1062
1063		let mut config = TextConfig::new(TextFormat::Vtt);
1064		config.role = TextRole::Caption;
1065		config.lang = Some("en".to_string());
1066
1067		let mut text = Text::default();
1068		text.insert("captions.en", config).expect("insert");
1069
1070		let catalog = Catalog::<()> {
1071			text,
1072			..Default::default()
1073		};
1074
1075		let json = catalog.to_json().expect("failed to encode");
1076		assert!(json.contains("\"text\""), "text section missing: {json}");
1077
1078		let decoded = Catalog::<()>::from_str(&json).expect("failed to decode");
1079		assert_eq!(catalog, decoded, "text section did not round-trip");
1080	}
1081
1082	#[test]
1083	fn unknown_text_role_keeps_the_catalog() {
1084		// A future `role` value must not take down the whole catalog: audio and video have to keep
1085		// playing even when a caption rendition is classified with a vocabulary we don't know yet.
1086		let json = r#"{"video":{"renditions":{}},"audio":{"renditions":{}},"text":{"renditions":{"subs":{"format":"vtt","role":"commentary"}}}}"#;
1087
1088		let catalog = Catalog::<()>::from_str(json).expect("unknown role rejected the catalog");
1089		assert_eq!(catalog.text.renditions.len(), 1);
1090		let encoded = catalog.to_json().expect("failed to encode unknown role");
1091		assert!(
1092			encoded.contains(r#""role":"commentary""#),
1093			"unknown role was not preserved: {encoded}"
1094		);
1095		assert!(!encoded.contains("\"video\""), "empty video section leaked: {encoded}");
1096		assert!(!encoded.contains("\"audio\""), "empty audio section leaked: {encoded}");
1097	}
1098
1099	#[test]
1100	fn data_sections_stay_off_the_wire_when_empty() {
1101		// Empty sections stay off the wire, video and audio included.
1102		let output = Catalog::<()>::default().to_json().expect("failed to encode");
1103		assert_eq!(output, "{}");
1104	}
1105
1106	#[test]
1107	fn sync_roundtrips_at_the_root() {
1108		let clock =
1109			crate::catalog::Clock::new(moq_net::Timestamp::from_micros(1_751_846_400_000_000).unwrap()).unwrap();
1110		let mut catalog = Catalog::<()>::default();
1111		catalog.sync.clock = Some(clock);
1112		catalog.sync.interval = Some(std::time::Duration::from_secs(2));
1113
1114		let json = catalog.to_json().expect("failed to encode");
1115		assert_eq!(
1116			json,
1117			r#"{"sync":{"clock":{"wall":1751846400000000,"timescale":1000000},"interval":2000}}"#
1118		);
1119		assert_eq!(Catalog::<()>::from_str(&json).expect("failed to decode"), catalog);
1120	}
1121
1122	/// Retired shapes are someone else's keys, ignored rather than read: the root `clock` and the
1123	/// `media` section that each held the clock before `sync`, and a rendition `hls` record.
1124	#[test]
1125	fn a_retired_clock_media_and_hls_field_are_ignored() {
1126		let rendition = serde_json::json!({"codec": "avc1.64001f", "container": {"kind": "legacy"}});
1127		let plain =
1128			Catalog::<()>::from_str(&serde_json::json!({"video": {"renditions": {"video": rendition}}}).to_string())
1129				.unwrap();
1130		let mut retired = rendition.clone();
1131		retired["hls"] = serde_json::json!({"track": "video.hls", "duration": 2000});
1132		let json = serde_json::json!({
1133			"video": {"renditions": {"video": retired}},
1134			"clock": {"wall": 1000, "timescale": 1000000},
1135			"media": {"clock": {"wall": 1000}, "join": {"interval": 2000}},
1136		});
1137		let catalog = Catalog::<()>::from_str(&json.to_string()).expect("retired fields must not reject media");
1138		assert_eq!(catalog, plain);
1139		assert_eq!(catalog.sync, crate::catalog::Timeline::default());
1140		assert_eq!(catalog.to_json().unwrap(), plain.to_json().unwrap());
1141	}
1142
1143	#[test]
1144	fn packaged_clock_fixture_decodes() {
1145		// The canonical shape: the clock and join interval under `sync`. A reader maps media
1146		// timestamps through the clock after timescale conversion.
1147		let json = include_str!("../../fixtures/catalog-clock.json");
1148		let catalog = Catalog::<()>::from_str(json).expect("the packaged fixture must decode");
1149
1150		let clock = catalog.sync.clock.expect("the fixture carries a clock");
1151		assert_eq!(clock.wall().scale().map(moq_net::Timescale::as_u64), Some(1_000_000));
1152		assert_eq!(catalog.sync.interval, Some(std::time::Duration::from_secs(2)));
1153
1154		// PTS 2000 ms lands 2s after the wall epoch, whatever the track timescale.
1155		let expected = moq_net::time::EPOCH + std::time::Duration::from_millis(1_751_846_402_000);
1156		assert_eq!(
1157			clock
1158				.wall_clock(moq_net::Timestamp::from_millis(2000).unwrap())
1159				.unwrap(),
1160			expected
1161		);
1162	}
1163
1164	#[test]
1165	fn a_retired_root_archive_is_ignored() {
1166		let video = serde_json::json!({
1167			"renditions": {"video": {"codec": "avc1.64001f", "container": {"kind": "legacy"}}}
1168		});
1169		let media = Catalog::<()>::from_str(&serde_json::json!({"video": video}).to_string()).unwrap();
1170		let archive = serde_json::json!({
1171			"timelines": {"video": {"track": "video.timeline.z", "duration": 2000}},
1172			"timescale": 1000,
1173			"replay": "./recordings/clip",
1174			"store": "https://objects.example/rec/",
1175			"version": 3
1176		});
1177		let json = serde_json::json!({"video": video, "archive": archive}).to_string();
1178		let catalog = Catalog::<()>::from_str(&json).expect("a retired archive must not reject the catalog");
1179		assert_eq!(catalog, media);
1180		assert!(!catalog.to_json().unwrap().contains("archive"));
1181	}
1182
1183	#[test]
1184	fn data_tracks_roundtrip() {
1185		let mut encoded = r#"{
1186			"json": {
1187				"tracks": {
1188					"chat": {
1189						"mode": "stream",
1190						"schema": "https://example.com/chat.schema.json"
1191					},
1192					"status": {
1193						"broadcast": "source",
1194						"mode": "snapshot"
1195					}
1196				}
1197			},
1198			"binary": {
1199				"tracks": {
1200					"thumbnail": {
1201						"mode": "snapshot",
1202						"mime": "image/jpeg"
1203					}
1204				}
1205			}
1206		}"#
1207		.to_string();
1208		encoded.retain(|c| !c.is_whitespace());
1209
1210		let mut chat = JsonConfig::new(Mode::Stream);
1211		chat.schema = Some("https://example.com/chat.schema.json".to_string());
1212
1213		let mut status = JsonConfig::new(Mode::Snapshot);
1214		status.broadcast = Some(moq_net::path::Relative::new("source").unwrap());
1215
1216		let mut thumbnail = BinaryConfig::new(Mode::Snapshot);
1217		thumbnail.mime = Some("image/jpeg".to_string());
1218
1219		let mut catalog = Catalog::<()>::default();
1220		catalog.json.insert("chat", chat).unwrap();
1221		catalog.json.insert("status", status).unwrap();
1222		catalog.binary.insert("thumbnail", thumbnail).unwrap();
1223
1224		let decoded = Catalog::<()>::from_str(&encoded).expect("failed to decode");
1225		assert_eq!(decoded, catalog, "decode mismatch");
1226
1227		let output = catalog.to_json().expect("failed to encode");
1228		assert_eq!(output, encoded, "encode mismatch");
1229	}
1230
1231	/// Data tracks carry the same optional `bitrate` and whole-millisecond `jitter` and `delay` as
1232	/// media.
1233	#[test]
1234	fn data_track_bitrate_and_jitter() {
1235		let encoded = r#"{"json":{"tracks":{"gps":{"mode":"stream","bitrate":8000,"jitter":100,"delay":250}}},"binary":{"tracks":{"frames":{"mode":"snapshot","bitrate":64000,"jitter":34}}}}"#;
1236
1237		let mut gps = JsonConfig::new(Mode::Stream);
1238		gps.bitrate = Some(8_000);
1239		gps.jitter = Some(std::time::Duration::from_millis(100));
1240		gps.delay = Some(std::time::Duration::from_micros(249_001));
1241
1242		let mut frames = BinaryConfig::new(Mode::Snapshot);
1243		frames.bitrate = Some(64_000);
1244		frames.jitter = Some(std::time::Duration::from_micros(33_334));
1245
1246		let mut catalog = Catalog::<()>::default();
1247		catalog.json.insert("gps", gps).unwrap();
1248		catalog.binary.insert("frames", frames).unwrap();
1249
1250		assert_eq!(
1251			catalog.to_json().unwrap(),
1252			encoded,
1253			"jitter rounds up to whole milliseconds"
1254		);
1255
1256		let decoded = Catalog::<()>::from_str(encoded).unwrap();
1257		assert_eq!(
1258			decoded.binary.tracks["frames"].jitter,
1259			Some(std::time::Duration::from_millis(34))
1260		);
1261		assert_eq!(decoded.json.tracks["gps"].bitrate, Some(8_000));
1262		assert_eq!(
1263			decoded.json.tracks["gps"].delay,
1264			Some(std::time::Duration::from_millis(250))
1265		);
1266	}
1267
1268	/// An application lists a data track in its own section with a nested data config, keeping config
1269	/// fields separate from the application's own fields.
1270	#[test]
1271	fn a_data_config_nests_in_an_application_entry() {
1272		#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
1273		struct Mavlink {
1274			config: BinaryConfig,
1275			sysid: u8,
1276		}
1277
1278		#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Clone)]
1279		struct Ext {
1280			#[serde(rename = "com.example.mavlink", default)]
1281			mavlink: BTreeMap<String, Mavlink>,
1282		}
1283
1284		let encoded = r#"{"com.example.mavlink":{"telemetry":{"config":{"mode":"stream","mime":"application/mavlink"},"sysid":1}}}"#;
1285
1286		let catalog = Catalog::<Ext>::from_str(encoded).unwrap();
1287		let entry = &catalog.ext.mavlink["telemetry"];
1288		assert_eq!(entry.sysid, 1);
1289		assert_eq!(entry.config.mode, Mode::Stream);
1290		assert_eq!(entry.config.mime.as_deref(), Some("application/mavlink"));
1291		assert_eq!(catalog.to_json().unwrap(), encoded);
1292	}
1293
1294	/// A track using a future mode must survive a reparse-and-republish intact, so a relay doesn't
1295	/// corrupt what it can't read. Its siblings stay readable.
1296	#[test]
1297	fn unknown_mode_keeps_siblings() {
1298		let encoded = r#"{
1299			"json": {
1300				"tracks": {
1301					"future": {"mode": "windowed"},
1302					"known": {"mode": "stream"}
1303				}
1304			}
1305		}"#;
1306
1307		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
1308
1309		let known = parsed.json.tracks.get("known").expect("missing track");
1310		assert_eq!(known.mode, Mode::Stream);
1311
1312		let future = parsed.json.tracks.get("future").expect("missing track");
1313		assert_eq!(future.mode, Mode::Unknown("windowed".to_string()));
1314
1315		let output = parsed.to_json().expect("failed to encode");
1316		assert!(
1317			output.contains(r#""mode":"windowed""#),
1318			"unknown mode dropped: {output}"
1319		);
1320		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
1321		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
1322	}
1323
1324	/// Preserving the mode string alone is not enough: a future mode comes with fields describing
1325	/// it, and a relay that reparsed and republished would otherwise strip them, leaving an entry
1326	/// nothing can act on.
1327	#[test]
1328	fn unknown_mode_fields_round_trip() {
1329		let encoded = r#"{"json":{"tracks":{"future":{"mode":"windowed","window":10}}}}"#;
1330
1331		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
1332		let future = parsed.json.tracks.get("future").expect("missing track");
1333		assert_eq!(future.mode, Mode::Unknown("windowed".to_string()));
1334		assert_eq!(future.extra.get("window"), Some(&serde_json::json!(10)));
1335
1336		let output = parsed.to_json().expect("failed to encode");
1337		assert!(output.contains(r#""window":10"#), "unknown fields dropped: {output}");
1338		assert_eq!(Catalog::<()>::from_str(&output).expect("re-decode"), parsed);
1339	}
1340
1341	/// There is no safe default: reading a stream as a snapshot silently drops every record but the
1342	/// last, so an entry without a mode is malformed rather than assumed.
1343	#[test]
1344	fn a_track_without_a_mode_is_rejected() {
1345		Catalog::<()>::from_str(r#"{"json":{"tracks":{"chat":{"schema":"chat"}}}}"#)
1346			.expect_err("a mode-less track must not decode");
1347	}
1348
1349	#[test]
1350	fn duplicate_data_track_names_are_rejected() {
1351		let mut catalog = Catalog::<()>::default();
1352		catalog.json.insert("chat", JsonConfig::new(Mode::Stream)).unwrap();
1353		assert!(matches!(
1354			catalog.json.insert("chat", JsonConfig::new(Mode::Snapshot)),
1355			Err(crate::Error::Duplicate(_))
1356		));
1357
1358		// The two sections are separate namespaces on the wire, so the same name in each is fine.
1359		catalog.binary.insert("chat", BinaryConfig::new(Mode::Stream)).unwrap();
1360	}
1361
1362	#[test]
1363	fn extension_roundtrip() {
1364		// An application extends the catalog with its own root section by flattening Catalog.
1365		#[derive(Serialize, Deserialize, PartialEq, Debug)]
1366		struct AppCatalog {
1367			#[serde(flatten)]
1368			base: Catalog,
1369			#[serde(skip_serializing_if = "Option::is_none")]
1370			scte35: Option<Scte35>,
1371		}
1372
1373		#[derive(Serialize, Deserialize, PartialEq, Debug)]
1374		struct Scte35 {
1375			splice_id: u32,
1376		}
1377
1378		let app = AppCatalog {
1379			base: Catalog::<()>::default(),
1380			scte35: Some(Scte35 { splice_id: 42 }),
1381		};
1382
1383		let json = serde_json::to_string(&app).expect("failed to encode");
1384
1385		// A base consumer ignores the unknown section.
1386		let base = Catalog::<()>::from_str(&json).expect("failed to decode base");
1387		assert_eq!(base, Catalog::<()>::default());
1388
1389		// The extended consumer round-trips its own section.
1390		let decoded: AppCatalog = serde_json::from_str(&json).expect("failed to decode app");
1391		assert_eq!(decoded, app);
1392	}
1393
1394	/// A newer draft may reshape a section, so the version is refused before any section is read,
1395	/// wherever it sits in the object.
1396	#[test]
1397	fn a_newer_version_is_refused() {
1398		for json in [
1399			r#"{"version":5}"#,
1400			r#"{"video":{"renditions":{"hd":{"codec":42}}},"version":5}"#,
1401		] {
1402			assert!(
1403				matches!(Catalog::<()>::from_str(json), Err(crate::Error::UnsupportedVersion(5))),
1404				"{json}"
1405			);
1406		}
1407
1408		// Plain serde refuses too, without the typed error.
1409		let err = serde_json::from_str::<Catalog>(r#"{"version":5}"#).unwrap_err();
1410		assert!(err.to_string().contains("unsupported catalog version 5"), "{err}");
1411	}
1412
1413	/// A repeated `version` is refused rather than resolved to either copy, so a newer catalog can't
1414	/// slip past the check by also claiming an old version.
1415	#[test]
1416	fn a_duplicate_version_is_refused() {
1417		for json in [r#"{"version":5,"version":3}"#, r#"{"version":3,"version":3}"#] {
1418			let err = Catalog::<()>::from_str(json).unwrap_err();
1419			assert!(err.to_string().contains("duplicate field `version`"), "{json}: {err}");
1420			assert!(Catalog::<()>::from_reader(json.as_bytes()).is_err(), "{json}");
1421			// So does plain serde, at the root and in an entry.
1422			assert!(serde_json::from_str::<Catalog>(json).is_err(), "{json}");
1423		}
1424		let entry = r#"{"video":{"renditions":{"hd":{"version":5,"version":3,"codec":"avc1.64001f"}}}}"#;
1425		assert!(Catalog::<()>::from_str(entry).is_err(), "{entry}");
1426		assert!(serde_json::from_str::<Catalog>(entry).is_err(), "{entry}");
1427
1428		// Any repeated member, not only `version`.
1429		let repeated = r#"{"video":{"renditions":{"hd":{"codec":"avc1.64001f","codec":"vp8"}}}}"#;
1430		assert!(Catalog::<()>::from_str(repeated).is_err(), "{repeated}");
1431		assert!(serde_json::from_str::<Catalog>(repeated).is_err(), "{repeated}");
1432	}
1433
1434	#[test]
1435	fn a_supported_version_is_read() {
1436		for json in [r#"{}"#, r#"{"version":3}"#, r#"{"version":4}"#] {
1437			assert_eq!(Catalog::<()>::from_str(json).unwrap(), Catalog::default(), "{json}");
1438		}
1439		for malformed in [r#"{"version":"4"}"#, r#"{"version":-1}"#, r#"{"version":4.5}"#] {
1440			assert!(
1441				matches!(Catalog::<()>::from_str(malformed), Err(crate::Error::Json(_))),
1442				"{malformed}"
1443			);
1444		}
1445	}
1446
1447	/// The version is the root's, so an extension never sees it, even one that passes every
1448	/// unknown member through.
1449	#[test]
1450	fn the_version_is_not_an_extension_member() {
1451		type Passthrough = serde_json::Map<String, serde_json::Value>;
1452		let catalog = Catalog::<Passthrough>::from_str(r#"{"version":4,"scte35":{}}"#).unwrap();
1453		assert!(catalog.ext.contains_key("scte35"));
1454		assert!(!catalog.ext.contains_key("version"));
1455	}
1456
1457	/// An extension member the specification reserves would sit beside the base member as a
1458	/// duplicate key: an extension `version` could override what the catalog actually needs.
1459	#[test]
1460	fn an_extension_reserved_member_is_refused() {
1461		#[derive(Serialize, Default)]
1462		struct Ext {
1463			version: u64,
1464		}
1465
1466		let catalog = Catalog {
1467			ext: Ext { version: 3 },
1468			..Default::default()
1469		};
1470		let err = catalog.to_json().unwrap_err();
1471		assert!(err.to_string().contains("reserved member `version`"), "{err}");
1472
1473		// Every section name too, which would otherwise sit beside the section as a duplicate key.
1474		for key in RESERVED {
1475			let mut passthrough = Catalog::<serde_json::Map<String, serde_json::Value>>::default();
1476			passthrough.ext.insert(key.into(), serde_json::json!({}));
1477			let err = passthrough.to_json().unwrap_err();
1478			assert!(err.to_string().contains(&format!("`{key}`")), "{key}: {err}");
1479		}
1480
1481		// Any other member still flattens beside the base sections.
1482		let ok = Catalog {
1483			ext: serde_json::json!({ "scte35": {} }),
1484			..Default::default()
1485		};
1486		assert_eq!(ok.to_json().unwrap(), r#"{"scte35":{}}"#);
1487	}
1488
1489	fn h264() -> VideoConfig {
1490		let mut config = VideoConfig::new(H264 {
1491			profile: 0x64,
1492			constraints: 0x00,
1493			level: 0x1f,
1494			inline: false,
1495		});
1496		config.container = Container::Legacy;
1497		config
1498	}
1499
1500	/// Only a field an older reader would misread raises an entry's version; one it would merely
1501	/// ignore leaves the entry readable by moq-hang-03. No moq-hang-04 field raises the root's.
1502	#[test]
1503	fn the_version_is_written_only_when_needed() {
1504		let versions = |catalog: &Catalog| {
1505			let value = serde_json::to_value(catalog).unwrap();
1506			assert_eq!(value.get("version"), None, "the root version is never written");
1507			let mut versions = BTreeMap::new();
1508			for (section, map) in [
1509				("video", "/video/renditions"),
1510				("audio", "/audio/renditions"),
1511				("json", "/json/tracks"),
1512				("include", "/include"),
1513			] {
1514				for (id, entry) in value.pointer(map).and_then(|v| v.as_object()).into_iter().flatten() {
1515					if let Some(version) = entry.get("version") {
1516						versions.insert(format!("{section}.{id}"), version.as_u64().unwrap());
1517					}
1518				}
1519			}
1520			versions
1521		};
1522
1523		let mut catalog = Catalog::<()>::default();
1524		catalog.video.renditions.insert("hd".into(), h264());
1525		let mut audio = AudioConfig::new(Opus, 48_000, 2);
1526		audio.warmup = Some(std::time::Duration::from_millis(80));
1527		catalog.audio.renditions.insert("en".into(), audio);
1528		catalog.include.insert(
1529			"extra".into(),
1530			crate::catalog::Include::new(moq_net::path::Relative::new("../extra").unwrap()),
1531		);
1532		assert_eq!(
1533			versions(&catalog),
1534			BTreeMap::new(),
1535			"an older reader still plays audio warmup"
1536		);
1537
1538		// A `track` naming the ID is what an older reader subscribes to anyway.
1539		catalog.video.renditions.get_mut("hd").unwrap().track = Some("hd".into());
1540		assert_eq!(versions(&catalog), BTreeMap::new());
1541
1542		catalog.video.renditions.get_mut("hd").unwrap().track = Some("video".into());
1543		assert_eq!(versions(&catalog), BTreeMap::from([("video.hd".into(), 4)]));
1544		let json = catalog.to_json().unwrap();
1545		assert!(json.contains(r#""hd":{"version":4,"#), "{json}");
1546		assert_eq!(Catalog::<()>::from_str(&json).unwrap(), catalog);
1547
1548		let mut chat = JsonConfig::new(Mode::Stream);
1549		chat.track = Some("chat.json".into());
1550		catalog.json.insert("chat", chat).unwrap();
1551		assert_eq!(
1552			versions(&catalog),
1553			BTreeMap::from([("video.hd".into(), 4), ("json.chat".into(), 4)])
1554		);
1555	}
1556
1557	/// moq-hang-04 defines `warmup` for audio only, so a video rendition's is an unknown field: read
1558	/// past, never written back, and no reason for a `version`.
1559	#[test]
1560	fn a_video_warmup_is_ignored() {
1561		let json = r#"{"video":{"renditions":{"hd":{"codec":"vp8","container":{"kind":"legacy"},"warmup":500}}}}"#;
1562		let catalog = Catalog::<()>::from_str(json).unwrap();
1563		assert_eq!(catalog.video.renditions["hd"].codec, crate::catalog::VideoCodec::VP8);
1564		assert_eq!(
1565			catalog.to_json().unwrap(),
1566			r#"{"video":{"renditions":{"hd":{"codec":"vp8","container":{"kind":"legacy"}}}}}"#
1567		);
1568	}
1569
1570	/// Versions are computed, never carried: republishing a catalog that claimed more than it
1571	/// uses writes what it actually needs.
1572	#[test]
1573	fn a_republish_recomputes_the_version() {
1574		let json = r#"{"version":4,"video":{"renditions":{"hd":{"version":4,"codec":"avc1.64001f"}}},
1575			"json":{"tracks":{"chat":{"version":4,"mode":"stream"}}}}"#;
1576		let catalog = Catalog::<()>::from_str(json).unwrap();
1577		assert!(
1578			catalog.json.tracks["chat"].extra.is_empty(),
1579			"the entry version is not an extension"
1580		);
1581		assert!(!catalog.to_json().unwrap().contains("version"));
1582	}
1583
1584	/// An entry a newer draft defines is skipped and reported, even one this reader would call
1585	/// malformed, while the rest of the catalog plays.
1586	#[test]
1587	fn a_newer_entry_is_skipped() {
1588		let json = r#"{
1589			"video": {"renditions": {
1590				"compat": {"codec": "avc1.64001f"},
1591				"next": {"version": 5, "codec": 42}
1592			}},
1593			"audio": {"renditions": {"next": {"version": 6}}},
1594			"text": {"renditions": {"next": {"version": 5}}},
1595			"json": {"tracks": {"next": {"version": 5}}},
1596			"binary": {"tracks": {"next": {"version": 5, "mode": []}}},
1597			"include": {"next": {"version": 5, "broadcast": 7}}
1598		}"#;
1599
1600		let check = |catalog: Catalog| {
1601			assert_eq!(catalog.video.renditions.keys().collect::<Vec<_>>(), ["compat"]);
1602			assert!(catalog.audio.is_empty() && catalog.text.is_empty() && catalog.include.is_empty());
1603			assert!(catalog.json.is_empty() && catalog.binary.is_empty());
1604
1605			let next = |version| BTreeMap::from([("next".to_string(), version)]);
1606			assert_eq!(catalog.skipped.video, next(5));
1607			assert_eq!(catalog.skipped.audio, next(6));
1608			assert_eq!(catalog.skipped.text, next(5));
1609			assert_eq!(catalog.skipped.json, next(5));
1610			assert_eq!(catalog.skipped.binary, next(5));
1611			assert_eq!(catalog.skipped.include, next(5));
1612			assert_eq!(catalog.skipped.version(), Some(6));
1613
1614			// Never written, so a republish lists only what this reader read.
1615			let republished = Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap();
1616			assert!(republished.skipped.is_empty());
1617			assert_eq!(republished.skipped.version(), None);
1618		};
1619		check(Catalog::from_str(json).unwrap());
1620		check(serde_json::from_str(json).unwrap());
1621
1622		// The root version still refuses the whole catalog.
1623		let root = json.replacen('{', r#"{"version":5,"#, 1);
1624		assert!(matches!(
1625			Catalog::<()>::from_str(&root),
1626			Err(crate::Error::UnsupportedVersion(5))
1627		));
1628
1629		// Even when the newer draft reshaped an entry's own `version`, wherever the root's sits.
1630		for entry in [r#"{"version":"new-shape"}"#, r#"{"version":5,"version":3}"#] {
1631			for json in [
1632				format!(r#"{{"version":5,"video":{{"renditions":{{"hd":{entry}}}}}}}"#),
1633				format!(r#"{{"video":{{"renditions":{{"hd":{entry}}}}},"version":5}}"#),
1634			] {
1635				assert!(
1636					matches!(Catalog::<()>::from_str(&json), Err(crate::Error::UnsupportedVersion(5))),
1637					"{json}"
1638				);
1639			}
1640		}
1641	}
1642
1643	/// An entry readable by this draft is read whatever version it claims.
1644	#[test]
1645	fn a_supported_entry_version_is_read() {
1646		for version in [0, 3, 4] {
1647			let json =
1648				format!(r#"{{"video":{{"renditions":{{"hd":{{"version":{version},"codec":"avc1.64001f"}}}}}}}}"#);
1649			let catalog = Catalog::<()>::from_str(&json).unwrap();
1650			assert!(catalog.video.renditions.contains_key("hd"), "{json}");
1651			assert!(catalog.skipped.is_empty(), "{json}");
1652		}
1653	}
1654
1655	/// An entry's version is refused, with the catalog, when malformed or repeated, as the root's is:
1656	/// otherwise a newer entry could slip past the check by also claiming an old version.
1657	#[test]
1658	fn a_malformed_entry_version_is_refused() {
1659		for version in [r#""5""#, "-1", "4.5", "null", "[]"] {
1660			let json = format!(r#"{{"json":{{"tracks":{{"chat":{{"version":{version},"mode":"stream"}}}}}}}}"#);
1661			assert!(Catalog::<()>::from_str(&json).is_err(), "{json}");
1662			assert!(serde_json::from_str::<Catalog>(&json).is_err(), "{json}");
1663		}
1664
1665		for versions in [r#""version":5,"version":3"#, r#""version":3,"version":3"#] {
1666			let json = format!(r#"{{"video":{{"renditions":{{"hd":{{{versions},"codec":"avc1.64001f"}}}}}}}}"#);
1667			let err = Catalog::<()>::from_str(&json).unwrap_err();
1668			assert!(err.to_string().contains("duplicate field `version`"), "{json}: {err}");
1669			assert!(Catalog::<()>::from_reader(json.as_bytes()).is_err(), "{json}");
1670		}
1671	}
1672
1673	/// A data track extension member named `version` would sit beside the computed one.
1674	#[test]
1675	fn an_entry_extension_version_is_refused() {
1676		let mut catalog = Catalog::<()>::default();
1677		let mut chat = JsonConfig::new(Mode::Stream);
1678		chat.extra.insert("version".into(), 3.into());
1679		catalog.json.insert("chat", chat).unwrap();
1680		let err = catalog.to_json().unwrap_err();
1681		assert!(err.to_string().contains("must not carry a member `version`"), "{err}");
1682	}
1683
1684	/// `without_ext` clears only the extension: every other field, including those a decoder fills,
1685	/// survives the copy.
1686	#[test]
1687	fn without_ext_keeps_every_other_field() {
1688		let mut catalog = Catalog::<serde_json::Map<String, serde_json::Value>> {
1689			echo: Some(crate::catalog::Echo::new(moq_net::path::Relative::new("echo").unwrap())),
1690			stats: Some(crate::catalog::Stats::new("stats")),
1691			..Default::default()
1692		};
1693		catalog.ext.insert("app".into(), 1.into());
1694		catalog.video.renditions.insert(
1695			"video".into(),
1696			VideoConfig::new(H264 {
1697				profile: 0x64,
1698				constraints: 0,
1699				level: 0x28,
1700				inline: false,
1701			}),
1702		);
1703		catalog
1704			.audio
1705			.renditions
1706			.insert("audio".into(), AudioConfig::new(Opus, 48_000, 2));
1707		catalog.sync.interval = Some(std::time::Duration::from_secs(2));
1708		catalog.json.insert("chat", JsonConfig::new(Mode::Stream)).unwrap();
1709		catalog
1710			.binary
1711			.insert("blob", BinaryConfig::new(Mode::Snapshot))
1712			.unwrap();
1713		catalog.include.insert(
1714			"other".into(),
1715			crate::catalog::Include::new(moq_net::path::Relative::new("other").unwrap()),
1716		);
1717		catalog.skipped.video.insert("future".into(), 9);
1718
1719		let stripped = catalog.without_ext();
1720		let expected = Catalog::<()> {
1721			video: catalog.video.clone(),
1722			audio: catalog.audio.clone(),
1723			sync: catalog.sync,
1724			text: catalog.text.clone(),
1725			json: catalog.json.clone(),
1726			binary: catalog.binary.clone(),
1727			stats: catalog.stats.clone(),
1728			echo: catalog.echo.clone(),
1729			include: catalog.include.clone(),
1730			ext: (),
1731			skipped: catalog.skipped.clone(),
1732		};
1733		assert_eq!(stripped, expected);
1734		assert!(!stripped.json.tracks.is_empty() && !stripped.skipped.video.is_empty());
1735		assert!(stripped.stats.is_some() && stripped.echo.is_some() && !stripped.include.is_empty());
1736	}
1737}