Skip to main content

moq_mux/catalog/
tracks.rs

1use std::marker::PhantomData;
2use std::time::Duration;
3
4use super::Estimate;
5use super::Producer;
6use super::hang::{Catalog, CatalogExt};
7
8/// A catalog config that can be published as a named rendition.
9///
10/// Implement it on your own config type to get the full catalog lifecycle: reservation gating,
11/// removal on drop, and optional jitter/bitrate detection. [`VideoConfig`](hang::catalog::VideoConfig)
12/// and [`AudioConfig`](hang::catalog::AudioConfig) implement it for every extension; a custom
13/// config implements it for the one [`CatalogExt`] that holds it. Publish a media track under it
14/// with [`Reserved::track`], or a data track with [`Producer::json_stream`] and the like when it
15/// embeds a data config (see [`IntoRendition`](super::IntoRendition)):
16///
17/// ```
18/// # use std::collections::BTreeMap;
19/// # use hang::catalog::{JsonConfig, Mode};
20/// # use moq_mux::catalog::{Estimate, RenditionConfig};
21/// # use moq_mux::catalog::hang::{Catalog, CatalogExt};
22/// # use serde::{Deserialize, Serialize};
23/// #[derive(Serialize, Deserialize, Clone, Default)]
24/// struct Ext {
25///     #[serde(rename = "com.example.mavlink", default)]
26///     mavlink: BTreeMap<String, Mavlink>,
27/// }
28/// impl CatalogExt for Ext {}
29///
30/// #[derive(Serialize, Deserialize, Clone)]
31/// struct Mavlink {
32///     config: JsonConfig,
33///     sysid: u8,
34/// }
35///
36/// impl AsMut<JsonConfig> for Mavlink {
37///     fn as_mut(&mut self) -> &mut JsonConfig {
38///         &mut self.config
39///     }
40/// }
41///
42/// impl RenditionConfig<Ext> for Mavlink {
43///     fn insert(self, catalog: &mut Catalog<Ext>, name: &str) {
44///         catalog.ext.mavlink.insert(name.to_string(), self);
45///     }
46///     fn get_mut<'a>(catalog: &'a mut Catalog<Ext>, name: &str) -> Option<&'a mut Self> {
47///         catalog.ext.mavlink.get_mut(name)
48///     }
49///     fn remove(catalog: &mut Catalog<Ext>, name: &str) {
50///         catalog.ext.mavlink.remove(name);
51///     }
52///
53///     // Opt into detection through the embedded config.
54///     fn detects() -> bool {
55///         true
56///     }
57///     fn estimate(&self) -> Estimate {
58///         Estimate::default()
59///             .with_bitrate(self.config.bitrate)
60///             .with_jitter(self.config.jitter)
61///             .with_delay(self.config.delay)
62///     }
63///     fn set_estimate(&mut self, estimate: Estimate) {
64///         self.config.bitrate = estimate.bitrate;
65///         self.config.jitter = estimate.jitter;
66///         self.config.delay = estimate.delay;
67///     }
68/// }
69///
70/// # fn example(
71/// #     broadcast: &mut moq_net::broadcast::Producer,
72/// #     catalog: &moq_mux::catalog::Producer<Ext>,
73/// # ) -> moq_mux::Result<()> {
74/// let info = moq_net::track::Info::default()
75///     .with_timescale(moq_net::Timescale::MILLI)
76///     .with_compression(moq_net::track::Compression::Deflate);
77/// let track = broadcast.create_track("telemetry", info).ok_or(moq_net::Error::Duplicate)?;
78/// // The producer fixes the mode, so the one passed here is only a placeholder.
79/// let entry = Mavlink { config: JsonConfig::new(Mode::Stream), sysid: 1 };
80/// let mut telemetry = catalog.json_stream::<serde_json::Value>(track, entry)?;
81/// telemetry.append(&serde_json::json!({ "heartbeat": 1 }), catalog.clock().now())?;
82/// # Ok(())
83/// # }
84/// ```
85///
86/// Note that `insert` takes the whole [`Catalog`], not just the extension, so the built-in media
87/// configs use the same trait. Writing to `catalog.video` / `catalog.audio` / `catalog.text` from a
88/// custom config fights the media pipeline for those sections; stay in your own.
89///
90/// [`Reserved::track`] and [`Producer::track`](super::Producer::track) enroll the track in the
91/// broadcast timeline, measure it, and keep its estimate current automatically.
92pub trait RenditionConfig<E: CatalogExt>: Clone + Send + 'static {
93	/// Whether container or data-track writes should update this config's estimate fields.
94	fn detects() -> bool {
95		false
96	}
97
98	/// Insert or replace this config under `name`.
99	fn insert(self, catalog: &mut Catalog<E>, name: &str);
100
101	/// Borrow the config stored under `name`, if it's present.
102	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self>;
103
104	/// Remove the config stored under `name`.
105	fn remove(catalog: &mut Catalog<E>, name: &str);
106
107	/// The config's current [`Estimate`] fields. Defaults to none, disabling detection.
108	fn estimate(&self) -> Estimate {
109		Estimate::default()
110	}
111
112	/// Replace the config's [`Estimate`] fields. Defaults to discarding them.
113	fn set_estimate(&mut self, _estimate: Estimate) {}
114}
115
116impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::JsonConfig {
117	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
118		catalog.json.tracks.insert(name.to_string(), self);
119	}
120	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
121		catalog.json.tracks.get_mut(name)
122	}
123	fn remove(catalog: &mut Catalog<E>, name: &str) {
124		catalog.json.tracks.remove(name);
125	}
126
127	fn detects() -> bool {
128		true
129	}
130	fn estimate(&self) -> Estimate {
131		Estimate::default()
132			.with_jitter(self.jitter)
133			.with_bitrate(self.bitrate)
134			.with_delay(self.delay)
135	}
136	fn set_estimate(&mut self, estimate: Estimate) {
137		self.jitter = estimate.jitter;
138		self.bitrate = estimate.bitrate;
139		self.delay = estimate.delay;
140	}
141}
142
143impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::BinaryConfig {
144	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
145		catalog.binary.tracks.insert(name.to_string(), self);
146	}
147	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
148		catalog.binary.tracks.get_mut(name)
149	}
150	fn remove(catalog: &mut Catalog<E>, name: &str) {
151		catalog.binary.tracks.remove(name);
152	}
153
154	fn detects() -> bool {
155		true
156	}
157	fn estimate(&self) -> Estimate {
158		Estimate::default()
159			.with_jitter(self.jitter)
160			.with_bitrate(self.bitrate)
161			.with_delay(self.delay)
162	}
163	fn set_estimate(&mut self, estimate: Estimate) {
164		self.jitter = estimate.jitter;
165		self.bitrate = estimate.bitrate;
166		self.delay = estimate.delay;
167	}
168}
169
170/// Caller-provided catalog fields for a video track: a starting point for what the importer detects.
171///
172/// Every field is optional and fills only a gap the stream leaves; a value the stream reveals (the
173/// dimensions from an SPS, ...) always wins, so a detected change just updates the catalog. A
174/// [`codec`](Self::codec) alone is enough to publish the catalog before the first keyframe (the
175/// decoder config then arrives in band). Use it for fields the stream can't reveal (bitrate) or to
176/// skip that wait. The MSF catalog declares only hinted estimates (`bitrate`, `framerate`, `jitter`,
177/// `delay`), never measured ones, so an MSF track carries only those set here.
178///
179/// Video importers take one because they build the [`VideoConfig`](hang::catalog::VideoConfig)
180/// themselves, out of the bitstream, so the caller never holds the config to set these on. An audio
181/// importer publishes a complete config from its init bytes, so the field those bytes can't carry
182/// (bitrate) rides on [`AudioInit`](crate::import::AudioInit) instead.
183#[derive(Clone, Default, Debug, PartialEq)]
184#[non_exhaustive]
185pub struct VideoHint {
186	/// Human-readable rendition name, plumbed through from [`Init::label`](crate::import::Init::label).
187	///
188	/// Not a hint: every other field here seeds something the stream may also reveal, while a label
189	/// can only ever come from the caller. It rides along so one `apply` writes the whole config.
190	pub(crate) label: Option<String>,
191	/// The video codec.
192	pub codec: Option<hang::catalog::VideoCodec>,
193	/// The encoded width in pixels.
194	pub coded_width: Option<u32>,
195	/// The encoded height in pixels.
196	pub coded_height: Option<u32>,
197	/// The width of the aspect ratio the whole picture is displayed at, not the sample aspect.
198	pub display_aspect_width: Option<u32>,
199	/// The height of the aspect ratio the whole picture is displayed at.
200	pub display_aspect_height: Option<u32>,
201	/// The colour the pixels carry. Each field the stream signals outranks the hint's.
202	pub color: Option<hang::catalog::Color>,
203	/// The maximum bitrate in bits per second.
204	pub bitrate: Option<u64>,
205	/// The frame rate in frames per second.
206	pub framerate: Option<f64>,
207	/// The rendition's [`reorder`](hang::catalog::VideoConfig::reorder) depth.
208	pub reorder: Option<u8>,
209	/// If true, the decoder optimizes for latency.
210	pub optimize_for_latency: Option<bool>,
211	/// The maximum jitter before the next frame is emitted.
212	pub jitter: Option<Duration>,
213	/// How far this rendition trails the broadcast's earliest rendition.
214	pub delay: Option<Duration>,
215	/// The container wrapping each frame on the wire.
216	///
217	/// Unlike the other fields this is a choice, not a hint: the bitstream never reveals a
218	/// container, so it is applied to every config the importer publishes rather than filling a gap.
219	pub container: hang::catalog::Container,
220	/// The rendition's [`preference`](hang::catalog::VideoConfig::preference).
221	///
222	/// A choice like the container: the bitstream never reveals it, so every config gets it.
223	pub preference: i32,
224}
225
226/// Fill `slot` from `value` only when the slot is still empty, so a value the stream detected always
227/// wins over the caller's hint.
228fn fill<T>(slot: &mut Option<T>, value: Option<T>) {
229	if slot.is_none() {
230		*slot = value;
231	}
232}
233
234impl From<hang::catalog::VideoConfig> for VideoHint {
235	/// Carry a whole rendition across as hints, for a caller that already knows what its encoder
236	/// emits (moq-video probes its encoder for exactly this).
237	///
238	/// Total by construction: every field the hint can hold is taken from the config, so there is no
239	/// per-field copy for a caller to forget. Fields with no hint slot (`broadcast`, `description`,
240	/// `enabled`) are set through the catalog directly.
241	fn from(config: hang::catalog::VideoConfig) -> Self {
242		Self {
243			label: config.label,
244			codec: Some(config.codec),
245			coded_width: config.coded_width,
246			coded_height: config.coded_height,
247			display_aspect_width: config.display_aspect_width,
248			display_aspect_height: config.display_aspect_height,
249			color: config.color,
250			bitrate: config.bitrate,
251			framerate: config.framerate,
252			reorder: config.reorder,
253			optimize_for_latency: config.optimize_for_latency,
254			jitter: config.jitter,
255			delay: config.delay,
256			container: config.container,
257			preference: config.preference,
258		}
259	}
260}
261
262impl VideoHint {
263	/// Fill a detected video config's absent optional fields from these hints.
264	///
265	/// Only the gaps: a value the stream detects (e.g. the dimensions from an SPS) is left untouched,
266	/// so a resolution change updates the catalog instead of conflicting with the hint. An importer
267	/// calls this on every config it publishes, before handing it to
268	/// [`container::Producer::set`](crate::container::Producer::set), so a hinted field counts as
269	/// supplied and is never overwritten by detection.
270	pub fn apply(&self, config: &mut hang::catalog::VideoConfig) {
271		fill(&mut config.label, self.label.clone());
272		fill(&mut config.coded_width, self.coded_width);
273		fill(&mut config.coded_height, self.coded_height);
274		fill(&mut config.display_aspect_width, self.display_aspect_width);
275		fill(&mut config.display_aspect_height, self.display_aspect_height);
276		crate::codec::color::fill(&mut config.color, self.color.as_ref(), "hint");
277		fill(&mut config.bitrate, self.bitrate);
278		fill(&mut config.framerate, self.framerate);
279		fill(&mut config.reorder, self.reorder);
280		fill(&mut config.optimize_for_latency, self.optimize_for_latency);
281		fill(&mut config.jitter, self.jitter);
282		fill(&mut config.delay, self.delay);
283		config.container = self.container.clone();
284		config.preference = self.preference;
285	}
286
287	/// Build a config from these fields alone, or `None` if the codec is missing. Used to publish
288	/// the catalog before the stream is parsed.
289	pub(crate) fn to_config(&self) -> Option<hang::catalog::VideoConfig> {
290		let codec = self.codec.clone()?;
291		let mut config = hang::catalog::VideoConfig::new(codec);
292		self.apply(&mut config);
293		Some(config)
294	}
295}
296
297impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::VideoConfig {
298	fn detects() -> bool {
299		true
300	}
301
302	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
303		catalog.video.renditions.insert(name.to_string(), self);
304	}
305	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
306		catalog.video.renditions.get_mut(name)
307	}
308	fn remove(catalog: &mut Catalog<E>, name: &str) {
309		catalog.video.renditions.remove(name);
310	}
311
312	fn estimate(&self) -> Estimate {
313		Estimate::default()
314			.with_jitter(self.jitter)
315			.with_bitrate(self.bitrate)
316			.with_delay(self.delay)
317			.with_framerate(self.framerate)
318	}
319	fn set_estimate(&mut self, estimate: Estimate) {
320		self.jitter = estimate.jitter;
321		self.bitrate = estimate.bitrate;
322		self.delay = estimate.delay;
323		self.framerate = estimate.framerate;
324	}
325}
326
327impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::AudioConfig {
328	fn detects() -> bool {
329		true
330	}
331
332	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
333		catalog.audio.renditions.insert(name.to_string(), self);
334	}
335	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
336		catalog.audio.renditions.get_mut(name)
337	}
338	fn remove(catalog: &mut Catalog<E>, name: &str) {
339		catalog.audio.renditions.remove(name);
340	}
341
342	fn estimate(&self) -> Estimate {
343		Estimate::default()
344			.with_jitter(self.jitter)
345			.with_bitrate(self.bitrate)
346			.with_delay(self.delay)
347	}
348	fn set_estimate(&mut self, estimate: Estimate) {
349		self.jitter = estimate.jitter;
350		self.bitrate = estimate.bitrate;
351		self.delay = estimate.delay;
352	}
353}
354
355impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::TextConfig {
356	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
357		catalog.text.renditions.insert(name.to_string(), self);
358	}
359	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
360		catalog.text.renditions.get_mut(name)
361	}
362	fn remove(catalog: &mut Catalog<E>, name: &str) {
363		catalog.text.renditions.remove(name);
364	}
365	fn estimate(&self) -> Estimate {
366		Estimate::default().with_jitter(self.jitter).with_delay(self.delay)
367	}
368	fn set_estimate(&mut self, estimate: Estimate) {
369		self.jitter = estimate.jitter;
370		self.delay = estimate.delay;
371	}
372}
373
374/// How far short of a whole frame duration a value still counts as reaching it, as a fraction of the
375/// period: a reorder of exactly one frame must not miss its step to rounding in the frame duration.
376const STEP_SLACK: u32 = 100;
377
378/// `measured` if it reaches a whole `period` beyond the one `published` sits in, else `published`.
379fn quantize(published: Option<Duration>, measured: Option<Duration>, period: Duration) -> Option<Duration> {
380	let step =
381		|value: Option<Duration>| value.map_or(0, |value| (value + period / STEP_SLACK).as_nanos() / period.as_nanos());
382	if step(measured) > step(published) {
383		measured
384	} else {
385		published
386	}
387}
388
389/// Write `config` under `name`, refusing it before any change if it redefines the rendition's
390/// identity or won't serialize, so the reserved snapshot never retains a bad edit.
391///
392/// The entry is checked in a catalog holding only it and the extension: the media and data sections
393/// serialize each entry on its own, and the rest was checked when it was written, so cloning or
394/// serializing them would make declaring N renditions cost N². The extension is kept whole because
395/// its serializer may depend on its combined entries.
396fn write<E: CatalogExt, C: RenditionConfig<E>>(catalog: &mut Catalog<E>, name: &str, config: C) -> crate::Result<()> {
397	let mut alone = Catalog::default();
398	alone.ext = catalog.ext.clone();
399	config.clone().insert(&mut alone, name);
400	check_identity(catalog, &alone, name)?;
401	serde_json::to_writer(std::io::sink(), &alone).map_err(moq_json::Error::from)?;
402	config.insert(catalog, name);
403	Ok(())
404}
405
406/// Refuse an edit that redefines rendition `name`'s track identity in place: a publisher whose
407/// decoder identity changed publishes under a new name instead.
408fn check_identity<E: CatalogExt>(previous: &Catalog<E>, next: &Catalog<E>, name: &str) -> crate::Result<()> {
409	if let (Some(previous), Some(next)) = (previous.video.renditions.get(name), next.video.renditions.get(name))
410		&& !previous.same_identity(next)
411	{
412		return Err(crate::Error::IdentityChanged(name.to_string()));
413	}
414	if let (Some(previous), Some(next)) = (previous.audio.renditions.get(name), next.audio.renditions.get(name))
415		&& !previous.same_identity(next)
416	{
417		return Err(crate::Error::IdentityChanged(name.to_string()));
418	}
419	Ok(())
420}
421
422/// A clonable reservation context handed to importers so they declare their tracks up front.
423///
424/// Made via [`Producer::reserve`]. While any `Reserved` clone is alive the track set may still
425/// grow, so the catalog is withheld from the broadcast. Each track constructor reserves a
426/// rendition by name and counts as outstanding until its returned producer publishes a config or
427/// is dropped. Once every clone is dropped *and* every reservation resolves, the first catalog
428/// snapshot is published atomically with the complete track list, so a one-shot muxer (fMP4,
429/// MPEG-TS) never sees a half-converged catalog.
430///
431/// It only gates the catalog: the timestamps written through it land verbatim on the catalog's
432/// clock. A source on a timeline of its own shifts them through a [`Timebase`](super::Timebase).
433pub struct Reserved<E: CatalogExt = ()> {
434	catalog: Producer<E>,
435	interval: Option<std::time::Duration>,
436}
437
438impl<E: CatalogExt> Reserved<E> {
439	pub(super) fn new(catalog: Producer<E>) -> Self {
440		catalog.add_reserver();
441		Self {
442			catalog,
443			interval: None,
444		}
445	}
446
447	/// Declare the track's longest group (its GOP), which the catalog's `sync.interval`
448	/// promises. Without one, a video or audio track measures it over its first second or group,
449	/// whichever is longer, before the interval is declared.
450	pub fn with_interval(mut self, interval: impl Into<Option<std::time::Duration>>) -> Self {
451		self.interval = interval.into();
452		self
453	}
454
455	/// Track properties for a media track under this catalog, carrying any max age it declares.
456	/// See [`Producer::track_info`](super::Producer::track_info).
457	pub fn track_info(&self, priority: i8) -> moq_net::track::Info {
458		self.catalog.track_info(priority)
459	}
460
461	/// Reserve a rendition of config type `C` under `name`, returning its internal owner.
462	///
463	/// The owner holds its own `Reserved` clone, so the catalog stays withheld until its config is
464	/// published (or it is dropped). Prefer [`video`](Self::video) / [`audio`](Self::audio) for the
465	/// built-in media configs.
466	///
467	/// Errors if the name is already taken in this section, whether by a live rendition or by an
468	/// entry in the catalog. Sections are independent, so the same name in `video` and `audio` is
469	/// two unrelated renditions.
470	pub(crate) fn init<C: RenditionConfig<E>>(&self, name: impl Into<String>) -> crate::Result<Rendition<E, C>> {
471		Rendition::new(self.clone(), name.into())
472	}
473
474	/// Publish a reserved video track and own its catalog rendition.
475	pub fn video<C: crate::container::Container>(
476		&self,
477		track: moq_net::track::Producer,
478		container: C,
479		config: impl Into<Option<hang::catalog::VideoConfig>>,
480	) -> crate::Result<crate::container::Producer<C, hang::catalog::VideoConfig>>
481	where
482		crate::Error: From<C::Error>,
483	{
484		self.track(track, container, config)
485	}
486
487	/// Publish a reserved audio track and own its catalog rendition.
488	pub fn audio<C: crate::container::Container>(
489		&self,
490		track: moq_net::track::Producer,
491		container: C,
492		config: impl Into<Option<hang::catalog::AudioConfig>>,
493	) -> crate::Result<crate::container::Producer<C, hang::catalog::AudioConfig>>
494	where
495		crate::Error: From<C::Error>,
496	{
497		self.track(track, container, config)
498	}
499
500	/// Publish a reserved text track and own its catalog rendition.
501	pub fn text<C: crate::container::Container>(
502		&self,
503		track: moq_net::track::Producer,
504		container: C,
505		config: impl Into<Option<hang::catalog::TextConfig>>,
506	) -> crate::Result<crate::container::Producer<C, hang::catalog::TextConfig>>
507	where
508		crate::Error: From<C::Error>,
509	{
510		self.track(track, container, config)
511	}
512
513	/// Publish a reserved track using a custom catalog config.
514	pub fn track<C, R>(
515		&self,
516		track: moq_net::track::Producer,
517		container: C,
518		config: impl Into<Option<R>>,
519	) -> crate::Result<crate::container::Producer<C, R>>
520	where
521		C: crate::container::Container,
522		R: RenditionConfig<E>,
523		crate::Error: From<C::Error>,
524	{
525		let rendition = self.init(track.name())?;
526		self.catalog
527			.media(track, container, rendition, config.into(), self.interval)
528	}
529
530	/// Resolve a timestamp on the broadcast's shared clock (see [`Producer::timestamp`]).
531	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
532		self.catalog.timestamp(hint)
533	}
534
535	/// The underlying catalog [`Producer`], for edits that outlive this reservation.
536	///
537	/// A container importer holds one to edit the catalog directly (e.g. its per-frame reconcile, or
538	/// track removals after its initial set is declared) while the reservation itself is dropped to
539	/// open the gate. The returned handle does not gate: only live `Reserved`s do.
540	pub(crate) fn producer(&self) -> Producer<E> {
541		self.catalog.clone()
542	}
543}
544
545impl<E: CatalogExt> Clone for Reserved<E> {
546	fn clone(&self) -> Self {
547		Self::new(self.catalog.clone()).with_interval(self.interval)
548	}
549}
550
551impl<E: CatalogExt> Drop for Reserved<E> {
552	fn drop(&mut self) {
553		self.catalog.release_reserver();
554	}
555}
556
557/// A reserved rendition of config type `C`, retired from the catalog on drop.
558///
559/// Made via [`Reserved::init`] (or [`video`](Reserved::video) / [`audio`](Reserved::audio)). Fill
560/// it in with [`set`](Self::set) and refine it in place with [`update`](Self::update). Until it's
561/// set (or dropped) it holds a [`Reserved`] clone, so an unresolved rendition keeps the initial
562/// catalog publish gated. On drop the rendition is removed from the shared catalog.
563///
564/// It owns its name for its whole lifetime, from reservation rather than from `set`, so nothing
565/// else can reserve that name in the same section meanwhile. That's what a lazily-configured
566/// importer needs: an H.264 track publishes no config until its first SPS, and the name has to be
567/// unavailable through that window or an entry written into it is overwritten by `set` and then
568/// deleted by this `Drop`. Author a rendition by holding one of these, not by writing to
569/// `catalog.video` / `catalog.audio` through a [`Guard`](super::Guard), which is raw access to the
570/// catalog document and enforces nothing.
571pub(crate) struct Rendition<E: CatalogExt, C: RenditionConfig<E>> {
572	catalog: Producer<E>,
573	name: String,
574	/// The reservation this rendition holds until its config is set (or it's dropped unfulfilled).
575	/// `Some` gates the initial publish; cleared by [`set`](Self::set).
576	gate: Option<Reserved<E>>,
577	/// Whether a config has been published, so a lazily-configured importer (e.g. H.264 before its
578	/// SPS) holds the handle without a catalog entry, and drops without a spurious removal.
579	present: bool,
580	/// The fields the config carried at [`set`](Self::set): authoritative, never overwritten by
581	/// detection. Whatever is absent here is what detection fills, and stays absent from MSF.
582	supplied: Estimate,
583	/// The last estimate handed to [`estimate`](Self::estimate), kept so a config set afterwards
584	/// starts from whatever was already measured.
585	detected: Estimate,
586	/// The last estimate written to the config, so an unchanged one doesn't republish the catalog.
587	published: Option<Estimate>,
588	_config: PhantomData<fn() -> C>,
589}
590
591/// A single video track's catalog rendition. See [`Rendition`].
592pub(crate) type VideoTrack<E = ()> = Rendition<E, hang::catalog::VideoConfig>;
593/// A single audio track's catalog rendition. See [`Rendition`].
594pub(crate) type AudioTrack<E = ()> = Rendition<E, hang::catalog::AudioConfig>;
595/// A single text (caption/subtitle) track's catalog rendition. See [`Rendition`].
596impl<E: CatalogExt, C: RenditionConfig<E>> Rendition<E, C> {
597	/// The successor of this rendition's track, under a newly minted name, for a decoder identity
598	/// change. `interval` carries the longest group the old track declared or measured.
599	pub(crate) fn fresh(
600		&self,
601		container: super::hang::Wire,
602		info: moq_net::track::Info,
603		interval: Option<std::time::Duration>,
604	) -> crate::Result<crate::container::Producer<super::hang::Wire, C>> {
605		let track = self.catalog.fresh_track(&self.name, info);
606		let rendition = self.catalog.rendition(track.name())?;
607		self.catalog.media(track, container, rendition, None, interval)
608	}
609
610	fn new(reserved: Reserved<E>, name: String) -> crate::Result<Self> {
611		Self::owned(reserved.producer(), Some(reserved), name)
612	}
613
614	pub(super) fn live(catalog: Producer<E>, name: String) -> crate::Result<Self> {
615		Self::owned(catalog, None, name)
616	}
617
618	fn owned(catalog: Producer<E>, gate: Option<Reserved<E>>, name: String) -> crate::Result<Self> {
619		// Take the name now, not at `set`: a lazily-configured importer (H.264 before its first SPS)
620		// has no catalog entry until much later, and the name has to be ours for that whole window.
621		catalog.acquire::<C>(&name)?;
622
623		Ok(Self {
624			catalog,
625			gate,
626			name,
627			present: false,
628			supplied: Estimate::default(),
629			detected: Estimate::default(),
630			published: None,
631			_config: PhantomData,
632		})
633	}
634
635	/// The track name this rendition is keyed by.
636	pub fn name(&self) -> &str {
637		&self.name
638	}
639
640	/// A fresh estimator measuring `delay` against the catalog's other renditions.
641	pub(crate) fn estimator(&self) -> super::Estimator {
642		self.catalog.estimator()
643	}
644
645	/// The broadcast clock the catalog stamps its tracks on, read without fixing it.
646	pub(crate) fn clock(&self) -> crate::Clock {
647		self.catalog.current_clock()
648	}
649
650	/// Resolve a timestamp on the broadcast's shared clock (see [`Producer::timestamp`]).
651	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
652		self.catalog.timestamp(hint)
653	}
654
655	/// Validate and publish the rendition, fulfilling its reservation only after the edit succeeds.
656	///
657	/// Whatever [`Estimate`] fields `config` already carries are authoritative and left alone; the
658	/// rest are filled by [`estimate`](Self::estimate), seeded with anything already measured before
659	/// the rendition existed (a dirty start or a B-frame reorder). Only the authoritative ones reach
660	/// the MSF catalog. A caller who wants to pre-empt detection sets the field on the config, or (for
661	/// a config an importer builds out of the bitstream) hands the importer a hint like [`VideoHint`].
662	/// Unset jitter and delay keep the published floor across reconfiguration.
663	pub(crate) fn set(&mut self, mut config: C) -> crate::Result<()> {
664		let supplied = config.estimate();
665		let mut resolved = Self::resolved(&supplied, &self.detected);
666		if self.present {
667			let published = self.config()?.estimate();
668			if supplied.jitter.is_none() {
669				resolved.jitter = resolved.jitter.max(published.jitter);
670			}
671			if supplied.delay.is_none() {
672				resolved.delay = resolved.delay.max(published.delay);
673			}
674			Self::check_decrease(&published, &resolved)?;
675		}
676		config.set_estimate(resolved.clone());
677		{
678			let mut guard = self.catalog.edit()?;
679			write(&mut guard, &self.name, config)?;
680			self.present = true;
681			guard.list::<C>(&self.name);
682			if C::detects() {
683				guard.hint::<C>(&self.name, supplied.clone());
684			}
685			guard.commit()?;
686		}
687		self.supplied = supplied;
688		self.published = Some(resolved);
689		self.gate = None;
690		Ok(())
691	}
692
693	/// The supplied fields, with anything absent filled from what was detected.
694	fn resolved(supplied: &Estimate, detected: &Estimate) -> Estimate {
695		let mut estimate = supplied.clone();
696		if estimate.jitter.is_none() {
697			estimate.jitter = detected.jitter;
698		}
699		if estimate.bitrate.is_none() {
700			estimate.bitrate = detected.bitrate;
701		}
702		if estimate.delay.is_none() {
703			estimate.delay = detected.delay;
704		}
705		if estimate.framerate.is_none() {
706			estimate.framerate = detected.framerate;
707		}
708		estimate
709	}
710
711	/// Publish a measured [`Estimate`], filling only the fields the config didn't supply at
712	/// [`set`](Self::set).
713	///
714	/// Mint the reading from an [`Estimator`](super::Estimator), usually the one owned by a
715	/// [`container::Producer`](crate::container::Producer). Call it after every write: an estimate
716	/// that resolves to what the catalog already carries doesn't republish it. A `jitter` or `delay`
717	/// rise republishes only once it reaches the next whole frame duration above the published value,
718	/// and then at most once a second (see [`Guard::commit_estimate`](super::Guard::commit_estimate)),
719	/// going out on a later call.
720	///
721	/// Calling this before [`set`](Self::set) is not wasted: the measurement is remembered and seeds
722	/// the config once it lands.
723	pub(crate) fn estimate(&mut self, reading: impl Into<super::Reading>) -> crate::Result<()> {
724		let super::Reading { estimate, period, .. } = reading.into();
725		if !C::detects() {
726			return Ok(());
727		}
728		if !self.present {
729			self.detected = estimate;
730			return Ok(());
731		}
732		let mut resolved = Self::resolved(&self.supplied, &estimate);
733		// A measurement never lowers the published jitter or delay, including one raised through
734		// `modify`.
735		let mut config = self.config()?;
736		let published = config.estimate();
737		resolved.jitter = resolved.jitter.max(published.jitter);
738		resolved.delay = resolved.delay.max(published.delay);
739		// Measurement creeps up as the encoder's latency does, a step per frame at worst; only a whole
740		// frame's rise is worth a republish. Until a period is known the throttle alone paces it.
741		let period = resolved
742			.framerate
743			.filter(|framerate| *framerate > 0.0)
744			.and_then(|framerate| Duration::try_from_secs_f64(framerate.recip()).ok())
745			.or(period)
746			.filter(|period| !period.is_zero());
747		if let Some(period) = period {
748			resolved.jitter = quantize(published.jitter, resolved.jitter, period);
749			resolved.delay = quantize(published.delay, resolved.delay, period);
750		}
751		self.detected = estimate;
752		if self.published.as_ref() == Some(&resolved) {
753			// Still an observation: it releases a rise held back until its window ended. A closed
754			// catalog has nothing left to release.
755			if let Ok(guard) = self.catalog.edit() {
756				guard.commit_estimate(true)?;
757			}
758			return Ok(());
759		}
760
761		// Bitrate and framerate are already measured over a second of media, so they never churn;
762		// only jitter and delay climb a step per frame.
763		let throttled = self.published.as_ref().is_some_and(|published| {
764			published.bitrate == resolved.bitrate && published.framerate == resolved.framerate
765		});
766		config.set_estimate(resolved.clone());
767		self.stage(config)?.commit_estimate(throttled)?;
768		self.published = Some(resolved);
769		Ok(())
770	}
771
772	/// Refuse a config that lowers the jitter or delay already advertised to subscribers.
773	fn check_decrease(previous: &Estimate, next: &Estimate) -> crate::Result<()> {
774		if next.jitter < previous.jitter {
775			return Err(crate::Error::JitterDecreased);
776		}
777		if next.delay < previous.delay {
778			return Err(crate::Error::DelayDecreased);
779		}
780		Ok(())
781	}
782
783	/// Why an unpublished rendition can't be edited: the catalog's terminal error once it is closed,
784	/// since a handle made after a failed finish must report that failure, else `NotPublished`.
785	fn unpublished(&self) -> crate::Error {
786		self.catalog.closed().unwrap_or(crate::Error::NotPublished)
787	}
788
789	/// Refine the rendition, refusing an unserializable edit before retaining it.
790	pub(crate) fn config(&self) -> crate::Result<C> {
791		if !self.present {
792			return Err(self.unpublished());
793		}
794		self.catalog.config::<C>(&self.name).ok_or(crate::Error::NotPublished)
795	}
796
797	pub(crate) fn replace(&mut self, config: C) -> crate::Result<()> {
798		self.stage(config)?.commit()
799	}
800
801	/// Advertise `bitrate` as a supplied value that measurement no longer replaces, leaving every
802	/// other field, measured or not, as published.
803	pub(crate) fn supply_bitrate(&mut self, bitrate: u64) -> crate::Result<()> {
804		let mut config = self.config()?;
805		let mut estimate = config.estimate();
806		estimate.bitrate = Some(bitrate);
807		config.set_estimate(estimate);
808		let mut supplied = self.supplied.clone();
809		supplied.bitrate = Some(bitrate);
810		let name = self.name.clone();
811		let mut guard = self.stage(config)?;
812		if C::detects() {
813			guard.hint::<C>(&name, supplied.clone());
814		}
815		guard.commit()?;
816		self.supplied = supplied;
817		Ok(())
818	}
819
820	/// Write `config` into the catalog, leaving the caller to choose how the guard publishes it.
821	fn stage(&mut self, config: C) -> crate::Result<super::Guard<'_, E>> {
822		if !self.present {
823			return Err(self.unpublished());
824		}
825		Self::check_decrease(&self.config()?.estimate(), &config.estimate())?;
826		let mut guard = self.catalog.edit()?;
827		write(&mut guard, &self.name, config)?;
828		Ok(guard)
829	}
830}
831
832// Manual so a config that isn't `Debug` doesn't cost the handle its own, and because the interesting
833// state is the name and whether it has published yet, not the estimate bookkeeping.
834impl<E: CatalogExt, C: RenditionConfig<E>> std::fmt::Debug for Rendition<E, C> {
835	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836		f.debug_struct("Rendition")
837			.field("name", &self.name)
838			.field("published", &self.present)
839			.finish_non_exhaustive()
840	}
841}
842
843impl<E: CatalogExt, C: RenditionConfig<E>> Drop for Rendition<E, C> {
844	fn drop(&mut self) {
845		// The entry and the name it holds are released together under one lock. Removing mutates the
846		// catalog, so the guard publishes it (immediately if live, else it accumulates until the gate
847		// opens). A closed catalog has nothing left to release from.
848		if let Ok(mut catalog) = self.catalog.edit() {
849			catalog.release::<C>(&self.name, self.present);
850		}
851		// Our reservation (`gate`) drops here. If still held (never set), its release flushes any
852		// staged change; if already released by `set`, this is a no-op.
853	}
854}
855
856#[cfg(test)]
857mod tests {
858	use super::*;
859
860	/// A millisecond track: the frames written here carry timestamps.
861	fn timed() -> moq_net::track::Info {
862		moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI)
863	}
864
865	fn video_track() -> (moq_net::broadcast::Producer, super::super::Producer, VideoTrack) {
866		let mut broadcast = moq_net::broadcast::Info::new().produce();
867		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
868		let reserved = catalog.reserve();
869		let rendition = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
870		// Drop the standalone reservation so only the rendition's own gate remains, which `set`
871		// clears; the broadcast handle is returned so the produced tracks outlive the catalog.
872		drop(reserved);
873		(broadcast, catalog, rendition)
874	}
875
876	fn config(bitrate: Option<u64>, jitter: Option<Duration>) -> hang::catalog::VideoConfig {
877		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
878		config.bitrate = bitrate;
879		config.jitter = jitter;
880		config
881	}
882
883	#[test]
884	fn video_identity_edits_are_refused_without_changing_the_catalog() {
885		let original = config(Some(1_000_000), None);
886		let mut changed = Vec::new();
887		let mut codec = original.clone();
888		codec.codec = "avc1.42c01e".parse().unwrap();
889		changed.push(codec);
890		let mut description = original.clone();
891		description.description = Some(bytes::Bytes::from_static(&[1, 2, 3]));
892		changed.push(description);
893		let mut container = original.clone();
894		container.container = hang::catalog::Container::Loc;
895		changed.push(container);
896		let mut width = original.clone();
897		width.display_aspect_width = Some(4);
898		changed.push(width);
899		let mut height = original.clone();
900		height.display_aspect_height = Some(3);
901		changed.push(height);
902		for next in changed {
903			for operation in ["set", "replace", "stage"] {
904				let (_broadcast, catalog, mut rendition) = video_track();
905				rendition.set(original.clone()).unwrap();
906				let refused = match operation {
907					"set" => rendition.set(next.clone()).is_err(),
908					"replace" => rendition.replace(next.clone()).is_err(),
909					"stage" => rendition.stage(next.clone()).is_err(),
910					_ => unreachable!(),
911				};
912				assert!(refused, "{operation} retained identity change {next:?}");
913				assert_eq!(catalog.snapshot().video.renditions["v"], original);
914			}
915		}
916	}
917
918	#[test]
919	fn video_size_and_estimates_can_change_in_place() {
920		let (_broadcast, catalog, mut rendition) = video_track();
921		let mut original = config(Some(1_000_000), None);
922		original.coded_width = Some(1280);
923		original.coded_height = Some(720);
924		original.framerate = Some(60.0);
925		rendition.set(original.clone()).unwrap();
926		let mut next = original;
927		next.coded_width = Some(1920);
928		next.coded_height = Some(1080);
929		next.bitrate = Some(500_000);
930		next.framerate = Some(30.0);
931		rendition.set(next.clone()).unwrap();
932		assert_eq!(catalog.snapshot().video.renditions["v"], next);
933	}
934
935	#[test]
936	fn audio_identity_edits_are_refused_without_changing_the_catalog() {
937		let original = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
938		let mut changed = Vec::new();
939		let mut codec = original.clone();
940		codec.codec = hang::catalog::AudioCodec::Flac;
941		changed.push(codec);
942		let mut description = original.clone();
943		description.description = Some(bytes::Bytes::from_static(&[1, 2, 3]));
944		changed.push(description);
945		let mut container = original.clone();
946		container.container = hang::catalog::Container::Loc;
947		changed.push(container);
948		let mut sample_rate = original.clone();
949		sample_rate.sample_rate = 44_100;
950		changed.push(sample_rate);
951		let mut channels = original.clone();
952		channels.channel_count = 1;
953		changed.push(channels);
954		for next in changed {
955			for operation in ["set", "replace", "stage"] {
956				let mut broadcast = moq_net::broadcast::Info::new().produce();
957				let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
958				let reserved = catalog.reserve();
959				let mut rendition = reserved.init::<hang::catalog::AudioConfig>("a").unwrap();
960				drop(reserved);
961				rendition.set(original.clone()).unwrap();
962				let refused = match operation {
963					"set" => rendition.set(next.clone()).is_err(),
964					"replace" => rendition.replace(next.clone()).is_err(),
965					"stage" => rendition.stage(next.clone()).is_err(),
966					_ => unreachable!(),
967				};
968				assert!(refused, "{operation} retained identity change {next:?}");
969				assert_eq!(catalog.snapshot().audio.renditions["a"], original);
970			}
971		}
972	}
973
974	#[test]
975	fn rejected_jitter_is_not_retained() {
976		let (_broadcast, catalog, mut rendition) = video_track();
977		for jitter in [Duration::ZERO, Duration::MAX] {
978			assert!(rendition.set(config(None, Some(jitter))).is_err());
979			assert!(catalog.snapshot().video.renditions.is_empty());
980		}
981		rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
982		let mut invalid = rendition.config().unwrap();
983		invalid.jitter = Some(Duration::ZERO);
984		assert!(rendition.replace(invalid).is_err());
985		assert_eq!(
986			catalog.snapshot().video.renditions.values().next().unwrap().jitter,
987			Some(Duration::from_millis(100))
988		);
989	}
990
991	#[test]
992	fn published_jitter_never_decreases() {
993		let (_broadcast, catalog, mut rendition) = video_track();
994		rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
995		let smaller = config(None, Some(Duration::from_millis(50)));
996		assert!(matches!(
997			rendition.set(smaller.clone()),
998			Err(crate::Error::JitterDecreased)
999		));
1000		assert!(matches!(rendition.replace(smaller), Err(crate::Error::JitterDecreased)));
1001		assert_eq!(
1002			catalog.snapshot().video.renditions["v"].jitter,
1003			Some(Duration::from_millis(100))
1004		);
1005
1006		let (_broadcast, catalog, mut detected) = video_track();
1007		detected.set(config(None, None)).unwrap();
1008		detected
1009			.estimate(Estimate::default().with_jitter(Duration::from_millis(100)))
1010			.unwrap();
1011		// A lower measurement holds the published value rather than failing the write path.
1012		detected
1013			.estimate(Estimate::default().with_jitter(Duration::from_millis(50)))
1014			.unwrap();
1015		assert_eq!(
1016			catalog.snapshot().video.renditions["v"].jitter,
1017			Some(Duration::from_millis(100))
1018		);
1019	}
1020
1021	#[test]
1022	fn reconfigure_floors_only_unsupplied_fields() {
1023		let ms = Duration::from_millis;
1024		for supplied_jitter in [false, true] {
1025			for supplied_delay in [false, true] {
1026				let (_broadcast, catalog, mut rendition) = video_track();
1027				rendition.set(config(None, None)).unwrap();
1028				rendition
1029					.estimate(Estimate::default().with_jitter(ms(100)).with_delay(ms(200)))
1030					.unwrap();
1031				// The most recent reading can be below what was already advertised.
1032				rendition
1033					.estimate(Estimate::default().with_jitter(ms(50)).with_delay(ms(100)))
1034					.unwrap();
1035				let mut next = config(Some(500_000), supplied_jitter.then_some(ms(150)));
1036				next.delay = supplied_delay.then_some(ms(250));
1037				next.coded_width = Some(1920);
1038				next.coded_height = Some(1080);
1039				next.framerate = Some(30.0);
1040				rendition.set(next.clone()).unwrap();
1041				let expected_jitter = Some(ms(if supplied_jitter { 150 } else { 100 }));
1042				let expected_delay = Some(ms(if supplied_delay { 250 } else { 200 }));
1043				next.jitter = expected_jitter;
1044				next.delay = expected_delay;
1045				assert_eq!(catalog.snapshot().video.renditions["v"], next);
1046
1047				// A floor does not turn an unsupplied field into a supplied hint.
1048				rendition
1049					.estimate(Estimate::default().with_jitter(ms(300)).with_delay(ms(400)))
1050					.unwrap();
1051				let current = rendition.config().unwrap();
1052				assert_eq!(
1053					current.jitter,
1054					if supplied_jitter {
1055						expected_jitter
1056					} else {
1057						Some(ms(300))
1058					}
1059				);
1060				assert_eq!(
1061					current.delay,
1062					if supplied_delay { expected_delay } else { Some(ms(400)) }
1063				);
1064			}
1065		}
1066	}
1067
1068	/// A supplied zero delay is a statement, not a gap: measurement never replaces it, and the
1069	/// catalog omits it on the wire, hang and MSF alike.
1070	#[test]
1071	fn a_supplied_zero_delay_is_never_measured() {
1072		let (_broadcast, catalog, mut rendition) = video_track();
1073		let mut supplied = config(None, None);
1074		supplied.delay = Some(Duration::ZERO);
1075		rendition.set(supplied).unwrap();
1076		rendition
1077			.estimate(Estimate::default().with_delay(Duration::from_millis(200)))
1078			.unwrap();
1079		assert_eq!(catalog.snapshot().video.renditions["v"].delay, Some(Duration::ZERO));
1080
1081		let json = catalog.snapshot().to_json().unwrap();
1082		assert!(!json.contains("delay"), "{json}");
1083		let rendered = super::super::producer::to_msf(&catalog.snapshot(), &moq_net::Path::default());
1084		assert!(rendered.tracks.iter().all(|track| track.delay.is_none()));
1085	}
1086
1087	#[test]
1088	fn published_delay_never_decreases() {
1089		let (_broadcast, catalog, mut rendition) = video_track();
1090		let delayed = |delay| {
1091			let mut config = config(None, None);
1092			config.delay = delay;
1093			config
1094		};
1095		rendition.set(delayed(Some(Duration::from_millis(200)))).unwrap();
1096		assert!(matches!(
1097			rendition.set(delayed(Some(Duration::from_millis(100)))),
1098			Err(crate::Error::DelayDecreased)
1099		));
1100		for smaller in [Some(Duration::from_millis(100)), None] {
1101			assert!(matches!(
1102				rendition.replace(delayed(smaller)),
1103				Err(crate::Error::DelayDecreased)
1104			));
1105		}
1106		rendition.set(delayed(None)).unwrap();
1107		assert_eq!(
1108			catalog.snapshot().video.renditions["v"].delay,
1109			Some(Duration::from_millis(200))
1110		);
1111
1112		let (_broadcast, catalog, mut detected) = video_track();
1113		detected.set(config(None, None)).unwrap();
1114		detected
1115			.estimate(Estimate::default().with_delay(Duration::from_millis(200)))
1116			.unwrap();
1117		// A lower measurement holds the published value rather than failing the write path.
1118		detected
1119			.estimate(Estimate::default().with_delay(Duration::from_millis(100)))
1120			.unwrap();
1121		assert_eq!(
1122			catalog.snapshot().video.renditions["v"].delay,
1123			Some(Duration::from_millis(200))
1124		);
1125	}
1126
1127	#[test]
1128	fn measurement_keeps_a_jitter_raised_by_modify() {
1129		let (_broadcast, catalog, mut rendition) = video_track();
1130		rendition.set(config(None, None)).unwrap();
1131		rendition
1132			.estimate(Estimate::default().with_jitter(Duration::from_millis(60)))
1133			.unwrap();
1134		let mut raised = rendition.config().unwrap();
1135		raised.jitter = Some(Duration::from_millis(200));
1136		rendition.replace(raised).unwrap();
1137
1138		rendition
1139			.estimate(Estimate::default().with_jitter(Duration::from_millis(80)))
1140			.unwrap();
1141		assert_eq!(
1142			catalog.snapshot().video.renditions["v"].jitter,
1143			Some(Duration::from_millis(200))
1144		);
1145		rendition
1146			.estimate(Estimate::default().with_jitter(Duration::from_millis(300)))
1147			.unwrap();
1148		assert_eq!(
1149			catalog.snapshot().video.renditions["v"].jitter,
1150			Some(Duration::from_millis(300))
1151		);
1152	}
1153
1154	#[test]
1155	fn published_text_jitter_never_decreases() {
1156		let mut broadcast = moq_net::broadcast::Info::new().produce();
1157		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1158		let reserved = catalog.reserve();
1159		let mut rendition = reserved.init::<hang::catalog::TextConfig>("t").unwrap();
1160		drop(reserved);
1161
1162		let text = |jitter| {
1163			let mut config = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Utf8);
1164			config.jitter = jitter;
1165			config
1166		};
1167		rendition.set(text(Some(Duration::from_millis(100)))).unwrap();
1168		assert!(matches!(
1169			rendition.set(text(Some(Duration::from_millis(50)))),
1170			Err(crate::Error::JitterDecreased)
1171		));
1172		rendition.set(text(None)).unwrap();
1173		assert_eq!(
1174			catalog.snapshot().text.renditions["t"].jitter,
1175			Some(Duration::from_millis(100))
1176		);
1177	}
1178
1179	#[test]
1180	fn importer_returns_rejected_jitter() {
1181		let mut broadcast = moq_net::broadcast::Info::new().produce();
1182		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1183		let reserved = catalog.reserve();
1184		let track = broadcast
1185			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1186			.unwrap();
1187		let mut config: hang::catalog::AudioConfig = crate::codec::aac::Config {
1188			profile: 2,
1189			sample_rate: 48_000,
1190			channel_count: 2,
1191		}
1192		.try_into()
1193		.unwrap();
1194		config.jitter = Some(Duration::ZERO);
1195		assert!(crate::codec::aac::Import::new(track, reserved, config).is_err());
1196		assert!(catalog.snapshot().audio.renditions.is_empty());
1197	}
1198
1199	fn ts(micros: u64) -> moq_net::Timestamp {
1200		moq_net::Timestamp::from_micros(micros).unwrap()
1201	}
1202
1203	/// Feed ~40ms 100 kB frames over more than the bitrate window, with a measured
1204	/// 40ms container batch span. PTS spacing alone says nothing about jitter.
1205	fn feed<E: CatalogExt, C: RenditionConfig<E>>(rendition: &mut Rendition<E, C>) {
1206		let mut estimator = super::super::Estimator::new();
1207		estimator.burst(Duration::from_millis(40));
1208		for i in 0..60u64 {
1209			let t = ts(i * 40_000);
1210			estimator.cut(Some(t));
1211			estimator.write(t, 100_000);
1212			rendition.estimate(estimator.reading()).unwrap();
1213		}
1214	}
1215
1216	#[test]
1217	fn detects_absent_jitter_and_bitrate() {
1218		let (_broadcast, catalog, mut rendition) = video_track();
1219		rendition.set(config(None, None)).unwrap();
1220		feed(&mut rendition);
1221
1222		let snapshot = catalog.snapshot();
1223		let config = snapshot.video.renditions.get("v").unwrap();
1224		assert!(config.jitter.is_some(), "absent jitter should be auto-detected");
1225		assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");
1226		assert_eq!(config.framerate, Some(25.0), "absent framerate should be auto-detected");
1227	}
1228
1229	#[test]
1230	fn keeps_provided_jitter_and_bitrate() {
1231		let (_broadcast, catalog, mut rendition) = video_track();
1232		rendition
1233			.set(config(Some(123), Some(Duration::from_millis(50))))
1234			.unwrap();
1235		feed(&mut rendition);
1236
1237		let snapshot = catalog.snapshot();
1238		let config = snapshot.video.renditions.get("v").unwrap();
1239		assert_eq!(config.bitrate, Some(123), "a provided bitrate must not be overwritten");
1240		assert_eq!(
1241			config.jitter,
1242			Some(Duration::from_millis(50)),
1243			"a provided jitter must not be overwritten"
1244		);
1245	}
1246
1247	/// A caller hands moq-video a whole `VideoConfig`, so the conversion into hints must be total.
1248	/// Hand-copying it field by field is what dropped the label on that path.
1249	#[test]
1250	fn a_config_converts_into_hints_without_losing_the_label() {
1251		let (_broadcast, catalog, mut rendition) = video_track();
1252
1253		let mut source = config(Some(456), None);
1254		source.label = Some("Main camera".to_string());
1255		source.coded_width = Some(1920);
1256		source.coded_height = Some(1080);
1257		let hint = VideoHint::from(source);
1258
1259		// The importer applies the hint to each config it publishes, so check the label survives
1260		// both the up-front publish and a later one the stream resolved.
1261		let mut first = config(None, None);
1262		hint.apply(&mut first);
1263		rendition.set(first).unwrap();
1264		feed(&mut rendition);
1265		assert_eq!(
1266			catalog.snapshot().video.renditions.get("v").unwrap().label.as_deref(),
1267			Some("Main camera"),
1268			"the label must survive the config the importer publishes up front"
1269		);
1270
1271		let mut resolved = config(None, None);
1272		resolved.coded_width = Some(1280);
1273		resolved.coded_height = Some(720);
1274		hint.apply(&mut resolved);
1275		rendition.set(resolved).unwrap();
1276		feed(&mut rendition);
1277
1278		let snapshot = catalog.snapshot();
1279		let published = snapshot.video.renditions.get("v").unwrap();
1280		assert_eq!(
1281			published.label.as_deref(),
1282			Some("Main camera"),
1283			"the label must survive a config the stream resolved later"
1284		);
1285		assert_eq!(published.bitrate, Some(456), "the rest of the config converts too");
1286	}
1287
1288	/// A hint is applied by the importer before `set`, so a hinted field is indistinguishable from
1289	/// one the stream revealed: supplied, and never overwritten by detection.
1290	#[test]
1291	fn hinted_fields_count_as_supplied() {
1292		let (_broadcast, catalog, mut rendition) = video_track();
1293
1294		let hint = VideoHint {
1295			bitrate: Some(456),
1296			framerate: Some(30.0),
1297			..Default::default()
1298		};
1299		let mut config = config(None, None);
1300		hint.apply(&mut config);
1301
1302		rendition.set(config).unwrap();
1303		feed(&mut rendition);
1304
1305		let snapshot = catalog.snapshot();
1306		let config = snapshot.video.renditions.get("v").unwrap();
1307		assert_eq!(config.bitrate, Some(456), "a hinted bitrate must not be overwritten");
1308		assert_eq!(
1309			config.framerate,
1310			Some(30.0),
1311			"a hinted framerate must not be overwritten"
1312		);
1313		assert!(config.jitter.is_some(), "the unhinted jitter should still be detected");
1314	}
1315
1316	/// Frames flow before the config resolves (H.264 publishes until its first SPS), so a
1317	/// measurement taken while the rendition is still empty has to seed the config once it lands.
1318	#[test]
1319	fn measurements_before_set_seed_the_config() {
1320		let (_broadcast, catalog, mut rendition) = video_track();
1321		feed(&mut rendition);
1322		rendition.set(config(None, None)).unwrap();
1323
1324		let snapshot = catalog.snapshot();
1325		let config = snapshot.video.renditions.get("v").unwrap();
1326		assert!(
1327			config.jitter.is_some(),
1328			"the jitter measured before `set` should carry over"
1329		);
1330		assert!(
1331			config.bitrate.is_some(),
1332			"the bitrate measured before `set` should carry over"
1333		);
1334	}
1335
1336	/// A detected value the stream later reveals wins: `set` recaptures what the new config carries.
1337	#[test]
1338	fn resetting_recaptures_supplied() {
1339		let (_broadcast, catalog, mut rendition) = video_track();
1340		rendition.set(config(None, None)).unwrap();
1341		feed(&mut rendition);
1342		assert!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate.is_some());
1343
1344		rendition.set(config(Some(789), None)).unwrap();
1345		feed(&mut rendition);
1346
1347		let snapshot = catalog.snapshot();
1348		let config = snapshot.video.renditions.get("v").unwrap();
1349		assert_eq!(config.bitrate, Some(789), "the re-set bitrate is now authoritative");
1350	}
1351
1352	/// A rendition owns its name from the moment it's reserved, not from `set`. H.264 publishes
1353	/// frames before its first SPS resolves the config, and the name has to be unavailable through
1354	/// that window: an entry written into the gap used to be overwritten by `set` and then deleted
1355	/// by the importer's `Drop`, taking the caller's rendition with it.
1356	#[test]
1357	fn an_unresolved_rendition_still_owns_its_name() {
1358		let (_broadcast, catalog, mut rendition) = video_track();
1359		assert!(
1360			catalog.snapshot().video.renditions.is_empty(),
1361			"nothing is published until the config resolves"
1362		);
1363
1364		let err = catalog
1365			.reserve()
1366			.init::<hang::catalog::VideoConfig>("v")
1367			.expect_err("an unresolved rendition still owns its name");
1368		assert!(matches!(err, crate::Error::Hang(hang::Error::Duplicate(name)) if name == "v"));
1369
1370		// The refusal left nothing behind, so the importer's own config is what lands.
1371		rendition.set(config(Some(123), None)).unwrap();
1372		assert_eq!(
1373			catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
1374			Some(123),
1375			"the importer's config owns the rendition"
1376		);
1377	}
1378
1379	/// A resolved rendition still owns its name, now backed by a catalog entry.
1380	#[test]
1381	fn a_resolved_rendition_still_owns_its_name() {
1382		let (_broadcast, catalog, mut rendition) = video_track();
1383		rendition.set(config(Some(789), None)).unwrap();
1384
1385		assert!(
1386			catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
1387			"owned by the live rendition"
1388		);
1389		assert_eq!(
1390			catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
1391			Some(789),
1392			"the refused reservation left the rendition intact"
1393		);
1394	}
1395
1396	/// Ownership lasts exactly as long as the rendition, so the name is free again once it drops
1397	/// and the entry it published goes with it.
1398	#[test]
1399	fn dropping_a_rendition_frees_its_name() {
1400		let (_broadcast, catalog, mut rendition) = video_track();
1401		rendition.set(config(None, None)).unwrap();
1402		drop(rendition);
1403		assert!(
1404			catalog.snapshot().video.renditions.is_empty(),
1405			"the entry is retired with its owner"
1406		);
1407
1408		let mut replacement = catalog
1409			.reserve()
1410			.init::<hang::catalog::VideoConfig>("v")
1411			.expect("the name is free once the rendition drops");
1412		replacement.set(config(Some(456), None)).unwrap();
1413		assert_eq!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate, Some(456));
1414	}
1415
1416	/// Sections are independent maps, so a video rendition says nothing about the same name in
1417	/// audio.
1418	#[test]
1419	fn a_name_is_owned_per_section() {
1420		let (_broadcast, catalog, _video) = video_track();
1421		catalog
1422			.reserve()
1423			.init::<hang::catalog::AudioConfig>("v")
1424			.expect("an audio rendition is a different section from a video one");
1425	}
1426
1427	/// An entry already in the catalog is taken too, even with no rendition behind it: a caller
1428	/// that hand-wrote one through the guard still gets to keep it.
1429	#[test]
1430	fn an_existing_entry_owns_its_name() {
1431		let mut broadcast = moq_net::broadcast::Info::new().produce();
1432		let mut catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1433		catalog.edit().unwrap().video.insert("v", config(None, None)).unwrap();
1434
1435		assert!(
1436			catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
1437			"the catalog already carries it"
1438		);
1439	}
1440
1441	mod custom {
1442		use std::collections::BTreeMap;
1443
1444		use serde::{Deserialize, Serialize};
1445
1446		use super::*;
1447
1448		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1449		struct TelemetryExt {
1450			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1451			telemetry: BTreeMap<String, Telemetry>,
1452			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1453			exploding: BTreeMap<String, Exploding>,
1454			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1455			stubborn: BTreeMap<String, Stubborn>,
1456			#[serde(default, skip_serializing_if = "BTreeMap::is_empty", serialize_with = "at_most_one")]
1457			solo: BTreeMap<String, Solo>,
1458		}
1459
1460		/// Serialize a section that refuses to hold more than one entry, so whether it serializes
1461		/// depends on every entry, not just the one being written.
1462		fn at_most_one<S: serde::Serializer>(solo: &BTreeMap<String, Solo>, serializer: S) -> Result<S::Ok, S::Error> {
1463			if solo.len() > 1 {
1464				return Err(serde::ser::Error::custom("only one solo entry"));
1465			}
1466			solo.serialize(serializer)
1467		}
1468
1469		impl CatalogExt for TelemetryExt {}
1470
1471		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1472		struct Telemetry {
1473			schema: String,
1474			#[serde(default, skip_serializing_if = "Option::is_none")]
1475			bitrate: Option<u64>,
1476		}
1477
1478		impl RenditionConfig<TelemetryExt> for Telemetry {
1479			fn detects() -> bool {
1480				true
1481			}
1482
1483			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1484				catalog.ext.telemetry.insert(name.to_string(), self);
1485			}
1486			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1487				catalog.ext.telemetry.get_mut(name)
1488			}
1489			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1490				catalog.ext.telemetry.remove(name);
1491			}
1492
1493			// Opts into bitrate detection only; jitter is left undetected.
1494			fn estimate(&self) -> Estimate {
1495				Estimate::default().with_bitrate(self.bitrate)
1496			}
1497			fn set_estimate(&mut self, estimate: Estimate) {
1498				self.bitrate = estimate.bitrate;
1499			}
1500		}
1501
1502		fn telemetry(bitrate: Option<u64>) -> Telemetry {
1503			Telemetry {
1504				schema: "gps/v1".to_string(),
1505				bitrate,
1506			}
1507		}
1508
1509		fn produce() -> (moq_net::broadcast::Producer, crate::catalog::Producer<TelemetryExt>) {
1510			let mut broadcast = moq_net::broadcast::Info::new().produce();
1511			let config = crate::catalog::Config::default().with_catalog(Catalog::<TelemetryExt>::default());
1512			let catalog = crate::catalog::Producer::new(&mut broadcast, config).unwrap();
1513			(broadcast, catalog)
1514		}
1515
1516		/// A config whose `insert` panics, to poison the catalog lock the way any third-party
1517		/// [`RenditionConfig`] can: `set` runs it while holding that lock.
1518		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1519		struct Exploding {
1520			/// Write the entry before panicking, leaving a partially applied config behind.
1521			wrote: bool,
1522		}
1523
1524		impl RenditionConfig<TelemetryExt> for Exploding {
1525			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1526				if self.wrote {
1527					catalog.ext.exploding.insert(name.to_string(), self);
1528				}
1529				panic!("insert exploded");
1530			}
1531			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1532				catalog.ext.exploding.get_mut(name)
1533			}
1534			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1535				catalog.ext.exploding.remove(name);
1536			}
1537		}
1538
1539		/// A panicking `insert` poisons the catalog lock while `set` holds it. The producer has to
1540		/// survive that: an unwinding `Rendition::drop` takes the same lock to release its name, and
1541		/// a panic there would be a panic during a panic, which aborts the process rather than
1542		/// failing a test.
1543		#[test]
1544		fn a_poisoned_lock_does_not_take_the_producer_down() {
1545			let (_broadcast, catalog) = produce();
1546			let reserved = catalog.reserve();
1547
1548			let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1549				let mut boom = reserved.init::<Exploding>("gps").unwrap();
1550				boom.set(Exploding { wrote: false }).unwrap();
1551			}))
1552			.expect_err("the config's insert panics");
1553			assert!(
1554				err.downcast_ref::<&str>().is_some_and(|msg| *msg == "insert exploded"),
1555				"the panic is the one the config raised, not a lock failure"
1556			);
1557
1558			// The rendition unwound, so it released its name and the catalog is still usable.
1559			assert!(catalog.snapshot().ext.telemetry.is_empty());
1560			reserved
1561				.init::<Exploding>("gps")
1562				.expect("the unwound rendition released its name");
1563		}
1564
1565		/// A config whose cleanup hook panics after mutating, the other half of untrusted caller code:
1566		/// `Drop` runs `remove` while holding the catalog lock.
1567		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1568		struct Stubborn;
1569
1570		impl RenditionConfig<TelemetryExt> for Stubborn {
1571			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1572				catalog.ext.stubborn.insert(name.to_string(), self);
1573			}
1574			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1575				catalog.ext.stubborn.get_mut(name)
1576			}
1577			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1578				catalog.ext.stubborn.remove(name);
1579				panic!("remove exploded");
1580			}
1581		}
1582
1583		/// A panicking `remove` must not cost the rendition its name. The name is released before any
1584		/// caller code runs, so the slot is reservable again even though the hook blew up on the way
1585		/// out.
1586		#[test]
1587		fn a_panicking_remove_still_frees_the_name() {
1588			let (_broadcast, catalog) = produce();
1589			let reserved = catalog.reserve();
1590
1591			let mut rendition = reserved.init::<Stubborn>("gps").unwrap();
1592			rendition.set(Stubborn).unwrap();
1593
1594			std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(rendition)))
1595				.expect_err("the config's remove panics");
1596
1597			reserved
1598				.init::<Stubborn>("gps")
1599				.expect("a name held by a blown-up cleanup hook would be lost forever");
1600		}
1601
1602		/// An insert that writes and then panics must leave no entry behind or strand its name.
1603		#[test]
1604		fn an_unwinding_rendition_retires_a_partially_written_entry() {
1605			let (_broadcast, catalog) = produce();
1606			let reserved = catalog.reserve();
1607
1608			std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1609				let mut boom = reserved.init::<Exploding>("gps").unwrap();
1610				boom.set(Exploding { wrote: true }).unwrap();
1611			}))
1612			.expect_err("the config's insert panics after writing");
1613
1614			assert!(
1615				catalog.snapshot().ext.exploding.is_empty(),
1616				"the entry the panicking insert wrote is retired with its owner"
1617			);
1618			reserved
1619				.init::<Exploding>("gps")
1620				.expect("a stranded entry would refuse this forever");
1621		}
1622
1623		/// A config whose section serializes only while it holds a single entry.
1624		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1625		struct Solo;
1626
1627		impl RenditionConfig<TelemetryExt> for Solo {
1628			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1629				catalog.ext.solo.insert(name.to_string(), self);
1630			}
1631			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1632				catalog.ext.solo.get_mut(name)
1633			}
1634			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1635				catalog.ext.solo.remove(name);
1636			}
1637		}
1638
1639		/// An entry that serializes alone but not beside the extension's other entries is refused
1640		/// before the catalog retains it.
1641		#[test]
1642		fn an_entry_that_breaks_the_extension_is_refused() {
1643			let (_broadcast, catalog) = produce();
1644			let reserved = catalog.reserve();
1645			let mut first = reserved.init::<Solo>("a").unwrap();
1646			let mut second = reserved.init::<Solo>("b").unwrap();
1647
1648			first.set(Solo).unwrap();
1649			assert!(
1650				matches!(second.set(Solo), Err(crate::Error::Json(_))),
1651				"the second entry makes the extension unserializable"
1652			);
1653
1654			let snapshot = catalog.snapshot();
1655			assert_eq!(snapshot.ext.solo.keys().collect::<Vec<_>>(), ["a"]);
1656			serde_json::to_string(&snapshot).expect("the refused edit left the catalog serializable");
1657		}
1658
1659		/// A custom kind gets the same detection and drop-removal as video/audio.
1660		#[test]
1661		fn detects_and_advertises() {
1662			let (_broadcast, catalog) = produce();
1663			let reserved = catalog.reserve();
1664			let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
1665			drop(reserved);
1666
1667			rendition.set(telemetry(None)).unwrap();
1668			feed(&mut rendition);
1669
1670			let snapshot = catalog.snapshot();
1671			let config = snapshot.ext.telemetry.get("gps").unwrap();
1672			assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");
1673
1674			drop(rendition);
1675			assert!(
1676				!catalog.snapshot().ext.telemetry.contains_key("gps"),
1677				"the rendition should be removed on drop"
1678			);
1679		}
1680
1681		/// The whole point of opting in: write a custom track through a
1682		/// [`container::Producer`](crate::container::Producer) and its catalog bitrate/jitter keep
1683		/// themselves current, with no per-frame bookkeeping in the caller.
1684		#[test]
1685		fn measures_a_custom_track() {
1686			let (broadcast, catalog) = produce();
1687			let reserved = catalog.reserve();
1688			let net = broadcast.create_track("gps", timed()).unwrap();
1689			let mut track = reserved
1690				.track(
1691					net,
1692					crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
1693					None,
1694				)
1695				.unwrap();
1696			drop(reserved);
1697			assert!(matches!(track.modify(), Err(crate::Error::NotPublished)));
1698			track.set(telemetry(None)).unwrap();
1699
1700			// 40ms records of 5 kB: 1 Mbps, over more than the bitrate window.
1701			for i in 0..60u64 {
1702				track
1703					.write(crate::container::Frame {
1704						timestamp: ts(i * 40_000),
1705						decode: None,
1706						duration: None,
1707						payload: bytes::Bytes::from(vec![0u8; 5_000]),
1708						keyframe: true,
1709					})
1710					.unwrap();
1711			}
1712
1713			let snapshot = catalog.snapshot();
1714			let config = snapshot.ext.telemetry.get("gps").unwrap();
1715			assert_eq!(config.bitrate, Some(1_000_000));
1716		}
1717
1718		/// A field the config supplies is authoritative even though the kind opts into detection.
1719		#[test]
1720		fn keeps_supplied_bitrate() {
1721			let (_broadcast, catalog) = produce();
1722			let reserved = catalog.reserve();
1723			let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
1724			drop(reserved);
1725
1726			rendition.set(telemetry(Some(4_200))).unwrap();
1727			feed(&mut rendition);
1728
1729			let snapshot = catalog.snapshot();
1730			assert_eq!(snapshot.ext.telemetry.get("gps").unwrap().bitrate, Some(4_200));
1731		}
1732
1733		/// Custom and media renditions share one reservation gate, so the first snapshot carries both.
1734		#[test]
1735		fn gates_with_media_tracks() {
1736			let (_broadcast, catalog) = produce();
1737			let mut consumer = catalog.consume().unwrap();
1738
1739			let reserved = catalog.reserve();
1740			let mut video = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
1741			let mut gps = reserved.init::<Telemetry>("gps").unwrap();
1742			drop(reserved);
1743
1744			let waiter = kio::Waiter::noop();
1745			video.set(config(None, None)).unwrap();
1746			assert!(
1747				matches!(consumer.poll_next(&waiter), std::task::Poll::Pending),
1748				"the catalog stays withheld while the telemetry rendition is unresolved"
1749			);
1750
1751			gps.set(telemetry(None)).unwrap();
1752
1753			let mut latest = None;
1754			while let std::task::Poll::Ready(Ok(Some(catalog))) = consumer.poll_next(&waiter) {
1755				latest = Some(catalog.value);
1756			}
1757			let published = latest.expect("catalog published");
1758			assert!(published.video.renditions.contains_key("v"));
1759			assert!(published.ext.telemetry.contains_key("gps"));
1760		}
1761	}
1762}