hang/catalog/text/mod.rs
1mod format;
2
3pub use format::*;
4
5use std::collections::{BTreeMap, btree_map};
6
7use serde::{Deserialize, Serialize};
8use serde_with::DisplayFromStr;
9
10use crate::catalog::millis::MillisCeil;
11
12use crate::catalog::Container;
13
14/// Information about the text (caption/subtitle) tracks in the catalog.
15///
16/// This struct contains a map of renditions, typically one per language.
17///
18/// Marked `#[non_exhaustive]` so additional optional fields can be added without
19/// bumping the major version. External callers start from [`Text::default`] and
20/// fill in what they need ([`insert`](Self::insert) for renditions); struct-literal
21/// construction (with or without `..base`) is not available outside this crate.
22#[serde_with::serde_as]
23#[serde_with::skip_serializing_none]
24#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
25#[serde(rename_all = "camelCase")]
26#[non_exhaustive]
27pub struct Text {
28 /// A map of track name to rendition configuration.
29 /// This is not an array so it will work with JSON Merge Patch.
30 /// We use a BTreeMap so keys are sorted alphabetically for *some* deterministic behavior.
31 #[serde(
32 deserialize_with = "crate::catalog::deserialize_entries",
33 serialize_with = "crate::catalog::serialize_entries"
34 )]
35 pub renditions: BTreeMap<String, TextConfig>,
36}
37
38impl crate::catalog::Entry for TextConfig {
39 fn version(&self, id: &str) -> Option<u64> {
40 crate::catalog::renamed_version(self, id)
41 }
42}
43
44impl Text {
45 /// Insert a track config, returning an error if the name already exists.
46 pub fn insert(&mut self, name: &str, config: TextConfig) -> crate::Result<()> {
47 let btree_map::Entry::Vacant(entry) = self.renditions.entry(name.to_string()) else {
48 return Err(crate::Error::Duplicate(name.to_string()));
49 };
50 entry.insert(config);
51 Ok(())
52 }
53
54 /// Remove the track from the catalog and return the configuration if found.
55 pub fn remove(&mut self, name: &str) -> Option<TextConfig> {
56 self.renditions.remove(name)
57 }
58
59 /// True when there are no renditions, so the section can be omitted from the catalog.
60 pub fn is_empty(&self) -> bool {
61 self.renditions.is_empty()
62 }
63}
64
65/// Timed-text (caption/subtitle) track configuration.
66///
67/// Unlike audio and video there is no WebCodecs decoder for text: a consumer parses the cue
68/// payload directly (see [`TextFormat`]) and renders it as an overlay. Each frame is one cue (or a
69/// self-contained segment of cues), and the frame timestamp is the cue's start time on the shared
70/// media clock.
71///
72/// Marked `#[non_exhaustive]` so additional optional fields can be added without bumping the major
73/// version. External callers build a config with [`TextConfig::new`] and then assign whichever
74/// optional fields they need; struct-literal construction (with or without `..base`) is not
75/// available outside this crate.
76#[serde_with::serde_as]
77#[serde_with::skip_serializing_none]
78#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
79#[serde(rename_all = "camelCase")]
80#[non_exhaustive]
81pub struct TextConfig {
82 /// Optional reference to another broadcast that publishes this track, expressed relative to the
83 /// broadcast that served this catalog (e.g. `../source`). If unset, the track lives in the same
84 /// broadcast as the catalog.
85 #[serde(default)]
86 #[serde_as(as = "crate::catalog::NotNull")]
87 pub broadcast: Option<moq_net::path::Relative>,
88
89 /// The track's name in its broadcast, when it differs from this entry's ID: its key in the
90 /// catalog. Absent means the ID is the track name, as in every catalog before this field.
91 ///
92 /// Set it only when the ID can't be the name, such as two renditions of same-named tracks
93 /// from different broadcasts. Readers resolve the name with
94 /// [`Reference::track`](crate::catalog::Reference::track); one that predates the
95 /// field subscribes to the ID instead.
96 #[serde(default)]
97 #[serde_as(as = "crate::catalog::NotNull")]
98 pub track: Option<String>,
99
100 /// The serialization format of each cue payload.
101 #[serde_as(as = "DisplayFromStr")]
102 pub format: TextFormat,
103
104 /// The accessibility role of the track. Defaults to [`TextRole::Subtitle`].
105 #[serde_as(as = "DisplayFromStr")]
106 #[serde(default)]
107 pub role: TextRole,
108
109 /// The BCP-47 language tag of the track (e.g. `en`, `es-419`), if known.
110 #[serde_as(as = "crate::catalog::NotNull")]
111 #[serde(default)]
112 pub lang: Option<String>,
113
114 /// A human-readable label for a track picker, when `lang` alone is ambiguous (e.g. distinguishing
115 /// "English" from "English (SDH)").
116 #[serde_as(as = "crate::catalog::NotNull")]
117 #[serde(default)]
118 pub label: Option<String>,
119
120 /// Container format for frame encoding. Defaults to "legacy" (a microsecond timestamp prefix
121 /// followed by the cue payload).
122 #[serde(default)]
123 pub container: Container,
124
125 /// The largest media span the publisher hands to the transport behind a cue's timestamp, with
126 /// the same meaning and whole-millisecond encoding as
127 /// [`VideoConfig::jitter`](crate::catalog::VideoConfig::jitter). A cue written in timestamp
128 /// order adds nothing.
129 #[serde_as(as = "MillisCeil")]
130 #[serde(default)]
131 pub jitter: Option<std::time::Duration>,
132
133 /// How far this rendition's frames reach the transport behind the broadcast's other
134 /// renditions: a constant offset, either supplied by the publisher or measured as the least
135 /// its frames trailed the others' over a window of a second of media, keeping the largest
136 /// window. Lateness only some frames have, such as B-frame reorder, is left out, since a
137 /// consumer measures it. Absent on a rendition that trails nothing, and on any rendition the
138 /// publisher neither supplied nor measured.
139 ///
140 /// A consumer adds a frame duration on top, so a publisher that knows its frames trail by no
141 /// more than their own duration, such as an encoder configured not to reorder or queue, states
142 /// `Some(Duration::ZERO)`. It is never measured, and is omitted on the
143 /// wire like an absent value, which means the same to a consumer. `None` leaves it to
144 /// measurement.
145 ///
146 /// A consumer holds `delay + jitter` for this rendition and MUST NOT subtract one rendition's
147 /// `delay` from another's: each is taken against whichever rendition was ahead, so two need not
148 /// share an origin. It only ever grows over the life of a stream, and is serialized like
149 /// [`jitter`](Self::jitter).
150 #[serde_as(as = "MillisCeil")]
151 #[serde(default, skip_serializing_if = "crate::catalog::millis::no_delay")]
152 pub delay: Option<std::time::Duration>,
153}
154
155impl TextConfig {
156 /// Construct a config with the required format set and every optional field cleared. `role`
157 /// defaults to [`TextRole::Subtitle`] and `container` to [`Container::default`]. Fields are
158 /// `pub`, so callers set whatever they need by assignment afterwards.
159 ///
160 /// This is the only path external crates have to build a `TextConfig` since the type is
161 /// `#[non_exhaustive]`.
162 pub fn new(format: TextFormat) -> Self {
163 Self {
164 broadcast: None,
165 track: None,
166 format,
167 role: TextRole::default(),
168 lang: None,
169 label: None,
170 container: Container::default(),
171 jitter: None,
172 delay: None,
173 }
174 }
175}
176
177#[cfg(test)]
178mod test {
179 use super::*;
180
181 #[test]
182 fn roundtrip() {
183 let mut encoded = r#"{
184 "renditions": {
185 "captions.en": {
186 "format": "vtt",
187 "role": "caption",
188 "lang": "en",
189 "label": "SDH",
190 "container": {"kind": "legacy"}
191 }
192 }
193 }"#
194 .to_string();
195 encoded.retain(|c| !c.is_whitespace());
196
197 let mut config = TextConfig::new(TextFormat::Vtt);
198 config.role = TextRole::Caption;
199 config.lang = Some("en".to_string());
200 config.label = Some("SDH".to_string());
201 config.container = Container::Legacy;
202
203 let mut text = Text::default();
204 text.insert("captions.en", config).unwrap();
205
206 let decoded: Text = serde_json::from_str(&encoded).expect("failed to decode");
207 assert_eq!(decoded, text, "wrong decoded output");
208
209 let output = serde_json::to_string(&text).expect("failed to encode");
210 assert_eq!(encoded, output, "wrong encoded output");
211 }
212
213 #[test]
214 fn optionals_omitted() {
215 // A minimal config omits the optional lang/label/broadcast so the wire stays small, while
216 // role (like container) always serializes and round-trips.
217 let mut text = Text::default();
218 text.insert("subs", TextConfig::new(TextFormat::Vtt)).unwrap();
219
220 let output = serde_json::to_string(&text).unwrap();
221 assert!(!output.contains("lang"), "empty lang leaked: {output}");
222 assert!(!output.contains("label"), "empty label leaked: {output}");
223 assert!(!output.contains("broadcast"), "empty broadcast leaked: {output}");
224
225 let decoded: Text = serde_json::from_str(&output).unwrap();
226 assert_eq!(decoded.renditions["subs"].role, TextRole::Subtitle);
227 }
228
229 #[test]
230 fn unknown_role_preserved() {
231 // A role from a newer publisher must not fail the decode: the MSF registry can grow, and
232 // rejecting the value would take the whole catalog (audio and video included) down with it.
233 let encoded = r#"{"renditions":{"subs":{"format":"vtt","role":"commentary","container":{"kind":"legacy"}}}}"#;
234
235 let decoded: Text = serde_json::from_str(encoded).expect("failed to decode");
236 assert_eq!(
237 decoded.renditions["subs"].role,
238 TextRole::Unknown("commentary".to_string())
239 );
240
241 // And it survives a republish verbatim, so a relaying consumer doesn't erase it.
242 let output = serde_json::to_string(&decoded).expect("failed to encode");
243 assert_eq!(encoded, output, "unknown role not preserved");
244 }
245}