Skip to main content

moq_mux/catalog/
producer.rs

1use moq_net::frame::Frame;
2use std::collections::hash_map::Entry;
3use std::collections::{BTreeMap, HashMap};
4use std::ops::{Deref, DerefMut};
5use std::sync::{Arc, Mutex, MutexGuard};
6
7use base64::Engine;
8use hang::catalog::Reference;
9
10use super::hang::{Catalog, CatalogExt, Consumer, Extra};
11
12/// Everything a catalog producer shares with its clones, under one lock.
13///
14/// One lock rather than one per concern. A name check only means anything if the catalog can't
15/// change under it: split those and two reservations of the same name both pass, which is the state
16/// that let one rendition's entry be written over and deleted by the other. Keeping the publish
17/// gate here too means a [`Guard`] never has to take a second lock while holding this one.
18struct State<E: CatalogExt> {
19	catalog: Catalog<E>,
20
21	/// The names live renditions hold, keyed by section (the [`RenditionConfig`](super::RenditionConfig)
22	/// type) and name. The section is part of the key because each writes a disjoint map: `video["v"]`
23	/// and `audio["v"]` are different renditions and neither says anything about the other. The
24	/// value is whether the rendition's config is listed, since a lazily-configured one holds its
25	/// name long before it has an entry.
26	owned: BTreeMap<(std::any::TypeId, String), bool>,
27
28	/// Reports whether the extension lists a track of its own, registered by an importer that
29	/// records tracks there (see [`Producer::count_ext_tracks`]).
30	ext_tracks: Option<fn(&mut E) -> bool>,
31
32	/// Gates the initial catalog publish until all reservations resolve (see
33	/// [`reserve`](Producer::reserve)).
34	gate: Gate,
35
36	/// Why the catalog tracks are closed, so [`Producer::modify`] refuses further edits with the
37	/// cause: [`Producer::finish`], [`Producer::abort`], or a failed drop-time publish.
38	closed: Option<crate::Error>,
39
40	/// The broadcast's shared clock, advertised as the catalog's `sync.clock`. Every importer on this
41	/// catalog reads it (the same timeline), so timestamps they synthesize when a caller has none
42	/// land on one timeline and audio/video stay in sync.
43	clock: crate::Clock,
44
45	/// Whether the clock's mapping is fixed: by [`Config::with_clock`], by an importer's first
46	/// frame placing it, by [`Producer::clock`] handing it out, or by the first publish putting it
47	/// on the wire. Until then an importer's first frame may still place it; after, every
48	/// importer offsets onto it instead.
49	anchored: bool,
50
51	/// Holds estimate-driven publishes to one per [`ESTIMATE_WINDOW`].
52	estimates: Throttle,
53
54	/// The last revision [`Producer::fresh_track`] handed out per base name, so a successor never
55	/// reuses a name.
56	revisions: std::collections::HashMap<String, u64>,
57
58	/// What the MSF catalog declares.
59	msf: Msf<E>,
60}
61
62impl<E: CatalogExt> State<E> {
63	/// Whether a buffering gate opens now: no reservation is outstanding and the catalog lists a
64	/// track. The track scan runs last, so releasing each of many reservations stays linear.
65	fn gate_opens(&mut self) -> bool {
66		matches!(self.gate, Gate::Buffering { reservers: 0, .. }) && self.lists_track()
67	}
68
69	/// Whether the catalog names anything this broadcast can serve, which the initial publish
70	/// waits for.
71	///
72	/// Root metadata and application sections can describe a stream before its media config is
73	/// known, and must not make an empty broadcast discoverable. A disabled video or audio rendition
74	/// promises no frames, so it doesn't count. A listed rendition covers application-defined
75	/// sections the base fields can't see, and an importer that lists tracks in the extension
76	/// reports them through [`ext_tracks`](Self::ext_tracks).
77	fn lists_track(&mut self) -> bool {
78		use std::any::TypeId;
79		// Video and audio carry `enabled`, which only the base check reads.
80		let base = [
81			TypeId::of::<hang::catalog::VideoConfig>(),
82			TypeId::of::<hang::catalog::AudioConfig>(),
83		];
84		let catalog = &mut self.catalog;
85		catalog.video.enabled().next().is_some()
86			|| catalog.audio.enabled().next().is_some()
87			|| !catalog.text.renditions.is_empty()
88			|| !catalog.json.tracks.is_empty()
89			|| !catalog.binary.tracks.is_empty()
90			|| self.ext_tracks.is_some_and(|lists| lists(&mut catalog.ext))
91			|| self.owned.iter().any(|((ty, _), &listed)| listed && !base.contains(ty))
92	}
93}
94
95/// How often a rising `jitter` or `delay` estimate may republish the catalog. Each republish makes
96/// every viewer update every media subscription, and an overloaded publisher's estimate rises a
97/// millisecond at a time.
98const ESTIMATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(1);
99
100/// The window an estimate-driven publish opens (see [`Guard::commit_estimate`]).
101///
102/// No timer: a held estimate goes out on the first observation after the window ends, so the
103/// catalog needs no runtime. If media stops, so does the estimate it would carry.
104#[derive(Default)]
105struct Throttle {
106	/// When the last publish carrying an estimate went out.
107	last: Option<kio::clock::Instant>,
108	/// An estimate is in the catalog but not yet on the wire.
109	pending: bool,
110}
111
112impl Throttle {
113	/// A publish is going out: any held estimate rides it and opens a new window.
114	fn fold(&mut self) {
115		if std::mem::take(&mut self.pending) {
116			self.last = Some(kio::clock::now());
117		}
118	}
119}
120
121/// The MSF catalog's publish state.
122///
123/// MSF declares only the estimates a publisher hinted, never measured ones: a demand-driven
124/// publisher measures nothing until a viewer subscribes, and an MSF viewer finds its tracks only
125/// through this catalog. MSF-01 ยง5.3 fixes a declared track's attributes, so each track keeps the
126/// estimates it was first declared with, and the MSF catalog changes only when the track list or a
127/// track's identity does. The hang catalog keeps updating its estimates in place.
128struct Msf<E: CatalogExt> {
129	/// The hinted estimates of each listed rendition that measures its own, keyed like
130	/// [`State::owned`]. MSF declares these in place of what the catalog carries.
131	hints: HashMap<(std::any::TypeId, String), Hint<E>>,
132	/// The estimates each MSF track was first declared with, by namespace and name.
133	declared: HashMap<(Option<String>, String), Declared>,
134	/// The last MSF catalog written, so an identical one isn't written again.
135	last: Option<String>,
136}
137
138impl<E: CatalogExt> Default for Msf<E> {
139	fn default() -> Self {
140		Self {
141			hints: HashMap::new(),
142			declared: HashMap::new(),
143			last: None,
144		}
145	}
146}
147
148/// A rendition's hinted estimates, and how to write them into its config.
149struct Hint<E: CatalogExt> {
150	estimate: super::Estimate,
151	apply: fn(&mut Catalog<E>, &str, super::Estimate),
152}
153
154impl<E: CatalogExt> Msf<E> {
155	/// The MSF catalog to write for `catalog`, or `None` when it matches the last one written.
156	fn render(&mut self, catalog: &Catalog<E>, base: &moq_net::Path) -> crate::Result<Option<String>> {
157		let mut msf = if self.hints.is_empty() {
158			to_msf(catalog, base)
159		} else {
160			let mut hinted = catalog.clone();
161			for ((_, name), hint) in &self.hints {
162				(hint.apply)(&mut hinted, name, hint.estimate.clone());
163			}
164			to_msf(&hinted, base)
165		};
166		// Rebuilt from the listed tracks, so a removed track's declaration goes with it.
167		let mut declared = HashMap::with_capacity(msf.tracks.len());
168		for track in &mut msf.tracks {
169			let key = (track.namespace.clone(), track.name.clone());
170			let first = self.declared.remove(&key).unwrap_or_else(|| Declared::of(track));
171			first.apply(track);
172			declared.insert(key, first);
173		}
174		self.declared = declared;
175
176		// The MSF catalog is derived from our own types, so a serialize failure means an extension
177		// broke the shape; report it like any other JSON failure rather than panicking.
178		let json = msf.to_json().map_err(moq_json::Error::from)?;
179		if self.last.as_ref() == Some(&json) {
180			return Ok(None);
181		}
182		self.last = Some(json.clone());
183		Ok(Some(json))
184	}
185}
186
187/// Write `estimate` over the estimates of the `C` config under `name`.
188fn apply_hint<E: CatalogExt, C: super::RenditionConfig<E>>(
189	catalog: &mut Catalog<E>,
190	name: &str,
191	estimate: super::Estimate,
192) {
193	if let Some(config) = C::get_mut(catalog, name) {
194		config.set_estimate(estimate);
195	}
196}
197
198/// The estimated fields an MSF track was first declared with.
199struct Declared {
200	bitrate: Option<u64>,
201	framerate: Option<f64>,
202	jitter: Option<std::time::Duration>,
203	delay: Option<std::time::Duration>,
204}
205
206impl Declared {
207	fn of(track: &moq_msf::Track) -> Self {
208		Self {
209			bitrate: track.bitrate,
210			framerate: track.framerate,
211			jitter: track.jitter,
212			delay: track.delay,
213		}
214	}
215
216	fn apply(&self, track: &mut moq_msf::Track) {
217		track.bitrate = self.bitrate;
218		track.framerate = self.framerate;
219		track.jitter = self.jitter;
220		track.delay = self.delay;
221	}
222}
223
224/// The producer's `clock` re-based on a `sync.clock` of `advertised`, or `None` when that is the
225/// mapping it already has. A changed mapping is adopted while nothing has `anchored` the clock and
226/// refused once something has. Clearing it is a change like any other: a derivative of a source with
227/// no `sync.clock` advertises none rather than a host wall clock the source never had.
228fn adopt(
229	clock: &crate::Clock,
230	anchored: bool,
231	advertised: Option<hang::catalog::Clock>,
232) -> crate::Result<Option<crate::Clock>> {
233	if advertised == clock.wall() {
234		return Ok(None);
235	}
236	let refuse = |why: &str| crate::Error::UnmappableTimestamp(format!("media clock {advertised:?} {why}"));
237	let wall = advertised.map(crate::Clock::exact).transpose()?;
238	// The same mapping in other units needs no host time, which may be unset or behind PTS zero.
239	if wall == clock.wall() {
240		return Ok(None);
241	}
242	if anchored {
243		return Err(refuse("changes the producer's clock after it was fixed"));
244	}
245	Ok(Some(match wall {
246		Some(wall) => clock.adopted(wall)?,
247		None => clock.unmapped(),
248	}))
249}
250
251/// `at` on clock `from` moved onto clock `to`, a re-basing of it: shifted by what separates their
252/// readings at one instant, so it names the same moment. Needs no wall mapping, which a clock placed
253/// on arrival without a host wall clock lacks.
254///
255/// A moment before `to`'s PTS zero, such as a change staged before the first frame placed the clock
256/// there, lands at zero: the earliest it can name, still in effect from the first frame on.
257fn restamp(from: &crate::Clock, to: &crate::Clock, at: moq_net::Timestamp) -> crate::Result<moq_net::Timestamp> {
258	Ok(shifted(from, to, at)?.unwrap_or(moq_net::Timestamp::ZERO))
259}
260
261/// `at` on clock `from` moved onto clock `to`, or `None` when it lands before `to`'s PTS zero.
262fn shifted(
263	from: &crate::Clock,
264	to: &crate::Clock,
265	at: moq_net::Timestamp,
266) -> crate::Result<Option<moq_net::Timestamp>> {
267	// One timeline reads alike however it is mapped: two readings of it could only add jitter.
268	if from == to {
269		return Ok(Some(at));
270	}
271	// The clocks' own source, not the caller's: an anchor may run on another thread or runtime.
272	let now = from.instant();
273	let shift = to.capture(now)?.as_micros()? as i128 - from.capture(now)?.as_micros()? as i128;
274	let micros = at.as_micros()? as i128 + shift;
275	if micros < 0 {
276		return Ok(None);
277	}
278	let micros = u64::try_from(micros)
279		.map_err(|_| crate::Error::UnmappableTimestamp(format!("{at:?} lands past the re-based clock's range")))?;
280	Ok(Some(moq_net::Timestamp::from_micros(micros)?))
281}
282
283/// Take the shared state, ignoring a poisoned lock.
284///
285/// A panic under this lock comes from code we hand the catalog to: a [`RenditionConfig::insert`]
286/// implementation, or serializing an extension during a publish. Neither leaves the state
287/// inconsistent (at worst the catalog is missing an entry, while `owned` and `gate` still
288/// describe exactly what is live), so poisoning protects nothing here. It would only turn the next
289/// [`Rendition`](super::Rendition) drop into a panic during unwinding, which aborts the process.
290fn take<E: CatalogExt>(state: &Mutex<State<E>>) -> MutexGuard<'_, State<E>> {
291	state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
292}
293
294/// The key a rendition name is held under: its section (the config type) plus the name.
295fn owner_key<C: 'static>(name: &str) -> (std::any::TypeId, String) {
296	(std::any::TypeId::of::<C>(), name.to_string())
297}
298
299/// The initial-publish gate, tracking the [`Reserved`](super::Reserved) handles still outstanding.
300///
301/// A live `Reserved` counts as one reserver; a [`Rendition`](super::Rendition) holds its own
302/// `Reserved` clone until it's fulfilled (or dropped), so an unresolved rendition keeps the gate
303/// shut too. See [`Reserved`](super::Reserved).
304#[derive(Default)]
305enum Gate {
306	/// Nothing ever reserved: an incremental producer publishes as it goes.
307	#[default]
308	Unreserved,
309	/// An importer's catalog, withholding its initial snapshot until no reservation is outstanding
310	/// and it [lists a track](State::lists_track), so input that declares none never announces.
311	Buffering {
312		reservers: usize,
313		/// A catalog change was made while buffering and is awaiting the initial publish. Without
314		/// this we'd emit an empty snapshot when the gate opens on a catalog nobody ever touched.
315		pending: bool,
316		/// The timestamp the last staged change was given (see [`Producer::modify`]), or `None`
317		/// to stamp the initial publish when it goes out.
318		at: Option<moq_net::Timestamp>,
319	},
320	/// The initial snapshot went out: every change publishes.
321	Published,
322}
323
324/// The catalog tracks.
325struct Outputs<E: CatalogExt> {
326	hang: moq_json::snapshot::Producer<Catalog<E>>,
327	hang_track: moq_net::track::Producer,
328	msf_track: moq_net::track::Producer,
329	/// Keeps the broadcast open while the catalog is, so a publisher may hand its own handle to a
330	/// media producer and drop it.
331	broadcast: moq_net::broadcast::Producer,
332	/// How many groups the hang and MSF tracks each took, for tests to count publishes by: group
333	/// starts are timestamps.
334	#[cfg(test)]
335	published: Arc<[std::sync::atomic::AtomicU64; 2]>,
336}
337
338impl<E: CatalogExt> Clone for Outputs<E> {
339	fn clone(&self) -> Self {
340		Self {
341			hang: self.hang.clone(),
342			hang_track: self.hang_track.clone(),
343			msf_track: self.msf_track.clone(),
344			broadcast: self.broadcast.clone(),
345			#[cfg(test)]
346			published: self.published.clone(),
347		}
348	}
349}
350
351impl<E: CatalogExt> Outputs<E> {
352	/// `now`, or a unit past the last catalog on either track and past `floor` when it doesn't pass
353	/// them, so two changes landing in one unit of the tracks' timescale both publish.
354	fn next(&self, now: moq_net::Timestamp, floor: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
355		let mut at = now;
356		if let Some(floor) = floor {
357			let info = self.hang_track.info();
358			let floor = info.rescale(floor)?;
359			if info.rescale(at)?.value() <= floor.value() {
360				let scale = floor.scale().ok_or(moq_net::Error::TimestampMismatch)?;
361				let bumped = floor.value().checked_add(1).ok_or(moq_net::Error::TimestampMismatch)?;
362				at = moq_net::Timestamp::new(bumped, scale).map_err(|_| moq_net::Error::TimestampMismatch)?;
363			}
364		}
365		let (_, at) = crate::start::next(&self.hang_track, at)?;
366		Ok(crate::start::next(&self.msf_track, at)?.1)
367	}
368
369	/// Emit the catalog to hang and MSF, stamped `at` or else [`next`](Self::next) on `clock`. Neither writes a
370	/// catalog identical to its last.
371	fn emit(
372		&mut self,
373		catalog: &Catalog<E>,
374		msf: &mut Msf<E>,
375		clock: &crate::Clock,
376		at: Option<moq_net::Timestamp>,
377	) -> crate::Result<()> {
378		// Every consumer refuses a catalog that fails this, so refuse it before it reaches one.
379		catalog.check_renditions()?;
380		// The media timeline, so the catalog in effect at a media timestamp is the one stamped at or
381		// before it, whichever thread or runtime publishes. Each catalog starts a group on both
382		// tracks.
383		let at = match at {
384			// A caller's timestamp marks the frame the change takes effect at, so moving it would
385			// misplace the change: one that doesn't pass the last publish on either track is refused
386			// before either is written.
387			Some(at) => {
388				crate::start::after(&self.hang_track, at)?;
389				crate::start::after(&self.msf_track, at)?;
390				at
391			}
392			// An edit no caller times goes out now.
393			None => self.next(clock.now(), None)?,
394		};
395		// One snapshot per group while deltas are disabled.
396		#[cfg(test)]
397		let before = self.hang_track.largest();
398		self.hang.update(catalog, at)?;
399		#[cfg(test)]
400		if self.hang_track.largest() != before {
401			self.published[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
402		}
403
404		// `abort` below is what keeps the tracks consistent if this fails after the hang track was
405		// updated.
406		let Some(msf) = msf.render(catalog, &self.msf_track.broadcast().path)? else {
407			return Ok(());
408		};
409		let group = self.msf_track.append_group(Frame::new(at, msf))?;
410		#[cfg(test)]
411		self.published[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
412		group.finish()?;
413
414		Ok(())
415	}
416
417	/// Abort every catalog track after a publish nobody could return the error for.
418	///
419	/// The two tracks carry one catalog, so a failure part way through `emit` must not leave some
420	/// of them serving a newer catalog than the others. Consumers see the error instead.
421	fn abort(&mut self, err: &crate::Error) {
422		let reason = err.reason();
423		// Idempotent: a track that is already closed keeps its first reason.
424		let _ = self.hang.clone().abort(reason.clone());
425		let _ = self.msf_track.clone().abort(reason);
426	}
427}
428
429/// Produces both a hang and MSF catalog track for a broadcast.
430///
431/// Generic over the application extension `E` (defaulting to `()` for none). The catalog is a
432/// [`Catalog<E>`](super::hang::Catalog): `video`/`audio` are direct fields (`catalog.video`) and the
433/// extension is reachable through `catalog.ext` (for example, `catalog.ext.scte35`). Define an
434/// extension with [`CatalogExt`](super::hang::CatalogExt). The MSF track carries the same catalog:
435/// the media sections become MSF tracks and the extension's sections ride the MSF root.
436///
437/// The JSON catalog is updated when tracks are added/removed but is *not* automatically published.
438/// You'll have to call [`modify`](Self::modify) to update and publish the catalog.
439/// Both the hang (`catalog.json`) and MSF (`catalog`) tracks are published on drop of the guard.
440///
441/// The hang track is published through [`moq_json`], which currently emits one snapshot per
442/// group (deltas disabled). This routes catalog publishing through the JSON merge-patch helper
443/// so deltas can be enabled later without changing the wire format used today.
444pub struct Producer<E: CatalogExt = ()> {
445	outputs: Outputs<E>,
446
447	current: Arc<Mutex<State<E>>>,
448
449	/// Every media track's join interval, declared once as `sync.interval`.
450	intervals: super::interval::Intervals,
451	/// The max age of the media tracks minted under this catalog, or `None` for no publisher
452	/// limit. Fixed at construction, so every clone and every [`Reserved`](super::Reserved)
453	/// mints tracks under one policy. See [`Config::with_max_age`].
454	max_age: Option<std::time::Duration>,
455	/// Connection allocator passthrough tracks claim their peak-hold bitrate on.
456	/// See [`Config::with_bandwidth`].
457	bandwidth: moq_net::bandwidth::Allocator,
458	/// The write order across this catalog's renditions, which each rendition's advertised
459	/// `delay` is measured against.
460	order: super::estimate::Order,
461	/// What each media track minted under this catalog has written. See [`stats`](Self::stats).
462	sent: Arc<crate::stats::Registry<crate::stats::Sent>>,
463}
464
465// Manual Clone so a producer is cheaply clonable regardless of whether `E` is.
466impl<E: CatalogExt> Clone for Producer<E> {
467	fn clone(&self) -> Self {
468		Self {
469			outputs: self.outputs.clone(),
470			current: self.current.clone(),
471			intervals: self.intervals.clone(),
472			max_age: self.max_age,
473			bandwidth: self.bandwidth.clone(),
474			order: self.order.clone(),
475			sent: self.sent.clone(),
476		}
477	}
478}
479
480/// Everything a catalog [`Producer`] is built from: the initial catalog and any overrides.
481///
482/// Start from [`default`](Default::default), which is the media-only catalog with hang's own
483/// defaults, and chain the setters.
484///
485/// These are constructor arguments rather than setters on a live producer, so a clone or a
486/// [`Reserved`](super::Reserved) taken at any point mints tracks under the same policy.
487#[derive(Clone)]
488pub struct Config<E: CatalogExt = ()> {
489	catalog: Catalog<E>,
490	max_age: Option<std::time::Duration>,
491	bandwidth: moq_net::bandwidth::Allocator,
492	clock: Option<crate::Clock>,
493}
494
495impl Default for Config<()> {
496	fn default() -> Self {
497		Self {
498			catalog: Catalog::default(),
499			max_age: Some(hang::container::MAX_AGE),
500			bandwidth: moq_net::bandwidth::Allocator::unlimited(),
501			clock: None,
502		}
503	}
504}
505
506impl<E: CatalogExt> Config<E> {
507	/// Start from an extended catalog rather than the media-only one, e.g. the untyped
508	/// [`Extra`] for the by-name / FFI path. Set application sections through
509	/// [`Producer::modify`](Producer::modify) afterwards. A `sync.clock` in it is adopted, not
510	/// replaced (see [`Producer::new`]).
511	pub fn with_catalog<F: CatalogExt>(self, catalog: Catalog<F>) -> Config<F> {
512		Config {
513			catalog,
514			max_age: self.max_age,
515			bandwidth: self.bandwidth,
516			clock: self.clock,
517		}
518	}
519
520	/// Publish with this broadcast clock instead of a fresh one.
521	///
522	/// The clock's wall mapping is advertised as the catalog's `sync.clock` and fixed from the start, so
523	/// every container importer (fMP4, MPEG-TS, FLV, MKV) shifts its stream's timestamps onto it,
524	/// its first frame landing at the clock's reading on arrival. Without this, the catalog starts
525	/// a fresh clock, and the first importer to receive a frame before anything fixes the clock
526	/// places it there instead, keeping its own timestamps verbatim (see [`Timebase`](super::Timebase)).
527	///
528	/// The `sync.clock` is this clock: a derivative that only learns its input's mapping later
529	/// writes it through [`Producer::modify`] instead, before anything fixes the clock.
530	pub fn with_clock(mut self, clock: crate::Clock) -> Self {
531		self.clock = Some(clock);
532		self
533	}
534
535	/// Set how long a superseded group of the media tracks minted under this catalog stays
536	/// fresh, or `None` for no publisher limit. Defaults to
537	/// [`MAX_AGE`](hang::container::MAX_AGE).
538	///
539	/// That default suits a segmented egress (HLS/DASH), which may only advertise segments a
540	/// FETCH can still reach. Lower it when nothing reads history; raise it for a deeper seek
541	/// window. It is a freshness bound, not a delivery one, so it never makes a subscriber play
542	/// further behind live -- it caps what one may ask to wait for, and a subscriber's own
543	/// budget still defaults to zero.
544	///
545	/// Applies to the media tracks the catalog mints and to the catalog tracks themselves, so a
546	/// reader playing behind the live edge still receives each catalog update it holds until its
547	/// timestamp.
548	pub fn with_max_age(mut self, max_age: impl Into<Option<std::time::Duration>>) -> Self {
549		self.max_age = max_age.into();
550		self
551	}
552
553	/// Claim each media track's peak-hold catalog bitrate on `bandwidth`.
554	///
555	/// A passthrough import has no configured ceiling, so it reserves the
556	/// measured maximum instead: taken on the first 1 s window, raised when a
557	/// later window exceeds it, never walked back. A co-resident encoder then
558	/// targets what is left of the uplink. `unlimited` (the default) claims
559	/// nothing a sender can follow.
560	pub fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self {
561		self.bandwidth = bandwidth;
562		self
563	}
564}
565
566impl<E: CatalogExt> Producer<E> {
567	/// Create a new catalog producer from a full [`Config`].
568	///
569	/// A `sync.clock` seeded through [`Config::with_catalog`] is adopted under the same rules as
570	/// [`modify`](Self::modify): the producer runs on it, unless [`Config::with_clock`] fixed a
571	/// different mapping, which is refused.
572	pub fn new(broadcast: &mut moq_net::broadcast::Producer, config: Config<E>) -> crate::Result<Self> {
573		// The broadcast clock is advertised as `sync.clock` from the first snapshot. A host with an
574		// unset wall clock advertises none.
575		// Resolved before any track exists, so a refused seed leaves the broadcast untouched.
576		let anchored = config.clock.is_some();
577		let mut catalog = config.catalog;
578		// An unseeded catalog runs on the configured clock, or a fresh one.
579		let clock = config.clock.unwrap_or_default();
580		let clock = match catalog.sync.clock {
581			None => clock,
582			seeded => adopt(&clock, anchored, seeded)?.unwrap_or(clock),
583		};
584		catalog.sync.clock = clock.wall();
585
586		// Compressed, as `default_track_info` sets: catalog JSON is small and repetitive. Fresh as
587		// long as the media, so a reader as far behind holds each update until its timestamp.
588		let info = hang::Catalog::default_track_info().with_max_age(config.max_age);
589		let hang_track = broadcast
590			.create_track(hang::Catalog::DEFAULT_NAME, info.clone())
591			.ok_or_else(|| hang::Error::Duplicate(hang::Catalog::DEFAULT_NAME.to_string()))?;
592		// The MSF track is the same catalog in another encoding, so it takes the same
593		// priority. Leaving it at the default would rank a subscriber reading MSF
594		// below every media track on a relay's upstream leg. It stays uncompressed: MSF is
595		// read by other implementations, which hang's compression decisions don't cover.
596		let msf_info = info.with_compression(moq_net::track::Compression::None);
597		let msf_track = broadcast
598			.create_track(moq_msf::DEFAULT_NAME, msf_info)
599			.ok_or_else(|| hang::Error::Duplicate(moq_msf::DEFAULT_NAME.to_string()))?;
600
601		// Disable deltas for now to stay byte-compatible with consumers that only read snapshots.
602		let json_config = moq_json::snapshot::Config::default().with_deltas(false);
603		let hang = moq_json::snapshot::Producer::new(hang_track.clone(), json_config);
604
605		Ok(Self {
606			outputs: Outputs {
607				hang,
608				hang_track,
609				msf_track,
610				broadcast: broadcast.clone(),
611				#[cfg(test)]
612				published: Arc::default(),
613			},
614			current: Arc::new(Mutex::new(State {
615				catalog,
616				owned: BTreeMap::new(),
617				ext_tracks: None,
618				gate: Gate::default(),
619				closed: None,
620				clock,
621				anchored,
622				estimates: Throttle::default(),
623				revisions: Default::default(),
624				msf: Msf::default(),
625			})),
626			intervals: Default::default(),
627			max_age: config.max_age,
628			bandwidth: config.bandwidth,
629			order: Default::default(),
630			sent: Default::default(),
631		})
632	}
633
634	/// Track properties for a media track under this catalog: hang's media defaults, with the
635	/// [`Config::with_max_age`] policy.
636	///
637	/// `priority` should come from [`PRIORITY`](hang::catalog::PRIORITY) for the kind of media
638	/// the track carries. Chain [`with_timescale`](moq_net::track::Info::with_timescale) for a
639	/// container that carries the source's own scale (CMAF and Matroska both do).
640	pub fn track_info(&self, priority: i8) -> moq_net::track::Info {
641		hang::container::track_info(priority).with_max_age(self.max_age)
642	}
643
644	/// Resolve a timestamp, synthesizing one from the broadcast's shared
645	/// [`Clock`](crate::Clock) when the caller has none.
646	///
647	/// Sharing the clock across the catalog's tracks keeps concurrently-produced
648	/// audio and video on a single timeline.
649	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
650		match hint {
651			Some(pts) => Ok(pts),
652			None => Ok(self.clock().now()),
653		}
654	}
655
656	/// Edit the catalog in place and publish the result.
657	///
658	/// The closure receives the current catalog, composed from every owner so far. Edit it in place;
659	/// on return the result is published, a no-op if the closure changed nothing. Independent owners
660	/// can each edit only their own sections, so they compose instead of clobbering one another.
661	///
662	/// This is [`modify`](Self::modify) opened at `timestamp` and committed for you; take the guard
663	/// to hold the lock across several edits, or to reach a [`Guard`] method like
664	/// [`set_section`](Guard::set_section).
665	pub fn mutate(&mut self, f: impl FnOnce(&mut Catalog<E>), timestamp: moq_net::Timestamp) -> crate::Result<()> {
666		let mut guard = self.modify(timestamp)?;
667		f(&mut guard);
668		guard.commit()
669	}
670
671	/// Get mutable access to the catalog, publishing it after any changes stamped at `timestamp`.
672	///
673	/// A catalog is a timed track like any media track, so the caller says when the change takes
674	/// effect on the producer's [`clock`](Self::clock): the timestamp of the frame it happens at, or
675	/// [`next_timestamp`](Self::next_timestamp) for a change no frame times. Fails with
676	/// [`TimestampRewind`](crate::container::TimestampRewind) before any edit unless `timestamp` is
677	/// past the last published catalog's, or the stamp of a change still waiting on the initial
678	/// publish; batch the edits at one frame into one guard. An edit that re-bases the clock by
679	/// writing `sync.clock` is stamped on the clock it adopts, unmoved: a derivative times it on its
680	/// input's timeline, the one it republishes. Don't stamp such an edit with
681	/// [`next_timestamp`](Self::next_timestamp), which reads the clock it replaces. So while a change
682	/// waits on the initial publish and nothing has fixed the clock, the guard checks its timestamp
683	/// when it publishes instead, against that change's stamp moved onto the clock the edit leaves. A
684	/// rewind there discards the edit, leaving the catalog and clock as they were: [`Guard::commit`]
685	/// returns it, and a drop logs it with the tracks left open. A guard with no edit publishes
686	/// nothing, so it checks nothing then.
687	///
688	/// The publish happens when the returned [`Guard`] drops. Use [`mutate`](Self::mutate) for a
689	/// single edit, which is this guard opened and committed for you. Fails once the catalog tracks
690	/// are closed, the one publication failure that happens in normal operation, so nothing is left
691	/// to check after the guard drops. Anything else that stops the drop from publishing (an extension
692	/// that won't serialize, a catalog too large for a frame) aborts the catalog tracks with that
693	/// error: consumers see it instead of a stale catalog, and the next `modify` returns it here.
694	/// Call [`Guard::commit`] to get the error back immediately instead.
695	///
696	/// The in-memory catalog is already mutated, so a panic while the guard is held still
697	/// publishes: skipping would leave `snapshot` ahead of the wire with no dirty flag to catch up.
698	///
699	/// The `sync.clock` is the producer's [`clock`](Self::clock). Writing a different one re-bases
700	/// the clock on it until something fixes the clock ([`Config::with_clock`], taking
701	/// [`clock`](Self::clock), an importer's first frame, or the first publish), so a derivative
702	/// adopts its input's mapping, or the lack of one. After that a changed `clock` is refused; writing
703	/// the same mapping again is no change. Writes through
704	/// [`Reserved::video`](super::Reserved::video) and the codec producers keep their timestamps
705	/// verbatim, so they mean something only under the mapping they were written for.
706	pub fn modify(&mut self, timestamp: moq_net::Timestamp) -> crate::Result<Guard<'_, E>> {
707		let mut guard = self.edit()?;
708		guard.stamp(timestamp)?;
709		Ok(guard)
710	}
711
712	/// A timestamp for a change no frame times: the producer's [`clock`](Self::clock) now, or a unit
713	/// past the last catalog when the clock hasn't passed it, so two changes in one millisecond both
714	/// publish. Another thread's publish between this and [`modify`](Self::modify) can still pass it,
715	/// such as an importer's estimate racing a binding's section edit: `modify` then returns
716	/// [`TimestampRewind`](crate::container::TimestampRewind) and the catalog is unchanged. That
717	/// window is accepted over an edit that picks its own timestamp, since every caller states when
718	/// its change takes effect. While the initial publish is buffering on a clock nothing fixed, the
719	/// refusal comes from [`Guard::commit`] instead, as [`modify`](Self::modify) describes.
720	pub fn next_timestamp(&self) -> moq_net::Timestamp {
721		let state = take(&self.current);
722		let now = state.clock.now();
723		let floor = match state.gate {
724			Gate::Buffering { at, .. } => at,
725			Gate::Unreserved | Gate::Published => None,
726		};
727		// Nothing past a scale-less or exhausted track: `modify` refuses it with the reason.
728		self.outputs.next(now, floor).unwrap_or(now)
729	}
730
731	/// The catalog for an edit no caller times, such as a rendition's config or a measured estimate,
732	/// published at [`next_timestamp`](Self::next_timestamp) under the lock.
733	pub(crate) fn edit(&mut self) -> crate::Result<Guard<'_, E>> {
734		let state = take(&self.current);
735		if let Some(err) = &state.closed {
736			return Err(err.clone());
737		}
738
739		Ok(Guard {
740			state,
741			outputs: &mut self.outputs,
742			updated: false,
743			stamp: Stamp::Unstamped,
744		})
745	}
746
747	/// Get a snapshot of the current catalog.
748	pub fn snapshot(&self) -> Catalog<E> {
749		take(&self.current).catalog.clone()
750	}
751
752	/// The broadcast's shared clock: the timeline producers stamp against and the wall mapping
753	/// advertised as the catalog's `sync.clock`.
754	///
755	/// Clones share the timeline, so handing them to concurrent producers keeps every track on
756	/// one clock. Taking the clock fixes it: an importer whose first frame arrives later shifts its
757	/// timestamps onto this clock rather than moving it, so a clone never goes stale.
758	pub fn clock(&self) -> crate::Clock {
759		let mut state = take(&self.current);
760		state.anchored = true;
761		state.clock.clone()
762	}
763
764	/// The clock as it stands, without fixing it: for readers that follow it on every use.
765	pub(super) fn current_clock(&self) -> crate::Clock {
766		take(&self.current).clock.clone()
767	}
768
769	/// The config `name` holds in `C`'s section, cloned without copying the rest of the catalog.
770	pub(super) fn config<C: super::RenditionConfig<E>>(&self, name: &str) -> Option<C> {
771		C::get_mut(&mut take(&self.current).catalog, name).cloned()
772	}
773
774	/// Anchor a timebase on its first timestamp `pts`, which happened at `wall` (or arrived now),
775	/// returning the timebase's offset.
776	///
777	/// A clock nothing has fixed yet is placed so `pts` lands at that instant, and the offset is
778	/// zero. A fixed one stays, and the offset shifts `pts` onto it. Either way the timebase keeps the
779	/// offset, so every later frame from any of its importers shifts alike.
780	pub(super) fn anchor(
781		&mut self,
782		timebase: &std::sync::OnceLock<super::Offset>,
783		pts: moq_net::Timestamp,
784		wall: Option<kio::clock::Wall>,
785	) -> crate::Result<super::Offset> {
786		let mut guard = self.edit()?;
787		// Another clone of the timebase may have anchored first; the lock orders them. A placement
788		// is refused then, since it would not land where it says.
789		if let Some(offset) = timebase.get() {
790			if wall.is_some() {
791				return Err(crate::Error::UnmappableTimestamp(
792					"the timebase already anchored on its first frame".to_string(),
793				));
794			}
795			return Ok(*offset);
796		}
797
798		let offset = if guard.state.anchored {
799			let clock = &guard.state.clock;
800			let at = match wall {
801				Some(wall) => clock.reading(wall)?,
802				None => clock.now().as_micros().expect("the broadcast clock is scaled") as i128,
803			};
804			super::Offset::from_micros(at - pts.as_micros()? as i128)?
805		} else {
806			let since = std::time::Duration::from_micros(u64::try_from(pts.as_micros()?).unwrap_or(u64::MAX));
807			// Moved, not replaced: it keeps reading the clock the broadcast was created under.
808			let clock = match wall {
809				Some(wall) => guard.state.clock.placed(since, wall)?,
810				None => guard.state.clock.arrival(since)?,
811			};
812			let advertised = clock.wall();
813			guard.retime(clock)?;
814			guard.state.anchored = true;
815			match wall {
816				// A placement can precede every track. It stages no publish, so the catalog first
817				// goes out listing them rather than carrying a clock alone.
818				Some(_) => guard.state.catalog.sync.clock = advertised,
819				None => guard.sync.clock = advertised,
820			}
821			super::Offset::default()
822		};
823
824		timebase.set(offset).expect("set under the catalog lock");
825		guard.commit()?;
826		Ok(offset)
827	}
828
829	/// A timestamp base for one source, shared by every importer reading it.
830	///
831	/// Hand it to each container importer with its `with_timebase`, or shift a source's timestamps
832	/// through it directly, so they all shift by one offset. See [`Timebase`](super::Timebase).
833	pub fn timebase(&self) -> super::Timebase<E> {
834		super::Timebase::new(self.clone())
835	}
836
837	/// Begin reserving the initial track set, returning a clonable [`Reserved`](super::Reserved).
838	///
839	/// Hand it (or clones) to importers, or call its role-specific track constructors. The catalog is
840	/// withheld until every reservation is dropped and every created producer either publishes its
841	/// config or drops, and after that until the catalog names a track. A one-shot muxer therefore
842	/// publishes the complete track list in its first snapshot instead of a half-converged one, and
843	/// input that declares no track publishes nothing. An application's extension track counts only
844	/// once a track constructor such as [`track`](Self::track) publishes it; one seeded or written
845	/// through [`modify`](Self::modify) is invisible to this check. Producers created directly on a
846	/// catalog that never reserved publish incrementally.
847	///
848	/// It only gates: timestamps written through it land verbatim on the catalog's clock (see
849	/// [`Timebase`](super::Timebase) for a source on a timeline of its own).
850	pub fn reserve(&self) -> super::Reserved<E> {
851		super::Reserved::new(self.clone())
852	}
853
854	/// Take a rendition name without withholding the catalog's initial snapshot.
855	///
856	/// Use this for a long-lived incremental producer whose config may arrive
857	/// later or never arrive. The returned handle owns the name immediately,
858	/// publishes the config on [`set`](super::Rendition::set), and retires it on
859	/// drop. Use [`reserve`](Self::reserve) when the initial catalog must wait for
860	/// the complete track set instead.
861	pub(super) fn rendition<C: super::RenditionConfig<E>>(
862		&self,
863		name: impl Into<String>,
864	) -> crate::Result<super::Rendition<E, C>> {
865		super::Rendition::live(self.clone(), name.into())
866	}
867
868	/// Publish a video track and own its catalog rendition.
869	pub fn video<C: crate::container::Container>(
870		&self,
871		track: moq_net::track::Producer,
872		container: C,
873		config: impl Into<Option<hang::catalog::VideoConfig>>,
874	) -> crate::Result<crate::container::Producer<C, hang::catalog::VideoConfig>>
875	where
876		crate::Error: From<C::Error>,
877	{
878		self.track(track, container, config)
879	}
880
881	/// Publish an audio track and own its catalog rendition.
882	pub fn audio<C: crate::container::Container>(
883		&self,
884		track: moq_net::track::Producer,
885		container: C,
886		config: impl Into<Option<hang::catalog::AudioConfig>>,
887	) -> crate::Result<crate::container::Producer<C, hang::catalog::AudioConfig>>
888	where
889		crate::Error: From<C::Error>,
890	{
891		self.track(track, container, config)
892	}
893
894	/// Publish a text track and own its catalog rendition.
895	pub fn text<C: crate::container::Container>(
896		&self,
897		track: moq_net::track::Producer,
898		container: C,
899		config: impl Into<Option<hang::catalog::TextConfig>>,
900	) -> crate::Result<crate::container::Producer<C, hang::catalog::TextConfig>>
901	where
902		crate::Error: From<C::Error>,
903	{
904		self.track(track, container, config)
905	}
906
907	/// Publish a track using a custom catalog config.
908	pub fn track<C, R>(
909		&self,
910		track: moq_net::track::Producer,
911		container: C,
912		config: impl Into<Option<R>>,
913	) -> crate::Result<crate::container::Producer<C, R>>
914	where
915		C: crate::container::Container,
916		R: super::RenditionConfig<E>,
917		crate::Error: From<C::Error>,
918	{
919		let rendition = self.rendition(track.name())?;
920		self.media(track, container, rendition, config.into(), None)
921	}
922
923	/// Count the tracks `lists` finds in the extension toward the initial publish's
924	/// [track requirement](State::lists_track), for an importer that records tracks there.
925	pub(crate) fn count_ext_tracks(&self, lists: fn(&mut E) -> bool) {
926		take(&self.current).ext_tracks = Some(lists);
927	}
928
929	/// Whether a live producer or published config already claims `name` in `R`'s section.
930	pub fn is_claimed<R: super::RenditionConfig<E>>(&self, name: &str) -> bool {
931		let mut state = take(&self.current);
932		R::get_mut(&mut state.catalog, name).is_some() || state.owned.contains_key(&owner_key::<R>(name))
933	}
934
935	/// Take `name` in `C`'s section for a new [`Rendition`](super::Rendition), which owns it until
936	/// the handle drops.
937	///
938	/// Errors if a live rendition already holds the name, or if the catalog already carries an entry
939	/// under it. That's what makes the rendition the only thing that writes or removes its own slot:
940	/// a lazily-configured importer (H.264 before its first SPS) has no catalog entry yet, and
941	/// without the name being held an outside write would land in the gap, be overwritten by
942	/// [`set`](super::Rendition::set), and then be deleted by the rendition's `Drop`.
943	pub(super) fn acquire<C: super::RenditionConfig<E>>(&self, name: &str) -> crate::Result<()> {
944		let mut state = take(&self.current);
945		let key = owner_key::<C>(name);
946		if C::get_mut(&mut state.catalog, name).is_some() || state.owned.contains_key(&key) {
947			return Err(hang::Error::Duplicate(name.to_string()).into());
948		}
949		state.owned.insert(key, false);
950		Ok(())
951	}
952
953	/// Register a live [`Reserved`](super::Reserved) handle.
954	pub(super) fn add_reserver(&self) {
955		let mut state = take(&self.current);
956		match &mut state.gate {
957			Gate::Unreserved => {
958				state.gate = Gate::Buffering {
959					reservers: 1,
960					pending: false,
961					at: None,
962				}
963			}
964			Gate::Buffering { reservers, .. } => *reservers += 1,
965			// Only the initial publish waits for reservations.
966			Gate::Published => {}
967		}
968	}
969
970	/// Drop a [`Reserved`](super::Reserved) handle, flushing the initial snapshot if that was the
971	/// last thing gating it and the catalog names a track.
972	pub(super) fn release_reserver(&mut self) {
973		{
974			let mut state = take(&self.current);
975			if let Gate::Buffering { reservers, .. } = &mut state.gate {
976				*reservers = reservers.saturating_sub(1);
977			}
978		}
979		self.flush_if_ready();
980	}
981
982	/// Publish the buffered snapshot once, if buffering has just finished with a change staged.
983	pub(super) fn flush_if_ready(&mut self) {
984		let mut state = take(&self.current);
985		// Nothing was staged (e.g. every stream was ignored): stay unpublished so a later change
986		// still triggers the first emit, rather than publishing an empty catalog now.
987		let Gate::Buffering { pending: true, at, .. } = state.gate else {
988			return;
989		};
990		if !state.gate_opens() {
991			return;
992		}
993		state.gate = Gate::Published;
994		// A snapshot on the wire is a mapping a reader may have copied.
995		state.anchored = true;
996		state.estimates.fold();
997		// Emitted under the lock, as a guard's publish is, since the MSF state belongs to it.
998		let state = &mut *state;
999		if let Err(err) = self.outputs.emit(&state.catalog, &mut state.msf, &state.clock, at) {
1000			tracing::error!(%err, "failed to publish the catalog, aborting its tracks");
1001			self.outputs.abort(&err);
1002			state.closed = Some(err);
1003		}
1004	}
1005
1006	/// Create the successor of track `name` under the next `<name>/<n>` this catalog has not
1007	/// handed out, for a rendition whose identity changed: a name always means the same content.
1008	///
1009	/// A successor's own successor counts on from the same base, so `v/1` is followed by `v/2`.
1010	pub(crate) fn fresh_track(&self, name: &str, info: moq_net::track::Info) -> moq_net::track::Producer {
1011		let mut state = take(&self.current);
1012		let base = match name.rsplit_once('/') {
1013			Some((base, n)) if n.parse::<u64>().is_ok() && state.revisions.contains_key(base) => base,
1014			_ => name,
1015		};
1016		let revision = state.revisions.entry(base.to_string()).or_default();
1017		loop {
1018			*revision += 1;
1019			// None when someone else published that name explicitly; try the next.
1020			if let Some(track) = self
1021				.outputs
1022				.broadcast
1023				.create_track(format!("{base}/{revision}"), info.clone())
1024			{
1025				return track;
1026			}
1027		}
1028	}
1029
1030	/// Build the media [`container::Producer`](crate::container::Producer) for `track`, joining a
1031	/// video or audio track to the broadcast's join interval with `interval`, its known longest group,
1032	/// or measuring it without one.
1033	pub(super) fn media<C, R>(
1034		&self,
1035		track: moq_net::track::Producer,
1036		container: C,
1037		rendition: super::Rendition<E, R>,
1038		config: Option<R>,
1039		interval: Option<std::time::Duration>,
1040	) -> crate::Result<crate::container::Producer<C, R>>
1041	where
1042		C: crate::container::Container,
1043		R: super::RenditionConfig<E>,
1044		crate::Error: From<C::Error>,
1045	{
1046		// Refused before the rendition publishes a config, so no consumer is told of a track whose
1047		// first write would fail.
1048		container.writable()?;
1049		// Only video and audio promise the interval: a sparse role (text) groups only as often as it
1050		// has something to say.
1051		let role = std::any::TypeId::of::<R>();
1052		let member = (role == std::any::TypeId::of::<hang::catalog::VideoConfig>()
1053			|| role == std::any::TypeId::of::<hang::catalog::AudioConfig>())
1054		.then(|| self.join(interval));
1055		let sent = self.sent(rendition.name());
1056		let mut producer = crate::container::Producer::with_rendition(track, container, rendition)
1057			.with_member(member)
1058			.with_bandwidth(self.bandwidth.clone())
1059			.with_sent(sent);
1060		if let Some(config) = config {
1061			producer.set(config)?;
1062		}
1063		Ok(producer)
1064	}
1065
1066	/// Build an internal container producer for a non-rendition catalog entry.
1067	pub(crate) fn media_raw<C>(
1068		&self,
1069		track: moq_net::track::Producer,
1070		container: C,
1071	) -> crate::Result<crate::container::Producer<C>>
1072	where
1073		C: crate::container::Container,
1074		crate::Error: From<C::Error>,
1075	{
1076		let sent = self.sent(track.name());
1077		Ok(crate::container::Producer::new(track, container)
1078			.with_bandwidth(self.bandwidth.clone())
1079			.with_sent(sent))
1080	}
1081
1082	/// The counters a track writing under catalog key `name` bumps, for one that writes its groups
1083	/// by hand rather than through a [`container::Producer`](crate::container::Producer).
1084	pub(crate) fn sent(&self, name: &str) -> Arc<crate::stats::Sent> {
1085		self.sent.track(name)
1086	}
1087
1088	/// What each media track minted under this catalog has written, keyed by its catalog key: the
1089	/// rendition ID, or the track name for a passthrough or verbatim `mpegts` track.
1090	///
1091	/// Counters are cumulative for the life of the catalog, so a track that ended keeps its final
1092	/// counts and a later track under the same key continues them, until 1,024 keys are held: then
1093	/// ended tracks make way for new ones. Fold this into a
1094	/// [`hang::stats::Snapshot`] on the stats interval.
1095	pub fn stats(&self) -> std::collections::BTreeMap<String, hang::stats::Rendition> {
1096		self.sent.sent()
1097	}
1098
1099	/// A fresh estimator whose `delay` is measured against this catalog's other renditions.
1100	pub(crate) fn estimator(&self) -> super::Estimator {
1101		super::Estimator::with_order(self.order.clone())
1102	}
1103
1104	/// The allocator passthrough tracks claim on. fMP4 writes groups by hand, so it reads this itself.
1105	pub(crate) fn bandwidth(&self) -> moq_net::bandwidth::Allocator {
1106		self.bandwidth.clone()
1107	}
1108
1109	/// Join a video or audio track to the broadcast's join interval with `interval`, its known
1110	/// longest group, or `None` to measure it. Once every member present has one, the largest is
1111	/// declared as `sync.interval`, unless the catalog already carries one.
1112	///
1113	/// The video and audio track constructors call this for you. fMP4 passthrough calls it directly
1114	/// because it writes groups by hand instead of using a [`container::Producer`](crate::container::Producer).
1115	pub(crate) fn join(&self, interval: Option<std::time::Duration>) -> super::interval::Member {
1116		let catalog = self.clone();
1117		self.intervals.join(
1118			interval,
1119			Box::new(move |interval| {
1120				let mut catalog = catalog.clone();
1121				let Ok(mut guard) = catalog.edit() else {
1122					return;
1123				};
1124				// The publisher's own declaration, seeded or written through `modify`, stands.
1125				if guard.sync.interval.is_some() {
1126					return;
1127				}
1128				guard.sync.interval = Some(interval);
1129				if let Err(err) = guard.commit() {
1130					tracing::error!(%err, "failed to publish the join interval");
1131				}
1132			}),
1133		)
1134	}
1135
1136	/// The join interval declared from the media tracks, once every one had its own.
1137	#[cfg(test)]
1138	pub(crate) fn declared_interval(&self) -> Option<std::time::Duration> {
1139		self.intervals.declared()
1140	}
1141
1142	/// Publish `track` as a latest-value JSON track, advertising it in the catalog.
1143	///
1144	/// The caller creates the track on the broadcast, as it does for a media track; this writes its
1145	/// catalog entry and removes the entry when the returned handle drops. The catalog key is
1146	/// [`track.name()`](moq_net::track::Producer::name) verbatim. Create `track` with a
1147	/// [`timescale`](moq_net::track::Info::timescale), since every write is stamped on the
1148	/// broadcast clock, and with [`compression`](moq_net::track::Info::compression) set: JSON is small and
1149	/// repetitive.
1150	///
1151	/// `config` is a [`json::Config`](crate::json::Config) for the `json` section, or an
1152	/// application's own entry embedding a [`JsonConfig`](hang::catalog::JsonConfig) (see
1153	/// [`IntoRendition`](super::IntoRendition)). The producer sets its `mode` and fills an absent
1154	/// `bitrate` from what it writes. `options`
1155	/// configures the encoder and is not written into the catalog entry. With
1156	/// [`deltas`](crate::json::Options::deltas), create `track` with a
1157	/// [`refresh`](moq_net::track::Info::refresh) ratio and drive
1158	/// [`Snapshot::poll_refresh`](crate::json::Snapshot::poll_refresh), so joiners get a fresh group.
1159	///
1160	/// Errors if the entry's section already carries that name, for example an entry seeded
1161	/// through [`Config::with_catalog`] or one pointing at a sibling broadcast, if the entry
1162	/// references another broadcast, or with [`moq_net::Error::TimestampMismatch`] if `track` has no
1163	/// timescale.
1164	pub fn json_snapshot<T: serde::Serialize>(
1165		&self,
1166		track: moq_net::track::Producer,
1167		config: impl super::IntoRendition<E, hang::catalog::JsonConfig>,
1168		options: crate::json::Options,
1169	) -> crate::Result<crate::json::Snapshot<T>> {
1170		let rendition = self.data_entry(track.name())?;
1171		crate::json::Snapshot::new(track, rendition, config.into_rendition(), options)
1172	}
1173
1174	/// Publish `track` as an append-log JSON track, advertising it in the catalog.
1175	///
1176	/// See [`json_snapshot`](Self::json_snapshot) for the lifecycle; this differs only in that every
1177	/// record is preserved rather than superseded.
1178	pub fn json_stream<T: serde::Serialize>(
1179		&self,
1180		track: moq_net::track::Producer,
1181		config: impl super::IntoRendition<E, hang::catalog::JsonConfig>,
1182	) -> crate::Result<crate::json::Stream<T>> {
1183		let rendition = self.data_entry(track.name())?;
1184		crate::json::Stream::new(track, rendition, config.into_rendition())
1185	}
1186
1187	/// Reserve the catalog entry a data producer owns, keyed by its track name.
1188	///
1189	/// The rendition is reserved but not yet set, so the caller fills it in with the config for the
1190	/// mode it is about to publish. Reserving is what rejects a name the catalog already carries,
1191	/// including an entry with no local track behind it (seeded through
1192	/// [`Config::with_catalog`], or pointing at a sibling broadcast), which publishing over would
1193	/// silently replace and then retire when this handle drops.
1194	fn data_entry<C: super::RenditionConfig<E>>(&self, name: &str) -> crate::Result<super::Rendition<E, C>> {
1195		self.reserve().init(name)
1196	}
1197
1198	/// Create a consumer for this catalog, receiving updates as they're published.
1199	pub fn consume(&self) -> Result<Consumer<E>, moq_net::Error> {
1200		Ok(Consumer::new(self.outputs.hang_track.consume()))
1201	}
1202
1203	/// Abort every catalog track with `err`, preventing further edits.
1204	pub fn abort(mut self, err: moq_net::Error) {
1205		let reason = crate::Error::from(err.clone());
1206		{
1207			let mut state = take(&self.current);
1208			if state.closed.is_some() {
1209				return;
1210			}
1211			state.closed = Some(reason.clone());
1212		}
1213		self.outputs.abort(&reason);
1214	}
1215
1216	/// The terminal outcome once the catalog tracks are closed.
1217	pub(crate) fn closed(&self) -> Option<crate::Error> {
1218		take(&self.current).closed.clone()
1219	}
1220
1221	/// Finish publishing to this catalog.
1222	///
1223	/// An estimate rise still held by the once-a-second limit is not published: media has ended.
1224	///
1225	/// A failure is final: both catalog tracks end (the other one aborted with that error), and every
1226	/// later call reports it.
1227	pub fn finish(&mut self) -> crate::Result<()> {
1228		let mut state = take(&self.current);
1229		if let Some(err) = &state.closed {
1230			return Err(err.clone());
1231		}
1232		// The shared outputs keep their own clones, whose appends the end refuses.
1233		let result = self
1234			.outputs
1235			.hang
1236			.clone()
1237			.finish()
1238			.map_err(crate::Error::from)
1239			.and_then(|_| {
1240				let msf = self.outputs.msf_track.clone().finish();
1241				msf.map(drop).map_err(crate::Error::from)
1242			});
1243		match result {
1244			Ok(()) => {
1245				state.closed = Some(moq_net::Error::Closed.into());
1246				Ok(())
1247			}
1248			Err(err) => {
1249				self.outputs.abort(&err);
1250				state.closed = Some(err.clone());
1251				Err(err)
1252			}
1253		}
1254	}
1255}
1256
1257/// RAII guard for modifying a catalog with automatic publishing on drop.
1258///
1259/// Obtained via [`Producer::modify`]. Derefs to the [`Catalog<E>`](super::hang::Catalog), so base
1260/// sections are editable directly and application sections are editable through `ext`.
1261///
1262/// On drop, the hang and MSF catalog tracks are updated if the catalog was
1263/// mutated. That publish cannot return an error, so a failure (an extension that won't serialize,
1264/// a catalog too large for a frame) aborts the catalog tracks instead: consumers see the error and
1265/// the next [`Producer::modify`] returns it. A stamp [refused](Producer::modify) on publishing is
1266/// the exception: the edit is undone, so it is logged and the tracks stay open. Call
1267/// [`commit`](Self::commit) when the caller can act on the failure itself.
1268pub struct Guard<'a, E: CatalogExt = ()> {
1269	state: MutexGuard<'a, State<E>>,
1270	outputs: &'a mut Outputs<E>,
1271	updated: bool,
1272	stamp: Stamp<E>,
1273}
1274
1275/// When a guard's publish lands, and whether that was checked yet.
1276enum Stamp<E> {
1277	/// Stamped on publishing.
1278	Unstamped,
1279	/// At the caller's timestamp, checked before the edit.
1280	Checked(moq_net::Timestamp),
1281	/// At the caller's timestamp, checked on publishing against the staged stamp: the edit may
1282	/// re-base the clock, and only then are both on the clock `at` was given on. `before` is the
1283	/// catalog to restore if it is refused.
1284	Deferred {
1285		at: moq_net::Timestamp,
1286		before: Box<Catalog<E>>,
1287	},
1288	/// The deferred check refused the edit, which was undone.
1289	Refused,
1290}
1291
1292impl<E> Stamp<E> {
1293	/// The caller's timestamp, if it gave one.
1294	fn at(&self) -> Option<moq_net::Timestamp> {
1295		match self {
1296			Self::Checked(at) | Self::Deferred { at, .. } => Some(*at),
1297			Self::Unstamped | Self::Refused => None,
1298		}
1299	}
1300}
1301
1302impl<E: CatalogExt> Guard<'_, E> {
1303	/// Publish the edited catalog to every catalog track, returning any error.
1304	///
1305	/// Consumes the guard, so the subsequent drop publishes nothing. A no-op if the catalog was never
1306	/// mutated, and still withheld while a [`Reserved`](super::Reserved) gates the initial snapshot.
1307	/// Unlike a drop, a failure here leaves the tracks open: the caller has the error and decides
1308	/// what to do with it.
1309	pub fn commit(mut self) -> crate::Result<()> {
1310		self.publish()
1311	}
1312
1313	/// Stamp this publish at `timestamp`, refused with
1314	/// [`TimestampRewind`](crate::container::TimestampRewind) unless it passes the last published
1315	/// catalog's, or the stamp still waiting on the initial publish.
1316	///
1317	/// Checked before any edit, unless a stamp is staged on a clock nothing fixed yet: the edit may
1318	/// re-base that clock by writing `sync.clock`, stamping itself on the clock it adopts, so
1319	/// [`publish`](Self::publish) checks it once the staged stamp moved there, and a refusal there
1320	/// discards the edit.
1321	fn stamp(&mut self, timestamp: moq_net::Timestamp) -> crate::Result<()> {
1322		// The guard holds the lock every publish runs under, so nothing lands before this one.
1323		// Nothing is on the wire yet while buffering, but the initial publish will be stamped at the
1324		// staged timestamp, which this one must pass.
1325		self.stamp = match self.state.gate {
1326			Gate::Buffering { at: Some(_), .. } if !self.state.anchored => {
1327				self.passes(timestamp, None)?;
1328				Stamp::Deferred {
1329					at: timestamp,
1330					before: Box::new(self.state.catalog.clone()),
1331				}
1332			}
1333			Gate::Buffering { at: floor, .. } => {
1334				self.passes(timestamp, floor)?;
1335				Stamp::Checked(timestamp)
1336			}
1337			Gate::Unreserved | Gate::Published => {
1338				for track in [&self.outputs.hang_track, &self.outputs.msf_track] {
1339					crate::start::after(track, timestamp)?;
1340				}
1341				Stamp::Checked(timestamp)
1342			}
1343		};
1344		Ok(())
1345	}
1346
1347	/// Whether `timestamp` lands past `floor` on both catalog tracks, or lands on them at all.
1348	fn passes(&self, timestamp: moq_net::Timestamp, floor: Option<moq_net::Timestamp>) -> crate::Result<()> {
1349		let start = |track: &moq_net::track::Producer, timestamp| -> crate::Result<u64> {
1350			Ok(track.info().rescale(timestamp)?.value())
1351		};
1352		for track in [&self.outputs.hang_track, &self.outputs.msf_track] {
1353			let at = start(track, timestamp)?;
1354			if let Some(floor) = floor
1355				&& at <= start(track, floor)?
1356			{
1357				return Err(crate::container::TimestampRewind { timestamp, floor }.into());
1358			}
1359		}
1360		Ok(())
1361	}
1362
1363	/// The stamp staged for the initial publish, moved onto `clock`, or `None` when none is.
1364	fn staged_on(&self, clock: &crate::Clock) -> crate::Result<Option<moq_net::Timestamp>> {
1365		match self.state.gate {
1366			Gate::Buffering { at: Some(staged), .. } => Ok(Some(restamp(&self.state.clock, clock, staged)?)),
1367			_ => Ok(None),
1368		}
1369	}
1370
1371	/// The floor a [deferred](Stamp::Deferred) stamp must pass: the staged stamp, moved onto the clock
1372	/// an edit `adopted`, or `None` when none is staged or it moved before that clock's PTS zero.
1373	fn floor(&self, adopted: Option<&crate::Clock>) -> crate::Result<Option<moq_net::Timestamp>> {
1374		let Gate::Buffering { at: Some(staged), .. } = self.state.gate else {
1375			return Ok(None);
1376		};
1377		// Before PTS zero, every timestamp on the clock passes it.
1378		shifted(&self.state.clock, adopted.unwrap_or(&self.state.clock), staged)
1379	}
1380
1381	/// Move the producer onto `clock`, a re-basing of the one it has, before anything fixed it.
1382	///
1383	/// The stamp staged for the initial publish was given on the old clock, so it moves onto the same
1384	/// moment on the new one, and one that can't is refused, leaving the clock as it was. This guard's
1385	/// own stamp stays: the edit adopting `clock` timed itself on it.
1386	fn retime(&mut self, clock: crate::Clock) -> crate::Result<()> {
1387		let staged = self.staged_on(&clock)?;
1388		if let (Gate::Buffering { at, .. }, Some(staged)) = (&mut self.state.gate, staged) {
1389			*at = Some(staged);
1390		}
1391		self.state.clock = clock;
1392		Ok(())
1393	}
1394
1395	/// Check a [deferred](Stamp::Deferred) stamp against the staged one, both on the clock this edit
1396	/// runs on: `adopted` if it re-bases the clock, else the clock as it is.
1397	fn check(&self, adopted: Option<&crate::Clock>) -> crate::Result<()> {
1398		match &self.stamp {
1399			Stamp::Deferred { at, .. } => self.passes(*at, self.floor(adopted)?),
1400			_ => Ok(()),
1401		}
1402	}
1403
1404	/// Publish a mutated catalog once, clearing the flag so it isn't published again.
1405	fn publish(&mut self) -> crate::Result<()> {
1406		if !self.updated {
1407			return Ok(());
1408		}
1409		self.updated = false;
1410
1411		// The `sync.clock` is the producer's clock: never advertise one it disagrees with.
1412		let adopted = adopt(&self.state.clock, self.state.anchored, self.state.catalog.sync.clock).and_then(|clock| {
1413			self.check(clock.as_ref())?;
1414			clock.map_or(Ok(()), |clock| self.retime(clock))
1415		});
1416		if adopted.is_err() && matches!(self.stamp, Stamp::Deferred { .. }) {
1417			// Refused whole, as a stamp checked before the edit is.
1418			if let Stamp::Deferred { before, .. } = std::mem::replace(&mut self.stamp, Stamp::Refused) {
1419				self.state.catalog = *before;
1420			}
1421		}
1422		self.state.catalog.sync.clock = self.state.clock.wall();
1423		adopted?;
1424
1425		// Withhold every emit while still buffering the initial reserved set, or until a reserved
1426		// catalog names a track; the mutation stays in `current` and `pending` marks it for the
1427		// flush once the gate opens.
1428		let mut at = self.stamp.at();
1429		if let Gate::Buffering {
1430			pending, at: staged, ..
1431		} = &mut self.state.gate
1432		{
1433			*pending = true;
1434			// An unstamped change keeps the staged stamp, landing no earlier than its neighbour, as
1435			// an unstamped publish lands past a stamped one. That holds for the change opening the
1436			// gate too.
1437			*staged = at.or(*staged);
1438			at = *staged;
1439			if !self.state.gate_opens() {
1440				return Ok(());
1441			}
1442		}
1443		self.state.gate = Gate::Published;
1444		// A snapshot on the wire is a mapping a reader may have copied.
1445		self.state.anchored = true;
1446
1447		// Folded only once it is on the wire, so a failed emit leaves the estimate held.
1448		let state = &mut *self.state;
1449		self.outputs.emit(&state.catalog, &mut state.msf, &state.clock, at)?;
1450		self.state.estimates.fold();
1451		Ok(())
1452	}
1453
1454	/// Publish an estimate-driven edit, at most once per [`ESTIMATE_WINDOW`] when `throttle` is set.
1455	///
1456	/// The first estimate publishes at once. Later ones inside the window stay in the catalog and go
1457	/// out with the first call after the window ends, which an unchanged estimate makes too, or with
1458	/// any [`commit`](Self::commit) before then. Without `throttle` it publishes at once, still
1459	/// opening a window.
1460	pub(super) fn commit_estimate(mut self, throttle: bool) -> crate::Result<()> {
1461		if std::mem::take(&mut self.updated) {
1462			self.state.estimates.pending = true;
1463		}
1464		let estimates = &self.state.estimates;
1465		if !estimates.pending {
1466			return Ok(());
1467		}
1468		let now = kio::clock::now();
1469		if throttle
1470			&& estimates
1471				.last
1472				.is_some_and(|last| now < last.saturating_add(ESTIMATE_WINDOW))
1473		{
1474			return Ok(());
1475		}
1476		self.updated = true;
1477		self.publish()
1478	}
1479
1480	/// Declare `estimate` in MSF for the rendition holding `name` in `C`'s section, in place of
1481	/// whatever it measures. It goes out with the next publish.
1482	pub(super) fn hint<C: super::RenditionConfig<E>>(&mut self, name: &str, estimate: super::Estimate) {
1483		let hint = Hint {
1484			estimate,
1485			apply: apply_hint::<E, C>,
1486		};
1487		self.state.msf.hints.insert(owner_key::<C>(name), hint);
1488	}
1489
1490	/// Mark the rendition holding `name` in `C`'s section as listed, so it counts toward the
1491	/// initial publish's [track requirement](State::lists_track).
1492	pub(super) fn list<C: super::RenditionConfig<E>>(&mut self, name: &str) {
1493		if let Some(listed) = self.state.owned.get_mut(&owner_key::<C>(name)) {
1494			*listed = true;
1495		}
1496	}
1497
1498	/// Release a name taken by [`Producer::acquire`], along with the entry it owns.
1499	///
1500	/// Both under one lock, so an [`acquire`](Producer::acquire) never sees the rendition half-gone:
1501	/// name freed with its entry still there (a spurious duplicate), or entry gone with the name
1502	/// still held (a spurious refusal).
1503	///
1504	/// The name goes first, before any caller code. [`RenditionConfig::remove`](super::RenditionConfig::remove)
1505	/// is a third-party hook that can panic, and a stranded entry is recoverable while a stranded
1506	/// name is not: nothing would ever reserve it again.
1507	pub(super) fn release<C: super::RenditionConfig<E>>(&mut self, name: &str, present: bool) {
1508		self.state.owned.remove(&owner_key::<C>(name));
1509		self.state.msf.hints.remove(&owner_key::<C>(name));
1510
1511		if present {
1512			C::remove(&mut self.state.catalog, name);
1513			self.updated = true;
1514		}
1515	}
1516}
1517
1518impl<E: CatalogExt> Deref for Guard<'_, E> {
1519	type Target = Catalog<E>;
1520
1521	fn deref(&self) -> &Self::Target {
1522		&self.state.catalog
1523	}
1524}
1525
1526impl<E: CatalogExt> DerefMut for Guard<'_, E> {
1527	fn deref_mut(&mut self) -> &mut Self::Target {
1528		self.updated = true;
1529		&mut self.state.catalog
1530	}
1531}
1532
1533impl Guard<'_, Extra> {
1534	/// Set (or replace) a top-level application catalog section, republished on drop.
1535	///
1536	/// Errors if `name` is a HANG root (`video`, `audio`, `sync`, `text`, `json`, `binary`,
1537	/// `stats`, `echo`, `include`, or the retired `archive`, `clock`, `media`, and `timeline`) or an
1538	/// MSF root (`version`, `generatedAt`, `isComplete`, `tracks`, or `initDataList`).
1539	pub fn set_section(&mut self, name: impl Into<String>, value: serde_json::Value) -> crate::Result<()> {
1540		self.state.catalog.ext.set(name, value)?;
1541		self.updated = true;
1542		Ok(())
1543	}
1544
1545	/// Remove a top-level application catalog section, republished on drop if it existed.
1546	///
1547	/// Returns the section's previous value, or `None` if it was absent.
1548	pub fn remove_section(&mut self, name: &str) -> Option<serde_json::Value> {
1549		let removed = self.state.catalog.ext.remove(name);
1550		if removed.is_some() {
1551			self.updated = true;
1552		}
1553		removed
1554	}
1555}
1556
1557impl<E: CatalogExt> Drop for Guard<'_, E> {
1558	fn drop(&mut self) {
1559		if let Err(err) = self.publish() {
1560			if matches!(self.stamp, Stamp::Refused) {
1561				// Undone, so the catalog is as it was: the next edit can go out.
1562				tracing::error!(%err, "refused a catalog edit on guard drop");
1563				return;
1564			}
1565			if !std::thread::panicking() {
1566				tracing::error!(%err, "failed to publish the catalog on guard drop, aborting its tracks");
1567			}
1568			self.outputs.abort(&err);
1569			self.state.closed = Some(err);
1570		}
1571	}
1572}
1573
1574/// Determine the SAP starting type for a given video codec.
1575///
1576/// SAP type 1: closed GOP with no leading pictures (IDR at every SAP).
1577/// Used for VP8, which has no B-frames.
1578///
1579/// SAP type 2: closed GOP with possible leading pictures. Used for codecs
1580/// that can carry B-frames (H.264, AV1, VP9) since the encoder may emit
1581/// leading B-frames after an IDR.
1582///
1583/// Returns None for unknown codecs (and H.265, which we don't yet validate
1584/// the SAP behavior of) so the field is omitted from the catalog.
1585fn video_sap_type(codec: &hang::catalog::VideoCodec) -> Option<u8> {
1586	use hang::catalog::VideoCodec;
1587	match codec {
1588		VideoCodec::VP8 => Some(1),
1589		VideoCodec::H264(_) | VideoCodec::AV1(_) | VideoCodec::VP9(_) => Some(2),
1590		_ => None,
1591	}
1592}
1593
1594/// The MSF packaging that announces `container`.
1595///
1596/// Exhaustive on purpose: a catch-all is what announced LOC as legacy, and it would do the same to the
1597/// next container added. hang says an unrecognized one must be ignored, so it keeps its wire kind (no
1598/// MSF consumer claims one it does not know).
1599fn packaging_of(container: &hang::catalog::Container) -> moq_msf::Packaging {
1600	match container {
1601		hang::catalog::Container::Cmaf { .. } => moq_msf::Packaging::Cmaf,
1602		hang::catalog::Container::Loc => moq_msf::Packaging::Loc,
1603		hang::catalog::Container::Legacy => moq_msf::Packaging::Legacy,
1604		hang::catalog::Container::Raw => moq_msf::Packaging::Raw,
1605		hang::catalog::Container::Cts => moq_msf::Packaging::Cts,
1606		hang::catalog::Container::Unknown(unknown) => moq_msf::Packaging::Unknown(unknown.kind().to_string()),
1607	}
1608}
1609
1610/// Convert a catalog to its MSF equivalent: the media sections become MSF tracks and the
1611/// extension rides the MSF root under the same member names it uses in the hang catalog.
1612pub(crate) fn to_msf<E: CatalogExt>(catalog: &Catalog<E>, base: &moq_net::Path) -> moq_msf::Catalog<E> {
1613	let mut msf = to_msf_media(&catalog.without_ext(), base);
1614	msf.ext = catalog.ext.clone();
1615	msf
1616}
1617
1618/// Convert the base media sections of a hang catalog into MSF tracks.
1619///
1620/// MSF names a track by its absolute namespace and wire name. An unresolvable reference, one
1621/// a reader would take as the catalog itself ([`names_catalog`](crate::catalog::msf::names_catalog)),
1622/// is refused instead of advertising the track on the catalog's broadcast. A later rendition with
1623/// the same identity replaces the earlier one.
1624fn to_msf_media<E: CatalogExt>(catalog: &hang::Catalog, base: &moq_net::Path) -> moq_msf::Catalog<E> {
1625	let mut tracks = Vec::new();
1626	let reference = |id: &str, config: &dyn Reference| {
1627		let name = config.track(id);
1628		let namespace = match config.broadcast().filter(|rel| !rel.is_empty()) {
1629			None => None,
1630			Some(rel) => {
1631				let Some(target) = base.try_resolve(rel) else {
1632					tracing::error!(rendition = id, %rel, %base, "MSF broadcast reference escapes the root");
1633					return None;
1634				};
1635				if target == *base {
1636					None
1637				} else if crate::catalog::msf::names_catalog(&target, base) {
1638					tracing::error!(rendition = id, %rel, %base, "MSF readers would take this namespace as the catalog's own");
1639					return None;
1640				} else {
1641					Some(target.to_string())
1642				}
1643			}
1644		};
1645		Some((name.to_string(), namespace))
1646	};
1647
1648	let has_multiple_video = catalog.video.renditions.len() > 1;
1649	for (name, config) in &catalog.video.renditions {
1650		let packaging = packaging_of(&config.container);
1651
1652		let init_data = match &config.container {
1653			hang::catalog::Container::Cmaf { init, .. } => Some(base64::engine::general_purpose::STANDARD.encode(init)),
1654			_ => config
1655				.description
1656				.as_ref()
1657				.map(|d| base64::engine::general_purpose::STANDARD.encode(d.as_ref())),
1658		};
1659
1660		let sap_type = video_sap_type(&config.codec);
1661		let Some((wire, namespace)) = reference(name, config) else {
1662			continue;
1663		};
1664		let mut track = moq_msf::Track::new(wire, packaging);
1665		track.namespace = namespace;
1666		track.is_live = true;
1667		track.role = Some(moq_msf::Role::Video);
1668		track.codec = Some(config.codec.to_string());
1669		track.width = config.coded_width;
1670		track.height = config.coded_height;
1671		track.framerate = config.framerate;
1672		track.bitrate = config.bitrate;
1673		track.init_data = init_data.map(Into::into);
1674		track.render_group = Some(1);
1675		track.alt_group = if has_multiple_video { Some(1) } else { None };
1676		track.max_grp_sap_starting_type = sap_type;
1677		track.max_obj_sap_starting_type = sap_type;
1678		track.jitter = config.jitter;
1679		track.delay = config.delay.filter(|delay| !delay.is_zero());
1680		tracks.push(track);
1681	}
1682
1683	let has_multiple_audio = catalog.audio.renditions.len() > 1;
1684	for (name, config) in &catalog.audio.renditions {
1685		let packaging = packaging_of(&config.container);
1686
1687		let init_data = match &config.container {
1688			hang::catalog::Container::Cmaf { init, .. } => Some(base64::engine::general_purpose::STANDARD.encode(init)),
1689			_ => config
1690				.description
1691				.as_ref()
1692				.map(|d| base64::engine::general_purpose::STANDARD.encode(d.as_ref())),
1693		};
1694
1695		let Some((wire, namespace)) = reference(name, config) else {
1696			continue;
1697		};
1698		let mut track = moq_msf::Track::new(wire, packaging);
1699		track.namespace = namespace;
1700		track.is_live = true;
1701		track.role = Some(moq_msf::Role::Audio);
1702		track.codec = Some(config.codec.to_string());
1703		track.samplerate = Some(config.sample_rate);
1704		track.channel_config = Some(config.channel_count.to_string());
1705		track.bitrate = config.bitrate;
1706		track.init_data = init_data.map(Into::into);
1707		track.render_group = Some(1);
1708		track.alt_group = if has_multiple_audio { Some(1) } else { None };
1709		track.max_grp_sap_starting_type = Some(1);
1710		track.max_obj_sap_starting_type = Some(1);
1711		track.jitter = config.jitter;
1712		track.delay = config.delay.filter(|delay| !delay.is_zero());
1713		tracks.push(track);
1714	}
1715
1716	for (name, config) in &catalog.text.renditions {
1717		let packaging = packaging_of(&config.container);
1718		let Some((wire, namespace)) = reference(name, config) else {
1719			continue;
1720		};
1721		let mut track = moq_msf::Track::new(wire, packaging);
1722		track.namespace = namespace;
1723		track.is_live = true;
1724		track.role = Some(config.role.to_string().parse().unwrap());
1725		track.codec = Some(config.format.to_string());
1726		track.lang = config.lang.clone();
1727		track.label = config.label.clone();
1728		if let hang::catalog::Container::Cmaf { init, .. } = &config.container {
1729			track.init_data = Some(base64::engine::general_purpose::STANDARD.encode(init).into());
1730		}
1731		track.render_group = Some(1);
1732		track.jitter = config.jitter;
1733		track.delay = config.delay.filter(|delay| !delay.is_zero());
1734		tracks.push(track);
1735	}
1736
1737	let mut index = HashMap::new();
1738	let mut unique: Vec<moq_msf::Track> = Vec::with_capacity(tracks.len());
1739	for track in tracks {
1740		match index.entry((track.namespace.clone(), track.name.clone())) {
1741			Entry::Occupied(entry) => unique[*entry.get()] = track,
1742			Entry::Vacant(entry) => {
1743				entry.insert(unique.len());
1744				unique.push(track);
1745			}
1746		}
1747	}
1748	moq_msf::Catalog::with_ext(unique, E::default())
1749}
1750
1751#[cfg(test)]
1752mod test {
1753	use std::collections::BTreeMap;
1754
1755	use std::str::FromStr;
1756	use std::task::Poll;
1757
1758	use bytes::Bytes;
1759	use hang::catalog::{AudioCodec, AudioConfig, Container, H264, VideoConfig};
1760
1761	use super::*;
1762
1763	#[tokio::test(start_paused = true)]
1764	async fn msf_publishes_the_referenced_namespace() {
1765		for (path, expected) in [(Some("room/catalog"), "room/left"), (Some(""), "left"), (None, "left")] {
1766			let (origin, driver) = moq_net::origin::Producer::new(Default::default());
1767			let driver = tokio::spawn(moq_net::time::run(driver));
1768			let mut broadcast = match path {
1769				Some(path) => origin
1770					.route(path, moq_net::origin::RouteOptions::hidden())
1771					.unwrap()
1772					.broadcast()
1773					.clone(),
1774				None => moq_net::broadcast::Info::new().produce(),
1775			};
1776			let mut producer = Producer::new(&mut broadcast, Config::default()).unwrap();
1777			let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
1778			config.container = Container::Loc;
1779			config.broadcast = Some(moq_net::path::Relative::new("./left").unwrap());
1780			producer
1781				.modify(producer.next_timestamp())
1782				.unwrap()
1783				.video
1784				.renditions
1785				.insert("video".into(), config);
1786			let mut track = broadcast
1787				.consume()
1788				.track(moq_msf::DEFAULT_NAME)
1789				.unwrap()
1790				.subscribe(None)
1791				.await
1792				.unwrap()
1793				.ordered();
1794			let mut group = track.next_group().await.unwrap().unwrap();
1795			let frame = group.read_frame().await.unwrap().unwrap();
1796			let wire: serde_json::Value = serde_json::from_slice(&frame.payload).unwrap();
1797			assert_eq!(wire["tracks"][0]["namespace"], expected);
1798			driver.abort();
1799		}
1800	}
1801
1802	#[test]
1803	fn msf_omits_media_report_discovery() {
1804		let catalog =
1805			hang::Catalog::<()>::from_str(include_str!("../../../hang/fixtures/catalog-stats-echo.json")).unwrap();
1806		let msf = to_msf::<()>(&catalog, &moq_net::Path::empty());
1807		let value = serde_json::to_value(msf).unwrap();
1808		assert!(value.get("stats").is_none());
1809		assert!(value.get("echo").is_none());
1810		assert!(!value["tracks"].as_array().unwrap().is_empty());
1811	}
1812
1813	#[tokio::test(start_paused = true)]
1814	async fn abort_preserves_the_cause_on_every_catalog_format_and_clone() {
1815		let mut broadcast = moq_net::broadcast::Info::default().produce();
1816		let catalog = Producer::<()>::new(&mut broadcast, Config::default()).unwrap();
1817		let mut copy = catalog.clone();
1818		let mut readers = Vec::new();
1819		for name in [hang::Catalog::DEFAULT_NAME, moq_msf::DEFAULT_NAME] {
1820			readers.push(broadcast.consume().track(name).unwrap().subscribe(None).await.unwrap());
1821		}
1822		catalog.abort(moq_net::Error::Unauthorized);
1823		for reader in &mut readers {
1824			assert!(matches!(reader.recv_group().await, Err(moq_net::Error::Unauthorized)));
1825		}
1826		assert!(copy.finish().is_err());
1827		assert!(matches!(
1828			copy.modify(copy.next_timestamp()).err(),
1829			Some(crate::Error::Moq(moq_net::Error::Unauthorized))
1830		));
1831		copy.abort(moq_net::Error::Cancel);
1832	}
1833
1834	#[tokio::test(start_paused = true)]
1835	async fn abort_does_not_replace_a_finished_catalog() {
1836		let mut broadcast = moq_net::broadcast::Info::default().produce();
1837		let mut catalog = Producer::<()>::new(&mut broadcast, Config::default()).unwrap();
1838		let copy = catalog.clone();
1839		let mut reader = broadcast
1840			.consume()
1841			.track(hang::Catalog::DEFAULT_NAME)
1842			.unwrap()
1843			.subscribe(None)
1844			.await
1845			.unwrap();
1846		catalog.finish().unwrap();
1847		copy.abort(moq_net::Error::Unauthorized);
1848		while reader.recv_group().await.unwrap().is_some() {}
1849		assert!(matches!(
1850			catalog.modify(catalog.next_timestamp()).err(),
1851			Some(crate::Error::Moq(moq_net::Error::Closed))
1852		));
1853	}
1854
1855	#[tokio::test(start_paused = true)]
1856	async fn a_failed_finish_is_final_and_ends_both_tracks() {
1857		let mut broadcast = moq_net::broadcast::Info::default().produce();
1858		let mut catalog = Producer::<()>::new(&mut broadcast, Config::default()).unwrap();
1859		let mut msf = broadcast
1860			.consume()
1861			.track(moq_msf::DEFAULT_NAME)
1862			.unwrap()
1863			.subscribe(None)
1864			.await
1865			.unwrap();
1866		catalog
1867			.outputs
1868			.hang
1869			.clone()
1870			.abort(moq_net::Error::Unauthorized)
1871			.unwrap();
1872		let err = catalog.finish().unwrap_err();
1873		loop {
1874			match msf.recv_group().await {
1875				Ok(Some(_)) => continue,
1876				Ok(None) => panic!("the MSF track ended cleanly after a failed finish"),
1877				Err(moq_net::Error::Unauthorized) => break,
1878				Err(other) => panic!("the MSF track ended with {other} instead of the finish cause"),
1879			}
1880		}
1881		assert_eq!(catalog.finish().unwrap_err().to_string(), err.to_string());
1882		assert_eq!(
1883			catalog.modify(catalog.next_timestamp()).err().unwrap().to_string(),
1884			err.to_string()
1885		);
1886
1887		// A handle made after the failure reports it too, not `NotPublished`.
1888		let net = broadcast
1889			.create_track("late", catalog.track_info(hang::catalog::PRIORITY.video))
1890			.unwrap();
1891		let mut late = catalog
1892			.video(
1893				net,
1894				crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
1895				None,
1896			)
1897			.unwrap();
1898		assert_eq!(late.modify().err().unwrap().to_string(), err.to_string());
1899	}
1900
1901	/// The catalog and its MSF twin both rank above media. They're the index a player reads
1902	/// before any media is useful, and they're small enough that sitting above media can't starve
1903	/// it. Regression: the MSF track was minted with no `Info` at all, so one broadcast advertised
1904	/// its hang catalog at 100 and the same catalog in MSF at 0.
1905	#[tokio::test]
1906	async fn non_media_tracks_rank_above_media() {
1907		use hang::catalog::PRIORITY;
1908
1909		let mut broadcast = moq_net::broadcast::Info::new().produce();
1910		let _catalog = Producer::<()>::new(&mut broadcast, Config::default()).unwrap();
1911
1912		let consumer = broadcast.consume();
1913		for name in [hang::Catalog::DEFAULT_NAME, moq_msf::DEFAULT_NAME] {
1914			let track = consumer.track(name).expect("track");
1915			let info = track.info().await.expect("info");
1916			assert_eq!(info.priority, PRIORITY.catalog, "{name} should rank with the catalog");
1917		}
1918	}
1919
1920	#[test]
1921	fn text_tracks_round_trip_through_msf() {
1922		for (format, role) in [
1923			(hang::catalog::TextFormat::Vtt, hang::catalog::TextRole::Caption),
1924			(hang::catalog::TextFormat::Ttml, hang::catalog::TextRole::Subtitle),
1925			(
1926				hang::catalog::TextFormat::Utf8,
1927				hang::catalog::TextRole::Unknown("commentary".into()),
1928			),
1929		] {
1930			let mut config = hang::catalog::TextConfig::new(format);
1931			config.role = role;
1932			config.lang = Some("es-419".into());
1933			config.label = Some("Espaรฑol".into());
1934			config.jitter = Some(std::time::Duration::from_millis(7));
1935			config.delay = Some(std::time::Duration::from_millis(11));
1936			config.container = Container::Loc;
1937			let mut catalog = hang::Catalog::<()>::default();
1938			catalog.text.insert("text", config.clone()).unwrap();
1939			let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
1940			assert_eq!(msf.tracks.len(), 1);
1941			let wire = msf.to_json().unwrap();
1942			assert!(wire.contains(r#""lang":"es-419""#));
1943			assert!(wire.contains(r#""label":"Espaรฑol""#));
1944			let msf = moq_msf::Catalog::<()>::from_str(&wire).unwrap();
1945			let decoded = crate::catalog::msf::from_msf(&msf, &moq_net::Path::empty()).unwrap();
1946			assert_eq!(decoded.text.renditions["text"], config);
1947			let mut roundtrip = hang::Catalog::<()>::default();
1948			roundtrip.text = decoded.text;
1949			assert_eq!(
1950				to_msf_media::<()>(&roundtrip, &moq_net::Path::empty()).tracks,
1951				msf.tracks
1952			);
1953		}
1954	}
1955
1956	#[test]
1957	fn msf_names_each_track_by_its_wire_name() {
1958		let catalog = hang::Catalog::<()>::from_str(
1959			r#"{"video": {"renditions": {
1960				"hd": {"codec": "avc1.64001f", "container": {"kind": "legacy"}},
1961				"left": {"broadcast": "./left", "track": "video", "codec": "avc1.64001f", "container": {"kind": "legacy"}},
1962				"right": {"broadcast": "./right", "track": "video", "codec": "avc1.64001f", "container": {"kind": "legacy"}}
1963			}}}"#,
1964		)
1965		.unwrap();
1966		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
1967		let names: Vec<_> = msf.tracks.iter().map(|track| track.name.as_str()).collect();
1968		assert_eq!(names, ["hd", "video", "video"]);
1969		assert_eq!(msf.tracks[1].namespace.as_deref(), Some("left"));
1970		assert_eq!(msf.tracks[2].namespace.as_deref(), Some("right"));
1971	}
1972
1973	#[test]
1974	fn cross_broadcast_renditions_round_trip_through_msf() {
1975		let base = moq_net::Path::from_static("room/catalog");
1976		let catalog = hang::Catalog::<()>::from_str(r#"{
1977			"video": {"renditions": {"view": {"broadcast": "./left", "track": "video", "codec": "vp8", "container": {"kind": "loc"}}}},
1978			"audio": {"renditions": {"sound": {"broadcast": "./right", "track": "audio", "codec": "opus", "sampleRate": 48000, "numberOfChannels": 2, "container": {"kind": "loc"}}}},
1979			"text": {"renditions": {"words": {"broadcast": "../captions", "track": "text", "format": "vtt", "role": "caption", "container": {"kind": "loc"}}}}
1980		}"#).unwrap();
1981		let msf = to_msf_media::<()>(&catalog, &base);
1982		let wire = msf.to_json().unwrap();
1983		let msf = moq_msf::Catalog::<()>::from_str(&wire).unwrap();
1984		let restored = crate::catalog::msf::from_msf(&msf, &base).unwrap();
1985		assert_eq!(
1986			base.try_resolve(restored.video.renditions["video"].broadcast.as_ref().unwrap()),
1987			Some(moq_net::Path::from_static("room/left"))
1988		);
1989		assert_eq!(
1990			base.try_resolve(restored.audio.renditions["audio"].broadcast.as_ref().unwrap()),
1991			Some(moq_net::Path::from_static("room/right"))
1992		);
1993		assert_eq!(
1994			base.try_resolve(restored.text.renditions["text"].broadcast.as_ref().unwrap()),
1995			Some(moq_net::Path::from_static("captions"))
1996		);
1997	}
1998
1999	#[test]
2000	fn msf_refuses_unresolvable_broadcast_references() {
2001		let base = moq_net::Path::from_static("room/catalog");
2002		for reference in ["../../left", "../../../left"] {
2003			let mut catalog = hang::Catalog::<()>::default();
2004			let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2005			config.broadcast = Some(moq_net::path::Relative::new(reference).unwrap());
2006			catalog.video.renditions.insert("video".into(), config);
2007			assert!(to_msf_media::<()>(&catalog, &base).tracks.is_empty());
2008			assert!(to_msf_media::<()>(&catalog, &moq_net::Path::empty()).tracks.is_empty());
2009		}
2010	}
2011
2012	/// A reader takes a namespace aligned with the catalog's tail as the catalog itself, so a
2013	/// reference to such a broadcast is refused rather than read from the catalog's broadcast.
2014	#[test]
2015	fn msf_refuses_references_readers_would_take_as_the_catalog() {
2016		let base = moq_net::Path::from_static("room/catalog");
2017		for reference in ["../catalog", "./catalog/room/catalog"] {
2018			let mut catalog = hang::Catalog::<()>::default();
2019			let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2020			config.container = Container::Loc;
2021			config.broadcast = Some(moq_net::path::Relative::new(reference).unwrap());
2022			catalog.video.renditions.insert("video".into(), config);
2023			assert!(to_msf_media::<()>(&catalog, &base).tracks.is_empty(), "{reference}");
2024		}
2025	}
2026
2027	/// MSF names a track by namespace and name, but a reader keys renditions by name alone, so
2028	/// the later of two same-named tracks wins there.
2029	#[test]
2030	fn msf_names_are_unique_per_namespace_and_the_last_wins_a_hang_id() {
2031		let base = moq_net::Path::from_static("room/catalog");
2032		let mut catalog = hang::Catalog::<()>::default();
2033		for (id, broadcast) in [("left", "./left"), ("right", "./right")] {
2034			let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2035			config.track = Some("video".into());
2036			config.broadcast = Some(moq_net::path::Relative::new(broadcast).unwrap());
2037			catalog.video.renditions.insert(id.into(), config);
2038		}
2039		let msf = to_msf_media::<()>(&catalog, &base);
2040		assert_eq!(msf.tracks.len(), 2);
2041		assert_eq!(msf.tracks[0].namespace.as_deref(), Some("room/left"));
2042		assert_eq!(msf.tracks[1].namespace.as_deref(), Some("room/right"));
2043		let restored = crate::catalog::msf::from_msf(&msf, &base).unwrap();
2044		assert_eq!(restored.video.renditions.len(), 1);
2045		assert_eq!(
2046			base.try_resolve(restored.video.renditions["video"].broadcast.as_ref().unwrap()),
2047			Some(moq_net::Path::from_static("room/right"))
2048		);
2049	}
2050
2051	/// Two renditions naming one track in one broadcast advertise it once, as the later one.
2052	#[test]
2053	fn msf_repeated_identity_keeps_the_last() {
2054		let mut catalog = hang::Catalog::<()>::default();
2055		for (id, width) in [("a", 640), ("b", 1280)] {
2056			let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
2057			config.container = Container::Loc;
2058			config.track = Some("video".into());
2059			config.coded_width = Some(width);
2060			catalog.video.renditions.insert(id.into(), config);
2061		}
2062		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
2063		assert_eq!(msf.tracks.len(), 1);
2064		assert_eq!(msf.tracks[0].name, "video");
2065		assert_eq!(msf.tracks[0].width, Some(1280));
2066	}
2067
2068	#[test]
2069	fn media_tracks_take_the_catalogs_max_age() {
2070		let mut broadcast = moq_net::broadcast::Info::new().produce();
2071
2072		// Unset, a catalog mints hang's media max age, sized so a segmented egress can serve a
2073		// full playlist window.
2074		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2075		assert_eq!(
2076			catalog.track_info(hang::catalog::PRIORITY.video).max_age,
2077			Some(hang::container::MAX_AGE)
2078		);
2079
2080		// `None` is an explicit unlimited, not a request for the default.
2081		let mut broadcast = moq_net::broadcast::Info::new().produce();
2082		let catalog = Producer::new(&mut broadcast, Config::default().with_max_age(None)).unwrap();
2083		assert_eq!(catalog.track_info(hang::catalog::PRIORITY.video).max_age, None);
2084
2085		// An override reaches every media track this catalog mints, and does NOT disturb the
2086		// timescale hang pins (or survive a retimescale for a source-scale container).
2087		let mut broadcast = moq_net::broadcast::Info::new().produce();
2088		let config = Config::default().with_max_age(std::time::Duration::from_secs(3));
2089		let catalog = Producer::new(&mut broadcast, config).unwrap();
2090
2091		let info = catalog.track_info(hang::catalog::PRIORITY.video);
2092		assert_eq!(info.max_age, Some(std::time::Duration::from_secs(3)));
2093		assert_eq!(info.timescale, Some(hang::container::TIMESCALE));
2094		// The catalog tracks stay fresh as long, for a reader holding each update until its timestamp.
2095		for track in [&catalog.outputs.hang_track, &catalog.outputs.msf_track] {
2096			assert_eq!(track.info().max_age, Some(std::time::Duration::from_secs(3)));
2097		}
2098
2099		let at = info.with_timescale(moq_net::Timescale::MILLI);
2100		assert_eq!(at.max_age, Some(std::time::Duration::from_secs(3)));
2101		assert_eq!(at.timescale, Some(moq_net::Timescale::MILLI));
2102
2103		// Every handle mints under the same policy, whatever order it was taken in: the codec
2104		// paths hold a reservation and the container paths hold a clone.
2105		assert_eq!(
2106			catalog.reserve().track_info(hang::catalog::PRIORITY.video).max_age,
2107			Some(std::time::Duration::from_secs(3))
2108		);
2109		assert_eq!(
2110			catalog.clone().track_info(hang::catalog::PRIORITY.video).max_age,
2111			Some(std::time::Duration::from_secs(3))
2112		);
2113	}
2114
2115	#[test]
2116	fn publishes_one_compressed_catalog_track() {
2117		let mut broadcast = moq_net::broadcast::Info::new().produce();
2118		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2119
2120		let track = catalog.outputs.hang_track.consume();
2121		assert_eq!(
2122			catalog.outputs.hang_track.info().compression,
2123			moq_net::track::Compression::Deflate,
2124			"catalog.json is compressed"
2125		);
2126		assert_eq!(
2127			catalog.outputs.msf_track.info().compression,
2128			moq_net::track::Compression::None,
2129			"the MSF catalog is not"
2130		);
2131		let mut consumer = Consumer::new(track);
2132
2133		{
2134			let mut guard = catalog.modify(catalog.next_timestamp()).unwrap();
2135			guard
2136				.audio
2137				.renditions
2138				.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2139		}
2140		let expected = catalog.snapshot();
2141
2142		let waiter = kio::Waiter::noop();
2143		let got = match consumer.poll_next(&waiter) {
2144			Poll::Ready(Ok(Some(c))) => c.value,
2145			other => panic!("expected a catalog, got {other:?}"),
2146		};
2147		assert_eq!(got, expected);
2148	}
2149
2150	#[test]
2151	fn mutate_composes_independent_owners() {
2152		let mut broadcast = moq_net::broadcast::Info::new().produce();
2153		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2154		let mut plain = Consumer::new(catalog.outputs.hang_track.consume());
2155
2156		catalog
2157			.mutate(
2158				|c| {
2159					c.audio
2160						.renditions
2161						.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2162				},
2163				catalog.next_timestamp(),
2164			)
2165			.unwrap();
2166
2167		// The second owner starts from the published catalog and adds its own section.
2168		catalog
2169			.mutate(
2170				|c| {
2171					c.video.renditions.insert("video0".to_string(), h264_config());
2172				},
2173				catalog.next_timestamp(),
2174			)
2175			.unwrap();
2176
2177		// A closure that changes nothing publishes nothing: the catalog track runs one snapshot per
2178		// group, so a third publish would open a third group.
2179		catalog.mutate(|_| {}, catalog.next_timestamp()).unwrap();
2180		assert_eq!(sent(&catalog), Some(1));
2181
2182		let expected = catalog.snapshot();
2183		let waiter = kio::Waiter::noop();
2184		let mut last = None;
2185		while let Poll::Ready(Ok(Some(c))) = plain.poll_next(&waiter) {
2186			last = Some(c.value);
2187		}
2188		assert_eq!(last.unwrap(), expected);
2189		assert!(expected.audio.renditions.contains_key("audio0"));
2190		assert!(expected.video.renditions.contains_key("video0"));
2191	}
2192
2193	#[test]
2194	fn modify_refuses_a_finished_catalog() {
2195		let mut broadcast = moq_net::broadcast::Info::new().produce();
2196		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2197
2198		catalog
2199			.modify(catalog.next_timestamp())
2200			.unwrap()
2201			.audio
2202			.renditions
2203			.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2204		catalog.finish().unwrap();
2205
2206		assert!(matches!(
2207			catalog.modify(catalog.next_timestamp()),
2208			Err(crate::Error::Moq(moq_net::Error::Closed))
2209		));
2210	}
2211
2212	#[test]
2213	fn a_dropped_failed_edit_aborts_every_catalog_track() {
2214		let mut broadcast = moq_net::broadcast::Info::new().produce();
2215		let config = Config::default().with_catalog(Catalog::<Extra>::default());
2216		let mut catalog = Producer::<Extra>::new(&mut broadcast, config).unwrap();
2217		let mut hang = catalog.outputs.hang.consume().ordered();
2218		let mut msf = catalog.outputs.msf_track.subscribe(None).ordered();
2219
2220		// Something the hang track rejects, so the publish fails before the MSF track is reached.
2221		catalog
2222			.modify(catalog.next_timestamp())
2223			.unwrap()
2224			.set_section("big", "x".repeat(crate::jitter::MAX_BYTES + 1).into())
2225			.unwrap();
2226
2227		assert!(matches!(
2228			catalog.modify(catalog.next_timestamp()),
2229			Err(crate::Error::Json(moq_json::Error::Net(moq_net::Error::FrameTooLarge)))
2230		));
2231		let waiter = kio::Waiter::noop();
2232		assert!(matches!(
2233			hang.poll_next_group(&waiter),
2234			Poll::Ready(Err(moq_net::Error::FrameTooLarge))
2235		));
2236		assert!(
2237			matches!(
2238				msf.poll_next_group(&waiter),
2239				Poll::Ready(Err(moq_net::Error::FrameTooLarge))
2240			),
2241			"a track the publish never reached must not outlive the others"
2242		);
2243	}
2244
2245	#[test]
2246	fn a_failed_commit_leaves_the_catalog_open() {
2247		let mut broadcast = moq_net::broadcast::Info::new().produce();
2248		let config = Config::default().with_catalog(Catalog::<Extra>::default());
2249		let mut catalog = Producer::<Extra>::new(&mut broadcast, config).unwrap();
2250
2251		let mut guard = catalog.modify(catalog.next_timestamp()).unwrap();
2252		guard
2253			.set_section("big", "x".repeat(crate::jitter::MAX_BYTES + 1).into())
2254			.unwrap();
2255		assert!(matches!(
2256			guard.commit(),
2257			Err(crate::Error::Json(moq_json::Error::Net(moq_net::Error::FrameTooLarge)))
2258		));
2259
2260		// The caller got the error, so the tracks stay usable once the catalog fits again.
2261		catalog
2262			.modify(catalog.next_timestamp())
2263			.unwrap()
2264			.remove_section("big")
2265			.unwrap();
2266		catalog.finish().unwrap();
2267		assert_eq!(sent(&catalog), Some(0));
2268	}
2269
2270	/// Every consumer refuses an ID naming both a video and an audio rendition, so the producer
2271	/// refuses to publish one.
2272	#[test]
2273	fn a_cross_kind_duplicate_id_is_refused() {
2274		let mut broadcast = moq_net::broadcast::Info::new().produce();
2275		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2276
2277		let result = catalog.mutate(
2278			|catalog| {
2279				catalog.video.renditions.insert(
2280					"main".to_string(),
2281					hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8),
2282				);
2283				catalog.audio.renditions.insert(
2284					"main".to_string(),
2285					hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2),
2286				);
2287			},
2288			catalog.next_timestamp(),
2289		);
2290		assert!(matches!(
2291			result,
2292			Err(crate::Error::Hang(hang::Error::DuplicateRendition(id))) if id == "main"
2293		));
2294		assert!(
2295			catalog.outputs.hang_track.largest().is_none(),
2296			"the refused catalog reached the wire"
2297		);
2298	}
2299
2300	#[test]
2301	fn commit_publishes_once() {
2302		let mut broadcast = moq_net::broadcast::Info::new().produce();
2303		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2304
2305		let mut guard = catalog.modify(catalog.next_timestamp()).unwrap();
2306		guard
2307			.audio
2308			.renditions
2309			.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2310		guard.commit().unwrap();
2311
2312		// The drop that follows `commit` must not publish a second snapshot.
2313		catalog.finish().unwrap();
2314		assert_eq!(sent(&catalog), Some(0));
2315	}
2316
2317	/// The newest group start on the hang and MSF catalog tracks, in their timescale.
2318	fn starts(catalog: &Producer) -> [Option<u64>; 2] {
2319		let outputs = &catalog.outputs;
2320		[&outputs.hang_track, &outputs.msf_track].map(|track| track.largest().map(|largest| largest.group))
2321	}
2322
2323	/// `ms` in the catalog tracks' timescale.
2324	fn start(catalog: &Producer, ms: u64) -> u64 {
2325		let at = moq_net::Timestamp::from_millis(ms).unwrap();
2326		catalog.outputs.hang_track.info().rescale(at).unwrap().value()
2327	}
2328
2329	fn ms(ms: u64) -> moq_net::Timestamp {
2330		moq_net::Timestamp::from_millis(ms).unwrap()
2331	}
2332
2333	/// Publish an Opus rendition `name` stamped at `at`.
2334	fn opus(catalog: &mut Producer, name: &str, at: moq_net::Timestamp) -> crate::Result<()> {
2335		let mut guard = catalog.modify(at)?;
2336		guard
2337			.audio
2338			.renditions
2339			.insert(name.to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2340		guard.commit()
2341	}
2342
2343	/// The audio renditions the catalog holds, by name.
2344	fn audio(catalog: &Producer) -> Vec<String> {
2345		catalog.snapshot().audio.renditions.into_keys().collect()
2346	}
2347
2348	/// A container this build only decodes is refused before its rendition is advertised, and the
2349	/// name stays free for a container it can write.
2350	#[test]
2351	fn a_decode_only_container_publishes_no_rendition() {
2352		let mut broadcast = moq_net::broadcast::Info::new().produce();
2353		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2354		let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
2355		config.container = Container::Cts;
2356		let info = catalog.track_info(hang::catalog::PRIORITY.audio);
2357
2358		let net = broadcast.create_track("audio0", info.clone()).unwrap();
2359		let wire = crate::catalog::hang::Wire::try_from(&config).unwrap();
2360		let err = catalog.audio(net, wire, config.clone()).err();
2361		assert!(
2362			matches!(err, Some(crate::Error::Moq(moq_net::Error::Unsupported))),
2363			"{err:?}"
2364		);
2365		assert!(audio(&catalog).is_empty());
2366
2367		config.container = Container::Raw;
2368		let net = broadcast.create_track("audio0", info).unwrap();
2369		let wire = crate::catalog::hang::Wire::try_from(&config).unwrap();
2370		let _audio = catalog.audio(net, wire, config).unwrap();
2371		assert_eq!(audio(&catalog), ["audio0"]);
2372	}
2373
2374	#[tokio::test(start_paused = true)]
2375	async fn a_timestamp_stamps_both_tracks() {
2376		let mut broadcast = moq_net::broadcast::Info::new().produce();
2377		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2378
2379		// Ahead of the clock, as a frame a pipeline composes early.
2380		opus(&mut catalog, "a", ms(60_000)).unwrap();
2381		let at = start(&catalog, 60_000);
2382		assert_eq!(starts(&catalog), [Some(at); 2]);
2383
2384		// The next timestamp lands after it, though the clock reads earlier.
2385		let next = catalog.next_timestamp();
2386		opus(&mut catalog, "b", next).unwrap();
2387		assert_eq!(starts(&catalog), [Some(at + 1); 2]);
2388
2389		opus(&mut catalog, "c", ms(90_000)).unwrap();
2390		assert_eq!(starts(&catalog), [Some(start(&catalog, 90_000)); 2]);
2391	}
2392
2393	#[tokio::test(start_paused = true)]
2394	async fn a_timestamp_that_does_not_advance_is_refused_before_any_edit() {
2395		let mut broadcast = moq_net::broadcast::Info::new().produce();
2396		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2397
2398		opus(&mut catalog, "a", ms(60_000)).unwrap();
2399		let published = starts(&catalog);
2400		for at in [60_000, 59_000] {
2401			let result = opus(&mut catalog, &format!("b{at}"), ms(at));
2402			assert!(
2403				matches!(result, Err(crate::Error::TimestampRewind(_))),
2404				"{at}: {result:?}"
2405			);
2406			assert_eq!(starts(&catalog), published, "a refused catalog reached the wire");
2407		}
2408		// The refusal leaves the tracks open: the next change goes out at its own timestamp, without
2409		// the refused ones.
2410		opus(&mut catalog, "c", ms(61_000)).unwrap();
2411		assert_eq!(starts(&catalog), [Some(start(&catalog, 61_000)); 2]);
2412		assert_eq!(audio(&catalog), ["a", "c"]);
2413	}
2414
2415	#[tokio::test(start_paused = true)]
2416	async fn a_buffered_timestamp_stamps_the_initial_publish() {
2417		let mut broadcast = moq_net::broadcast::Info::new().produce();
2418		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2419
2420		let reserved = catalog.reserve();
2421		opus(&mut catalog, "a", ms(60_000)).unwrap();
2422		assert_eq!(starts(&catalog), [None; 2], "published before the reservation resolved");
2423		// A staged stamp is the floor for the next, which the next timestamp passes.
2424		let result = opus(&mut catalog, "b", ms(59_000));
2425		assert!(matches!(result, Err(crate::Error::TimestampRewind(_))), "{result:?}");
2426		let next = catalog.next_timestamp();
2427		opus(&mut catalog, "c", next).unwrap();
2428		drop(reserved);
2429		assert_eq!(starts(&catalog), [Some(start(&catalog, 60_000) + 1); 2]);
2430		assert_eq!(audio(&catalog), ["a", "c"]);
2431	}
2432
2433	/// An importer's first frame re-bases the clock after a change was staged: the staged stamp moves
2434	/// with it, so the initial publish lands at the same moment on the clock the media runs on.
2435	#[tokio::test(start_paused = true)]
2436	async fn a_staged_timestamp_moves_with_the_clock_an_importer_anchors() {
2437		let mut broadcast = moq_net::broadcast::Info::new().produce();
2438		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2439
2440		let timebase = catalog.timebase();
2441		let reserved = catalog.reserve();
2442		// Staged on the fresh clock, which reads ten seconds.
2443		let staged = catalog.next_timestamp();
2444		opus(&mut catalog, "a", staged).unwrap();
2445
2446		// The first frame, at PTS 1.4s, places the clock so it reads 1.4s now.
2447		timebase.anchor(ms(1_400)).unwrap();
2448		drop(reserved);
2449		assert_eq!(starts(&catalog), [Some(start(&catalog, 1_400)); 2]);
2450	}
2451
2452	/// A change staged before a zero-based input's first frame lands at PTS zero, the earliest moment
2453	/// the clock placed at that frame can name, rather than failing the import.
2454	#[tokio::test(start_paused = true)]
2455	async fn a_timestamp_staged_before_a_zero_based_first_frame_lands_at_zero() {
2456		let mut broadcast = moq_net::broadcast::Info::new().produce();
2457		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2458
2459		let timebase = catalog.timebase();
2460		let reserved = catalog.reserve();
2461		let staged = catalog.next_timestamp();
2462		opus(&mut catalog, "a", staged).unwrap();
2463
2464		// The input takes a while to deliver its first frame, at PTS zero.
2465		tokio::time::advance(std::time::Duration::from_secs(2)).await;
2466		timebase.anchor(ms(0)).unwrap();
2467		drop(reserved);
2468		assert_eq!(starts(&catalog), [Some(0); 2]);
2469	}
2470
2471	/// The anchor may come from a thread outside the runtime the producer was made in: the stamp still
2472	/// moves by the clocks' own readings, not that thread's.
2473	#[tokio::test(start_paused = true)]
2474	async fn a_staged_timestamp_moves_with_an_anchor_from_another_thread() {
2475		// The runtime's time runs a minute ahead of the host's, more than the fresh clock reads.
2476		tokio::time::advance(std::time::Duration::from_secs(60)).await;
2477		let mut broadcast = moq_net::broadcast::Info::new().produce();
2478		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2479
2480		let timebase = catalog.timebase();
2481		let reserved = catalog.reserve();
2482		let staged = catalog.next_timestamp();
2483		opus(&mut catalog, "a", staged).unwrap();
2484
2485		std::thread::spawn(move || timebase.anchor(ms(1_400)).map(drop))
2486			.join()
2487			.unwrap()
2488			.unwrap();
2489		drop(reserved);
2490		assert_eq!(starts(&catalog), [Some(start(&catalog, 1_400)); 2]);
2491	}
2492
2493	#[tokio::test(start_paused = true)]
2494	async fn a_staged_timestamp_stamps_the_internal_edit_opening_the_gate() {
2495		let mut broadcast = moq_net::broadcast::Info::new().produce();
2496		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2497
2498		// A disabled rendition lists no track, so the gate stays shut past the reservation.
2499		drop(catalog.reserve());
2500		let mut guard = catalog.modify(ms(60_000)).unwrap();
2501		let mut disabled = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
2502		disabled.enabled = false;
2503		guard.audio.renditions.insert("a".to_string(), disabled);
2504		guard.commit().unwrap();
2505		assert_eq!(
2506			starts(&catalog),
2507			[None; 2],
2508			"published before the catalog listed a track"
2509		);
2510
2511		// An edit no caller times, such as a rendition's config, that lists one goes out at the
2512		// staged stamp.
2513		let mut guard = catalog.edit().unwrap();
2514		guard
2515			.audio
2516			.renditions
2517			.insert("b".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2518		guard.commit().unwrap();
2519		assert_eq!(starts(&catalog), [Some(start(&catalog, 60_000)); 2]);
2520	}
2521
2522	/// A video rendition `video0` on `catalog`, with a keyframe group at each of `starts` (ms).
2523	fn video0(
2524		broadcast: &mut moq_net::broadcast::Producer,
2525		catalog: &Producer,
2526		starts: &[u64],
2527	) -> crate::container::Producer<crate::catalog::hang::Wire, VideoConfig> {
2528		let net = broadcast
2529			.create_track("video0", catalog.track_info(hang::catalog::PRIORITY.video))
2530			.unwrap();
2531		let mut video = catalog
2532			.video(
2533				net,
2534				crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
2535				VideoConfig::new(hang::catalog::VideoCodec::VP8),
2536			)
2537			.unwrap();
2538		for start in starts {
2539			video
2540				.write(crate::container::Frame {
2541					timestamp: moq_net::Timestamp::from_millis(*start).unwrap(),
2542					decode: None,
2543					duration: None,
2544					payload: Bytes::from_static(b"keyframe"),
2545					keyframe: true,
2546				})
2547				.unwrap();
2548		}
2549		video
2550	}
2551
2552	/// A hinted track declares its hint, not what it measured, once a window has closed.
2553	#[test]
2554	fn a_hint_declares_the_join_interval() {
2555		let mut broadcast = moq_net::broadcast::Info::new().produce();
2556		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2557		let net = broadcast
2558			.create_track("video0", catalog.track_info(hang::catalog::PRIORITY.video))
2559			.unwrap();
2560		let mut video = catalog
2561			.reserve()
2562			.with_interval(std::time::Duration::from_secs(4))
2563			.video(
2564				net,
2565				crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
2566				VideoConfig::new(hang::catalog::VideoCodec::VP8),
2567			)
2568			.unwrap();
2569		for start in [0, 1_000, 2_000] {
2570			assert_eq!(
2571				catalog.snapshot().sync.interval,
2572				None,
2573				"nothing has measured a window yet"
2574			);
2575			video
2576				.write(crate::container::Frame {
2577					timestamp: moq_net::Timestamp::from_millis(start).unwrap(),
2578					decode: None,
2579					duration: None,
2580					payload: Bytes::from_static(b"keyframe"),
2581					keyframe: true,
2582				})
2583				.unwrap();
2584		}
2585		assert_eq!(
2586			catalog.snapshot().sync.interval,
2587			Some(std::time::Duration::from_secs(4))
2588		);
2589	}
2590
2591	/// Without a hint, the interval is measured over a second or a group, whichever is longer,
2592	/// then declared and never changed.
2593	#[tokio::test]
2594	async fn an_unhinted_track_declares_its_measured_interval() {
2595		let mut broadcast = moq_net::broadcast::Info::new().produce();
2596		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2597		let mut video = video0(&mut broadcast, &catalog, &[0, 2_000]);
2598		assert_eq!(catalog.snapshot().sync.interval, None, "still measuring");
2599
2600		for start in [4_000, 9_000, 10_000] {
2601			video
2602				.write(crate::container::Frame {
2603					timestamp: moq_net::Timestamp::from_millis(start).unwrap(),
2604					decode: None,
2605					duration: None,
2606					payload: Bytes::from_static(b"keyframe"),
2607					keyframe: true,
2608				})
2609				.unwrap();
2610		}
2611		// The second group closed the window at two seconds; the five-second group after it overruns.
2612		assert_eq!(
2613			catalog.snapshot().sync.interval,
2614			Some(std::time::Duration::from_secs(2))
2615		);
2616		assert_eq!(catalog.declared_interval(), Some(std::time::Duration::from_secs(2)));
2617	}
2618
2619	/// A track that finishes before its first window closes declares what it saw, so a short
2620	/// publication is still HLS-renderable.
2621	#[test]
2622	fn a_short_track_declares_its_interval_when_it_finishes() {
2623		let mut broadcast = moq_net::broadcast::Info::new().produce();
2624		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2625		let video = video0(&mut broadcast, &catalog, &[0, 500]);
2626		assert_eq!(catalog.snapshot().sync.interval, None, "still measuring");
2627		let _finished = video.finish().unwrap();
2628		assert_eq!(
2629			catalog.snapshot().sync.interval,
2630			Some(std::time::Duration::from_millis(500))
2631		);
2632	}
2633
2634	/// A text track groups only when it has something to say, so it never holds the interval back.
2635	#[test]
2636	fn a_text_track_does_not_join_the_interval() {
2637		let mut broadcast = moq_net::broadcast::Info::new().produce();
2638		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2639		let net = broadcast
2640			.create_track("text0", catalog.track_info(hang::catalog::PRIORITY.text))
2641			.unwrap();
2642		let _text = catalog
2643			.text(
2644				net,
2645				crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
2646				hang::catalog::TextConfig::new(hang::catalog::TextFormat::Vtt),
2647			)
2648			.unwrap();
2649		let _video = video0(&mut broadcast, &catalog, &[0, 2_000, 4_000]);
2650		assert_eq!(
2651			catalog.snapshot().sync.interval,
2652			Some(std::time::Duration::from_secs(2))
2653		);
2654	}
2655
2656	/// A publisher that declares `sync.interval` itself keeps it.
2657	#[test]
2658	fn a_seeded_interval_stands() {
2659		let mut broadcast = moq_net::broadcast::Info::new().produce();
2660		let mut seeded = Catalog::<()>::default();
2661		seeded.sync.interval = Some(std::time::Duration::from_secs(6));
2662		let catalog = Producer::new(&mut broadcast, Config::default().with_catalog(seeded)).unwrap();
2663		let _video = video0(&mut broadcast, &catalog, &[0, 2_000, 4_000]);
2664		assert_eq!(
2665			catalog.snapshot().sync.interval,
2666			Some(std::time::Duration::from_secs(6))
2667		);
2668	}
2669
2670	#[test]
2671	fn clock_is_advertised_under_media() {
2672		let mut broadcast = moq_net::broadcast::Info::new().produce();
2673		let catalog = Producer::<()>::new(&mut broadcast, Config::default()).unwrap();
2674
2675		let snapshot = catalog.snapshot();
2676		assert_eq!(snapshot.sync.clock, catalog.clock().wall());
2677	}
2678
2679	#[test]
2680	fn sibling_broadcasts_share_a_clock_and_capture_time() {
2681		use std::time::Duration;
2682
2683		let captured = kio::clock::now();
2684		let wall = moq_net::time::EPOCH + Duration::from_millis(60_000);
2685		let clock = crate::Clock::at(captured, wall).unwrap();
2686		let (origin, _driver) = moq_net::origin::Producer::new(Default::default());
2687		let front = origin
2688			.route("robot/front.hang", moq_net::origin::RouteOptions::hidden())
2689			.unwrap();
2690		let rear = origin
2691			.route("robot/rear.hang", moq_net::origin::RouteOptions::hidden())
2692			.unwrap();
2693		let catalogs = [
2694			Producer::new(
2695				&mut front.broadcast().clone(),
2696				Config::default().with_clock(clock.clone()),
2697			)
2698			.unwrap(),
2699			Producer::new(
2700				&mut rear.broadcast().clone(),
2701				Config::default().with_clock(clock.clone()),
2702			)
2703			.unwrap(),
2704		];
2705		let mut broadcasts = [front, rear];
2706		for (catalog, broadcast) in catalogs.iter().zip(&mut broadcasts) {
2707			assert_eq!(catalog.snapshot().sync.clock, clock.wall());
2708			let timestamp = catalog.clock().capture(captured).unwrap();
2709			let track = broadcast
2710				.broadcast()
2711				.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
2712				.unwrap();
2713			let mut video = catalog
2714				.video(
2715					track,
2716					crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
2717					VideoConfig::new(hang::catalog::VideoCodec::VP8),
2718				)
2719				.unwrap();
2720			let mut consumer = video.consume();
2721			video
2722				.write(crate::container::Frame {
2723					timestamp,
2724					decode: None,
2725					duration: None,
2726					payload: Bytes::from_static(b"keyframe"),
2727					keyframe: true,
2728				})
2729				.unwrap();
2730			let waiter = kio::Waiter::noop();
2731			let Poll::Ready(Ok(Some(mut group))) = consumer.poll_recv_group(&waiter) else {
2732				panic!("captured group is published");
2733			};
2734			let Poll::Ready(Ok(Some(frame))) = group.poll_read_frame(&waiter) else {
2735				panic!("captured frame is published");
2736			};
2737			let timestamp = frame.timestamp;
2738			assert_eq!(catalog.clock().wall_clock(timestamp).unwrap(), wall);
2739			assert_eq!(
2740				catalog.snapshot().sync.clock.unwrap().wall_clock(timestamp).unwrap(),
2741				wall
2742			);
2743		}
2744	}
2745
2746	/// A broadcast built under one clock and written from others, a paused runtime a minute behind
2747	/// it and a plain thread on the host's, stamps every track on the clock it was built under, so
2748	/// none of them goes back: media and both catalogs.
2749	#[test]
2750	fn a_broadcast_written_from_two_clock_contexts_never_rewinds() {
2751		use hang::catalog::{JsonConfig, Mode};
2752		use std::time::Duration;
2753
2754		let paused = || {
2755			tokio::runtime::Builder::new_current_thread()
2756				.enable_time()
2757				.start_paused(true)
2758				.build()
2759				.unwrap()
2760		};
2761		let (home, away) = (paused(), paused());
2762		let mut broadcast = moq_net::broadcast::Info::default().produce();
2763		let (mut catalog, mut video, readers) = home.block_on(async {
2764			tokio::time::advance(Duration::from_secs(60)).await;
2765			let catalog = Producer::new(
2766				&mut broadcast,
2767				Config::default().with_max_age(Duration::from_secs(3600)),
2768			)
2769			.unwrap();
2770			let video = video0(&mut broadcast, &catalog, &[]);
2771			let consumer = broadcast.consume();
2772			let mut readers = Vec::new();
2773			for name in [hang::Catalog::DEFAULT_NAME, moq_msf::DEFAULT_NAME, "video0"] {
2774				let all = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]);
2775				let track = consumer.track(name).unwrap().subscribe(all).await.unwrap();
2776				readers.push((name, track.ordered()));
2777			}
2778			(catalog, video, readers)
2779		});
2780
2781		// One keyframe group, and one catalog change, so one hang catalog group.
2782		let write = |catalog: &mut Producer, video: &mut crate::container::Producer<_, VideoConfig>, n: u64| {
2783			let timestamp = catalog.timestamp(None).unwrap();
2784			video
2785				.write(crate::container::Frame {
2786					timestamp,
2787					decode: None,
2788					duration: None,
2789					payload: Bytes::from_static(b"keyframe"),
2790					keyframe: true,
2791				})
2792				.unwrap();
2793			catalog
2794				.mutate(
2795					|catalog| {
2796						catalog
2797							.json
2798							.tracks
2799							.insert(format!("json{n}"), JsonConfig::new(Mode::Snapshot));
2800					},
2801					catalog.next_timestamp(),
2802				)
2803				.unwrap();
2804		};
2805		for n in 0..4 {
2806			// Only the clock the broadcast was built under moves it.
2807			home.block_on(tokio::time::advance(Duration::from_secs(4)));
2808			match n % 2 {
2809				0 => away.block_on(async { write(&mut catalog, &mut video, n) }),
2810				_ => std::thread::scope(|scope| {
2811					scope.spawn(|| write(&mut catalog, &mut video, n));
2812				}),
2813			}
2814		}
2815		away.block_on(async {
2816			let _finished = video.finish().unwrap();
2817			catalog.finish().unwrap();
2818		});
2819
2820		home.block_on(async {
2821			for (name, mut track) in readers {
2822				let (mut stamps, mut starts) = (Vec::new(), Vec::<u128>::new());
2823				while let Some(mut group) = track.next_group().await.unwrap() {
2824					let first = stamps.len();
2825					while let Some(frame) = group.read_frame().await.unwrap() {
2826						stamps.push(frame.timestamp.as_micros().unwrap());
2827					}
2828					starts.extend(stamps.get(first).copied());
2829				}
2830				assert!(stamps.is_sorted(), "{name} went back: {stamps:?}");
2831				// The clock read ten seconds when built, and only `home` advanced it, to 26.
2832				let timeline = 10_000_000..=26_000_000;
2833				assert!(
2834					stamps.iter().all(|stamp| timeline.contains(stamp)),
2835					"{name}: {stamps:?}"
2836				);
2837				if name == "video0" {
2838					assert_eq!(starts, [14, 18, 22, 26].map(|secs| secs * 1_000_000), "{name}");
2839				}
2840			}
2841		});
2842	}
2843
2844	/// How far `pts` lands from `clock`'s reading now, which is zero for a frame live on arrival.
2845	fn lateness(clock: &crate::Clock, pts: moq_net::Timestamp) -> std::time::Duration {
2846		let now = clock.now().as_micros().unwrap();
2847		std::time::Duration::from_micros(now.abs_diff(pts.as_micros().unwrap()) as u64)
2848	}
2849
2850	/// A `with_clock` catalog is fixed from the start: even the first importer shifts onto it,
2851	/// landing at the clock's reading on arrival, and the advertised mapping never moves.
2852	#[kio::test]
2853	async fn with_clock_shifts_the_first_importer() {
2854		use std::time::Duration;
2855
2856		kio::clock::sleep(Duration::from_secs(5)).await;
2857		let mut broadcast = moq_net::broadcast::Info::new().produce();
2858		let wall = moq_net::time::EPOCH + Duration::from_millis(60_000);
2859		let start = kio::clock::now().saturating_sub(Duration::from_secs(5));
2860		let config = Config::default().with_clock(crate::Clock::at(start, wall).expect("a representable wall"));
2861		let catalog = Producer::new(&mut broadcast, config).unwrap();
2862
2863		let advertised = Some(moq_net::Timestamp::from_micros(60_000_000).unwrap());
2864		assert_eq!(catalog.snapshot().sync.clock.map(|clock| clock.wall()), advertised);
2865
2866		// The stream starts an hour in; the clock reads five seconds.
2867		let first = moq_net::Timestamp::from_micros(3_600_000_000).unwrap();
2868		let shifted = catalog.timebase().shift(first).unwrap();
2869		assert!(
2870			lateness(&catalog.clock(), shifted) < Duration::from_secs(1),
2871			"{shifted:?}"
2872		);
2873		assert_eq!(catalog.snapshot().sync.clock.map(|clock| clock.wall()), advertised);
2874	}
2875
2876	/// The first timebase to anchor on a clock nothing fixed places it, keeping its timestamps
2877	/// verbatim; its clones share that, while another timebase offsets onto the placed clock.
2878	#[test]
2879	fn the_first_input_places_the_clock() {
2880		use std::time::Duration;
2881
2882		let mut broadcast = moq_net::broadcast::Info::new().produce();
2883		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2884		let timebase = catalog.timebase();
2885
2886		let first = moq_net::Timestamp::from_micros(3_600_000_000).unwrap();
2887		assert_eq!(
2888			timebase.clone().shift(first).unwrap(),
2889			first,
2890			"the first timebase stays verbatim"
2891		);
2892		let clock = catalog.clock();
2893		assert_eq!(catalog.snapshot().sync.clock, clock.wall(), "the anchor is advertised");
2894		let actual = clock.wall_clock(first).unwrap();
2895		let now = kio::clock::wall();
2896		let drift = actual.max(now).saturating_duration_since(actual.min(now));
2897		assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival");
2898
2899		// Its clones keep the offset, whatever they see first.
2900		let later = moq_net::Timestamp::from_micros(3_601_000_000).unwrap();
2901		assert_eq!(timebase.shift(later).unwrap(), later);
2902
2903		// A separate timebase starting at zero lands at now, and the clock stays.
2904		let other = catalog
2905			.timebase()
2906			.shift(moq_net::Timestamp::from_micros(0).unwrap())
2907			.unwrap();
2908		assert!(lateness(&clock, other) < Duration::from_secs(1), "{other:?}");
2909		assert_eq!(
2910			catalog.clock().wall(),
2911			clock.wall(),
2912			"a second timebase never moves the clock"
2913		);
2914	}
2915
2916	/// Taking the clock fixes it, so a copy handed to a capture never goes stale.
2917	#[test]
2918	fn taking_the_clock_fixes_it() {
2919		let mut broadcast = moq_net::broadcast::Info::new().produce();
2920		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2921		let clock = catalog.clock();
2922
2923		let shifted = catalog
2924			.timebase()
2925			.shift(moq_net::Timestamp::from_micros(3_600_000_000).unwrap())
2926			.unwrap();
2927		assert_eq!(catalog.clock().wall(), clock.wall());
2928		assert!(
2929			lateness(&clock, shifted) < std::time::Duration::from_secs(1),
2930			"{shifted:?}"
2931		);
2932	}
2933
2934	/// The first publish fixes the clock too: a snapshot on the wire is a mapping a reader may have
2935	/// copied. A stream at PTS zero would otherwise step it back ten seconds.
2936	#[test]
2937	fn the_first_publish_fixes_the_clock() {
2938		let mut broadcast = moq_net::broadcast::Info::new().produce();
2939		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2940		catalog
2941			.mutate(
2942				|c| {
2943					c.audio
2944						.renditions
2945						.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
2946				},
2947				catalog.next_timestamp(),
2948			)
2949			.unwrap();
2950		let published = catalog.snapshot().sync.clock;
2951
2952		let shifted = catalog
2953			.timebase()
2954			.shift(moq_net::Timestamp::from_micros(0).unwrap())
2955			.unwrap();
2956		assert_eq!(catalog.snapshot().sync.clock, published);
2957		assert!(
2958			shifted.as_micros().unwrap() >= 10_000_000,
2959			"{shifted:?} lands at the clock's reading"
2960		);
2961	}
2962
2963	/// A timebase that knows when its timestamps happened places them there, on a clock it places
2964	/// or one already fixed alike, so two importers of one stream publish identical timestamps.
2965	#[test]
2966	fn a_placed_input_lands_where_it_says() {
2967		use std::time::Duration;
2968
2969		let wall = kio::clock::Wall::now() - Duration::from_secs(2);
2970		let pts = moq_net::Timestamp::from_micros(100_000_000).unwrap();
2971		let later = moq_net::Timestamp::from_micros(101_000_000).unwrap();
2972
2973		let mut broadcast = moq_net::broadcast::Info::new().produce();
2974		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
2975		let timebase = catalog.timebase();
2976		timebase.place(pts, wall).unwrap();
2977		assert_eq!(
2978			timebase.shift(later).unwrap(),
2979			later,
2980			"it placed the clock, so it stays verbatim"
2981		);
2982		let placed = catalog.clock();
2983		assert_eq!(placed.reading(wall).unwrap(), pts.as_micros().unwrap() as i128);
2984
2985		// Placed again on the now fixed clock, the same mapping shifts by nothing.
2986		let again = catalog.timebase();
2987		again.place(pts, wall).unwrap();
2988		assert_eq!(again.shift(later).unwrap(), later);
2989		assert_eq!(catalog.clock().wall(), placed.wall());
2990
2991		// A timebase that already anchored keeps its offset.
2992		assert!(matches!(
2993			timebase.place(pts, wall),
2994			Err(crate::Error::UnmappableTimestamp(_))
2995		));
2996	}
2997
2998	/// A placement lists no track, so alone it publishes nothing: an importer placed before its
2999	/// input declares a track has no catalog to announce until it does, and that catalog carries
3000	/// the placed clock.
3001	#[test]
3002	fn a_placement_alone_publishes_nothing() {
3003		use std::time::Duration;
3004
3005		let wall = kio::clock::Wall::now() - Duration::from_secs(2);
3006		let mut broadcast = moq_net::broadcast::Info::new().produce();
3007		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3008		catalog.timebase().place(moq_net::Timestamp::ZERO, wall).unwrap();
3009		assert_eq!(sent(&catalog), None, "a clock alone reached the wire");
3010
3011		catalog
3012			.mutate(
3013				|catalog| {
3014					catalog
3015						.audio
3016						.renditions
3017						.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3018				},
3019				catalog.next_timestamp(),
3020			)
3021			.unwrap();
3022		assert_eq!(sent(&catalog), Some(0));
3023		assert_eq!(catalog.clock().reading(wall).unwrap(), 0);
3024		assert_eq!(wire(&catalog).sync.clock, catalog.clock().wall());
3025	}
3026
3027	/// Fake this thread's host now a day past the moq epoch, returning a `sync.clock` an hour
3028	/// before it in `scale` units.
3029	fn an_hour_ago(scale: moq_net::Timescale) -> hang::catalog::Clock {
3030		use std::time::Duration;
3031
3032		let now = Duration::from_secs(86_400);
3033		crate::clock::fake_host_wall(moq_net::time::EPOCH + now);
3034		let zero = moq_net::Timestamp::from_secs(now.as_secs() - 3600).unwrap();
3035		hang::catalog::Clock::new(zero.convert(scale).unwrap()).unwrap()
3036	}
3037
3038	/// A derivative writes its input's mapping through `modify()` before anything fixes the clock,
3039	/// and the producer's clock re-bases on it: what it stamps lands under the input's mapping.
3040	#[tokio::test(start_paused = true)]
3041	async fn a_root_clock_written_before_the_clock_is_fixed_rebases_it() {
3042		let input = an_hour_ago(moq_net::Timescale::MICRO);
3043		let mut broadcast = moq_net::broadcast::Info::new().produce();
3044		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3045		// Stamped on its input's timeline, which the adopted clock runs on, the edit stays put.
3046		let at = moq_net::Timestamp::from_secs(3_590).unwrap();
3047		catalog.mutate(|c| c.sync.clock = Some(input), at).unwrap();
3048		assert_eq!(starts(&catalog), [Some(start(&catalog, 3_590_000)); 2]);
3049
3050		assert_eq!(catalog.snapshot().sync.clock, Some(input), "advertised unchanged");
3051		let clock = catalog.clock();
3052		assert_eq!(clock.wall(), Some(input));
3053		assert_eq!(
3054			clock.now(),
3055			moq_net::Timestamp::from_secs(3600)
3056				.unwrap()
3057				.convert(crate::Clock::TIMESCALE)
3058				.unwrap()
3059		);
3060
3061		// The faked host wall clock moves with time, as a real one does.
3062		tokio::time::advance(std::time::Duration::from_secs(3)).await;
3063		crate::clock::fake_host_wall(moq_net::time::EPOCH + std::time::Duration::from_secs(86_403));
3064		assert_eq!(
3065			catalog.timestamp(None).unwrap(),
3066			moq_net::Timestamp::from_micros(3_603_000_000).unwrap()
3067		);
3068
3069		// Re-applying the same mapping once fixed changes nothing.
3070		catalog
3071			.mutate(|c| c.sync.clock = Some(input), catalog.next_timestamp())
3072			.unwrap();
3073		assert_eq!(catalog.clock(), clock);
3074	}
3075
3076	/// An importer stages a change on the fresh clock, which reads ten seconds, then a derivative
3077	/// adopts an input mapping whose clock reads five: returns the producer and that mapping.
3078	fn staged_before_an_adoption() -> (
3079		moq_net::broadcast::Producer,
3080		Producer,
3081		super::super::Reserved,
3082		hang::catalog::Clock,
3083	) {
3084		let now = std::time::Duration::from_secs(86_400);
3085		crate::clock::fake_host_wall(moq_net::time::EPOCH + now);
3086		let zero = moq_net::Timestamp::from_secs(now.as_secs() - 5).unwrap();
3087		let input = hang::catalog::Clock::new(zero.convert(moq_net::Timescale::MICRO).unwrap()).unwrap();
3088
3089		let mut broadcast = moq_net::broadcast::Info::new().produce();
3090		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3091		let reserved = catalog.reserve();
3092		let staged = catalog.next_timestamp();
3093		assert_eq!(staged, ms(10_000).convert(crate::Clock::TIMESCALE).unwrap());
3094		opus(&mut catalog, "a", staged).unwrap();
3095		(broadcast, catalog, reserved, input)
3096	}
3097
3098	/// An edit adopting a `sync.clock` is stamped on the clock it adopts, so it passes the staged
3099	/// stamp once that moves onto the same clock, though it reads earlier than the old one.
3100	#[tokio::test(start_paused = true)]
3101	async fn an_adopting_edit_passes_a_staged_stamp_on_the_clock_it_adopts() {
3102		let (_broadcast, mut catalog, reserved, input) = staged_before_an_adoption();
3103
3104		// Six seconds on the input's clock: past the staged stamp's five there, short of its ten.
3105		catalog
3106			.mutate(
3107				|c| {
3108					c.sync.clock = Some(input);
3109					c.audio
3110						.renditions
3111						.insert("b".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3112				},
3113				ms(6_000),
3114			)
3115			.unwrap();
3116		drop(reserved);
3117		assert_eq!(starts(&catalog), [Some(start(&catalog, 6_000)); 2]);
3118		assert_eq!(audio(&catalog), ["a", "b"]);
3119		assert_eq!(catalog.snapshot().sync.clock, Some(input));
3120	}
3121
3122	/// An adopting edit stamped before the staged stamp, once both are on the clock it adopts, is a
3123	/// rewind: refused with the catalog, clock, and staged stamp unchanged.
3124	#[tokio::test(start_paused = true)]
3125	async fn an_adopting_edit_before_the_staged_stamp_is_refused() {
3126		let (_broadcast, mut catalog, reserved, input) = staged_before_an_adoption();
3127		let clock = catalog.current_clock();
3128
3129		let result = catalog.mutate(
3130			|c| {
3131				c.sync.clock = Some(input);
3132				c.audio
3133					.renditions
3134					.insert("b".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3135			},
3136			ms(4_000),
3137		);
3138		assert!(matches!(result, Err(crate::Error::TimestampRewind(_))), "{result:?}");
3139		assert_eq!(audio(&catalog), ["a"], "the refused edit stayed");
3140		assert_eq!(catalog.current_clock(), clock, "the refused edit moved the clock");
3141
3142		drop(reserved);
3143		assert_eq!(starts(&catalog), [Some(start(&catalog, 10_000)); 2]);
3144	}
3145
3146	/// A dropped guard whose stamp the publish refuses undoes its edit and leaves the tracks open, as
3147	/// a refusal before the edit does.
3148	#[tokio::test(start_paused = true)]
3149	async fn a_dropped_guard_refused_on_publish_keeps_the_tracks_open() {
3150		let (_broadcast, mut catalog, reserved, _input) = staged_before_an_adoption();
3151
3152		let mut guard = catalog.modify(ms(4_000)).unwrap();
3153		guard
3154			.audio
3155			.renditions
3156			.insert("b".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3157		drop(guard);
3158		assert!(catalog.closed().is_none(), "a refused edit closed the catalog");
3159		assert_eq!(audio(&catalog), ["a"]);
3160
3161		let next = catalog.next_timestamp();
3162		opus(&mut catalog, "c", next).unwrap();
3163		drop(reserved);
3164		assert_eq!(audio(&catalog), ["a", "c"]);
3165	}
3166
3167	/// A change staged before the adopted clock's PTS zero precedes every timestamp on it, PTS zero
3168	/// included.
3169	#[tokio::test(start_paused = true)]
3170	async fn an_adopting_edit_at_zero_passes_a_stamp_staged_before_zero() {
3171		let day = std::time::Duration::from_secs(86_400);
3172		crate::clock::fake_host_wall(moq_net::time::EPOCH + day);
3173		let mut broadcast = moq_net::broadcast::Info::new().produce();
3174		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3175		let reserved = catalog.reserve();
3176		let staged = catalog.next_timestamp();
3177		opus(&mut catalog, "a", staged).unwrap();
3178
3179		// The input starts two seconds later, its PTS zero now.
3180		tokio::time::advance(std::time::Duration::from_secs(2)).await;
3181		let now = day + std::time::Duration::from_secs(2);
3182		crate::clock::fake_host_wall(moq_net::time::EPOCH + now);
3183		let zero = moq_net::Timestamp::from_secs(now.as_secs()).unwrap();
3184		let input = hang::catalog::Clock::new(zero.convert(moq_net::Timescale::MICRO).unwrap()).unwrap();
3185
3186		catalog.mutate(|c| c.sync.clock = Some(input), ms(0)).unwrap();
3187		drop(reserved);
3188		assert_eq!(starts(&catalog), [Some(0); 2]);
3189	}
3190
3191	/// A `sync.clock` seeded through `with_catalog` is adopted like one written through `modify()`,
3192	/// never replaced by a fresh clock; one that disagrees with `with_clock` is refused.
3193	#[test]
3194	fn a_seeded_root_clock_is_adopted() {
3195		use std::time::Duration;
3196
3197		let input = an_hour_ago(moq_net::Timescale::MICRO);
3198		let mut seed = Catalog::<()>::default();
3199		seed.sync.clock = Some(input);
3200		let mut broadcast = moq_net::broadcast::Info::new().produce();
3201		let catalog = Producer::new(&mut broadcast, Config::default().with_catalog(seed.clone())).unwrap();
3202		assert_eq!(catalog.snapshot().sync.clock, Some(input));
3203		assert_eq!(catalog.clock().wall(), Some(input));
3204
3205		// The same mapping from `with_clock` agrees in any units, without reading the host's wall
3206		// clock, which may be unset.
3207		let zero = moq_net::time::EPOCH + Duration::from_micros(input.wall().as_micros().unwrap() as u64);
3208		let fixed = crate::Clock::at(kio::clock::now(), zero).unwrap();
3209		seed.sync.clock = Some(an_hour_ago(moq_net::Timescale::MILLI));
3210		crate::clock::fake_host_wall(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400));
3211		let config = Config::default().with_catalog(seed.clone()).with_clock(fixed.clone());
3212		let mut broadcast = moq_net::broadcast::Info::new().produce();
3213		let mut catalog = Producer::new(&mut broadcast, config).unwrap();
3214		assert_eq!(catalog.clock(), fixed);
3215		catalog
3216			.mutate(|c| c.sync.clock = seed.sync.clock, catalog.next_timestamp())
3217			.unwrap();
3218		assert_eq!(catalog.snapshot().sync.clock, Some(input));
3219
3220		// A different one is refused before any catalog track exists.
3221		let other = crate::Clock::at(kio::clock::now(), zero + Duration::from_secs(1)).unwrap();
3222		let config = Config::default().with_catalog(seed).with_clock(other);
3223		let mut broadcast = moq_net::broadcast::Info::new().produce();
3224		assert!(matches!(
3225			Producer::new(&mut broadcast, config),
3226			Err(crate::Error::UnmappableTimestamp(_))
3227		));
3228		broadcast
3229			.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info())
3230			.expect("a refused seed leaves the broadcast untouched");
3231	}
3232
3233	/// A millisecond wall is the same mapping in the clock's microseconds, advertised as such.
3234	#[test]
3235	fn a_millisecond_root_clock_converts() {
3236		let input = an_hour_ago(moq_net::Timescale::MILLI);
3237		let micro = an_hour_ago(moq_net::Timescale::MICRO);
3238		let mut broadcast = moq_net::broadcast::Info::new().produce();
3239		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3240		catalog
3241			.mutate(|c| c.sync.clock = Some(input), catalog.next_timestamp())
3242			.unwrap();
3243		assert_eq!(catalog.snapshot().sync.clock, Some(micro));
3244		assert_eq!(catalog.clock().wall(), Some(micro));
3245
3246		// The millisecond spelling of the fixed mapping is no change.
3247		catalog
3248			.mutate(|c| c.sync.clock = Some(input), catalog.next_timestamp())
3249			.unwrap();
3250		assert_eq!(catalog.snapshot().sync.clock, Some(micro));
3251	}
3252
3253	/// A root `clock` the producer cannot run on is refused, and the catalog keeps advertising the
3254	/// producer's own.
3255	#[test]
3256	fn an_unadoptable_root_clock_is_refused() {
3257		let mut broadcast = moq_net::broadcast::Info::new().produce();
3258		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3259		let own = catalog.current_clock().wall();
3260		let refused = |catalog: &mut Producer, clock: Option<hang::catalog::Clock>| {
3261			let err = catalog
3262				.mutate(|c| c.sync.clock = clock, catalog.next_timestamp())
3263				.unwrap_err();
3264			assert!(matches!(err, crate::Error::UnmappableTimestamp(_)), "{err}");
3265			assert_eq!(catalog.snapshot().sync.clock, own);
3266		};
3267
3268		// One 90 kHz tick is no whole microsecond.
3269		let inexact = an_hour_ago(moq_net::Timescale::MICRO)
3270			.wall()
3271			.convert(moq_net::Timescale::new(90_000).unwrap());
3272		let inexact = moq_net::Timestamp::new(inexact.unwrap().value() + 1, moq_net::Timescale::new(90_000).unwrap());
3273		refused(&mut catalog, Some(hang::catalog::Clock::new(inexact.unwrap()).unwrap()));
3274
3275		// PTS zero a minute after this host's now.
3276		let future = an_hour_ago(moq_net::Timescale::SECOND).wall().value() + 3660;
3277		let future = hang::catalog::Clock::new(moq_net::Timestamp::from_secs(future).unwrap()).unwrap();
3278		refused(&mut catalog, Some(future));
3279
3280		// A change once the clock is handed out, clearing it included.
3281		let taken = catalog.clock();
3282		refused(&mut catalog, Some(an_hour_ago(moq_net::Timescale::MICRO)));
3283		refused(&mut catalog, None);
3284		assert_eq!(catalog.clock(), taken);
3285	}
3286
3287	/// A derivative of a source with no `sync.clock` clears the producer's host wall clock before
3288	/// anything fixes it, and advertises none, on the same timeline. Once fixed, a mapping is refused.
3289	#[tokio::test(start_paused = true)]
3290	async fn a_cleared_root_clock_before_the_clock_is_fixed_advertises_none() {
3291		let _ = an_hour_ago(moq_net::Timescale::MICRO);
3292		let mut broadcast = moq_net::broadcast::Info::new().produce();
3293		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3294		assert!(catalog.snapshot().sync.clock.is_some());
3295		let before = catalog.current_clock();
3296
3297		catalog
3298			.mutate(|c| c.sync.clock = None, catalog.next_timestamp())
3299			.unwrap();
3300		assert_eq!(catalog.snapshot().sync.clock, None, "no wall is invented");
3301		let clock = catalog.clock();
3302		assert_eq!(clock.wall(), None);
3303		assert_eq!(clock, before, "the timeline is unchanged");
3304
3305		// Clearing it again is no change; adopting a mapping now is refused.
3306		catalog
3307			.mutate(|c| c.sync.clock = None, catalog.next_timestamp())
3308			.unwrap();
3309		let err = catalog
3310			.mutate(
3311				|c| c.sync.clock = Some(an_hour_ago(moq_net::Timescale::MICRO)),
3312				catalog.next_timestamp(),
3313			)
3314			.unwrap_err();
3315		assert!(matches!(err, crate::Error::UnmappableTimestamp(_)), "{err}");
3316	}
3317
3318	/// A host whose wall clock reads before 2020 (booted before NTP sync) publishes its media on the
3319	/// monotonic timeline with no root `clock`, rather than advertise a false one. Placing a source's
3320	/// wall time is refused, whether it would place the clock or offset onto it.
3321	#[test]
3322	fn an_unset_host_clock_publishes_without_a_wall() {
3323		use std::time::Duration;
3324
3325		crate::clock::fake_host_wall(kio::clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400));
3326		let mut broadcast = moq_net::broadcast::Info::new().produce();
3327		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3328		assert_eq!(catalog.snapshot().sync.clock, None);
3329
3330		let wall = moq_net::time::EPOCH;
3331		let pts = moq_net::Timestamp::from_micros(1_000_000).unwrap();
3332		assert!(matches!(
3333			catalog.timebase().place(pts, wall),
3334			Err(crate::Error::UnmappableTimestamp(_))
3335		));
3336
3337		let net = broadcast
3338			.create_track("video0", catalog.track_info(hang::catalog::PRIORITY.video))
3339			.unwrap();
3340		let mut video = catalog
3341			.video(
3342				net,
3343				crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
3344				VideoConfig::new(hang::catalog::VideoCodec::VP8),
3345			)
3346			.unwrap();
3347		let mut subscriber = video.consume();
3348		let timestamp = catalog.timestamp(None).unwrap();
3349		video
3350			.write(crate::container::Frame {
3351				timestamp,
3352				decode: None,
3353				duration: None,
3354				payload: Bytes::from_static(b"keyframe"),
3355				keyframe: true,
3356			})
3357			.unwrap();
3358
3359		let snapshot = catalog.snapshot();
3360		assert!(snapshot.video.renditions.contains_key("video0"));
3361		assert_eq!(snapshot.sync.clock, None, "publishing never invents a wall");
3362		let waiter = kio::Waiter::noop();
3363		let Poll::Ready(Ok(Some(mut group))) = subscriber.poll_recv_group(&waiter) else {
3364			panic!("the frame's group is published");
3365		};
3366		let Poll::Ready(Ok(Some(frame))) = group.poll_read_frame(&waiter) else {
3367			panic!("the frame is published");
3368		};
3369		assert_eq!(frame.timestamp, timestamp);
3370
3371		// The catalog clock is fixed now, and has no wall to offset a placement onto.
3372		assert!(matches!(
3373			catalog.timebase().place(pts, wall),
3374			Err(crate::Error::UnmappableTimestamp(_))
3375		));
3376	}
3377
3378	fn h264_config() -> VideoConfig {
3379		let mut config = VideoConfig::new(H264 {
3380			profile: 0x64,
3381			constraints: 0x00,
3382			level: 0x1f,
3383			inline: true,
3384		});
3385		config.container = Container::Legacy;
3386		config
3387	}
3388
3389	// A reserved audio rendition that resolves before a reserved video rendition must not publish an
3390	// audio-only catalog; the first snapshot a consumer sees carries the complete track set. This is
3391	// the moq-dev/moq#1979 convergence race.
3392	#[test]
3393	fn reservation_gates_until_all_renditions_resolve() {
3394		let mut broadcast = moq_net::broadcast::Info::new().produce();
3395		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3396		let mut consumer: Consumer = Consumer::new(catalog.outputs.hang_track.consume());
3397		let waiter = kio::Waiter::noop();
3398
3399		let reserved = catalog.reserve();
3400		let mut audio = reserved.init::<AudioConfig>("audio0").unwrap();
3401		let mut video = reserved.init::<VideoConfig>("video0").unwrap();
3402		drop(reserved); // done reserving; both renditions still outstanding
3403
3404		// Audio resolves first: withheld, because video is still outstanding.
3405		audio.set(AudioConfig::new(AudioCodec::Opus, 48_000, 2)).unwrap();
3406		assert!(
3407			matches!(consumer.poll_next(&waiter), Poll::Pending),
3408			"an audio-only catalog must not publish while video is unresolved"
3409		);
3410
3411		// Video resolves: the complete catalog publishes now, in one snapshot.
3412		video.set(h264_config()).unwrap();
3413		let snapshot = match consumer.poll_next(&waiter) {
3414			Poll::Ready(Ok(Some(c))) => c.value,
3415			other => panic!("expected the complete catalog, got {other:?}"),
3416		};
3417		assert!(snapshot.audio.renditions.contains_key("audio0"));
3418		assert!(snapshot.video.renditions.contains_key("video0"));
3419		assert!(
3420			matches!(consumer.poll_next(&waiter), Poll::Pending),
3421			"only the one complete snapshot should be published"
3422		);
3423	}
3424
3425	#[test]
3426	fn live_rendition_owns_its_name_without_gating_the_catalog() {
3427		let mut broadcast = moq_net::broadcast::Info::new().produce();
3428		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3429		let mut consumer: Consumer = Consumer::new(catalog.outputs.hang_track.consume());
3430		let waiter = kio::Waiter::noop();
3431
3432		let _unresolved = catalog.rendition::<VideoConfig>("video0").unwrap();
3433		assert!(
3434			catalog.rendition::<VideoConfig>("video0").is_err(),
3435			"the unresolved live rendition owns its name"
3436		);
3437		let mut audio = catalog.rendition::<AudioConfig>("audio0").unwrap();
3438		audio.set(AudioConfig::new(AudioCodec::Opus, 48_000, 2)).unwrap();
3439
3440		let snapshot = match consumer.poll_next(&waiter) {
3441			Poll::Ready(Ok(Some(c))) => c.value,
3442			other => panic!("expected the incremental audio catalog, got {other:?}"),
3443		};
3444		assert!(snapshot.audio.renditions.contains_key("audio0"));
3445		assert!(!snapshot.video.renditions.contains_key("video0"));
3446	}
3447
3448	#[test]
3449	fn metadata_alone_does_not_publish_the_initial_catalog() {
3450		let mut broadcast = moq_net::broadcast::Info::new().produce();
3451		let config = Config::default().with_catalog(Catalog::<Extra>::default());
3452		let mut catalog = Producer::new(&mut broadcast, config).unwrap();
3453		let mut consumer: Consumer<Extra> = Consumer::new(catalog.outputs.hang_track.consume());
3454		let waiter = kio::Waiter::noop();
3455		let reserved = catalog.reserve();
3456
3457		catalog
3458			.modify(catalog.next_timestamp())
3459			.unwrap()
3460			.set_section("mpegts", serde_json::json!({ "programs": [1] }))
3461			.unwrap();
3462		assert!(
3463			matches!(consumer.poll_next(&waiter), Poll::Pending),
3464			"extension metadata must not publish an empty broadcast"
3465		);
3466		drop(reserved);
3467		assert!(
3468			matches!(consumer.poll_next(&waiter), Poll::Pending),
3469			"releasing the importer must not publish metadata without a track"
3470		);
3471
3472		catalog
3473			.modify(catalog.next_timestamp())
3474			.unwrap()
3475			.audio
3476			.renditions
3477			.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3478		let snapshot = match consumer.poll_next(&waiter) {
3479			Poll::Ready(Ok(Some(c))) => c.value,
3480			other => panic!("expected a catalog naming the track, got {other:?}"),
3481		};
3482		assert!(snapshot.audio.renditions.contains_key("audio0"));
3483		assert!(snapshot.ext.get("mpegts").is_some());
3484	}
3485
3486	/// A metadata edit after the last reservation released is still an initial publish, so it waits
3487	/// for a track too.
3488	#[test]
3489	fn metadata_after_release_does_not_publish_the_initial_catalog() {
3490		let mut broadcast = moq_net::broadcast::Info::new().produce();
3491		let config = Config::default().with_catalog(Catalog::<Extra>::default());
3492		let mut catalog = Producer::new(&mut broadcast, config).unwrap();
3493		let mut consumer: Consumer<Extra> = Consumer::new(catalog.outputs.hang_track.consume());
3494		let waiter = kio::Waiter::noop();
3495
3496		let reserved = catalog.reserve();
3497		catalog
3498			.modify(catalog.next_timestamp())
3499			.unwrap()
3500			.set_section("mpegts", serde_json::json!({ "programs": [1] }))
3501			.unwrap();
3502		drop(reserved);
3503		catalog
3504			.modify(catalog.next_timestamp())
3505			.unwrap()
3506			.set_section("mpegts", serde_json::json!({ "programs": [1], "muxRate": 1 }))
3507			.unwrap();
3508		assert!(
3509			matches!(consumer.poll_next(&waiter), Poll::Pending),
3510			"a later metadata edit must not publish an empty broadcast"
3511		);
3512
3513		catalog
3514			.modify(catalog.next_timestamp())
3515			.unwrap()
3516			.audio
3517			.renditions
3518			.insert("audio0".to_string(), AudioConfig::new(AudioCodec::Opus, 48_000, 2));
3519		let snapshot = match consumer.poll_next(&waiter) {
3520			Poll::Ready(Ok(Some(c))) => c.value,
3521			other => panic!("expected a catalog naming the track, got {other:?}"),
3522		};
3523		assert!(snapshot.audio.renditions.contains_key("audio0"));
3524	}
3525
3526	/// A live rendition holds its name before its config arrives, which lists no track yet.
3527	#[test]
3528	fn an_unconfigured_rendition_does_not_publish_the_initial_catalog() {
3529		let mut broadcast = moq_net::broadcast::Info::new().produce();
3530		let config = Config::default().with_catalog(Catalog::<Extra>::default());
3531		let mut catalog = Producer::new(&mut broadcast, config).unwrap();
3532		let mut consumer: Consumer<Extra> = Consumer::new(catalog.outputs.hang_track.consume());
3533		let waiter = kio::Waiter::noop();
3534
3535		let net = broadcast
3536			.create_track("video0", catalog.track_info(hang::catalog::PRIORITY.video))
3537			.unwrap();
3538		let mut video = catalog
3539			.video(
3540				net,
3541				crate::catalog::hang::Wire::legacy(crate::container::Kind::Video),
3542				None,
3543			)
3544			.unwrap();
3545		let reserved = catalog.reserve();
3546		catalog
3547			.modify(catalog.next_timestamp())
3548			.unwrap()
3549			.set_section("mpegts", serde_json::json!({ "programs": [1] }))
3550			.unwrap();
3551		drop(reserved);
3552		assert!(
3553			matches!(consumer.poll_next(&waiter), Poll::Pending),
3554			"an unconfigured rendition is not a listed track"
3555		);
3556
3557		video.set(VideoConfig::new(hang::catalog::VideoCodec::VP8)).unwrap();
3558		let snapshot = match consumer.poll_next(&waiter) {
3559			Poll::Ready(Ok(Some(c))) => c.value,
3560			other => panic!("expected a catalog naming the track, got {other:?}"),
3561		};
3562		assert!(snapshot.video.renditions.contains_key("video0"));
3563	}
3564
3565	/// A disabled rendition promises no frames, so it lists no track until it is enabled.
3566	#[test]
3567	fn a_disabled_rendition_does_not_publish_the_initial_catalog() {
3568		let mut broadcast = moq_net::broadcast::Info::new().produce();
3569		let config = Config::default().with_catalog(Catalog::<Extra>::default());
3570		let catalog = Producer::new(&mut broadcast, config).unwrap();
3571		let mut consumer: Consumer<Extra> = Consumer::new(catalog.outputs.hang_track.consume());
3572		let waiter = kio::Waiter::noop();
3573
3574		let net = broadcast
3575			.create_track("audio0", catalog.track_info(hang::catalog::PRIORITY.audio))
3576			.unwrap();
3577		let mut audio = catalog
3578			.audio(
3579				net,
3580				crate::catalog::hang::Wire::legacy(crate::container::Kind::Audio),
3581				None,
3582			)
3583			.unwrap();
3584		let reserved = catalog.reserve();
3585		let mut disabled = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
3586		disabled.enabled = false;
3587		audio.set(disabled.clone()).unwrap();
3588		drop(reserved);
3589		assert!(
3590			matches!(consumer.poll_next(&waiter), Poll::Pending),
3591			"a disabled rendition is not a servable track"
3592		);
3593
3594		disabled.enabled = true;
3595		audio.set(disabled).unwrap();
3596		let snapshot = match consumer.poll_next(&waiter) {
3597			Poll::Ready(Ok(Some(c))) => c.value,
3598			other => panic!("expected a catalog naming the track, got {other:?}"),
3599		};
3600		assert!(snapshot.audio.renditions["audio0"].enabled);
3601	}
3602
3603	// Dropping a reservation without fulfilling it (a stream that never produced a config) still opens
3604	// the gate, publishing whatever did resolve.
3605	#[test]
3606	fn reservation_gate_opens_when_unresolved_reservation_is_dropped() {
3607		let mut broadcast = moq_net::broadcast::Info::new().produce();
3608		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3609		let mut consumer: Consumer = Consumer::new(catalog.outputs.hang_track.consume());
3610		let waiter = kio::Waiter::noop();
3611
3612		let reserved = catalog.reserve();
3613		let mut audio = reserved.init::<AudioConfig>("audio0").unwrap();
3614		let video = reserved.init::<VideoConfig>("video0").unwrap();
3615		drop(reserved);
3616
3617		audio.set(AudioConfig::new(AudioCodec::Opus, 48_000, 2)).unwrap();
3618		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
3619
3620		// The video stream never resolves and is cancelled; the audio-only catalog publishes.
3621		drop(video);
3622		let snapshot = match consumer.poll_next(&waiter) {
3623			Poll::Ready(Ok(Some(c))) => c.value,
3624			other => panic!("expected the audio catalog, got {other:?}"),
3625		};
3626		assert!(snapshot.audio.renditions.contains_key("audio0"));
3627		assert!(!snapshot.video.renditions.contains_key("video0"));
3628	}
3629
3630	// A change staged while a deferred importer still holds a reservation (mimicking a TS stream whose
3631	// config resolves late, e.g. AAC) must not publish until that rendition resolves, so no incomplete
3632	// intermediate snapshot leaks out.
3633	#[test]
3634	fn staged_change_waits_for_a_held_reservation() {
3635		let mut broadcast = moq_net::broadcast::Info::new().produce();
3636		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3637		let mut consumer: Consumer = Consumer::new(catalog.outputs.hang_track.consume());
3638		let waiter = kio::Waiter::noop();
3639
3640		// A deferred importer grabs a reservation up front and holds it until it can resolve.
3641		let deferred = catalog.reserve();
3642
3643		// Meanwhile an eager rendition resolves and stages a catalog change. The importer keeps its
3644		// rendition alive (dropping it would retire the track), so bind it.
3645		let early = catalog.reserve();
3646		let mut a0 = early.init::<AudioConfig>("audio0").unwrap();
3647		a0.set(AudioConfig::new(AudioCodec::Opus, 48_000, 2)).unwrap();
3648		drop(early);
3649		assert!(
3650			matches!(consumer.poll_next(&waiter), Poll::Pending),
3651			"the staged rendition must wait for the deferred importer's held reservation"
3652		);
3653
3654		// The deferred importer finally builds its rendition and resolves it.
3655		let mut late = deferred.init::<AudioConfig>("audio1").unwrap();
3656		drop(deferred); // the importer releases its own hold; only the rendition's remains
3657		assert!(matches!(consumer.poll_next(&waiter), Poll::Pending));
3658		late.set(AudioConfig::new(AudioCodec::Opus, 48_000, 1)).unwrap();
3659
3660		let snapshot = match consumer.poll_next(&waiter) {
3661			Poll::Ready(Ok(Some(c))) => c.value,
3662			other => panic!("expected one complete catalog, got {other:?}"),
3663		};
3664		assert!(snapshot.audio.renditions.contains_key("audio0"));
3665		assert!(snapshot.audio.renditions.contains_key("audio1"));
3666		assert!(
3667			matches!(consumer.poll_next(&waiter), Poll::Pending),
3668			"only the one complete snapshot should be published"
3669		);
3670	}
3671
3672	#[test]
3673	fn convert_simple() {
3674		let mut video_config = VideoConfig::new(H264 {
3675			profile: 0x64,
3676			constraints: 0x00,
3677			level: 0x1f,
3678			inline: true,
3679		});
3680		video_config.coded_width = Some(1280);
3681		video_config.coded_height = Some(720);
3682		video_config.bitrate = Some(6_000_000);
3683		video_config.framerate = Some(30.0);
3684		video_config.container = Container::Legacy;
3685
3686		let mut video_renditions = BTreeMap::new();
3687		video_renditions.insert("video0.avc3".to_string(), video_config);
3688
3689		let mut audio_config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
3690		audio_config.bitrate = Some(128_000);
3691		audio_config.container = Container::Legacy;
3692
3693		let mut audio_renditions = BTreeMap::new();
3694		audio_renditions.insert("audio0".to_string(), audio_config);
3695
3696		let mut catalog = hang::Catalog::default();
3697		catalog.video.renditions = video_renditions;
3698		catalog.audio.renditions = audio_renditions;
3699
3700		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3701
3702		assert_eq!(msf.tracks.len(), 2);
3703
3704		let video = &msf.tracks[0];
3705		assert_eq!(video.name, "video0.avc3");
3706		assert_eq!(video.role, Some(moq_msf::Role::Video));
3707		assert_eq!(video.packaging, moq_msf::Packaging::Legacy);
3708		assert_eq!(video.codec, Some("avc3.64001f".to_string()));
3709		assert_eq!(video.width, Some(1280));
3710		assert_eq!(video.height, Some(720));
3711		assert_eq!(video.framerate, Some(30.0));
3712		assert_eq!(video.bitrate, Some(6_000_000));
3713		assert!(video.init_data.is_none());
3714		// H.264 may carry B-frames, so SAP starting type is 2 (leading pictures allowed).
3715		assert_eq!(video.max_grp_sap_starting_type, Some(2));
3716		assert_eq!(video.max_obj_sap_starting_type, Some(2));
3717		assert_eq!(video.jitter, None);
3718
3719		let audio = &msf.tracks[1];
3720		assert_eq!(audio.name, "audio0");
3721		assert_eq!(audio.role, Some(moq_msf::Role::Audio));
3722		assert_eq!(audio.packaging, moq_msf::Packaging::Legacy);
3723		assert_eq!(audio.codec, Some("opus".to_string()));
3724		assert_eq!(audio.samplerate, Some(48_000));
3725		assert_eq!(audio.channel_config, Some("2".to_string()));
3726		assert_eq!(audio.bitrate, Some(128_000));
3727		assert_eq!(audio.max_grp_sap_starting_type, Some(1));
3728		assert_eq!(audio.max_obj_sap_starting_type, Some(1));
3729		assert_eq!(audio.jitter, None);
3730	}
3731
3732	// A LOC rendition must advertise `packaging: loc`. MSF-01 has no legacy packaging, so falling into
3733	// the legacy arm published a catalog that named a container the receiver would not find on the wire.
3734	#[test]
3735	fn convert_video_loc_container() {
3736		let mut video_config = VideoConfig::new(H264 {
3737			profile: 0x64,
3738			constraints: 0x00,
3739			level: 0x1f,
3740			inline: true,
3741		});
3742		video_config.container = Container::Loc;
3743
3744		let mut video_renditions = BTreeMap::new();
3745		video_renditions.insert("video0.avc3".to_string(), video_config);
3746
3747		let mut catalog = hang::Catalog::default();
3748		catalog.video.renditions = video_renditions;
3749
3750		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3751		assert_eq!(msf.tracks.len(), 1);
3752		assert_eq!(msf.tracks[0].packaging, moq_msf::Packaging::Loc);
3753	}
3754
3755	#[test]
3756	fn convert_audio_loc_container() {
3757		let mut audio_config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
3758		audio_config.container = Container::Loc;
3759
3760		let mut audio_renditions = BTreeMap::new();
3761		audio_renditions.insert("audio0".to_string(), audio_config);
3762
3763		let mut catalog = hang::Catalog::default();
3764		catalog.audio.renditions = audio_renditions;
3765
3766		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3767		assert_eq!(msf.tracks.len(), 1);
3768		assert_eq!(msf.tracks[0].packaging, moq_msf::Packaging::Loc);
3769	}
3770
3771	// An unrecognized container keeps its wire kind instead of posing as legacy: hang says such a
3772	// rendition must be ignored, and no MSF consumer claims an unknown packaging.
3773	#[test]
3774	fn convert_unknown_container_keeps_its_kind() {
3775		let container: Container = serde_json::from_value(serde_json::json!({ "kind": "future" })).unwrap();
3776		assert!(matches!(container, Container::Unknown(_)));
3777
3778		let mut audio_config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
3779		audio_config.container = container;
3780
3781		let mut audio_renditions = BTreeMap::new();
3782		audio_renditions.insert("audio0".to_string(), audio_config);
3783
3784		let mut catalog = hang::Catalog::default();
3785		catalog.audio.renditions = audio_renditions;
3786
3787		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3788		assert_eq!(msf.tracks.len(), 1);
3789		assert_eq!(
3790			msf.tracks[0].packaging,
3791			moq_msf::Packaging::Unknown("future".to_string())
3792		);
3793	}
3794
3795	#[test]
3796	fn convert_with_description() {
3797		let mut video_config = VideoConfig::new(H264 {
3798			profile: 0x64,
3799			constraints: 0x00,
3800			level: 0x1f,
3801			inline: false,
3802		});
3803		video_config.description = Some(Bytes::from_static(&[0x01, 0x02, 0x03]));
3804		video_config.coded_width = Some(1920);
3805		video_config.coded_height = Some(1080);
3806		video_config.container = Container::Legacy;
3807
3808		let mut video_renditions = BTreeMap::new();
3809		video_renditions.insert("video0.m4s".to_string(), video_config);
3810
3811		let mut catalog = hang::Catalog::default();
3812		catalog.video.renditions = video_renditions;
3813
3814		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3815		let video = &msf.tracks[0];
3816		assert_eq!(video.init_data.as_deref(), Some("AQID"));
3817	}
3818
3819	#[test]
3820	fn convert_empty() {
3821		let catalog = hang::Catalog::default();
3822		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3823		assert!(msf.tracks.is_empty());
3824	}
3825
3826	#[test]
3827	fn convert_cmaf_packaging() {
3828		let mut video_config = VideoConfig::new(H264 {
3829			profile: 0x64,
3830			constraints: 0x00,
3831			level: 0x28,
3832			inline: false,
3833		});
3834		video_config.coded_width = Some(1920);
3835		video_config.coded_height = Some(1080);
3836		video_config.container = Container::Cmaf {
3837			init: base64::engine::general_purpose::STANDARD
3838				.decode("AAAYZ2Z0eXA=")
3839				.unwrap()
3840				.into(),
3841		};
3842
3843		let mut video_renditions = BTreeMap::new();
3844		video_renditions.insert("video0.m4s".to_string(), video_config);
3845
3846		let mut catalog = hang::Catalog::default();
3847		catalog.video.renditions = video_renditions;
3848
3849		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3850		let video = &msf.tracks[0];
3851		assert_eq!(video.packaging, moq_msf::Packaging::Cmaf);
3852		assert_eq!(video.init_data.as_deref(), Some("AAAYZ2Z0eXA="));
3853	}
3854
3855	#[test]
3856	fn convert_sap_h264_with_jitter() {
3857		let mut video_config = VideoConfig::new(H264 {
3858			profile: 0x64,
3859			constraints: 0x00,
3860			level: 0x1f,
3861			inline: true,
3862		});
3863		video_config.coded_width = Some(1280);
3864		video_config.coded_height = Some(720);
3865		video_config.framerate = Some(30.0);
3866		video_config.container = Container::Legacy;
3867		video_config.jitter = Some(std::time::Duration::from_millis(100));
3868		video_config.delay = Some(std::time::Duration::from_millis(200));
3869
3870		let mut video_renditions = BTreeMap::new();
3871		video_renditions.insert("video0".to_string(), video_config);
3872
3873		let mut audio_config = AudioConfig::new(AudioCodec::Opus, 48_000, 2);
3874		audio_config.container = Container::Legacy;
3875		audio_config.jitter = Some(std::time::Duration::from_millis(40));
3876		audio_config.delay = Some(std::time::Duration::from_millis(80));
3877
3878		let mut audio_renditions = BTreeMap::new();
3879		audio_renditions.insert("audio0".to_string(), audio_config);
3880
3881		let mut catalog = hang::Catalog::default();
3882		catalog.video.renditions = video_renditions;
3883		catalog.audio.renditions = audio_renditions;
3884
3885		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3886
3887		let video = &msf.tracks[0];
3888		assert_eq!(video.role, Some(moq_msf::Role::Video));
3889		// H.264 may carry B-frames, so SAP starting type is 2.
3890		assert_eq!(video.max_grp_sap_starting_type, Some(2));
3891		assert_eq!(video.max_obj_sap_starting_type, Some(2));
3892		assert_eq!(video.jitter, Some(std::time::Duration::from_millis(100)));
3893		assert_eq!(video.delay, Some(std::time::Duration::from_millis(200)));
3894
3895		let audio = &msf.tracks[1];
3896		assert_eq!(audio.role, Some(moq_msf::Role::Audio));
3897		assert_eq!(audio.max_grp_sap_starting_type, Some(1));
3898		assert_eq!(audio.max_obj_sap_starting_type, Some(1));
3899		assert_eq!(audio.jitter, Some(std::time::Duration::from_millis(40)));
3900		assert_eq!(audio.delay, Some(std::time::Duration::from_millis(80)));
3901	}
3902
3903	#[test]
3904	fn convert_sap_h265() {
3905		use hang::catalog::H265;
3906
3907		let mut video_config = VideoConfig::new(H265 {
3908			in_band: false,
3909			profile_space: 0,
3910			profile_idc: 1,
3911			profile_compatibility_flags: [0, 0, 0, 0],
3912			tier_flag: false,
3913			level_idc: 93,
3914			constraint_flags: [0, 0, 0, 0, 0, 0],
3915		});
3916		video_config.coded_width = Some(1920);
3917		video_config.coded_height = Some(1080);
3918		video_config.framerate = Some(60.0);
3919		video_config.container = Container::Legacy;
3920
3921		let mut video_renditions = BTreeMap::new();
3922		video_renditions.insert("video0".to_string(), video_config);
3923
3924		let mut catalog = hang::Catalog::default();
3925		catalog.video.renditions = video_renditions;
3926
3927		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3928		let video = &msf.tracks[0];
3929		// H.265 SAP behavior isn't validated end-to-end yet, so we omit the
3930		// SAP fields rather than advertise something we haven't verified.
3931		assert_eq!(video.max_grp_sap_starting_type, None);
3932		assert_eq!(video.max_obj_sap_starting_type, None);
3933		assert_eq!(video.jitter, None);
3934	}
3935
3936	#[test]
3937	fn convert_sap_unknown_codec() {
3938		use hang::catalog::VideoCodec;
3939
3940		let mut video_config = VideoConfig::new(VideoCodec::Unknown("future-codec.01".to_string()));
3941		video_config.container = Container::Legacy;
3942
3943		let mut video_renditions = BTreeMap::new();
3944		video_renditions.insert("video0".to_string(), video_config);
3945
3946		let mut catalog = hang::Catalog::default();
3947		catalog.video.renditions = video_renditions;
3948
3949		let msf = to_msf_media::<()>(&catalog, &moq_net::Path::empty());
3950		let video = &msf.tracks[0];
3951		assert_eq!(video.max_grp_sap_starting_type, None);
3952		assert_eq!(video.max_obj_sap_starting_type, None);
3953	}
3954
3955	/// A catalog with live video renditions named `names`, each already set.
3956	fn estimating(names: &[&str]) -> (moq_net::broadcast::Producer, Producer, Vec<super::super::VideoTrack>) {
3957		let mut broadcast = moq_net::broadcast::Info::new().produce();
3958		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
3959		let reserved = catalog.reserve();
3960		let renditions = names
3961			.iter()
3962			.map(|name| {
3963				let mut rendition = reserved.init::<VideoConfig>(*name).unwrap();
3964				rendition.set(VideoConfig::new(hang::catalog::VideoCodec::VP8)).unwrap();
3965				rendition
3966			})
3967			.collect();
3968		drop(reserved);
3969		(broadcast, catalog, renditions)
3970	}
3971
3972	fn jitter(ms: u64) -> super::super::Estimate {
3973		super::super::Estimate::default().with_jitter(std::time::Duration::from_millis(ms))
3974	}
3975
3976	/// How many catalogs have gone out on the wire.
3977	/// How many hang catalogs went out before the newest, or `None` before the first.
3978	fn sent<E: CatalogExt>(catalog: &Producer<E>) -> Option<u64> {
3979		catalog.outputs.published[0]
3980			.load(std::sync::atomic::Ordering::Relaxed)
3981			.checked_sub(1)
3982	}
3983
3984	/// The catalog a viewer joining now receives.
3985	fn wire(catalog: &Producer) -> Catalog<()> {
3986		let mut consumer: Consumer = Consumer::new(catalog.outputs.hang_track.consume());
3987		match consumer.poll_next(&kio::Waiter::noop()) {
3988			Poll::Ready(Ok(Some(catalog))) => catalog.value,
3989			_ => panic!("a published catalog"),
3990		}
3991	}
3992
3993	fn wire_jitter(catalog: &Producer, name: &str) -> Option<std::time::Duration> {
3994		wire(catalog).video.renditions[name].jitter
3995	}
3996
3997	/// Two renditions with two B-frames plus audio, written in lockstep in decode order, one frame
3998	/// each per 20 ms and a group per frame, each reading handed to its rendition after every write.
3999	/// The tracks in `late` start measuring at the third frame, as after a late join or a
4000	/// discontinuity; the audio may be `offset` behind. Returns each delay on the wire.
4001	async fn lockstep_on_the_wire(late: &[usize], offset: u64) -> Vec<Option<std::time::Duration>> {
4002		let names = ["hevc", "avc", "audio"];
4003		let (_broadcast, catalog, mut renditions) = estimating(&names);
4004		let order = super::super::estimate::Order::default();
4005		let mut estimators: Vec<_> = (0..3)
4006			.map(|_| super::super::Estimator::with_order(order.clone()))
4007			.collect();
4008		let decode_order = [0u64, 60, 20, 40].into_iter().chain((1..50u64).flat_map(|gop| {
4009			let base = gop * 60;
4010			[base + 60, base + 20, base + 40]
4011		}));
4012		for (tick, pts) in decode_order.enumerate() {
4013			let audio = (tick as u64 * 20).saturating_sub(offset);
4014			for (i, pts) in [pts, pts, audio].into_iter().enumerate() {
4015				if tick < 2 && late.contains(&i) {
4016					continue;
4017				}
4018				estimators[i].write(moq_net::Timestamp::from_micros(pts * 1_000).unwrap(), 1_000);
4019				estimators[i].cut(None);
4020				renditions[i].estimate(estimators[i].reading()).unwrap();
4021			}
4022			tokio::time::advance(std::time::Duration::from_millis(20)).await;
4023		}
4024		names
4025			.iter()
4026			.map(|name| wire(&catalog).video.renditions[*name].delay)
4027			.collect()
4028	}
4029
4030	/// A track that starts measuring on a B-frame, or on audio trailing one, never publishes the
4031	/// reorder as `delay`, which the catalog could then never lower. A constant offset still does.
4032	///
4033	/// Regression, from [moq-dev/moq#7689](https://github.com/moq-dev/moq/pull/7689): the least
4034	/// trail over everything written so far started at the reorder, went out, and stuck.
4035	#[tokio::test(start_paused = true)]
4036	async fn a_late_start_publishes_no_reorder_delay() {
4037		assert_eq!(lockstep_on_the_wire(&[], 0).await, [None, None, None]);
4038		assert_eq!(lockstep_on_the_wire(&[0, 2], 0).await, [None, None, None]);
4039		let ms = std::time::Duration::from_millis;
4040		assert_eq!(lockstep_on_the_wire(&[0, 2], 200).await, [None, None, Some(ms(200))]);
4041	}
4042
4043	/// A rising estimate publishes at once, then coalesces until an observation after the window,
4044	/// which carries the latest value. Regression: every rise republished the catalog.
4045	#[tokio::test(start_paused = true)]
4046	async fn estimate_rises_publish_at_the_leading_edge_and_coalesce() {
4047		let (_broadcast, catalog, mut renditions) = estimating(&["v"]);
4048		let v = &mut renditions[0];
4049		let initial = sent(&catalog);
4050
4051		v.estimate(jitter(1)).unwrap();
4052		let leading = sent(&catalog);
4053		assert_ne!(leading, initial, "the first rise publishes at once");
4054		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(1)));
4055
4056		for ms in 2..=17 {
4057			tokio::time::advance(std::time::Duration::from_millis(50)).await;
4058			v.estimate(jitter(ms)).unwrap();
4059		}
4060		assert_eq!(sent(&catalog), leading, "rises inside the window are held");
4061		assert_eq!(
4062			catalog.snapshot().video.renditions["v"].jitter,
4063			Some(std::time::Duration::from_millis(17)),
4064			"the held value is already in the catalog"
4065		);
4066
4067		// No timer: the window ending publishes nothing until the next observation.
4068		tokio::time::advance(std::time::Duration::from_millis(200)).await;
4069		assert_eq!(sent(&catalog), leading);
4070		v.estimate(jitter(17)).unwrap();
4071		let trailing = sent(&catalog);
4072		assert_ne!(trailing, leading, "an unchanged observation releases the held rise");
4073		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(17)));
4074
4075		// Nothing is held, so later observations publish nothing.
4076		tokio::time::advance(std::time::Duration::from_secs(2)).await;
4077		v.estimate(jitter(17)).unwrap();
4078		assert_eq!(sent(&catalog), trailing);
4079
4080		// A rise a window after the trailing publish is a new leading edge.
4081		v.estimate(jitter(18)).unwrap();
4082		assert_ne!(sent(&catalog), trailing);
4083		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(18)));
4084	}
4085
4086	/// A structural edit never waits, carries the held estimate, and opens a new window.
4087	#[tokio::test(start_paused = true)]
4088	async fn structural_edit_folds_a_held_estimate() {
4089		let (_broadcast, mut catalog, mut renditions) = estimating(&["v"]);
4090		let v = &mut renditions[0];
4091		v.estimate(jitter(1)).unwrap();
4092		tokio::time::advance(std::time::Duration::from_millis(100)).await;
4093		v.estimate(jitter(2)).unwrap();
4094		let held = sent(&catalog);
4095
4096		catalog
4097			.mutate(
4098				|catalog| {
4099					catalog.video.display = Some(hang::catalog::Display {
4100						width: 1280,
4101						height: 720,
4102					})
4103				},
4104				catalog.next_timestamp(),
4105			)
4106			.unwrap();
4107		let folded = sent(&catalog);
4108		assert_ne!(folded, held, "a structural edit publishes at once");
4109		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(2)));
4110
4111		// The fold opened a window: the next rise inside it is held, and nothing is left to flush.
4112		tokio::time::advance(std::time::Duration::from_millis(950)).await;
4113		v.estimate(jitter(3)).unwrap();
4114		assert_eq!(sent(&catalog), folded);
4115		tokio::time::advance(std::time::Duration::from_millis(50)).await;
4116		v.estimate(jitter(3)).unwrap();
4117		assert_ne!(sent(&catalog), folded);
4118		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(3)));
4119	}
4120
4121	/// The window is the catalog's, so a delay rise on one track waits behind a jitter rise on
4122	/// another, and any track's next observation releases it.
4123	#[tokio::test(start_paused = true)]
4124	async fn estimate_window_is_shared_across_renditions() {
4125		let (_broadcast, catalog, mut renditions) = estimating(&["a", "b"]);
4126		let [a, b] = renditions.as_mut_slice() else {
4127			unreachable!()
4128		};
4129		a.estimate(jitter(1)).unwrap();
4130		let leading = sent(&catalog);
4131		b.estimate(super::super::Estimate::default().with_delay(std::time::Duration::from_millis(7)))
4132			.unwrap();
4133		assert_eq!(sent(&catalog), leading);
4134
4135		tokio::time::advance(std::time::Duration::from_secs(1)).await;
4136		a.estimate(jitter(1)).unwrap();
4137		assert_ne!(sent(&catalog), leading);
4138		let snapshot = wire(&catalog);
4139		assert_eq!(
4140			snapshot.video.renditions["b"].delay,
4141			Some(std::time::Duration::from_millis(7))
4142		);
4143	}
4144
4145	/// Bitrate and framerate are already measured per second, so a new value never waits, but it
4146	/// still opens a window for the jitter it carries.
4147	#[tokio::test(start_paused = true)]
4148	async fn a_bitrate_estimate_publishes_immediately() {
4149		let (_broadcast, catalog, mut renditions) = estimating(&["v"]);
4150		let v = &mut renditions[0];
4151		v.estimate(jitter(1).with_bitrate(1_000_000)).unwrap();
4152		let first = sent(&catalog);
4153		v.estimate(jitter(2).with_bitrate(1_000_000)).unwrap();
4154		assert_eq!(sent(&catalog), first, "the bitrate publish opened a window");
4155
4156		tokio::time::advance(std::time::Duration::from_millis(10)).await;
4157		v.estimate(jitter(3).with_bitrate(2_000_000)).unwrap();
4158		assert_ne!(sent(&catalog), first);
4159		let snapshot = wire(&catalog);
4160		assert_eq!(snapshot.video.renditions["v"].bitrate, Some(2_000_000));
4161		assert_eq!(
4162			snapshot.video.renditions["v"].jitter,
4163			Some(std::time::Duration::from_millis(3))
4164		);
4165	}
4166
4167	/// A rise while the initial catalog is reserved is held by the gate, goes out with the first
4168	/// snapshot, and that snapshot opens the window.
4169	#[tokio::test(start_paused = true)]
4170	async fn estimate_rise_waits_for_the_reservation_gate() {
4171		let mut broadcast = moq_net::broadcast::Info::new().produce();
4172		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
4173		let reserved = catalog.reserve();
4174		let mut v = reserved.init::<VideoConfig>("v").unwrap();
4175		v.set(VideoConfig::new(hang::catalog::VideoCodec::VP8)).unwrap();
4176		v.estimate(jitter(1)).unwrap();
4177		assert_eq!(sent(&catalog), None, "the gate withholds the rise");
4178
4179		drop(reserved);
4180		assert_eq!(sent(&catalog), Some(0));
4181		assert_eq!(wire_jitter(&catalog, "v"), Some(std::time::Duration::from_millis(1)));
4182		v.estimate(jitter(2)).unwrap();
4183		assert_eq!(sent(&catalog), Some(0), "the gated publish opened a window");
4184	}
4185
4186	fn delay(ms: u64) -> super::super::Reading {
4187		super::super::Reading {
4188			estimate: super::super::Estimate::default().with_delay(std::time::Duration::from_millis(ms)),
4189			period: Some(std::time::Duration::from_millis(10)),
4190			interval: None,
4191		}
4192	}
4193
4194	/// A measured delay creeping a millisecond at a time republishes once per frame duration it
4195	/// crosses, carrying the value measured then. Regression: every rise republished, once a second.
4196	#[tokio::test(start_paused = true)]
4197	async fn a_creeping_delay_republishes_once_per_frame() {
4198		let (_broadcast, catalog, mut renditions) = estimating(&["v"]);
4199		let v = &mut renditions[0];
4200		let initial = sent(&catalog).unwrap();
4201
4202		let mut published = Vec::new();
4203		for ms in 1..=35 {
4204			// Past the once-a-second window, so only the frame step holds a rise back.
4205			tokio::time::advance(std::time::Duration::from_secs(2)).await;
4206			let before = sent(&catalog);
4207			v.estimate(delay(ms)).unwrap();
4208			if sent(&catalog) != before {
4209				published.push(wire(&catalog).video.renditions["v"].delay.unwrap().as_millis());
4210			}
4211		}
4212		assert_eq!(published, [10, 20, 30]);
4213		assert_eq!(sent(&catalog), Some(initial + 3));
4214		assert_eq!(
4215			catalog.snapshot().video.renditions["v"].delay,
4216			Some(std::time::Duration::from_millis(30)),
4217			"a rise short of a frame is not even staged"
4218		);
4219	}
4220
4221	/// A known framerate sets the step, whatever shorter advance the timestamps show.
4222	#[tokio::test(start_paused = true)]
4223	async fn a_framerate_sets_the_delay_step() {
4224		let mut broadcast = moq_net::broadcast::Info::new().produce();
4225		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
4226		let reserved = catalog.reserve();
4227		let mut v = reserved.init::<VideoConfig>("v").unwrap();
4228		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
4229		config.framerate = Some(25.0);
4230		v.set(config).unwrap();
4231		drop(reserved);
4232
4233		v.estimate(delay(39)).unwrap();
4234		assert_eq!(wire(&catalog).video.renditions["v"].delay, None);
4235		v.estimate(delay(40)).unwrap();
4236		assert_eq!(
4237			wire(&catalog).video.renditions["v"].delay,
4238			Some(std::time::Duration::from_millis(40))
4239		);
4240	}
4241
4242	/// How many MSF catalogs have gone out on the wire.
4243	/// How many MSF catalogs went out before the newest, or `None` before the first.
4244	fn msf_sent<E: CatalogExt>(catalog: &Producer<E>) -> Option<u64> {
4245		catalog.outputs.published[1]
4246			.load(std::sync::atomic::Ordering::Relaxed)
4247			.checked_sub(1)
4248	}
4249
4250	/// The last MSF catalog on the wire.
4251	fn msf_wire(catalog: &Producer) -> moq_msf::Catalog<()> {
4252		let state = take(&catalog.current);
4253		moq_msf::Catalog::from_str(state.msf.last.as_deref().expect("a published MSF catalog")).unwrap()
4254	}
4255
4256	/// A change MSF doesn't carry republishes hang but not MSF.
4257	#[test]
4258	fn identical_msf_content_publishes_once() {
4259		let mut broadcast = moq_net::broadcast::Info::new().produce();
4260		let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
4261		catalog
4262			.mutate(
4263				|catalog| {
4264					catalog
4265						.video
4266						.renditions
4267						.insert("v".to_string(), VideoConfig::new(hang::catalog::VideoCodec::VP8));
4268				},
4269				catalog.next_timestamp(),
4270			)
4271			.unwrap();
4272		assert_eq!(msf_sent(&catalog), Some(0));
4273		let hang = sent(&catalog);
4274
4275		catalog
4276			.mutate(
4277				|catalog| {
4278					catalog.video.display = Some(hang::catalog::Display {
4279						width: 1280,
4280						height: 720,
4281					})
4282				},
4283				catalog.next_timestamp(),
4284			)
4285			.unwrap();
4286		assert_ne!(sent(&catalog), hang);
4287		assert_eq!(msf_sent(&catalog), Some(0));
4288	}
4289
4290	/// A demand-driven track measures nothing until a viewer subscribes, which an MSF viewer can do
4291	/// only once MSF lists it. So an unhinted track declares MSF at once without estimates, and they
4292	/// stay absent once hang measures them. Regression: MSF waited for the estimates.
4293	#[tokio::test(start_paused = true)]
4294	async fn an_unhinted_track_declares_msf_at_once() {
4295		let (_broadcast, catalog, mut renditions) = estimating(&["v"]);
4296		let v = &mut renditions[0];
4297		assert_eq!(msf_sent(&catalog), Some(0), "no media has been written");
4298		let track = &msf_wire(&catalog).tracks[0];
4299		assert_eq!((track.bitrate, track.framerate), (None, None));
4300		assert_eq!((track.jitter, track.delay), (None, None));
4301
4302		// 25 fps in 2 s groups.
4303		let mut estimator = super::super::Estimator::new();
4304		for i in 0..=150u64 {
4305			let ts = moq_net::Timestamp::from_micros(i * 40_000).unwrap();
4306			if i % 50 == 0 {
4307				estimator.cut(Some(ts));
4308			}
4309			estimator.write(ts, 1_000);
4310			v.estimate(estimator.reading()).unwrap();
4311		}
4312		let hang = &wire(&catalog).video.renditions["v"];
4313		assert!(hang.bitrate.is_some());
4314		assert_eq!(hang.framerate, Some(25.0));
4315		assert_eq!(msf_sent(&catalog), Some(0), "measurements leave MSF alone");
4316	}
4317
4318	/// MSF declares the estimates a track hinted, and keeps those it first declared when a hint
4319	/// changes. A field left unhinted stays absent whatever hang measures.
4320	#[tokio::test(start_paused = true)]
4321	async fn a_hinted_track_carries_its_hints() {
4322		let mut broadcast = moq_net::broadcast::Info::new().produce();
4323		let catalog = Producer::new(&mut broadcast, Config::default()).unwrap();
4324		let reserved = catalog.reserve();
4325		let mut v = reserved.init::<VideoConfig>("v").unwrap();
4326		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
4327		config.bitrate = Some(1_000_000);
4328		config.framerate = Some(30.0);
4329		v.set(config).unwrap();
4330		drop(reserved);
4331		assert_eq!(msf_sent(&catalog), Some(0));
4332		let track = &msf_wire(&catalog).tracks[0];
4333		assert_eq!((track.bitrate, track.framerate), (Some(1_000_000), Some(30.0)));
4334
4335		v.estimate(delay(40)).unwrap();
4336		v.supply_bitrate(2_000_000).unwrap();
4337		let hang = &wire(&catalog).video.renditions["v"];
4338		assert_eq!(hang.delay, Some(std::time::Duration::from_millis(40)));
4339		assert_eq!(hang.bitrate, Some(2_000_000));
4340		assert_eq!(msf_sent(&catalog), Some(0));
4341		let track = &msf_wire(&catalog).tracks[0];
4342		assert_eq!((track.bitrate, track.delay), (Some(1_000_000), None));
4343	}
4344}