Skip to main content

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