Skip to main content

hang/catalog/
container.rs

1use bytes::Bytes;
2use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
3use serde_with::{base64::Base64, serde_as};
4
5/// Container format for frame timestamp encoding and frame payload structure.
6///
7/// JSON examples:
8/// ```json
9/// { "kind": "cmaf", "init": "<base64-encoded ftyp+moov>" }
10/// { "kind": "loc" }
11/// ```
12///
13/// An unrecognized `kind` decodes to [`Container::Unknown`] instead of failing, so one
14/// rendition using a future container does not take down the rest of the catalog. Such a
15/// rendition must be ignored by consumers. A `kind` that is absent or not a string is malformed.
16#[derive(Debug, Clone, PartialEq, Default)]
17pub enum Container {
18	/// A QUIC varint timestamp prefix followed by the raw codec payload.
19	/// Timestamps are in microseconds.
20	#[default]
21	Legacy,
22
23	/// Fragmented MP4: each frame is a complete moof+mdat fragment.
24	Cmaf {
25		/// CMAF init segment (ftyp+moov). Encoded as base64 over the wire.
26		init: Bytes,
27	},
28
29	/// Low Overhead Container (draft-ietf-moq-loc): each frame is a small
30	/// property block followed by the codec payload.
31	Loc,
32
33	/// No container header: each frame is the raw codec payload and its presentation
34	/// timestamp is the MoQ transport timestamp (DTS == PTS). Requires a timed track.
35	Raw,
36
37	/// A QUIC varint composition time offset (CTS, in the track's timescale) followed
38	/// by the raw codec payload; PTS is transport timestamp + CTS. Requires a timed track.
39	Cts,
40
41	/// A container this build does not recognize, preserved verbatim.
42	Unknown(UnknownContainer),
43}
44
45/// The raw JSON of a container whose `kind` is not recognized.
46///
47/// Kept intact so a relay or transcoder that reparses and republishes a catalog round-trips
48/// the rendition byte-for-byte rather than corrupting it.
49#[derive(Debug, Clone, PartialEq)]
50pub struct UnknownContainer(serde_json::Map<String, serde_json::Value>);
51
52impl UnknownContainer {
53	/// The `kind` as it appeared on the wire.
54	pub fn kind(&self) -> &str {
55		// Deserialize refuses a container without a string kind, so this is never empty.
56		self.0
57			.get("kind")
58			.and_then(serde_json::Value::as_str)
59			.unwrap_or_default()
60	}
61
62	/// The full JSON object, including `kind`.
63	pub fn fields(&self) -> &serde_json::Map<String, serde_json::Value> {
64		&self.0
65	}
66}
67
68/// The containers this build knows how to encode and decode.
69///
70/// Split out so the tagged representation stays derived while [`Container`] keeps a catch-all.
71#[serde_as]
72#[derive(Serialize, Deserialize)]
73#[serde(rename_all = "camelCase")]
74#[serde(tag = "kind")]
75enum Known {
76	#[serde(rename = "legacy")]
77	Legacy,
78	Cmaf {
79		#[serde_as(as = "Base64")]
80		init: Bytes,
81	},
82	Loc,
83	Raw,
84	Cts,
85}
86
87impl Serialize for Container {
88	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
89		let known = match self {
90			Self::Legacy => Known::Legacy,
91			// Bytes is refcounted, so this clone is cheap.
92			Self::Cmaf { init } => Known::Cmaf { init: init.clone() },
93			Self::Loc => Known::Loc,
94			Self::Raw => Known::Raw,
95			Self::Cts => Known::Cts,
96			Self::Unknown(unknown) => return unknown.0.serialize(serializer),
97		};
98
99		known.serialize(serializer)
100	}
101}
102
103impl<'de> Deserialize<'de> for Container {
104	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
105		let object = serde_json::Map::deserialize(deserializer)?;
106
107		// Only route to the derived enum for kinds we know, so a malformed known container is
108		// still a hard error instead of silently becoming Unknown.
109		match object.get("kind").and_then(serde_json::Value::as_str) {
110			Some("legacy" | "cmaf" | "loc" | "raw" | "cts") => {
111				let known = Known::deserialize(serde_json::Value::Object(object)).map_err(de::Error::custom)?;
112				Ok(match known {
113					Known::Legacy => Self::Legacy,
114					Known::Cmaf { init } => Self::Cmaf { init },
115					Known::Loc => Self::Loc,
116					Known::Raw => Self::Raw,
117					Known::Cts => Self::Cts,
118				})
119			}
120			Some(_) => Ok(Self::Unknown(UnknownContainer(object))),
121			None => Err(de::Error::custom("container `kind` must be a string")),
122		}
123	}
124}
125
126#[cfg(test)]
127mod tests {
128	use super::*;
129
130	#[test]
131	fn legacy_roundtrip() {
132		let parsed: Container = serde_json::from_str(r#"{"kind":"legacy"}"#).unwrap();
133		assert_eq!(parsed, Container::Legacy);
134		assert_eq!(serde_json::to_string(&parsed).unwrap(), r#"{"kind":"legacy"}"#);
135	}
136
137	#[test]
138	fn cmaf_roundtrip() {
139		let parsed: Container = serde_json::from_str(r#"{"kind":"cmaf","init":"AAEC"}"#).unwrap();
140		assert_eq!(
141			parsed,
142			Container::Cmaf {
143				init: Bytes::from_static(&[0, 1, 2])
144			}
145		);
146		assert_eq!(
147			serde_json::to_string(&parsed).unwrap(),
148			r#"{"kind":"cmaf","init":"AAEC"}"#
149		);
150	}
151
152	#[test]
153	fn loc_roundtrip() {
154		let parsed: Container = serde_json::from_str(r#"{"kind":"loc"}"#).unwrap();
155		assert_eq!(parsed, Container::Loc);
156		assert_eq!(serde_json::to_string(&parsed).unwrap(), r#"{"kind":"loc"}"#);
157	}
158
159	#[test]
160	fn raw_and_cts_roundtrip() {
161		let raw: Container = serde_json::from_str(r#"{"kind":"raw"}"#).unwrap();
162		assert_eq!(raw, Container::Raw);
163		assert_eq!(serde_json::to_string(&raw).unwrap(), r#"{"kind":"raw"}"#);
164
165		let cts: Container = serde_json::from_str(r#"{"kind":"cts"}"#).unwrap();
166		assert_eq!(cts, Container::Cts);
167		assert_eq!(serde_json::to_string(&cts).unwrap(), r#"{"kind":"cts"}"#);
168	}
169
170	#[test]
171	fn unknown_roundtrip() {
172		// Keys are sorted because serde_json::Map is a BTreeMap by default.
173		let json = r#"{"extra":{"nested":[1,2]},"flag":true,"kind":"future"}"#;
174		let parsed: Container = serde_json::from_str(json).unwrap();
175
176		let Container::Unknown(unknown) = &parsed else {
177			panic!("expected unknown: {parsed:?}");
178		};
179		assert_eq!(unknown.kind(), "future");
180		assert_eq!(unknown.fields().len(), 3);
181
182		assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
183	}
184
185	#[test]
186	fn malformed_known_kind_errors() {
187		// cmaf without init is not a valid cmaf container and must not degrade to Unknown.
188		serde_json::from_str::<Container>(r#"{"kind":"cmaf"}"#).unwrap_err();
189	}
190
191	#[test]
192	fn kindless_container_errors() {
193		for json in [r#"{}"#, r#"{"kind":5}"#, r#"{"kind":null}"#] {
194			serde_json::from_str::<Container>(json).unwrap_err();
195		}
196	}
197}