Skip to main content

hang/catalog/
json.rs

1use std::collections::{BTreeMap, btree_map};
2
3use serde::{Deserialize, Serialize};
4
5use crate::catalog::Mode;
6use crate::catalog::millis::MillisCeil;
7
8/// The JSON tracks a broadcast publishes, keyed by track name.
9///
10/// These are application data tracks, not media: a chat log, a telemetry feed, a status document.
11/// Each entry says how to read the track (its [`mode`](JsonConfig::mode)) without a consumer having to
12/// know the application.
13///
14/// Marked `#[non_exhaustive]` so additional optional fields can be added without bumping the major
15/// version. External callers start from [`Json::default`] and fill in what they need
16/// ([`insert`](Self::insert)); struct-literal construction is not available outside this crate.
17#[serde_with::skip_serializing_none]
18#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
19#[serde(rename_all = "camelCase")]
20#[non_exhaustive]
21pub struct Json {
22	/// A map of track name to configuration.
23	///
24	/// A map rather than an array so it works with JSON Merge Patch, and a `BTreeMap` so keys are
25	/// sorted for *some* deterministic behavior.
26	#[serde(
27		deserialize_with = "crate::catalog::deserialize_entries",
28		serialize_with = "crate::catalog::serialize_entries"
29	)]
30	pub tracks: BTreeMap<String, JsonConfig>,
31}
32
33impl crate::catalog::Entry for JsonConfig {
34	fn version(&self, id: &str) -> Option<u64> {
35		crate::catalog::renamed_version(self, id)
36	}
37
38	fn claims_version(&self) -> bool {
39		self.extra.contains_key("version")
40	}
41}
42
43impl Json {
44	/// Insert a track config, returning an error if the name already exists.
45	pub fn insert(&mut self, name: &str, config: JsonConfig) -> crate::Result<()> {
46		let btree_map::Entry::Vacant(entry) = self.tracks.entry(name.to_string()) else {
47			return Err(crate::Error::Duplicate(name.to_string()));
48		};
49		entry.insert(config);
50		Ok(())
51	}
52
53	/// Remove the track from the catalog and return its configuration if found.
54	pub fn remove(&mut self, name: &str) -> Option<JsonConfig> {
55		self.tracks.remove(name)
56	}
57
58	/// Whether there are no JSON tracks, in which case the section is left off the wire.
59	pub fn is_empty(&self) -> bool {
60		self.tracks.is_empty()
61	}
62}
63
64/// How to read one JSON track.
65///
66/// Each frame is a UTF-8 JSON value; [`mode`](Self::mode) says how the track's groups compose
67/// those frames into the value a consumer sees.
68///
69/// Marked `#[non_exhaustive]` so additional optional fields can be added without bumping the major
70/// version. External callers build one with [`JsonConfig::new`] and assign the optional fields they
71/// need; struct-literal construction is not available outside this crate.
72#[serde_with::serde_as]
73#[serde_with::skip_serializing_none]
74#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
75#[serde(rename_all = "camelCase")]
76#[non_exhaustive]
77pub struct JsonConfig {
78	/// Optional reference to another broadcast that publishes this track, expressed relative to the
79	/// broadcast that served this catalog (e.g. `./source`). If unset, the track lives in the same
80	/// broadcast as the catalog.
81	#[serde(default)]
82	#[serde_as(as = "crate::catalog::NotNull")]
83	pub broadcast: Option<moq_net::path::Relative>,
84
85	/// The track's name in its broadcast, when it differs from this entry's ID: its key in the
86	/// catalog. Absent means the ID is the track name, as in every catalog before this field.
87	///
88	/// Set it only when the ID can't be the name, such as two renditions of same-named tracks
89	/// from different broadcasts. Readers resolve the name with
90	/// [`Reference::track`](crate::catalog::Reference::track); one that predates the
91	/// field subscribes to the ID instead.
92	#[serde(default)]
93	#[serde_as(as = "crate::catalog::NotNull")]
94	pub track: Option<String>,
95
96	/// Whether the track is a latest-value document or an append log. Always stated: see [`Mode`].
97	#[serde_as(as = "serde_with::DisplayFromStr")]
98	pub mode: Mode,
99
100	/// An optional identifier for the shape of each value, typically a JSON Schema URL. Purely
101	/// descriptive: a consumer that doesn't recognize it can still read the track.
102	#[serde(default)]
103	#[serde_as(as = "crate::catalog::NotNull")]
104	pub schema: Option<String>,
105
106	/// The maximum bitrate of the track in bits per second, if known, at most 2^53 - 1.
107	#[serde(default)]
108	#[serde_as(as = "crate::catalog::NotNull<crate::snapshot::Number>")]
109	pub bitrate: Option<u64>,
110
111	/// The largest media span the publisher hands to the transport behind a payload's timestamp,
112	/// with the same meaning and whole-millisecond encoding as
113	/// [`VideoConfig::jitter`](crate::catalog::VideoConfig::jitter).
114	#[serde_as(as = "MillisCeil")]
115	#[serde(default)]
116	pub jitter: Option<std::time::Duration>,
117
118	/// How far this track's payloads persistently trail what the broadcast's other tracks already
119	/// wrote, with the same meaning and encoding as
120	/// [`VideoConfig::delay`](crate::catalog::VideoConfig::delay). Only measured for payloads that
121	/// carry a capture time.
122	#[serde_as(as = "MillisCeil")]
123	#[serde(default, skip_serializing_if = "crate::catalog::millis::no_delay")]
124	pub delay: Option<std::time::Duration>,
125
126	/// Fields this build doesn't recognize, kept so the entry round-trips. Never `version`, which
127	/// is computed when the entry is written.
128	///
129	/// A future [`Mode`] almost certainly comes with fields describing it, and
130	/// preserving the discriminant without them would leave a relay republishing an entry nothing
131	/// can act on. Same reason [`Container`](crate::catalog::Container) keeps an unknown container
132	/// verbatim.
133	#[serde(flatten)]
134	pub extra: serde_json::Map<String, serde_json::Value>,
135}
136
137impl JsonConfig {
138	/// A config for a track read in `mode`, with no optional fields set.
139	pub fn new(mode: Mode) -> Self {
140		Self {
141			broadcast: None,
142			track: None,
143			mode,
144			schema: None,
145			bitrate: None,
146			jitter: None,
147			delay: None,
148			extra: Default::default(),
149		}
150	}
151}
152
153/// The config itself, so a data producer takes it wherever it takes an entry embedding one.
154impl AsMut<JsonConfig> for JsonConfig {
155	fn as_mut(&mut self) -> &mut Self {
156		self
157	}
158}