Skip to main content

moq_mux/container/
producer.rs

1use bytes::Bytes;
2
3use super::{Container, Frame, Kind, Writer};
4
5fn add_micros(timestamp: moq_net::Timestamp, extra: moq_net::Timestamp) -> Option<moq_net::Timestamp> {
6	let micros = timestamp.as_micros().ok()?.saturating_add(extra.as_micros().ok()?);
7	let micros = u64::try_from(micros).ok()?;
8	moq_net::Timestamp::from_micros(micros).ok()
9}
10
11/// Whether `left` is before `right` to the microsecond; false when either is unscaled.
12fn timestamp_lt(left: moq_net::Timestamp, right: moq_net::Timestamp) -> bool {
13	matches!((left.as_micros(), right.as_micros()), (Ok(left), Ok(right)) if left < right)
14}
15
16/// Whether `left` is before `right` at full precision, a tie across scales included as not
17/// before; false when either is unscaled.
18fn timestamp_before(left: moq_net::Timestamp, right: moq_net::Timestamp) -> bool {
19	match (left.scale(), right.scale()) {
20		(Some(lhs), Some(rhs)) => {
21			(left.value() as u128) * (rhs.as_u64() as u128) < (right.value() as u128) * (lhs.as_u64() as u128)
22		}
23		_ => false,
24	}
25}
26
27/// Refuse a frame without a time with [`TimestampMismatch`](moq_net::Error::TimestampMismatch):
28/// media is timed, and a scale-less track's [unscaled](moq_net::Timestamp::unscaled) key is not.
29fn timed(timestamp: moq_net::Timestamp, duration: Option<moq_net::Timestamp>) -> Result<(), moq_net::Error> {
30	match timestamp.scale().is_some() && duration.is_none_or(|duration| duration.scale().is_some()) {
31		true => Ok(()),
32		false => Err(moq_net::Error::TimestampMismatch),
33	}
34}
35
36/// Move `frame` to decode at `at` rather than `source`, as a group start moves a keyframe, keeping
37/// its presentation time the same distance after.
38fn moved(frame: &mut Frame, source: moq_net::Timestamp, at: moq_net::Timestamp) -> Result<(), moq_net::Error> {
39	let Some(decode) = frame.decode else {
40		frame.timestamp = at;
41		return Ok(());
42	};
43	frame.decode = Some(at);
44	if at == source && at.scale() == source.scale() {
45		return Ok(());
46	}
47	let scale = at.scale().ok_or(moq_net::Error::TimestampMismatch)?;
48	let moved = |t: moq_net::Timestamp| t.convert(scale).map_err(|_| moq_net::Error::TimestampMismatch);
49	let offset = moved(frame.timestamp)?
50		.checked_sub(moved(decode)?)
51		.map_err(|_| moq_net::Error::TimestampMismatch)?;
52	frame.timestamp = at.checked_add(offset).map_err(|_| moq_net::Error::TimestampMismatch)?;
53	Ok(())
54}
55
56/// A buffered group a keyframe closed, finished once the group after it is created: at `end`, or
57/// at that group's start when its first batch starts below `end`, as a CMAF fragment carrying an
58/// open GOP's leading pictures does. Until then [`Producer::ended`] doesn't count it.
59struct Closing {
60	group: moq_net::group::Producer,
61	/// Where the group ends, in the track's timescale.
62	end: moq_net::Timestamp,
63}
64
65/// A group a keyframe opened, which the track creates with the container's first frame.
66struct Open {
67	/// The group on the track, `None` until its first frame is written.
68	created: Option<moq_net::group::Producer>,
69	/// The group's key, which a later keyframe has to pass to open another, even while the group
70	/// is still buffered and the track doesn't hold it yet.
71	key: u64,
72	/// The group the keyframe opening this one closed, while buffering keeps this one from the
73	/// track and so its start unknown.
74	previous: Option<Closing>,
75}
76
77/// A producer for media tracks that manages group boundaries.
78///
79/// Generic over `C: Container` to support different container encodings
80/// (Legacy, CMAF, LOC). Use [`catalog::hang::Wire`](crate::catalog::hang::Wire)
81/// to dispatch on the catalog at runtime.
82///
83/// ## Group Management
84///
85/// `keyframe = true` means "start a new group": it closes the previous group (if any) and opens a
86/// new one, so every group begins with a keyframe. A non-keyframe extends the current group, and
87/// writing one when no group is open is a protocol violation.
88///
89/// A stream where every frame is independently decodable (e.g. audio) still drives grouping through
90/// this bit: mark only the *first* frame of each group a keyframe and the rest non-keyframes, so the
91/// caller's [`cut`](Self::cut) boundaries define the groups instead of every
92/// frame opening its own (one QUIC stream per frame). [`needs_keyframe`](Self::needs_keyframe)
93/// reports whether the next frame has to be one.
94///
95/// [`cut`](Self::cut) closes the current group early, ideally saying where its content
96/// ends; the next write must be a keyframe. Reach for it when the following keyframe won't
97/// supply that boundary in time, or to bound each group of an accumulating audio track.
98/// [`discontinuity`](Self::discontinuity) publishes a marker group with no media, for
99/// when the timeline is about to jump rather than merely continue. Timestamps never fall
100/// below the live edge earlier groups reached.
101///
102/// ## Buffering
103///
104/// When the buffer duration is zero (default), each frame is written immediately as its
105/// own container frame. When non-zero, frames are buffered and flushed together when:
106/// - A keyframe arrives (flushes the previous group's buffer, starts new group),
107/// - The buffered duration exceeds the configured duration,
108/// - `finish()` is called.
109///
110/// This is useful for CMAF where multiple samples should be packed into one moof+mdat.
111pub struct Producer<C: Container, R = ()> {
112	/// The catalog rendition this media producer owns, when it was created through a catalog.
113	/// Dropped before the track, so a handler asked for the track again finds the name free.
114	rendition: Option<Box<dyn Rendition<R>>>,
115	inner: moq_net::track::Producer,
116	container: C,
117	group: Option<Open>,
118	buffer: Vec<Frame>,
119
120	buffer_duration: std::time::Duration,
121
122	/// This track's place in the broadcast's join interval, for a video or audio track a catalog
123	/// minted: it reports the longest group measured.
124	member: Option<crate::catalog::interval::Member>,
125
126	/// The furthest presentation point written, i.e. `max(timestamp + duration)`: the base for a
127	/// duration marker when the caller does not pass a bound.
128	end: Option<moq_net::Timestamp>,
129
130	/// Exclusive presentation end of finished groups, where a payload with no timestamp of its
131	/// own lands. Not a floor: a group may start below it.
132	live_edge: Option<moq_net::Timestamp>,
133	/// The latest frame timestamp written, which a discontinuity marker never falls below: a frame
134	/// without a duration reaches only its own timestamp, so the live edge can sit right on it.
135	newest: Option<moq_net::Timestamp>,
136	/// The End of the latest group that ended whole, in the track's timescale. Its span runs to
137	/// there, so no later group starts below it, a discontinuity marker included.
138	ended: Option<moq_net::Timestamp>,
139	/// The source and published timestamps of the keyframe that opened the open group, when its
140	/// start moved it past a span. A frame at that source timestamp, such as the picture parameter
141	/// sets precede, is published with it.
142	moved: Option<(moq_net::Timestamp, moq_net::Timestamp)>,
143	/// The newest source timestamp in the open group, which a source end must reach.
144	source_end: Option<moq_net::Timestamp>,
145
146	/// The source timestamp of the keyframe that opened the latest group. The next group may not
147	/// start below it.
148	start: Option<moq_net::Timestamp>,
149	/// The start of the group before the latest one. A frame below it is a restart, not a splice.
150	floor: Option<moq_net::Timestamp>,
151	/// The newest frame of every group before the latest one: every frame of the latest group
152	/// presents after it.
153	ceiling: Option<moq_net::Timestamp>,
154	/// A keyframe was dropped with no group open, so the frames decoding from it are dropped too,
155	/// until a keyframe opens a group.
156	skipping: bool,
157	/// The latest keyframe written, whose leading pictures are the frames after it presenting
158	/// before it.
159	keyframe: Option<moq_net::Timestamp>,
160	/// A leading picture of [`keyframe`](Self::keyframe) was dropped, so its later leading pictures
161	/// are dropped too: they may reference it, and pictures presenting after the keyframe never
162	/// reference a leading picture.
163	tainted: bool,
164
165	/// Duration of the frame that last raised [`end`](Self::end), if it had one. Distinguishes
166	/// an exclusive presentation point from a max timestamp that still needs an estimate.
167	last_duration: Option<moq_net::Timestamp>,
168
169	/// Previous source and published decode timestamps within the group, and the cadence observed
170	/// within this epoch.
171	previous_timestamp: Option<(moq_net::Timestamp, moq_net::Timestamp)>,
172	/// The previous frame's presentation timestamp within the group, which a reordered frame
173	/// presents below.
174	presented: Option<moq_net::Timestamp>,
175	cadence: Option<moq_net::Timestamp>,
176	/// A presentation endpoint cannot bound the decode-order tail after reordering.
177	reordered: bool,
178
179	/// Measures bitrate, reorder, batch, and explicit encoder flush observations for the catalog.
180	/// A caller without a published rendition simply never reads the estimate.
181	estimator: crate::catalog::Estimator,
182	/// Frames at or before this are history caught up behind the live edge; see [`Self::history`].
183	history: Option<moq_net::Timestamp>,
184
185	/// Peak-hold claim on the connection allocator, when one was supplied.
186	/// Named `bandwidth` so it is not confused with the catalog-gate [`Reserved`].
187	bandwidth: Option<crate::catalog::Claim>,
188
189	/// The counters the catalog reports for this track, when it was created through a catalog.
190	sent: Option<std::sync::Arc<crate::stats::Sent>>,
191}
192
193/// A frame whose payload streams into its track as it arrives, opened by [`Producer::open`].
194///
195/// It holds the track's open group until [`Producer::commit`] returns it, so nothing else writes to
196/// the track meanwhile. Dropping it unfinished aborts that group.
197pub(crate) struct Streamed {
198	payload: Payload,
199	/// The decode timestamp the source gave, which the producer measures; a group start may have
200	/// moved the one written.
201	source: moq_net::Timestamp,
202	/// The presentation timestamp the source gave.
203	presentation: moq_net::Timestamp,
204	/// The decode timestamp written.
205	timestamp: moq_net::Timestamp,
206	duration: Option<moq_net::Timestamp>,
207	keyframe: bool,
208	size: usize,
209}
210
211/// Where a [`Streamed`] frame's payload goes.
212#[expect(
213	clippy::large_enum_variant,
214	reason = "nearly every frame is written; boxing the writer would allocate for each"
215)]
216enum Payload {
217	Written(moq_net::frame::Producer),
218	/// The producer dropped the frame (see [`Producer::write`]); this many bytes are still to come.
219	Dropped(usize),
220}
221
222impl Streamed {
223	/// Append payload bytes, readable by subscribers at once.
224	pub fn write(&mut self, chunk: &[u8]) -> crate::Result<()> {
225		match &mut self.payload {
226			Payload::Written(writer) => writer.write(chunk)?,
227			Payload::Dropped(remaining) => {
228				*remaining = remaining.checked_sub(chunk.len()).ok_or(moq_net::Error::WrongSize)?;
229			}
230		}
231		Ok(())
232	}
233
234	/// Payload bytes still to write.
235	pub fn remaining(&self) -> usize {
236		match &self.payload {
237			Payload::Written(writer) => writer.remaining(),
238			Payload::Dropped(remaining) => *remaining,
239		}
240	}
241
242	/// Abort the frame and its group with `err`.
243	pub fn abort(self, err: moq_net::Error) {
244		if let Payload::Written(writer) = self.payload {
245			let _ = writer.abort(err);
246		}
247	}
248}
249
250impl<R: Clone + Send + 'static> Producer<crate::catalog::hang::Wire, R> {
251	/// Open a `frame` of `size` payload bytes, written through the returned [`Streamed`] as they
252	/// arrive, for a source that learns a frame's size before its bytes. The frame's own payload
253	/// is ignored.
254	///
255	/// Groups and refuses frames the way [`write`](Self::write) does; the frame is measured once
256	/// [`commit`](Self::commit)ted. The group's storage takes the bytes as they are written, so a
257	/// declared size commits no memory, and one past the group's limit is refused up front. A
258	/// buffering producer, or CMAF, whose `moof` describes the payload, cannot stream.
259	pub(crate) fn open(&mut self, mut frame: Frame, size: usize) -> crate::Result<Streamed> {
260		if !self.buffer_duration.is_zero() || self.container.prefix(frame.timestamp)?.is_none() {
261			return Err(crate::Error::UnsupportedContainer("a streamed frame".into()));
262		}
263		let (keyframe, duration) = (frame.keyframe, frame.duration);
264		timed(frame.timestamp, duration)?;
265		if !self.container.decode_order() {
266			frame.decode = None;
267		}
268		if let Some(decode) = frame.decode {
269			timed(decode, None)?;
270		}
271		// Only an empty frame is whole before its bytes arrive, so only it can be checked up front.
272		frame.payload = Bytes::new();
273		if size == 0 {
274			self.container.check(&frame)?;
275		}
276		let presentation = frame.timestamp;
277		let source = frame.decode.unwrap_or(presentation);
278		let Some(timestamp) = self.prepare(source, keyframe, frame.decode.is_some())? else {
279			return Ok(Streamed {
280				payload: Payload::Dropped(size),
281				source,
282				presentation,
283				timestamp: source,
284				duration,
285				keyframe,
286				size,
287			});
288		};
289		// At the times the frame is written at, which a group start may have moved.
290		self.place(&mut frame, source, timestamp)?;
291		// A prefix carrying the presentation time leaves the transport the newest so far, as
292		// [`hang::container::Frame::write_to`] stamps it. A decode-order container's transport
293		// is its timing, so a frame below the group's latest is refused, before the group is
294		// taken so the frames already written still finish.
295		let latest = (self.group.as_ref())
296			.and_then(|open| open.created.as_ref())
297			.and_then(|group| group.latest());
298		let transport = match latest {
299			Some(latest) if timestamp < latest => match self.container.decode_order() {
300				true => return Err(moq_net::Error::TimestampMismatch.into()),
301				false => latest,
302			},
303			_ => timestamp,
304		};
305		let prefix = (self.container.prefix(frame.timestamp)?)
306			.ok_or_else(|| crate::Error::UnsupportedContainer("a streamed frame".into()))?;
307		let open = self.group.take().expect("prepare opens a group");
308		let total = prefix.len().checked_add(size).ok_or(moq_net::Error::FrameTooLarge)?;
309		let info = moq_net::frame::Info {
310			timestamp: transport,
311			size: total as u64,
312		};
313		// The group's first frame creates it on the track.
314		let mut writer = match open.created {
315			Some(group) => group.create_frame(info)?,
316			None => self.inner.append_frame(info)?,
317		};
318		writer.write(prefix)?;
319		Ok(Streamed {
320			payload: Payload::Written(writer),
321			source,
322			presentation,
323			timestamp,
324			duration,
325			keyframe,
326			size,
327		})
328	}
329
330	/// Finish a frame [`open`](Self::open) returned once its payload is written, handing its group
331	/// back to the track.
332	pub(crate) fn commit(&mut self, frame: Streamed) -> crate::Result<()> {
333		let writer = match frame.payload {
334			Payload::Written(writer) => writer,
335			Payload::Dropped(0) => return Ok(()),
336			Payload::Dropped(_) => return Err(moq_net::Error::WrongSize.into()),
337		};
338		let group = writer.finish()?;
339		self.group = Some(Open {
340			key: group.start,
341			created: Some(group),
342			previous: None,
343		});
344		// Only once the frame is in, so a refused one leaves the group's order as it was.
345		self.present(frame.presentation, frame.source);
346		self.written(
347			frame.source,
348			frame.presentation,
349			frame.timestamp,
350			frame.duration,
351			frame.size,
352			frame.keyframe,
353		);
354		Ok(())
355	}
356}
357
358trait Rendition<R>: Send {
359	fn name(&self) -> &str;
360	fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp>;
361	fn set(&mut self, config: R) -> crate::Result<()>;
362	fn config(&self) -> crate::Result<R>;
363	fn replace(&mut self, config: R) -> crate::Result<()>;
364	fn estimate(&mut self, reading: crate::catalog::Reading) -> crate::Result<()>;
365	fn supply_bitrate(&mut self, bitrate: u64) -> crate::Result<()>;
366	fn fresh(
367		&self,
368		container: crate::catalog::hang::Wire,
369		info: moq_net::track::Info,
370		interval: Option<std::time::Duration>,
371	) -> crate::Result<Producer<crate::catalog::hang::Wire, R>>;
372}
373
374impl<E, R> Rendition<R> for crate::catalog::tracks::Rendition<E, R>
375where
376	E: crate::catalog::hang::CatalogExt,
377	R: crate::catalog::RenditionConfig<E>,
378{
379	fn name(&self) -> &str {
380		self.name()
381	}
382
383	fn fresh(
384		&self,
385		container: crate::catalog::hang::Wire,
386		info: moq_net::track::Info,
387		interval: Option<std::time::Duration>,
388	) -> crate::Result<Producer<crate::catalog::hang::Wire, R>> {
389		self.fresh(container, info, interval)
390	}
391
392	fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
393		self.timestamp(hint)
394	}
395
396	fn set(&mut self, config: R) -> crate::Result<()> {
397		self.set(config)
398	}
399
400	fn config(&self) -> crate::Result<R> {
401		self.config()
402	}
403
404	fn replace(&mut self, config: R) -> crate::Result<()> {
405		self.replace(config)
406	}
407
408	fn estimate(&mut self, reading: crate::catalog::Reading) -> crate::Result<()> {
409		self.estimate(reading)
410	}
411
412	fn supply_bitrate(&mut self, bitrate: u64) -> crate::Result<()> {
413		self.supply_bitrate(bitrate)
414	}
415}
416
417impl<C: Container> Producer<C> {
418	/// Create a Producer wrapping the given moq-lite producer, muxing into `container`.
419	///
420	/// A plain media track by default: no buffering, no timeline. Add buffering with
421	/// [`with_buffer`](Self::with_buffer); the join interval is wired by the catalog (see
422	/// [`catalog::Producer::video`](crate::catalog::Producer::video) and its sibling APIs).
423	pub fn new(track: moq_net::track::Producer, container: C) -> Self {
424		Self {
425			inner: track,
426			container,
427			group: None,
428			buffer: Vec::new(),
429			buffer_duration: std::time::Duration::ZERO,
430			member: None,
431			end: None,
432			live_edge: None,
433			newest: None,
434			ended: None,
435			moved: None,
436			source_end: None,
437			start: None,
438			floor: None,
439			ceiling: None,
440			skipping: false,
441			keyframe: None,
442			tainted: false,
443			last_duration: None,
444			previous_timestamp: None,
445			presented: None,
446			cadence: None,
447			reordered: false,
448			estimator: crate::catalog::Estimator::new(),
449			history: None,
450			bandwidth: None,
451			rendition: None,
452			sent: None,
453		}
454	}
455}
456
457impl<C: Container, R: Clone + Send + 'static> Producer<C, R>
458where
459	crate::Error: From<C::Error>,
460{
461	pub(crate) fn with_rendition<E>(
462		track: moq_net::track::Producer,
463		container: C,
464		rendition: crate::catalog::tracks::Rendition<E, R>,
465	) -> Self
466	where
467		E: crate::catalog::hang::CatalogExt,
468		R: crate::catalog::RenditionConfig<E>,
469	{
470		Self {
471			inner: track,
472			container,
473			group: None,
474			buffer: Vec::new(),
475			buffer_duration: std::time::Duration::ZERO,
476			member: None,
477			end: None,
478			live_edge: None,
479			newest: None,
480			ended: None,
481			moved: None,
482			source_end: None,
483			start: None,
484			floor: None,
485			ceiling: None,
486			skipping: false,
487			keyframe: None,
488			tainted: false,
489			last_duration: None,
490			previous_timestamp: None,
491			presented: None,
492			cadence: None,
493			reordered: false,
494			estimator: rendition.estimator(),
495			history: None,
496			bandwidth: None,
497			rendition: Some(Box::new(rendition)),
498			sent: None,
499		}
500	}
501
502	/// Publish or replace this track's catalog config.
503	///
504	/// Unset jitter and delay keep their published floor; explicitly lowering either is refused.
505	pub fn set(&mut self, config: R) -> crate::Result<()> {
506		self.rendition.as_mut().ok_or(crate::Error::NotPublished)?.set(config)
507	}
508
509	/// Advertise `bitrate` as the rendition's maximum, such as an encoder's retuned target, which
510	/// later measurement no longer replaces. Every other published field stays as it is.
511	pub fn set_bitrate(&mut self, bitrate: u64) -> crate::Result<()> {
512		self.rendition
513			.as_mut()
514			.ok_or(crate::Error::NotPublished)?
515			.supply_bitrate(bitrate)
516	}
517
518	/// Modify the published catalog config.
519	///
520	/// Estimate fields the config left to detection at [`set`](Self::set) stay owned by detection:
521	/// an edit to them here is published but replaced by the next measurement, except that jitter
522	/// and delay never drop below the published value. Call `set` with the field filled in to pin it.
523	pub fn modify(&mut self) -> crate::Result<Guard<'_, R>> {
524		let rendition = self.rendition.as_mut().ok_or(crate::Error::NotPublished)?;
525		let config = rendition.config()?;
526		Ok(Guard {
527			rendition: rendition.as_mut(),
528			config: Some(config),
529		})
530	}
531
532	/// Resolve a timestamp on the broadcast's shared clock: `hint`, or the clock's reading now.
533	///
534	/// A reading comes from the clock rather than media, so one landing on the newest group's start,
535	/// as a burst of untimed frames can, is moved one unit of the track's timescale past it: group
536	/// starts strictly increase.
537	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
538		let rendition = self.rendition.as_ref().ok_or(crate::Error::NotPublished)?;
539		match hint {
540			Some(pts) => rendition.timestamp(Some(pts)),
541			None => Ok(crate::start::next(&self.inner, rendition.timestamp(None)?)?.1),
542		}
543	}
544
545	fn publish_estimate(&mut self) -> crate::Result<()> {
546		let reading = self.estimator.reading();
547		if let Some(member) = self.member.as_mut() {
548			member.report(reading.interval);
549		}
550		if let Some(rendition) = self.rendition.as_mut() {
551			rendition.estimate(reading)?;
552		}
553		Ok(())
554	}
555
556	/// The catalog key owned by this producer.
557	pub fn name(&self) -> &str {
558		self.rendition
559			.as_ref()
560			.map_or(self.inner.name(), |rendition| rendition.name())
561	}
562
563	/// A watch-only handle to this track's subscriber demand.
564	pub fn demand(&self) -> moq_net::track::Demand {
565		self.inner.demand()
566	}
567}
568
569impl Producer<crate::catalog::hang::Wire, hang::catalog::VideoConfig> {
570	/// Publish a decoder change under a fresh raw track name.
571	pub(crate) fn reconfigure(&mut self, config: hang::catalog::VideoConfig) -> crate::Result<()> {
572		let rendition = self.rendition.as_ref().ok_or(crate::Error::NotPublished)?;
573		let previous = match rendition.config() {
574			Ok(previous) => previous,
575			Err(crate::Error::NotPublished) => return self.set(config),
576			Err(err) => return Err(err),
577		};
578		if previous.same_identity(&config) {
579			return self.set(config);
580		}
581		let container = crate::catalog::hang::Wire::try_from(&config)?;
582		let interval = self.member.as_ref().and_then(|member| member.interval());
583		let mut next = rendition.fresh(container, self.inner.info().clone(), interval)?;
584		next.buffer_duration = self.buffer_duration;
585		next.set(config)?;
586		self.end_with(None)?;
587		*self = next;
588		Ok(())
589	}
590}
591
592/// A published rendition config edited in place.
593pub struct Guard<'a, R> {
594	rendition: &'a mut dyn Rendition<R>,
595	config: Option<R>,
596}
597
598impl<R> Guard<'_, R> {
599	/// Publish the edited config and return any error.
600	pub fn commit(mut self) -> crate::Result<()> {
601		let config = self.config.take().expect("config is present until commit");
602		self.rendition.replace(config)
603	}
604}
605
606impl<R> std::ops::Deref for Guard<'_, R> {
607	type Target = R;
608
609	fn deref(&self) -> &Self::Target {
610		self.config.as_ref().expect("config is present until commit")
611	}
612}
613
614impl<R> std::ops::DerefMut for Guard<'_, R> {
615	fn deref_mut(&mut self) -> &mut Self::Target {
616		self.config.as_mut().expect("config is present until commit")
617	}
618}
619
620impl<R> Drop for Guard<'_, R> {
621	fn drop(&mut self) {
622		let Some(config) = self.config.take() else {
623			return;
624		};
625		if let Err(err) = self.rendition.replace(config) {
626			tracing::error!(%err, "failed to publish modified rendition");
627		}
628	}
629}
630
631impl<C: Container, R: Clone + Send + 'static> Producer<C, R>
632where
633	crate::Error: From<C::Error>,
634{
635	#[cfg(test)]
636	fn bandwidth_ceiling(&self) -> Option<moq_net::bandwidth::Rate> {
637		self.bandwidth.as_ref().and_then(|claim| claim.ceiling())
638	}
639
640	/// The jitter, bitrate, delay, and framerate measured from the frames written so far.
641	///
642	/// A catalog-owned producer publishes this automatically.
643	pub fn estimate(&self) -> crate::catalog::Estimate {
644		self.estimator.estimate()
645	}
646
647	/// Record a frame's reorder delay (`PTS - DTS`), raising the measured jitter to the decode
648	/// buffer a B-frame stream needs.
649	///
650	/// A [decode-order](super::Container::decode_order) container measures it from each frame's
651	/// [`decode`](Frame::decode) time; for the others, a caller that demuxed one supplies it.
652	pub fn reorder(&mut self, delay: std::time::Duration) {
653		self.estimator.reorder(delay);
654	}
655
656	/// Mark frames at or before `until` as retained history being caught up, rather than live
657	/// frames written late.
658	///
659	/// History never measures [`delay`](crate::catalog::Estimate::delay) against the other tracks:
660	/// a publisher replaying a backlog behind the live edge would otherwise advertise the backlog's
661	/// age as playout delay for the rest of the track.
662	pub fn history(&mut self, until: moq_net::Timestamp) {
663		self.history = Some(until);
664	}
665
666	/// Record the media duration emitted together by a container importer.
667	pub(crate) fn burst(&mut self, duration: std::time::Duration) -> crate::Result<()> {
668		self.estimator.burst(duration);
669		self.publish_estimate()
670	}
671
672	/// Whether the next [`write`](Self::write) has to be a keyframe, i.e. no group is currently open
673	/// (at the start, or after a [`cut`](Self::cut)).
674	///
675	/// A stream where every frame is independently decodable (audio) uses this to mark only the first
676	/// frame of each group a keyframe: `write(Frame { keyframe: producer.needs_keyframe(), .. })`, so
677	/// grouping follows the caller's `cut` boundaries rather than opening a group per frame.
678	pub fn needs_keyframe(&self) -> bool {
679		self.group.is_none()
680	}
681
682	/// Whether the container reads [`Frame::decode`]; the others drop it.
683	pub(crate) fn decode_order(&self) -> bool {
684		self.container.decode_order()
685	}
686
687	/// Buffer up to `duration` of frames into each container frame.
688	///
689	/// When non-zero, frames are buffered and flushed together once the buffered duration exceeds
690	/// it, or a keyframe arrives, packing multiple samples into one container frame (e.g. a CMAF
691	/// moof+mdat). Zero (the default) flushes each frame immediately.
692	///
693	/// This is the publisher-side counterpart to the consumer's max delay, and the one
694	/// knob here that genuinely *adds* delay. A batch's oldest frame reaches the transport
695	/// as late as the batch's span, so the catalog advertises that span as `jitter`. A group a
696	/// keyframe closes ends only once the next group's first batch flushes or the producer ends,
697	/// since a CMAF fragment may start that group below the keyframe.
698	pub fn with_buffer(mut self, duration: std::time::Duration) -> Self {
699		self.buffer_duration = duration;
700		self
701	}
702
703	/// Report the longest group measured through `member` into the broadcast's join interval.
704	pub(crate) fn with_member(mut self, member: Option<crate::catalog::interval::Member>) -> Self {
705		self.member = member;
706		self
707	}
708
709	/// Claim this track's peak-hold catalog bitrate on `allocator`.
710	///
711	/// A passthrough track has no configured ceiling, so it reserves the measured
712	/// maximum instead: nothing until the first 1 s window closes, then only
713	/// upward. A co-resident encoder targets what is left. The claim is named
714	/// `bandwidth` so it is not confused with the catalog-gate `Reserved`.
715	pub fn with_bandwidth(mut self, allocator: moq_net::bandwidth::Allocator) -> Self {
716		self.bandwidth = Some(crate::catalog::Claim::new(allocator));
717		self
718	}
719
720	/// Count every frame this track writes into `sent`, which its catalog reports.
721	pub(crate) fn with_sent(mut self, sent: std::sync::Arc<crate::stats::Sent>) -> Self {
722		self.sent = Some(sent);
723		self
724	}
725
726	/// Report `frames` frames the source produced but never handed to this track, such as ones an
727	/// encoder fell behind on, in its catalog's [`stats`](crate::catalog::Producer::stats).
728	pub fn report_skipped(&self, frames: u64) {
729		if let Some(sent) = &self.sent {
730			sent.skip(frames);
731		}
732	}
733
734	/// Report the encoder's latest target bitrate in its catalog's
735	/// [`stats`](crate::catalog::Producer::stats). The catalog's `bitrate` stays the maximum.
736	pub fn report_bitrate(&self, bitrate: moq_net::bandwidth::Rate) {
737		if let Some(sent) = &self.sent {
738			sent.target(bitrate);
739		}
740	}
741
742	/// Count a written frame. Only video keyframes count as keyframes: elsewhere the bit only
743	/// marks where a group starts.
744	fn count(&self, bytes: usize, keyframe: bool) {
745		if let Some(sent) = &self.sent {
746			let keyframe = keyframe && self.container.kind() == Kind::Video;
747			sent.add(1, bytes, keyframe.into());
748		}
749	}
750
751	/// Raise the standing claim when the catalog estimate has a new peak.
752	fn claim(&mut self) {
753		let Some(bandwidth) = self.bandwidth.as_mut() else {
754			return;
755		};
756		bandwidth.update(&self.inner.demand(), self.estimator.estimate().bitrate);
757	}
758
759	/// The underlying moq-lite track producer. Read-only; mutating it directly
760	/// would sidestep group/keyframe invariants.
761	pub fn track(&self) -> &moq_net::track::Producer {
762		&self.inner
763	}
764
765	/// The exclusive presentation end earlier groups have reached, if any.
766	///
767	/// A source with no timestamp of its own (a section, a PES without PTS) lands on it. It is
768	/// not a floor: a keyframe may start below it (see [`write`](Self::write)).
769	pub fn live_edge(&self) -> Option<moq_net::Timestamp> {
770		self.live_edge
771	}
772
773	/// Write a frame to the track.
774	///
775	/// A keyframe closes any open group and starts a new one. A non-keyframe extends the current
776	/// group; if no group is open it returns [`MissingKeyframe`](super::MissingKeyframe), so a caller
777	/// joining mid-stream can skip frames until the first keyframe. A source where every frame is
778	/// independently decodable (audio) marks only the first frame of each group a keyframe (see
779	/// [`needs_keyframe`](Self::needs_keyframe)) so the group spans more than one frame.
780	///
781	/// A group starts at its keyframe's timestamp, in the track's timescale, and every frame of a
782	/// group presents after every frame of the groups before it. Frames within a group may still
783	/// reorder (B-frames, open-GOP leading pictures). A keyframe that doesn't start after the newest
784	/// frame written continues the open group, as at a splice whose keyframe dips below the old
785	/// content's last frames. A later frame presenting at or before the previous groups' newest,
786	/// such as a leading picture after a splice, is dropped and counted as
787	/// [skipped](Self::report_skipped), and so is a keyframe at or before the newest frame with no
788	/// group open, such as after a [`cut`](Self::cut), with the frames after it until a keyframe
789	/// opens a group.
790	///
791	/// Group starts strictly increase, and no group starts inside the span of one that ended whole
792	/// at a [`cut`](Self::cut)'s end. So with no group open, a keyframe past the newest frame but at
793	/// the latest group's start, such as media resuming right at a
794	/// [discontinuity](Self::discontinuity)'s marker, or below that end, such as one a cadence or a
795	/// rounded duration estimated past it, is stamped at the first start past both. A frame at that
796	/// keyframe's own timestamp, such as the picture its parameter sets precede, is stamped with
797	/// it, and the group's End is still estimated from the source's timestamps, so a move never
798	/// adds up across groups.
799	///
800	/// Group starts never go backwards: a keyframe below the start of the latest group, or any
801	/// frame below the start of the group before its own, returns
802	/// [`TimestampRewind`](super::TimestampRewind) with the refused timestamp and that start,
803	/// without writing, the way an oversized frame is refused. That is a restart, which is a new
804	/// broadcast.
805	///
806	/// In a [decode-order](super::Container::decode_order) container, a frame with a
807	/// [`decode`](Frame::decode) time is judged by it instead, and groups by decode time: those
808	/// never decrease within a group, so one decoding below the newest frame closes the open group
809	/// and is dropped, with the frames after it until a keyframe past the newest. The transport
810	/// carries each frame's decode time. Elsewhere decode times are ignored and the transport
811	/// carries the latest presentation time so far in the group, which never decreases either,
812	/// while the payload keeps the frame's own.
813	pub fn write(&mut self, mut frame: Frame) -> crate::Result<()> {
814		timed(frame.timestamp, frame.duration)?;
815		if !self.container.decode_order() {
816			frame.decode = None;
817		}
818		if let Some(decode) = frame.decode {
819			timed(decode, None)?;
820		}
821		// Before a keyframe cuts the open group or the buffer takes the frame, so a refused frame
822		// leaves both as they were.
823		self.container.check(&frame)?;
824		let presentation = frame.timestamp;
825		let source = frame.decode.unwrap_or(presentation);
826		let Some(timestamp) = self.prepare(source, frame.keyframe, frame.decode.is_some())? else {
827			return Ok(());
828		};
829		self.place(&mut frame, source, timestamp)?;
830
831		// Buffer or write the frame.
832		if self.buffer_duration.is_zero() {
833			let open = self.group.as_mut().unwrap();
834			let (duration, bytes) = (frame.duration, frame.payload.len());
835			let keyframe = frame.keyframe;
836			if let Err(err) = self
837				.container
838				.write(&mut Writer::new(&self.inner, &mut open.created), &[frame])
839			{
840				// A refused first frame leaves no group, so the next write has to open one.
841				if open.created.is_none() {
842					self.group = None;
843				}
844				return Err(err.into());
845			}
846			// Only once the frame is in, so a refused one leaves the group's order as it was.
847			self.present(presentation, source);
848			// Only what the container accepted is measured. A rejected frame (too large for the
849			// group, a timestamp that won't convert) leaves the producer usable, and the estimate's
850			// extrema never fall, so counting one would inflate the catalog for good.
851			self.written(source, presentation, timestamp, duration, bytes, keyframe);
852		} else {
853			// Buffered frames count toward the rates on the way in instead. The flush that eventually
854			// writes them takes the track down with it when it fails, so there is nothing to unwind.
855			// Their place in the write order waits for that flush, which is when the transport has them.
856			self.present(presentation, source);
857			self.estimator.rate(presentation, frame.payload.len());
858			self.observe_end(source, timestamp, frame.duration);
859			self.buffer.push(frame);
860
861			// Flush if the buffered span has reached the buffer duration.
862			if self.buffered_span() >= self.buffer_duration {
863				self.flush_buffer(None)?;
864			}
865		}
866
867		Ok(())
868	}
869
870	/// Check `timestamp` against the groups before it and open a group for a keyframe, returning
871	/// the timestamp to write the frame at, or `None` to drop it.
872	///
873	/// `decoded` says `timestamp` is a decode time, which never decreases within a group; a
874	/// presentation time may, with B-frames.
875	fn prepare(
876		&mut self,
877		timestamp: moq_net::Timestamp,
878		keyframe: bool,
879		decoded: bool,
880	) -> crate::Result<Option<moq_net::Timestamp>> {
881		// A frame sharing the moved keyframe's source timestamp goes with it, as the picture after
882		// its parameter sets does.
883		let source = timestamp;
884		let timestamp = match self.moved {
885			Some((moved, at)) if self.group.is_some() && timestamp == moved => at,
886			_ => timestamp,
887		};
888		let floor = match keyframe {
889			true => self.start,
890			false => self.floor,
891		};
892		if let Some(floor) = floor
893			&& timestamp_lt(timestamp, floor)
894		{
895			return Err(super::TimestampRewind { timestamp, floor }.into());
896		}
897		// Every frame of a group presents after every frame of the groups before it, so a keyframe
898		// that doesn't start after the newest frame written continues the open group: a splice whose
899		// keyframe dips below the old content's last frames, as a TS content join does, publishes
900		// one longer group. With no group open, as after bytes were lost, it has nothing to continue
901		// and is dropped like the frames that follow it, until a keyframe past the newest frame.
902		if keyframe
903			&& let Some(newest) = self.newest
904			&& !timestamp_lt(newest, timestamp)
905		{
906			return match self.group {
907				Some(_) if !decoded || !timestamp_before(timestamp, newest) => Ok(self.continue_keyframe(timestamp)),
908				_ => self.skip(timestamp),
909			};
910		}
911		// A group's decode times never decrease, so a frame decoding below the newest closes the
912		// open group, and it and the frames after it are dropped until a keyframe past the newest.
913		if decoded
914			&& self.group.is_some()
915			&& let Some(newest) = self.newest
916			&& timestamp_before(timestamp, newest)
917		{
918			return self.skip(timestamp);
919		}
920
921		// A keyframe opens a group keyed by its timestamp, which has to start after every group the
922		// track holds. With one open, a keyframe that doesn't, such as parameter sets and the picture
923		// they precede written as two keyframes at one timestamp, continues it instead. With none
924		// open, nor may it start inside the span of the group a cut ended whole, which runs to its
925		// End: one at the latest group's start, such as media resuming right where a break's marker
926		// sits, or below that End, as after an End estimated from a cadence or a rounded duration,
927		// is stamped at the first start past both. One below the latest group's start is refused,
928		// before anything changes.
929		let mut timestamp = timestamp;
930		if keyframe {
931			match self.group {
932				Some(Open { key: open, .. })
933					if crate::start::opens(&self.inner, timestamp)?.is_none_or(|key| key <= open) =>
934				{
935					return Ok(self.continue_keyframe(timestamp));
936				}
937				Some(_) => {}
938				None => {
939					let (_, at) = crate::start::resume(&self.inner, timestamp, self.ended)?;
940					if at != timestamp {
941						tracing::debug!(?timestamp, ?at, "a keyframe starts past the group before it");
942					}
943					timestamp = at;
944				}
945			}
946		}
947
948		// Start a new group if needed; the first frame of a group must be a keyframe.
949		if keyframe || self.group.is_none() {
950			if !keyframe {
951				if self.skipping {
952					return Ok(self.drop_frame(timestamp));
953				}
954				// No group yet and this delta can't anchor one. The caller (e.g. a
955				// mid-stream join) decides whether to skip until the first keyframe.
956				return Err(super::MissingKeyframe.into());
957			}
958			let key = crate::start::key(&self.inner, timestamp)?;
959			// The keyframe cuts the previous group, its timestamp the boundary where that group's
960			// content ends.
961			let previous = self.close_at(Some(timestamp), true)?;
962			self.floor = self.start;
963			self.ceiling = self.newest;
964			self.skipping = false;
965			// Measured from the source, so a moved start never adds up across groups.
966			self.start = Some(source);
967			self.moved = (timestamp != source).then_some((source, timestamp));
968			self.source_end = None;
969			// Created on the track, keyed by its first frame, once the container writes that.
970			self.group = Some(Open {
971				created: None,
972				key,
973				previous,
974			});
975			self.keyframe = Some(timestamp);
976			self.tainted = false;
977		} else if self.ceiling.is_some_and(|ceiling| !timestamp_lt(ceiling, timestamp)) {
978			// A frame presenting with the groups before its own, such as a leading picture after a
979			// splice, is dropped: it references pictures from before the splice, or shows new
980			// content while the old still plays.
981			self.tainted = true;
982			return Ok(self.drop_frame(timestamp));
983		} else if self.tainted && self.keyframe.is_some_and(|keyframe| timestamp_lt(timestamp, keyframe)) {
984			// A later leading picture of the same keyframe may reference the dropped one.
985			return Ok(self.drop_frame(timestamp));
986		}
987
988		Ok(Some(timestamp))
989	}
990
991	/// Move `frame`, which [`prepare`](Self::prepare) placed `at`.
992	fn place(&mut self, frame: &mut Frame, source: moq_net::Timestamp, at: moq_net::Timestamp) -> crate::Result<()> {
993		Ok(moved(frame, source, at)?)
994	}
995
996	/// Note a frame's presentation time, marking the group reordered when it presents below its
997	/// predecessor, and the reorder delay it needs.
998	fn present(&mut self, presentation: moq_net::Timestamp, decode: moq_net::Timestamp) {
999		self.reordered |= self.presented.is_some_and(|previous| presentation < previous);
1000		self.presented = Some(presentation);
1001		if let Ok(delay) = presentation.checked_sub(decode)
1002			&& let Ok(delay) = std::time::Duration::try_from(delay)
1003			&& !delay.is_zero()
1004		{
1005			self.estimator.reorder(delay);
1006		}
1007	}
1008
1009	/// Close the open group without an end and drop `timestamp`'s frame and those decoding from it,
1010	/// until a keyframe opens a group.
1011	fn skip(&mut self, timestamp: moq_net::Timestamp) -> crate::Result<Option<moq_net::Timestamp>> {
1012		if self.group.is_some() {
1013			self.cut_unended()?;
1014		}
1015		self.skipping = true;
1016		Ok(self.drop_frame(timestamp))
1017	}
1018
1019	/// Note a keyframe that continues the open group, whose leading pictures are judged afresh.
1020	fn continue_keyframe(&mut self, timestamp: moq_net::Timestamp) -> Option<moq_net::Timestamp> {
1021		self.keyframe = Some(timestamp);
1022		self.tainted = false;
1023		Some(timestamp)
1024	}
1025
1026	/// Count a frame that presents with the groups before it as skipped rather than writing it,
1027	/// returning `None` for [`prepare`](Self::prepare) to report.
1028	fn drop_frame(&self, timestamp: moq_net::Timestamp) -> Option<moq_net::Timestamp> {
1029		tracing::debug!(
1030			?timestamp,
1031			"dropping a frame that presents before an earlier group ends"
1032		);
1033		self.report_skipped(1);
1034		None
1035	}
1036
1037	/// Measure and report a frame the group accepted unbuffered.
1038	fn written(
1039		&mut self,
1040		source: moq_net::Timestamp,
1041		presentation: moq_net::Timestamp,
1042		at: moq_net::Timestamp,
1043		duration: Option<moq_net::Timestamp>,
1044		bytes: usize,
1045		keyframe: bool,
1046	) {
1047		self.estimator.rate(presentation, bytes);
1048		self.order(presentation);
1049		self.count(bytes, keyframe);
1050		self.observe_end(source, at, duration);
1051	}
1052
1053	/// Place a written frame in the write order, unless it is history; see [`Self::history`].
1054	fn order(&mut self, timestamp: moq_net::Timestamp) {
1055		if self.history.is_none_or(|until| timestamp_lt(until, timestamp)) {
1056			self.estimator.order(timestamp);
1057		}
1058	}
1059
1060	/// Cut the current group, flushing buffered frames and closing it.
1061	///
1062	/// `end` bounds the final buffered frame when the publisher knows where the
1063	/// group's content stops. A video track that writes duration markers appends an
1064	/// empty frame at that bound, or at the last timestamp plus its estimated
1065	/// duration. Reordered groups omit this marker because their presentation end
1066	/// does not bound the last frame in decode order. An unreordered media group, or one given an
1067	/// explicit bound, ends whole there, so the next group starts at or after it (see
1068	/// [`write`](Self::write)). The next write must be a keyframe. An explicit bound
1069	/// below a frame the group holds, in the track's timescale, returns
1070	/// [`InvalidEnd`](super::InvalidEnd) without flushing or closing the group. A bound at or past
1071	/// the source timestamp of a keyframe [`write`](Self::write) moved past an earlier group's end
1072	/// is the source's: the group ends at the moved keyframe instead.
1073	pub fn cut(&mut self, end: Option<moq_net::Timestamp>) -> crate::Result<()> {
1074		self.close_at(end, false).map(|_| ())
1075	}
1076
1077	/// [`cut`](Self::cut) at `end`, where a keyframe opens the `next` group straight after, which
1078	/// takes the closed group while buffering keeps its own start unknown (see [`Open::previous`]).
1079	fn close_at(&mut self, end: Option<moq_net::Timestamp>, next: bool) -> crate::Result<Option<Closing>> {
1080		let bound = self.bound(end)?;
1081		let marker_at = bound.or_else(|| self.estimated_end());
1082		// Without a bound, the group's media still lasts past its last frame's timestamp. A data item
1083		// has no cadence to last for, so its estimate stays out of the bitrate.
1084		let measured = end.or(marker_at.filter(|_| self.container.kind() != Kind::Data));
1085		self.close(measured, bound, marker_at, None, next)
1086	}
1087
1088	/// Close the current group without declaring where it ends, for a source that can't tell where
1089	/// its last frame stops. The next write must be a keyframe.
1090	pub(crate) fn cut_unended(&mut self) -> crate::Result<()> {
1091		self.close(None, None, None, None, false).map(|_| ())
1092	}
1093
1094	/// Where a group cut at `end` ends: there, or at its moved keyframe when only that frame
1095	/// presents past it.
1096	fn bound(&self, end: Option<moq_net::Timestamp>) -> crate::Result<Option<moq_net::Timestamp>> {
1097		// A group never ends below a frame of its own, compared in the track's timescale as
1098		// `finish_at` checks it.
1099		let key = |timestamp| crate::start::key(&self.inner, timestamp).ok();
1100		let (Some(end), Some(newest)) = (end, self.newest) else {
1101			return Ok(end);
1102		};
1103		if self.group.is_none() || key(end) >= key(newest) {
1104			return Ok(Some(end));
1105		}
1106		match self.moved {
1107			Some((source, at)) if key(at) == key(newest) && key(end) >= key(self.source_end.unwrap_or(source)) => {
1108				Ok(Some(at))
1109			}
1110			_ => Err(super::InvalidEnd.into()),
1111		}
1112	}
1113
1114	/// Close the current group, ending a video track's group with a duration marker at `marker_at`.
1115	///
1116	/// The group ends whole at `whole`, else at a bound the caller knows, such as the next
1117	/// keyframe, else where a media track's duration marker goes, so a reader can tell the group
1118	/// starting there continues it. The catalog's estimate measures to `measured`, the source's
1119	/// end, which a moved keyframe can put below `bound`. Returns the group for the `next` one to
1120	/// finish, as [`close_group`](Self::close_group) does.
1121	fn close(
1122		&mut self,
1123		measured: Option<moq_net::Timestamp>,
1124		bound: Option<moq_net::Timestamp>,
1125		marker_at: Option<moq_net::Timestamp>,
1126		whole: Option<moq_net::Timestamp>,
1127		next: bool,
1128	) -> crate::Result<Option<Closing>> {
1129		// Before the flush, which can fail: an unbounded cut leaves the measurement open to fold
1130		// into the next group anyway, so cutting often costs the catalog nothing.
1131		self.estimator.cut(measured);
1132		let end = bound;
1133		self.claim();
1134
1135		// The group's own state ends with it, whether or not closing it succeeds.
1136		let reordered = std::mem::take(&mut self.reordered);
1137		// Where this group's content stops: the duration marker when we write one, else the
1138		// caller's bound, else the furthest point we wrote.
1139		let reached = match (marker_at.or(end), self.end.take()) {
1140			(Some(bound), Some(written)) => Some(super::later(written, bound)),
1141			(bound, written) => bound.or(written),
1142		};
1143		self.last_duration = None;
1144		self.previous_timestamp = None;
1145		self.presented = None;
1146
1147		let tail_end = marker_at.filter(|_| !reordered);
1148		// Media ends whole where its last frame does, as the duration marker says. A data track's
1149		// items have no cadence to estimate that from.
1150		let estimated = tail_end.filter(|_| self.container.kind() != Kind::Data);
1151		let closing = match self.close_group(whole.or(end).or(estimated), tail_end, reached, next) {
1152			Ok(closing) => closing,
1153			Err(err) => {
1154				// A group that fails to close fails with the cause, rather than staying open for the
1155				// next write to continue. The one before it was whole.
1156				self.buffer.clear();
1157				self.drop_group(err.reason());
1158				return Err(err);
1159			}
1160		};
1161		// The closed group still finishes, at its own End, so readers see it whole.
1162		if let Err(err) = self.publish_estimate() {
1163			if let Some(closing) = closing {
1164				self.finish_closing(closing, None)?;
1165			}
1166			return Err(err);
1167		}
1168		Ok(closing)
1169	}
1170
1171	/// Take the open group, aborting it with `err`, and finish the whole one waiting on it at its
1172	/// own End.
1173	fn drop_group(&mut self, err: moq_net::Error) {
1174		let Some(Open { created, previous, .. }) = self.group.take() else {
1175			return;
1176		};
1177		if let Some(previous) = previous {
1178			let _ = self.finish_closing(previous, None);
1179		}
1180		if let Some(group) = created {
1181			let _ = group.abort(err);
1182		}
1183	}
1184
1185	/// Flush the buffer into the open group and finish it, raising the live edge to `reached`. With
1186	/// a `bound`, the group ends whole there rather than only closing. While buffering, a group a
1187	/// keyframe closes for the `next` one is returned for that one to finish once its own start is
1188	/// known (see [`Open::previous`]).
1189	fn close_group(
1190		&mut self,
1191		bound: Option<moq_net::Timestamp>,
1192		tail_end: Option<moq_net::Timestamp>,
1193		reached: Option<moq_net::Timestamp>,
1194		next: bool,
1195	) -> crate::Result<Option<Closing>> {
1196		self.flush_buffer(tail_end)?;
1197		// A group whose first frame was never written holds nothing to end.
1198		if let Some(Open { created: Some(_), .. }) = &self.group {
1199			let open = self.group.as_mut().unwrap();
1200			self.container
1201				.finish_group(&mut Writer::new(&self.inner, &mut open.created), tail_end)?;
1202		}
1203		let Some(Open { created, previous, .. }) = self.group.take() else {
1204			return Ok(None);
1205		};
1206		// The flush that created the group settled the one before, unless nothing created it.
1207		if let Some(previous) = previous {
1208			self.finish_closing(previous, None)?;
1209		}
1210		let Some(group) = created else {
1211			return Ok(None);
1212		};
1213		let mut closing = None;
1214		match bound.and_then(|bound| crate::start::end(&self.inner, group.start, bound)) {
1215			Some(end) if next && !self.buffer_duration.is_zero() => closing = Some(Closing { group, end }),
1216			Some(end) => {
1217				group.finish_at(end.value())?;
1218				self.ended = Some(end);
1219			}
1220			None => {
1221				group.finish()?;
1222			}
1223		}
1224		// Only a closed group reaches anything; a cut with none open names a point nothing reached.
1225		if let Some(end) = reached {
1226			self.raise_live_edge(end);
1227		}
1228		Ok(closing)
1229	}
1230
1231	/// Finish the group waiting on the open one once the track created the open one.
1232	fn settle(&mut self) -> crate::Result<()> {
1233		let Some(open) = self.group.as_mut() else {
1234			return Ok(());
1235		};
1236		let Some(start) = open.created.as_ref().map(|group| group.start) else {
1237			return Ok(());
1238		};
1239		match open.previous.take() {
1240			Some(previous) => self.finish_closing(previous, Some(start)),
1241			None => Ok(()),
1242		}
1243	}
1244
1245	/// Finish `closing` at `start`, where the group after it starts, when that is below its End and
1246	/// not below its frames, else at its End, and record where it ended.
1247	fn finish_closing(&mut self, Closing { group, end }: Closing, start: Option<u64>) -> crate::Result<()> {
1248		let lowered = start
1249			.filter(|&start| start < end.value() && group.latest().is_none_or(|latest| latest.value() <= start))
1250			.and_then(|start| moq_net::Timestamp::new(start, end.scale()?).ok());
1251		let end = lowered.unwrap_or(end);
1252		group.finish_at(end.value())?;
1253		self.ended = Some(end);
1254		Ok(())
1255	}
1256
1257	fn raise_live_edge(&mut self, timestamp: moq_net::Timestamp) {
1258		if self.live_edge.is_none_or(|edge| !timestamp_lt(timestamp, edge)) {
1259			self.live_edge = Some(timestamp);
1260		}
1261	}
1262
1263	/// Raise the furthest presentation point written, for [`cut`](Self::cut) to report, from the
1264	/// `source` timestamp of a frame written `at`. Estimates follow the source, so a keyframe a group
1265	/// start moved never pushes the next estimated End, and the move after it, further.
1266	fn observe_end(
1267		&mut self,
1268		timestamp: moq_net::Timestamp,
1269		at: moq_net::Timestamp,
1270		duration: Option<moq_net::Timestamp>,
1271	) {
1272		// Either order stepping back is a reorder: a frame after a keyframe a group start moved can
1273		// publish below it, so the source's order alone misses it.
1274		self.reordered |= self
1275			.previous_timestamp
1276			.is_some_and(|(previous, published)| timestamp < previous || timestamp_before(at, published));
1277		if let Some((previous, _)) = self.previous_timestamp
1278			&& let Ok(delta) = timestamp.checked_sub(previous)
1279			&& !delta.is_zero()
1280		{
1281			self.cadence = Some(delta);
1282		}
1283		self.previous_timestamp = Some((timestamp, at));
1284		self.source_end = Some(self.source_end.map_or(timestamp, |end| super::later(end, timestamp)));
1285		// At full precision, so the group's floor is its highest frame as `finish_at` sees it.
1286		self.newest = Some(self.newest.map_or(at, |newest| super::later(newest, at)));
1287
1288		// Timestamp and duration can be at different scales, so add them in micros; the
1289		// sub-microsecond rounding that costs is far below a segment boundary.
1290		let Ok(micros) = timestamp.as_micros() else { return };
1291		let Ok(extra) = duration.map_or(Ok(0), |duration| duration.as_micros()) else {
1292			return;
1293		};
1294		let Ok(micros) = u64::try_from(micros + extra) else {
1295			return;
1296		};
1297		let Ok(end) = moq_net::Timestamp::from_micros(micros) else {
1298			return;
1299		};
1300		if duration.is_some() {
1301			self.estimator.reach(end);
1302		}
1303		if self.end.is_none_or(|prev| end >= prev) {
1304			self.end = Some(end);
1305			self.last_duration = duration.filter(|duration| !duration.is_zero());
1306		}
1307	}
1308
1309	/// Exclusive group end from a known duration or the observed sample cadence, never below the
1310	/// newest frame, which a sum rounded to the microsecond can fall under on a finer track.
1311	fn estimated_end(&self) -> Option<moq_net::Timestamp> {
1312		let last = self.end?;
1313		let end = match self.last_duration {
1314			Some(_) => last,
1315			None => add_micros(last, self.cadence?)?,
1316		};
1317		Some(self.newest.map_or(end, |newest| super::later(end, newest)))
1318	}
1319
1320	/// Publish a marker group standing for a break in the timeline: content stopped, and
1321	/// whatever comes next does not continue it.
1322	///
1323	/// Call this whenever the timeline is about to jump -- pausing an encoder, switching
1324	/// source, resuming on a re-anchored clock. Without it a break is invisible: the next
1325	/// group looks exactly like the one that would have followed, and a consumer bounding a
1326	/// sample by the next group's first frame hands it the entire gap as its duration. That
1327	/// produced a 2405 second video sample out of a publisher that had been paused 40 minutes.
1328	/// Group starts alone can't rule a pause out, so this
1329	/// marker is the only thing that can say one happened.
1330	///
1331	/// It also fixes what a subscriber joining mid-break sees. A subscription starts at the
1332	/// track's latest group, and creating this one advances that -- so a late joiner lands on
1333	/// the marker and waits for real media, instead of being served the group from *before*
1334	/// the break as though it were live.
1335	///
1336	/// Audio and video write one empty frame one unit of the track's timescale before the exclusive
1337	/// end of the previous epoch, so what resumes at that end starts after it, but never below the
1338	/// latest frame written: a frame without a duration ends where it starts, so what resumes then
1339	/// has to start after that frame. Nor below the end a [`cut`](Self::cut) gave the closing group,
1340	/// whose span runs to there: the marker starts at that end. That object exists on
1341	/// moq-transport, so the live edge moves immediately; a consumer MUST NOT submit it to a
1342	/// decoder. An empty payload is data on a data track, so its marker is one object with no
1343	/// bytes at all, not even the container's timestamp. The next [`write`](Self::write) opens the
1344	/// group after the marker, which it has to start after: group starts strictly increase, so a
1345	/// keyframe at the marker is stamped one unit past it.
1346	///
1347	/// Before anything is written there is no timeline to break, so it publishes nothing.
1348	///
1349	/// To bound the closing group's final frame, [`cut(end)`](Self::cut) before calling this.
1350	/// Otherwise the open group closes without a duration marker: what resumes may land sooner
1351	/// than one estimated frame later (a capture that reopens at once), and a guessed end past
1352	/// it would read as a rewind to every consumer.
1353	pub fn discontinuity(&mut self) -> crate::Result<()> {
1354		// The live edge once the open group closes, which raises it to the furthest point written.
1355		let edge = match (&self.group, self.end) {
1356			(Some(_), Some(end)) if self.live_edge.is_none_or(|edge| !timestamp_lt(end, edge)) => Some(end),
1357			_ => self.live_edge,
1358		};
1359		// The marker starts one unit of the track's timescale before the live edge, so media
1360		// resuming right at the edge still starts after it, but not below the latest frame, which
1361		// it would otherwise claim to end before. Or one unit past the newest group when that
1362		// doesn't pass the group's start. The open group ends whole there, so a reader can tell
1363		// the marker follows it.
1364		let marker = match edge {
1365			// Nothing was written, so there is no timeline to break.
1366			None => None,
1367			Some(edge) => {
1368				// Nor inside the span of a group a cut ended whole, which runs to its End.
1369				let newest = self.newest.unwrap_or(moq_net::Timestamp::ZERO);
1370				let floor = self.ended.map_or(newest, |ended| super::later(newest, ended));
1371				Some(crate::start::before(&self.inner, edge, floor)?.1)
1372			}
1373		};
1374		self.close(None, None, None, marker, false)?;
1375		// Nothing is measured across the break: the frames still open on this side have no end, and
1376		// the gap to the far side is not a frame duration.
1377		self.estimator.discontinuity();
1378		self.cadence = None;
1379		let Some(timestamp) = marker else {
1380			return Ok(());
1381		};
1382		let mut group = None;
1383		let mut writer = Writer::new(&self.inner, &mut group);
1384		match self.container.kind() {
1385			Kind::Data => writer.write_frame(timestamp, Bytes::new())?,
1386			Kind::Audio | Kind::Video => self.container.write(
1387				&mut writer,
1388				&[Frame {
1389					timestamp,
1390					decode: None,
1391					payload: Bytes::new(),
1392					keyframe: false,
1393					duration: None,
1394				}],
1395			)?,
1396		}
1397		if let Some(group) = group {
1398			group.finish()?;
1399		}
1400		Ok(())
1401	}
1402
1403	/// The presentation span of the buffered frames, zero for fewer than two.
1404	///
1405	/// Taken across the buffer rather than first to last: frames within a track are in *decode*
1406	/// order, and B-frames have non-monotonic PTS, so `last - first` can shrink as a B-frame lands
1407	/// between two earlier-PTS frames.
1408	fn buffered_span(&self) -> std::time::Duration {
1409		let mut timestamps = self
1410			.buffer
1411			.iter()
1412			.filter_map(|frame| std::time::Duration::try_from(frame.timestamp).ok());
1413		let Some(first) = timestamps.next() else {
1414			return std::time::Duration::ZERO;
1415		};
1416		let (min, max) = timestamps.fold((first, first), |(min, max), ts| (min.min(ts), max.max(ts)));
1417		max - min
1418	}
1419
1420	/// Flush any buffered frames into the current group without closing it.
1421	///
1422	/// Backfills the per-sample duration the source didn't provide. A CMAF fragment
1423	/// reconstructs each sample's DTS by accumulating durations, so every non-final
1424	/// sample packed into one fragment needs one or the decoder collapses their
1425	/// timestamps. Frames are in decode order, so a sample's duration is the gap to the
1426	/// next buffered sample; the final sample borrows `next` (the timestamp of the
1427	/// keyframe that rolled the group over), which is already in hand so this adds no
1428	/// latency. Frames that already carry a duration (e.g. fMP4 passthrough) keep it,
1429	/// and a backwards gap (a B-frame whose successor presents earlier) is left unset.
1430	/// Containers that don't use per-frame durations (Legacy, LOC) ignore the field.
1431	/// The boundary is converted into the frame's own scale first, so the duration
1432	/// stays exact in native ticks; a micros round-trip would quantize scales like
1433	/// 90 kHz (3003 ticks is not a whole number of micros) and fMP4 would refuse
1434	/// the inexact `trun` conversion.
1435	fn flush_buffer(&mut self, next: Option<moq_net::Timestamp>) -> crate::Result<()> {
1436		if self.buffer.is_empty() {
1437			return Ok(());
1438		}
1439
1440		for i in 0..self.buffer.len() {
1441			if self.buffer[i].duration.is_some() {
1442				continue;
1443			}
1444			// A sample lasts until the next one decodes.
1445			let decode = self.buffer[i].decode.unwrap_or(self.buffer[i].timestamp);
1446			let boundary = (self.buffer.get(i + 1))
1447				.map(|f| f.decode.unwrap_or(f.timestamp))
1448				.or(next);
1449			if let Some(boundary) = boundary
1450				&& let Some(scale) = decode.scale()
1451				&& let Ok(boundary) = boundary.convert(scale)
1452				&& let Ok(duration) = boundary.checked_sub(decode)
1453			{
1454				self.buffer[i].duration = Some(duration);
1455			}
1456		}
1457
1458		let open = match &mut self.group {
1459			Some(open) => open,
1460			None => return Ok(()),
1461		};
1462
1463		self.container
1464			.write(&mut Writer::new(&self.inner, &mut open.created), &self.buffer)?;
1465		self.settle()?;
1466		// The batch reaches the transport at once, so its earliest frame is as late as the span to its
1467		// latest. That is jitter, not delay: the latest frame isn't late at all.
1468		let span = self.buffered_span();
1469		self.estimator.burst(span);
1470		// Counted only once written: an abort discards the buffer, and those frames were never sent.
1471		let mut buffer = std::mem::take(&mut self.buffer);
1472		for frame in &buffer {
1473			self.order(frame.timestamp);
1474			self.count(frame.payload.len(), frame.keyframe);
1475		}
1476		buffer.clear();
1477		self.buffer = buffer;
1478
1479		Ok(())
1480	}
1481
1482	/// Finish the track, flushing any buffered frames and closing any open group, and return
1483	/// the [`Finished`] track.
1484	///
1485	/// A finish that fails ends the track with the cause instead, so it can't be retried.
1486	pub fn finish(mut self) -> crate::Result<Finished<C, R>> {
1487		self.end_with(None)?;
1488		Ok(Finished { producer: self })
1489	}
1490
1491	/// [`finish`](Self::finish) the track with `err`, for a source that failed after
1492	/// producing media worth keeping.
1493	///
1494	/// Unlike [`abort`](Self::abort), every group written stays readable and keeps being
1495	/// served; a reader reaching the end gets `err` instead of the end of stream. Over IETF
1496	/// moq-transport, a remote subscriber is told only of a generic internal error.
1497	pub fn fail(mut self, err: moq_net::Error) -> crate::Result<Finished<C, R>> {
1498		self.end_with(Some(err))?;
1499		Ok(Finished { producer: self })
1500	}
1501
1502	/// Flush and end the track, cleanly or with `err`, for an owner that keeps this producer.
1503	pub(crate) fn end_with(&mut self, err: Option<moq_net::Error>) -> crate::Result<()> {
1504		if let Err(cause) = self.cut(None) {
1505			// A track that cannot close its last group ends with the cause rather than staying open.
1506			let _ = self.inner.clone().abort(cause.reason());
1507			return Err(cause);
1508		}
1509		// The producer keeps its own clone, whose appends the end refuses.
1510		match err {
1511			None => drop(self.inner.clone().finish()?),
1512			Some(err) => drop(self.inner.clone().fail(err)?),
1513		}
1514		let published = self.publish_estimate();
1515		// A track that ended before measuring declares what it saw, and no longer holds the join
1516		// interval back.
1517		if let Some(mut member) = self.member.take() {
1518			member.finish(self.estimator.partial_interval());
1519		}
1520		// A finished track may be kept around, but its media stops holding the other tracks back.
1521		self.estimator.discontinuity();
1522		published
1523	}
1524
1525	/// [`finish`](Self::finish) the track unless it already ended, for an owner about to drop it.
1526	pub(crate) fn end(&mut self) -> crate::Result<()> {
1527		if self.inner.finished().is_some() || self.inner.is_closed() {
1528			return Ok(());
1529		}
1530		self.end_with(None)
1531	}
1532
1533	/// Abort the track and any open group with the given error.
1534	///
1535	/// The counterpart to [`Self::finish`] for a failed teardown: consumers observe
1536	/// `err` instead of the generic [`moq_net::Error::Dropped`] a bare drop surfaces,
1537	/// so the real cause (a disconnect, a decode failure) reaches them. Any buffered
1538	/// frames are discarded, not flushed. Consumes the producer.
1539	pub fn abort(mut self, err: moq_net::Error) {
1540		self.buffer.clear();
1541		self.drop_group(err.clone());
1542		let _ = self.inner.abort(err);
1543	}
1544
1545	/// Create a consumer for this track.
1546	pub fn consume(&self) -> moq_net::track::Subscriber {
1547		self.inner.subscribe(None)
1548	}
1549}
1550
1551/// A media track whose producer [finished](Producer::finish) it: every frame is written, and it
1552/// can still be read or aborted, but not written to.
1553///
1554/// Dropping it releases the track like dropping a [`Producer`]: it leaves its broadcast's listing,
1555/// and a catalog rendition it owns leaves the catalog.
1556///
1557/// ```compile_fail,E0599
1558/// # fn cannot_write(track: moq_mux::container::Finished<moq_mux::catalog::hang::Wire>) {
1559/// track.discontinuity().unwrap();
1560/// # }
1561/// ```
1562#[must_use = "dropping it releases the track and its catalog rendition"]
1563pub struct Finished<C: Container, R = ()> {
1564	producer: Producer<C, R>,
1565}
1566
1567impl<C: Container, R: Clone + Send + 'static> Finished<C, R>
1568where
1569	crate::Error: From<C::Error>,
1570{
1571	/// The catalog key owned by this track; see [`Producer::name`].
1572	pub fn name(&self) -> &str {
1573		self.producer.name()
1574	}
1575
1576	/// A watch-only handle to this track's subscriber demand.
1577	pub fn demand(&self) -> moq_net::track::Demand {
1578		self.producer.inner.demand()
1579	}
1580
1581	/// The properties the track was created with.
1582	pub fn info(&self) -> &moq_net::track::Info {
1583		self.producer.inner.info()
1584	}
1585
1586	/// Create a consumer for this track.
1587	pub fn consume(&self) -> moq_net::track::Subscriber {
1588		self.producer.inner.subscribe(None)
1589	}
1590
1591	/// The jitter, bitrate, delay, and framerate measured from every frame written; see
1592	/// [`Producer::estimate`].
1593	pub fn estimate(&self) -> crate::catalog::Estimate {
1594		self.producer.estimate()
1595	}
1596
1597	/// Abort the track with `err`; see [`moq_net::track::Finished::abort`]. Readers still draining get the end
1598	/// the track declared instead once every group below it finished: the clean end after [`Producer::finish`],
1599	/// or the error [`Producer::fail`] gave.
1600	pub fn abort(self, err: moq_net::Error) {
1601		self.producer.abort(err);
1602	}
1603}
1604
1605impl<C: Container, R> std::ops::Deref for Producer<C, R> {
1606	type Target = moq_net::track::Producer;
1607
1608	fn deref(&self) -> &Self::Target {
1609		&self.inner
1610	}
1611}
1612
1613#[cfg(test)]
1614mod tests {
1615	use super::*;
1616	use crate::catalog::hang::Wire;
1617	use moq_net::Timestamp;
1618
1619	/// Mint a standalone track for tests via a throwaway broadcast, since tracks are
1620	/// born from their broadcast (no public `track::Producer::new`).
1621	fn track_producer(
1622		name: impl Into<std::sync::Arc<str>>,
1623		info: impl Into<Option<moq_net::track::Info>>,
1624	) -> moq_net::track::Producer {
1625		moq_net::broadcast::Info::new()
1626			.produce()
1627			.create_track(name, info)
1628			.unwrap()
1629	}
1630
1631	/// A replay window wide enough to read a whole batch back.
1632	///
1633	/// These tests write every group up front and only then read, which the default
1634	/// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) budget collapses to the live
1635	/// edge: history has to be asked for.
1636	/// Oldest first, as they are read back.
1637	fn replay() -> moq_net::track::Subscription {
1638		moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1639			moq_net::track::Start::Live {
1640				min: Some(RECORDING_MAX_DELAY),
1641				max: Some(RECORDING_MAX_DELAY),
1642			},
1643		)
1644		.with_order(moq_net::track::Order::Ascending)])
1645	}
1646
1647	/// The media track's full max age, so readers started after publishing
1648	/// can still consume every fresh group.
1649	const RECORDING_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);
1650
1651	fn frame(timestamp_us: u64, keyframe: bool) -> Frame {
1652		Frame {
1653			timestamp: Timestamp::from_micros(timestamp_us).unwrap(),
1654			decode: None,
1655			payload: Bytes::from_static(&[0xDE, 0xAD]),
1656			keyframe,
1657			duration: None,
1658		}
1659	}
1660
1661	fn sized_frame(timestamp_us: u64, keyframe: bool, bytes: usize) -> Frame {
1662		Frame {
1663			payload: Bytes::from(vec![0u8; bytes]),
1664			..frame(timestamp_us, keyframe)
1665		}
1666	}
1667
1668	/// Two keyframes landing on one key of a coarser track stay in one group, even while the first
1669	/// is still buffered and the track doesn't hold its group yet.
1670	#[tokio::test]
1671	async fn a_buffered_group_keeps_a_keyframe_on_its_key() {
1672		let info = hang::container::track_info(hang::catalog::PRIORITY.video).with_timescale(moq_net::Timescale::MILLI);
1673		let track = track_producer("test", info);
1674		let consumer = track.consume();
1675		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data))
1676			.with_buffer(std::time::Duration::from_secs(10));
1677		producer.write(frame(1_500, true)).unwrap();
1678		producer.write(frame(1_600, true)).unwrap();
1679		producer.write(frame(3_000, true)).unwrap();
1680		let _producer = producer.finish().unwrap();
1681
1682		let mut groups = Vec::new();
1683		let from_zero = moq_net::track::Subscription::default()
1684			.with_ranges([moq_net::track::Range::from(moq_net::track::Start::Time(0))]);
1685		let mut reader = consumer.subscribe(from_zero).await.unwrap();
1686		while let Some(mut group) = reader.recv_group().await.unwrap() {
1687			let mut frames = 0;
1688			while group.read_frame().await.unwrap().is_some() {
1689				frames += 1;
1690			}
1691			groups.push((group.start, frames));
1692		}
1693		groups.sort();
1694		assert_eq!(groups, [(1, 2), (3, 1)]);
1695	}
1696
1697	/// A buffered CMAF group whose open-GOP leading pictures present below its keyframe starts
1698	/// at the fragment's earliest presentation time, so the group before it ends there rather
1699	/// than at the keyframe, and the two spans never overlap.
1700	#[tokio::test]
1701	async fn a_buffered_open_gop_group_starts_where_the_one_before_ended() {
1702		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
1703		config.coded_width = Some(320);
1704		config.coded_height = Some(240);
1705		let muxer = crate::container::fmp4::Muxer::video(&config).unwrap();
1706		let init = muxer.init().unwrap().expect("VP8 init should be available");
1707		let cmaf = hang::catalog::Container::Cmaf { init };
1708		let format = crate::catalog::hang::Wire::new(&cmaf, crate::container::Kind::Video).unwrap();
1709		let info = hang::container::track_info(hang::catalog::PRIORITY.video).with_timescale(muxer.timescale());
1710		let track = track_producer("video", info);
1711		let consumer = track.consume();
1712		let mut producer = Producer::new(track, format).with_buffer(std::time::Duration::from_secs(10));
1713		// The keyframe at 100ms is followed by leading pictures presenting at 93ms and 96ms, after
1714		// the group before it.
1715		for (ms, keyframe) in [
1716			(0, true),
1717			(40, false),
1718			(90, false),
1719			(100, true),
1720			(93, false),
1721			(96, false),
1722		] {
1723			producer.write(frame(ms * 1000, keyframe)).unwrap();
1724		}
1725		let _producer = producer.finish().unwrap();
1726
1727		let from_zero = moq_net::track::Subscription::default()
1728			.with_ranges([moq_net::track::Range::from(moq_net::track::Start::Time(0))]);
1729		let mut reader = consumer.subscribe(from_zero).await.unwrap();
1730		let mut groups = Vec::new();
1731		while let Some(mut group) = reader.recv_group().await.unwrap() {
1732			while group.read_frame().await.unwrap().is_some() {}
1733			groups.push((group.start, group.end()));
1734		}
1735		groups.sort();
1736		let ms = |ms: u64| {
1737			moq_net::Timestamp::from_millis(ms)
1738				.unwrap()
1739				.convert(muxer.timescale())
1740				.unwrap()
1741				.value()
1742		};
1743		// The group before ends where the fragment's earliest picture starts the next.
1744		assert_eq!(groups.len(), 2, "{groups:?}");
1745		assert_eq!(groups[0], (0, Some(ms(93))), "{groups:?}");
1746		assert_eq!(groups[1].0, ms(93), "{groups:?}");
1747	}
1748
1749	/// Aborting while the group a keyframe closed still waits for the next one's start finishes
1750	/// that group at its own End: it was whole, so its readers see it end rather than the abort.
1751	#[tokio::test]
1752	async fn an_abort_finishes_the_buffered_group_before() {
1753		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
1754		config.coded_width = Some(320);
1755		config.coded_height = Some(240);
1756		let muxer = crate::container::fmp4::Muxer::video(&config).unwrap();
1757		let init = muxer.init().unwrap().expect("VP8 init should be available");
1758		let cmaf = hang::catalog::Container::Cmaf { init };
1759		let format = crate::catalog::hang::Wire::new(&cmaf, crate::container::Kind::Video).unwrap();
1760		let info = hang::container::track_info(hang::catalog::PRIORITY.video).with_timescale(muxer.timescale());
1761		let track = track_producer("video", info);
1762		let consumer = track.consume();
1763		let from_zero = moq_net::track::Subscription::default()
1764			.with_ranges([moq_net::track::Range::from(moq_net::track::Start::Time(0))]);
1765		let mut reader = consumer.subscribe(from_zero).await.unwrap();
1766		let mut producer = Producer::new(track, format).with_buffer(std::time::Duration::from_secs(10));
1767		for (ms, keyframe) in [(0, true), (40, false), (100, true)] {
1768			producer.write(frame(ms * 1000, keyframe)).unwrap();
1769		}
1770		let mut group = reader.recv_group().await.unwrap().expect("the first group");
1771		producer.abort(moq_net::Error::Cancel);
1772
1773		while group.read_frame().await.unwrap().is_some() {}
1774		let end = moq_net::Timestamp::from_millis(100)
1775			.unwrap()
1776			.convert(muxer.timescale())
1777			.unwrap()
1778			.value();
1779		assert_eq!((group.start, group.end()), (0, Some(end)));
1780	}
1781
1782	/// The catalog estimate falls out of the writes themselves: a publisher never records anything
1783	/// by hand, it just hands `estimate()` to its rendition.
1784	#[tokio::test]
1785	async fn writes_measure_bitrate_without_inventing_jitter() {
1786		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
1787		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
1788
1789		// 25ms frames of 5 kB, a keyframe every 10, over more than the bitrate window.
1790		for i in 0..80u64 {
1791			producer.write(sized_frame(i * 25_000, i % 10 == 0, 5_000)).unwrap();
1792		}
1793		let producer = producer.finish().unwrap();
1794
1795		let estimate = producer.estimate();
1796		assert_eq!(estimate.jitter, None, "PTS spacing alone is not jitter");
1797		assert_eq!(estimate.bitrate, Some(1_600_000));
1798	}
1799
1800	/// A streamed frame presenting below its group's latest rides the transport at the latest
1801	/// when its prefix carries the presentation time, and is refused where the transport is
1802	/// the frame's only timing, as the buffered path refuses it.
1803	#[test]
1804	fn a_streamed_reordered_frame_is_raised_or_refused() {
1805		use crate::container::Kind;
1806		for (container, raised) in [(Wire::legacy(Kind::Video), true), (Wire::raw(Kind::Video), false)] {
1807			let track = track_producer("video", hang::container::track_info(hang::catalog::PRIORITY.video));
1808			let mut producer = Producer::new(track, container);
1809			let stream = |producer: &mut Producer<Wire>, at: u64, keyframe: bool| {
1810				let mut streamed = producer.open(frame(at, keyframe), 2)?;
1811				streamed.write(&[0xDE, 0xAD])?;
1812				producer.commit(streamed)
1813			};
1814			stream(&mut producer, 0, true).unwrap();
1815			stream(&mut producer, 66_000, false).unwrap();
1816			let result = stream(&mut producer, 33_000, false);
1817			assert_eq!(result.is_ok(), raised, "{result:?}");
1818			// A refusal leaves the group open for the frames after it.
1819			stream(&mut producer, 100_000, false).unwrap();
1820		}
1821	}
1822
1823	type Rendition = Producer<Wire, hang::catalog::VideoConfig>;
1824
1825	/// Video renditions sharing one catalog, each opened with a keyframe at 0.
1826	fn renditions(names: &[&str]) -> (moq_net::broadcast::Producer, crate::catalog::Producer, Vec<Rendition>) {
1827		let mut broadcast = moq_net::broadcast::Info::new().produce();
1828		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
1829		let mut tracks = Vec::new();
1830		for name in names {
1831			let net = broadcast
1832				.create_track(*name, catalog.track_info(hang::catalog::PRIORITY.video))
1833				.unwrap();
1834			let config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
1835			let mut track = catalog
1836				.video(net, Wire::legacy(crate::container::Kind::Video), config)
1837				.unwrap();
1838			track.write(frame(0, true)).unwrap();
1839			tracks.push(track);
1840		}
1841		(broadcast, catalog, tracks)
1842	}
1843
1844	#[test]
1845	fn catalog_write_order_measures_delay_across_renditions() {
1846		let (_broadcast, catalog, mut tracks) = renditions(&["fast", "slow"]);
1847
1848		// The slow rendition writes each frame after the fast one has written 200ms past it, for longer
1849		// than the window delay is measured over.
1850		for i in 1..40u64 {
1851			tracks[0].write(frame(i * 40_000 + 200_000, true)).unwrap();
1852			tracks[1].write(frame(i * 40_000, true)).unwrap();
1853		}
1854		for track in &mut tracks {
1855			track.cut(None).unwrap();
1856		}
1857
1858		let ms = std::time::Duration::from_millis;
1859		let renditions = catalog.snapshot().video.renditions;
1860		assert_eq!(renditions["slow"].delay, Some(ms(200)));
1861		assert_eq!(renditions["fast"].delay, None);
1862		assert_eq!(renditions["slow"].jitter, None, "a constant trail is not jitter");
1863	}
1864
1865	#[test]
1866	fn reconfigure_keeps_floors_until_the_track_identity_changes() {
1867		let ms = std::time::Duration::from_millis;
1868		for codec in ["avc3.42c01e", "hev1.1.6.L93.B0"] {
1869			let (_broadcast, catalog, mut tracks) = renditions(&["fast", "slow"]);
1870			let slow = &mut tracks[1];
1871			// Start a new identity, as an importer does when it resolves its codec.
1872			let mut config = hang::catalog::VideoConfig::new(codec.parse::<hang::catalog::VideoCodec>().unwrap());
1873			config.coded_width = Some(640);
1874			config.coded_height = Some(360);
1875			slow.reconfigure(config.clone()).unwrap();
1876			let name = slow.name().to_string();
1877			tracks[1].reorder(std::time::Duration::from_millis(100));
1878			for i in 1..40u64 {
1879				tracks[0].write(frame(i * 40_000 + 200_000, true)).unwrap();
1880				tracks[1].write(frame(i * 40_000, true)).unwrap();
1881			}
1882			tracks[1].cut(None).unwrap();
1883			let measured = catalog.snapshot().video.renditions[&name].clone();
1884			assert_eq!((measured.jitter, measured.delay), (Some(ms(100)), Some(ms(200))));
1885
1886			// Match an external catalog edit, such as the HLS conformance fixture's raise.
1887			let mut edit = tracks[1].modify().unwrap();
1888			edit.jitter = Some(ms(300));
1889			edit.delay = Some(ms(400));
1890			edit.commit().unwrap();
1891			config.coded_width = Some(1280);
1892			config.coded_height = Some(720);
1893			tracks[1].reconfigure(config.clone()).unwrap();
1894			assert_eq!(tracks[1].name(), name);
1895			let current = catalog.snapshot().video.renditions[&name].clone();
1896			assert_eq!((current.coded_width, current.coded_height), (Some(1280), Some(720)));
1897			assert_eq!((current.jitter, current.delay), (Some(ms(300)), Some(ms(400))));
1898
1899			for (jitter, delay) in [(Some(ms(250)), None), (None, Some(ms(350)))] {
1900				let mut lower = config.clone();
1901				lower.jitter = jitter;
1902				lower.delay = delay;
1903				let err = tracks[1].reconfigure(lower).unwrap_err();
1904				assert!(matches!(
1905					(jitter, err),
1906					(Some(_), crate::Error::JitterDecreased) | (None, crate::Error::DelayDecreased)
1907				));
1908				assert_eq!(catalog.snapshot().video.renditions[&name], current);
1909			}
1910
1911			// A new identity owns a new floor, even when it supplies lower values.
1912			config.codec = hang::catalog::VideoCodec::VP8;
1913			config.jitter = Some(ms(20));
1914			config.delay = Some(ms(30));
1915			tracks[1].reconfigure(config).unwrap();
1916			assert_ne!(tracks[1].name(), name);
1917			let current = catalog.snapshot().video.renditions[tracks[1].name()].clone();
1918			assert_eq!((current.jitter, current.delay), (Some(ms(20)), Some(ms(30))));
1919		}
1920	}
1921
1922	/// History caught up behind the live edge is not a late write: only what follows it measures delay.
1923	#[test]
1924	fn history_measures_no_delay() {
1925		let (_broadcast, catalog, mut tracks) = renditions(&["live", "replay"]);
1926		tracks[0].write(frame(2_000_000, true)).unwrap();
1927
1928		tracks[1].history(moq_net::Timestamp::from_micros(1_960_000).unwrap());
1929		for i in 1..=49u64 {
1930			tracks[1].write(frame(i * 40_000, true)).unwrap();
1931		}
1932		tracks[1].cut(None).unwrap();
1933		assert_eq!(catalog.snapshot().video.renditions["replay"].delay, None);
1934
1935		// Live frames past the history that still trail the other rendition are late writes.
1936		for i in 0..40u64 {
1937			tracks[0].write(frame(2_040_000 + i * 40_000, true)).unwrap();
1938			tracks[1].write(frame(2_020_000 + i * 40_000, true)).unwrap();
1939		}
1940		tracks[1].cut(None).unwrap();
1941		assert_eq!(tracks[1].estimate().delay, Some(std::time::Duration::from_millis(20)));
1942	}
1943
1944	/// Buffered frames reach the transport when the buffer flushes, so a second-long buffer's oldest
1945	/// frame trails the other rendition by the batch's span, and its newest by nothing: the span is
1946	/// jitter, not delay.
1947	#[test]
1948	fn a_buffered_rendition_flushes_its_span_as_jitter() {
1949		let (_broadcast, catalog, tracks) = renditions(&["live", "buffered"]);
1950		let [mut live, buffered] = <[Rendition; 2]>::try_from(tracks).ok().unwrap();
1951		let mut buffered = buffered.with_buffer(std::time::Duration::from_secs(1));
1952
1953		for i in 1..=25u64 {
1954			live.write(frame(i * 40_000, false)).unwrap();
1955			buffered.write(frame(i * 40_000, false)).unwrap();
1956		}
1957		buffered.cut(None).unwrap();
1958
1959		let buffered = &catalog.snapshot().video.renditions["buffered"];
1960		assert_eq!(
1961			(buffered.jitter, buffered.delay),
1962			(Some(std::time::Duration::from_millis(960)), None)
1963		);
1964	}
1965
1966	/// A finished rendition may be kept around, but its media stops holding the others back.
1967	#[test]
1968	fn a_finished_rendition_stops_holding_others_back() {
1969		let (_broadcast, catalog, tracks) = renditions(&["ended", "live"]);
1970		let Ok([mut ended, mut live]) = <[_; 2]>::try_from(tracks) else {
1971			unreachable!("two renditions")
1972		};
1973		ended.write(frame(10_000_000, true)).unwrap();
1974		let _ended = ended.finish().unwrap();
1975
1976		live.write(frame(1_000_000, true)).unwrap();
1977		assert_eq!(catalog.snapshot().video.renditions["live"].delay, None);
1978	}
1979
1980	/// A passthrough producer claims nothing until the first window closes, then
1981	/// reserves that peak, raises the ceiling on a louder later window, and holds
1982	/// it when a quieter one follows.
1983	#[tokio::test]
1984	async fn a_passthrough_producer_ratchets_its_bandwidth_claim() {
1985		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
1986		let _sub = track.subscribe(None);
1987		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data))
1988			.with_bandwidth(moq_net::bandwidth::Allocator::unlimited());
1989
1990		producer.write(sized_frame(0, true, 100_000)).unwrap();
1991		producer.write(sized_frame(500_000, false, 100_000)).unwrap();
1992		assert_eq!(producer.bandwidth_ceiling(), None, "the first window has not closed");
1993
1994		producer.cut(Some(Timestamp::from_micros(1_000_000).unwrap())).unwrap();
1995		assert_eq!(
1996			producer.bandwidth_ceiling(),
1997			Some(moq_net::bandwidth::Rate::from_bps(1_600_000))
1998		);
1999
2000		producer.write(sized_frame(1_000_000, true, 25_000)).unwrap();
2001		producer.cut(Some(Timestamp::from_micros(2_000_000).unwrap())).unwrap();
2002		assert_eq!(
2003			producer.bandwidth_ceiling(),
2004			Some(moq_net::bandwidth::Rate::from_bps(1_600_000)),
2005			"a quieter window never hands the room away"
2006		);
2007
2008		producer.write(sized_frame(2_000_000, true, 250_000)).unwrap();
2009		producer.cut(Some(Timestamp::from_micros(3_000_000).unwrap())).unwrap();
2010		assert_eq!(
2011			producer.bandwidth_ceiling(),
2012			Some(moq_net::bandwidth::Rate::from_bps(2_000_000))
2013		);
2014	}
2015
2016	/// A passthrough want at its peak lowers a co-resident encoder's grant by
2017	/// exactly that amount, which is the whole reason the import claims at all.
2018	#[tokio::test]
2019	async fn a_passthrough_peak_lowers_a_coresident_encoder_grant() {
2020		let estimate = moq_net::bandwidth::Producer::new();
2021		let allocator = moq_net::bandwidth::Allocator::new(estimate.consume());
2022		estimate
2023			.set(Some(moq_net::bandwidth::Rate::from_bps(6_000_000)))
2024			.unwrap();
2025
2026		fn video_track() -> (moq_net::broadcast::Producer, moq_net::track::Producer) {
2027			let broadcast = moq_net::broadcast::Info::new().produce();
2028			let track = broadcast
2029				.create_track("t", hang::container::track_info(hang::catalog::PRIORITY.video))
2030				.unwrap();
2031			(broadcast, track)
2032		}
2033
2034		let (_encoder_broadcast, encoder_track) = video_track();
2035		let _encoder_sub = encoder_track.subscribe(None);
2036		let encoder = allocator.reserve(&encoder_track.demand(), moq_net::bandwidth::Rate::from_bps(8_000_000));
2037		assert_eq!(
2038			encoder.rate(),
2039			Some(moq_net::bandwidth::Rate::from_bps(6_000_000)),
2040			"alone, the encoder takes the whole estimate"
2041		);
2042
2043		let (_passthrough_broadcast, passthrough) = video_track();
2044		let _passthrough_sub = passthrough.subscribe(None);
2045		let mut producer =
2046			Producer::new(passthrough, Wire::legacy(crate::container::Kind::Data)).with_bandwidth(allocator);
2047
2048		producer.write(sized_frame(0, true, 100_000)).unwrap();
2049		producer.write(sized_frame(500_000, false, 100_000)).unwrap();
2050		assert_eq!(
2051			encoder.rate(),
2052			Some(moq_net::bandwidth::Rate::from_bps(6_000_000)),
2053			"nothing claimed before the first window"
2054		);
2055
2056		producer.cut(Some(Timestamp::from_micros(1_000_000).unwrap())).unwrap();
2057		assert_eq!(
2058			encoder.rate(),
2059			Some(moq_net::bandwidth::Rate::from_bps(4_400_000)),
2060			"the encoder's grant drops by the passthrough peak (1.6 Mbps)"
2061		);
2062	}
2063
2064	/// One group per frame (how the importer facade drives audio) closes each group with an
2065	/// unbounded `cut`, which leaves the measurement open for the next frame's timestamp to close.
2066	/// Dropping it there instead would leave an audio track's bitrate permanently undetectable.
2067	#[tokio::test]
2068	async fn per_frame_groups_still_measure_bitrate() {
2069		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2070		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2071
2072		// 40ms packets of 5 kB: 1 Mbps.
2073		for i in 0..40u64 {
2074			let keyframe = producer.needs_keyframe();
2075			producer.write(sized_frame(i * 40_000, keyframe, 5_000)).unwrap();
2076			producer.cut(None).unwrap();
2077		}
2078
2079		assert_eq!(producer.estimate().bitrate, Some(1_000_000));
2080	}
2081
2082	/// A data item has no cadence to last for, so an unbounded cut measures to the next item rather
2083	/// than to an end estimated from items spaced closer earlier.
2084	#[tokio::test]
2085	async fn unbounded_data_cuts_measure_to_the_next_item() {
2086		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2087		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2088
2089		// 250 bytes every 40 ms, 50 kbps: first as two items 10 ms apart, then one item at a time.
2090		producer.write(sized_frame(0, true, 125)).unwrap();
2091		producer.write(sized_frame(10_000, false, 125)).unwrap();
2092		producer.cut(None).unwrap();
2093		for i in 1..40u64 {
2094			producer.write(sized_frame(i * 40_000, true, 250)).unwrap();
2095			producer.cut(None).unwrap();
2096		}
2097
2098		// A maximum, which the first group's close pair lifts a little, never to the 10 ms spacing.
2099		let bitrate = producer.estimate().bitrate;
2100		assert!(
2101			bitrate.is_some_and(|bitrate| (50_000..55_000).contains(&bitrate)),
2102			"{bitrate:?}"
2103		);
2104	}
2105
2106	#[tokio::test]
2107	async fn grouped_unbounded_cuts_measure_the_last_frame() {
2108		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2109		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2110		for i in 0..200u64 {
2111			// 20 ms packets of 250 bytes: 100 kbps.
2112			producer.write(sized_frame(i * 20_000, i % 5 == 0, 250)).unwrap();
2113			if i % 5 == 4 {
2114				producer.cut(None).unwrap();
2115			}
2116		}
2117		assert_eq!(producer.estimate().bitrate, Some(100_000));
2118	}
2119
2120	/// A break in the timeline is not a frame duration, so the estimate never spans one. Without the
2121	/// reset a paused publisher would advertise the whole gap as the buffer a player must hold.
2122	#[tokio::test]
2123	async fn discontinuity_is_not_measured_across() {
2124		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2125		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2126
2127		producer.write(sized_frame(0, true, 5_000)).unwrap();
2128		producer.discontinuity().unwrap();
2129		// Resumed 40 minutes later, on a re-anchored clock.
2130		producer.write(sized_frame(2_405_070_000, true, 5_000)).unwrap();
2131		let producer = producer.finish().unwrap();
2132
2133		assert_eq!(producer.estimate().jitter, None);
2134		assert_eq!(producer.estimate().bitrate, None);
2135	}
2136
2137	/// Write-only container that rejects the frame at a given timestamp, standing in for one the
2138	/// container can't encode (over the group size limit, a timestamp that won't convert).
2139	#[derive(Clone)]
2140	struct RejectAt(u64);
2141
2142	impl super::Container for RejectAt {
2143		type Error = crate::Error;
2144
2145		fn write(&self, _group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
2146			match frames
2147				.iter()
2148				.any(|f| f.timestamp.as_micros().unwrap() == self.0 as u128)
2149			{
2150				true => Err(moq_net::Error::FrameTooLarge.into()),
2151				false => Ok(()),
2152			}
2153		}
2154
2155		fn decode(&self, _frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
2156			unreachable!("RejectAt is write-only")
2157		}
2158	}
2159
2160	/// A rejected frame leaves the producer usable, so the caller can carry on. Its bytes never
2161	/// reached the wire, and the estimate's maximum never falls, so counting them would pin an
2162	/// inflated bitrate on the catalog permanently.
2163	#[tokio::test]
2164	async fn a_rejected_frame_is_not_measured() {
2165		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2166		let mut producer = Producer::new(track, RejectAt(40_000));
2167
2168		// 40ms frames of 5 kB (1 Mbps), except one 500 kB frame the container turns away.
2169		for i in 0..40u64 {
2170			let bytes = if i == 1 { 500_000 } else { 5_000 };
2171			let result = producer.write(sized_frame(i * 40_000, true, bytes));
2172			assert_eq!(result.is_err(), i == 1, "only the rejected frame fails");
2173		}
2174
2175		assert_eq!(producer.estimate().bitrate, Some(1_000_000));
2176	}
2177
2178	/// Legacy video, except a frame at the given microsecond timestamp, which it turns away.
2179	#[derive(Clone)]
2180	struct LegacyRejectingAt(u64);
2181
2182	impl super::Container for LegacyRejectingAt {
2183		type Error = crate::Error;
2184
2185		fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
2186			match frames
2187				.iter()
2188				.any(|f| f.timestamp.as_micros().unwrap() == self.0 as u128)
2189			{
2190				true => Err(moq_net::Error::FrameTooLarge.into()),
2191				false => Wire::legacy(crate::container::Kind::Video).write(group, frames),
2192			}
2193		}
2194
2195		fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
2196			Wire::legacy(crate::container::Kind::Video).decode(frame)
2197		}
2198
2199		fn end(&self, frame: &Frame) -> Option<Timestamp> {
2200			Wire::legacy(crate::container::Kind::Video).end(frame)
2201		}
2202
2203		fn kind(&self) -> Kind {
2204			Kind::Video
2205		}
2206
2207		fn finish_group(
2208			&self,
2209			group: &mut crate::container::Writer<'_>,
2210			end: Option<Timestamp>,
2211		) -> Result<(), Self::Error> {
2212			Wire::legacy(crate::container::Kind::Video).finish_group(group, end)
2213		}
2214	}
2215
2216	/// A B-frame the container turns away never marks its group reordered, so the frames it
2217	/// did take still end with their duration marker.
2218	#[tokio::test]
2219	async fn a_rejected_reordered_frame_keeps_the_group_in_order() {
2220		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2221		let consumer = track.subscribe(replay());
2222		let mut producer = Producer::new(track, LegacyRejectingAt(33_000));
2223		producer.write(frame(0, true)).unwrap();
2224		producer.write(frame(66_000, false)).unwrap();
2225		assert!(producer.write(frame(33_000, false)).is_err());
2226		let _finished = producer.finish().unwrap();
2227		assert_eq!(collect_payloads(consumer).await[0].last(), Some(&(132_000, 0)));
2228	}
2229
2230	/// Reorder delay is the one input the writes can't reveal, since frames carry no decode time.
2231	#[tokio::test]
2232	async fn reorder_raises_the_measured_jitter() {
2233		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2234		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2235
2236		producer.write(frame(0, true)).unwrap();
2237		producer.write(frame(16_000, false)).unwrap();
2238		assert_eq!(producer.estimate().jitter, None, "PTS spacing alone is not flush delay");
2239
2240		producer.reorder(std::time::Duration::from_millis(48));
2241		assert_eq!(
2242			producer.estimate().jitter,
2243			Some(std::time::Duration::from_millis(48)),
2244			"a B-frame stream needs the deeper decode buffer"
2245		);
2246	}
2247
2248	/// Drain all groups from a finished track, returning their frame counts.
2249	async fn collect_groups(consumer: moq_net::track::Subscriber) -> Vec<usize> {
2250		// Key order, oldest first, whatever the subscription's Group Order.
2251		let mut consumer = consumer.ordered();
2252		let mut groups = Vec::new();
2253		while let Some(mut group) = consumer.next_group().await.unwrap() {
2254			let mut count = 0;
2255			while group.next_frame().await.unwrap().is_some() {
2256				count += 1;
2257			}
2258			groups.push(count);
2259		}
2260		groups
2261	}
2262
2263	/// A discontinuity lands as its own marker group (one empty frame) between the
2264	/// content either side, so a consumer can see the break instead of inferring
2265	/// continuity from adjacent sequences.
2266	#[tokio::test]
2267	async fn discontinuity_publishes_an_empty_group() {
2268		// The resumed clock jumps forty minutes, so both the max age and the
2269		// drift budget have to cover it or the pre-discontinuity group reads as ancient.
2270		let discontinuity_max_age = std::time::Duration::from_secs(41 * 60);
2271		let info = hang::container::track_info(hang::catalog::PRIORITY.audio).with_max_age(discontinuity_max_age);
2272		let track = track_producer("test", info);
2273		let consumer =
2274			track.subscribe(
2275				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
2276					moq_net::track::Start::Live {
2277						min: Some(discontinuity_max_age),
2278						max: Some(discontinuity_max_age),
2279					},
2280				)]),
2281			);
2282		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2283
2284		producer.write(frame(0, true)).unwrap();
2285		producer.write(frame(10_000, false)).unwrap();
2286		producer.discontinuity().unwrap();
2287		// Resumed on a re-anchored clock, 40 minutes later.
2288		producer.write(frame(2_405_070_000, true)).unwrap();
2289		let _finished = producer.finish().unwrap();
2290
2291		let groups = collect_payloads(consumer).await;
2292		assert_eq!(groups.len(), 3);
2293		assert_eq!(groups[0], vec![(0, 2), (10_000, 2)]);
2294		assert_eq!(
2295			groups[1],
2296			vec![(10_000, 0)],
2297			"the marker is one empty frame at the last frame, which has no duration to end later"
2298		);
2299		assert_eq!(groups[2][0], (2_405_070_000, 2));
2300	}
2301
2302	/// A subscription starts at the track's LATEST group, and the marker advances it even
2303	/// though it carries nothing. So a subscriber arriving mid-break waits for real media
2304	/// rather than being handed the pre-break group as if it were live -- which is how a
2305	/// 40-minute-stale frame once reached a VOD recording.
2306	#[test]
2307	fn discontinuity_moves_the_live_edge_off_stale_content() {
2308		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2309		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2310
2311		producer.write(frame(0, true)).unwrap();
2312		let stale = producer.track().largest().map(|largest| largest.group);
2313
2314		producer.discontinuity().unwrap();
2315		let fresh = producer.track().largest().map(|largest| largest.group);
2316
2317		assert!(fresh > stale, "the marker group is the live edge now");
2318	}
2319
2320	/// The marker sits at the duration marker a cut wrote, where the cut ended its group whole: not
2321	/// a unit before it, inside that group's span, nor at the last frame below it, which a consumer
2322	/// bounding groups by their reach would read as a rewind.
2323	#[tokio::test]
2324	async fn discontinuity_after_a_cut_starts_at_the_duration_marker() {
2325		for (end, marker) in [(Some(25_000), 25_000), (None, 20_000)] {
2326			let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2327			let consumer = track.subscribe(replay());
2328			let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2329
2330			producer.write(frame(0, true)).unwrap();
2331			assert_eq!(producer.live_edge(), None, "no group has ended yet");
2332			producer.write(frame(10_000, false)).unwrap();
2333			producer.cut(end.map(|us| Timestamp::from_micros(us).unwrap())).unwrap();
2334			// With no group open, a cut's bound is a point nothing reached.
2335			producer.cut(Some(Timestamp::from_micros(90_000).unwrap())).unwrap();
2336			producer.discontinuity().unwrap();
2337			let _finished = producer.finish().unwrap();
2338
2339			let groups = collect_payloads(consumer).await;
2340			assert_eq!(
2341				groups[0].last(),
2342				Some(&(marker, 0)),
2343				"cut({end:?}) writes its duration marker"
2344			);
2345			assert_eq!(groups[1], vec![(marker, 0)], "cut({end:?}) then discontinuity");
2346		}
2347	}
2348
2349	/// Explicit keyframe closes the current group and starts a new one.
2350	#[tokio::test]
2351	async fn keyframe_closes_group_immediately() {
2352		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2353		let consumer = track.subscribe(replay());
2354		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2355
2356		producer.write(frame(0, true)).unwrap(); // first frame must be a keyframe
2357		producer.write(frame(10_000, false)).unwrap();
2358		producer.write(frame(20_000, true)).unwrap(); // keyframe → new group
2359		producer.write(frame(30_000, false)).unwrap();
2360		let _finished = producer.finish().unwrap();
2361
2362		assert_eq!(collect_groups(consumer).await, vec![2, 2]);
2363	}
2364
2365	/// `needs_keyframe` tracks whether a group is open, so an audio importer can mark only the first
2366	/// frame of each group a keyframe (`keyframe: producer.needs_keyframe()`) and accumulate the rest
2367	/// into that group until it cuts. Regression guard for the "one group (one QUIC stream)
2368	/// per audio packet" storm.
2369	#[tokio::test]
2370	async fn needs_keyframe_drives_audio_grouping() {
2371		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2372		let consumer = track.subscribe(replay());
2373		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2374
2375		// Drive grouping off `needs_keyframe`, as the audio importers do: the first frame of each
2376		// group is a keyframe, the rest are not, so they accumulate into ONE group...
2377		for ts in [0, 10_000, 20_000] {
2378			let keyframe = producer.needs_keyframe();
2379			producer.write(frame(ts, keyframe)).unwrap();
2380		}
2381		producer.cut(None).unwrap();
2382		// ...until the caller draws a boundary, which opens the next group.
2383		for ts in [30_000, 40_000] {
2384			let keyframe = producer.needs_keyframe();
2385			producer.write(frame(ts, keyframe)).unwrap();
2386		}
2387		let _finished = producer.finish().unwrap();
2388
2389		assert_eq!(collect_groups(consumer).await, vec![3, 2]);
2390	}
2391
2392	/// Drain all groups, returning each group's (timestamp_micros, payload_len) pairs.
2393	async fn collect_payloads(consumer: moq_net::track::Subscriber) -> Vec<Vec<(u128, usize)>> {
2394		// Key order, oldest first, whatever the subscription's Group Order.
2395		let mut consumer = consumer.ordered();
2396		let mut groups = Vec::new();
2397		while let Some(mut group) = consumer.next_group().await.unwrap() {
2398			let mut frames = Vec::new();
2399			while let Some(frame) = group.read_frame().await.unwrap() {
2400				let decoded = hang::container::Frame::decode(frame.payload).unwrap();
2401				frames.push((decoded.timestamp.as_micros().unwrap(), decoded.payload.len()));
2402			}
2403			groups.push(frames);
2404		}
2405		groups
2406	}
2407
2408	/// A video group ends with an empty frame at the next keyframe's timestamp.
2409	#[tokio::test]
2410	async fn cut_writes_a_duration_marker_at_the_callers_bound() {
2411		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2412		let consumer = track.subscribe(replay());
2413		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2414
2415		producer.write(frame(0, true)).unwrap();
2416		producer.write(frame(10_000, false)).unwrap();
2417		producer
2418			.cut(Some(moq_net::Timestamp::from_micros(15_000).unwrap()))
2419			.unwrap();
2420		producer.write(frame(20_000, true)).unwrap();
2421		let _finished = producer.finish().unwrap();
2422
2423		let groups = collect_payloads(consumer).await;
2424		assert_eq!(groups[0], vec![(0, 2), (10_000, 2), (15_000, 0)]);
2425		assert_eq!(groups[1][0], (20_000, 2));
2426		assert_eq!(groups[1].last().unwrap().1, 0, "finish closes the last group");
2427	}
2428
2429	/// Audio never writes a duration marker, even at finish.
2430	#[tokio::test]
2431	async fn audio_cut_writes_no_duration_marker() {
2432		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2433		let consumer = track.subscribe(replay());
2434		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2435
2436		producer.write(frame(0, true)).unwrap();
2437		producer.write(frame(20_000, false)).unwrap();
2438		let _finished = producer.finish().unwrap();
2439
2440		assert_eq!(collect_payloads(consumer).await, vec![vec![(0, 2), (20_000, 2)]]);
2441	}
2442
2443	/// Drain all LOC groups, returning each group's (timestamp_micros, payload_len) pairs.
2444	async fn collect_loc_payloads(consumer: moq_net::track::Subscriber) -> Vec<Vec<(u64, usize)>> {
2445		// Key order, oldest first, whatever the subscription's Group Order.
2446		let mut consumer = consumer.ordered();
2447		let mut groups = Vec::new();
2448		while let Some(mut group) = consumer.next_group().await.unwrap() {
2449			let mut frames = Vec::new();
2450			while let Some(frame) = group.read_frame().await.unwrap() {
2451				let decoded = moq_loc::decode(frame.payload).unwrap();
2452				frames.push((decoded.timestamp, decoded.payload.len()));
2453			}
2454			groups.push(frames);
2455		}
2456		groups
2457	}
2458
2459	/// A LOC video group ends with an empty frame at the next keyframe's timestamp, like Legacy.
2460	#[tokio::test]
2461	async fn loc_cut_writes_a_duration_marker_at_the_callers_bound() {
2462		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2463		let consumer = track.subscribe(replay());
2464		let mut producer = Producer::new(track, Wire::loc(crate::container::Kind::Video));
2465
2466		producer.write(frame(0, true)).unwrap();
2467		producer.write(frame(10_000, false)).unwrap();
2468		producer
2469			.cut(Some(moq_net::Timestamp::from_micros(15_000).unwrap()))
2470			.unwrap();
2471		producer.write(frame(20_000, true)).unwrap();
2472		let _finished = producer.finish().unwrap();
2473
2474		let groups = collect_loc_payloads(consumer).await;
2475		assert_eq!(groups[0], vec![(0, 2), (10_000, 2), (15_000, 0)]);
2476		assert_eq!(groups[1][0], (20_000, 2));
2477		assert_eq!(groups[1].last().unwrap().1, 0, "finish closes the last group");
2478	}
2479
2480	/// LOC audio never writes a duration marker, even at finish.
2481	#[tokio::test]
2482	async fn loc_audio_writes_no_duration_marker() {
2483		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2484		let consumer = track.subscribe(replay());
2485		let mut producer = Producer::new(track, Wire::loc(crate::container::Kind::Audio));
2486
2487		producer.write(frame(0, true)).unwrap();
2488		producer.write(frame(20_000, false)).unwrap();
2489		producer
2490			.cut(Some(moq_net::Timestamp::from_micros(30_000).unwrap()))
2491			.unwrap();
2492		producer.write(frame(40_000, true)).unwrap();
2493		let _finished = producer.finish().unwrap();
2494
2495		assert_eq!(
2496			collect_loc_payloads(consumer).await,
2497			vec![vec![(0, 2), (20_000, 2)], vec![(40_000, 2)]]
2498		);
2499	}
2500
2501	/// LOC data tracks never write a duration marker, so an empty data frame stays data.
2502	#[tokio::test]
2503	async fn loc_data_writes_no_duration_marker() {
2504		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2505		let consumer = track.subscribe(replay());
2506		let mut producer = Producer::new(track, Wire::loc(crate::container::Kind::Data));
2507
2508		producer.write(frame(0, true)).unwrap();
2509		producer
2510			.cut(Some(moq_net::Timestamp::from_micros(15_000).unwrap()))
2511			.unwrap();
2512		producer.write(frame(20_000, true)).unwrap();
2513		let _finished = producer.finish().unwrap();
2514
2515		assert_eq!(
2516			collect_loc_payloads(consumer).await,
2517			vec![vec![(0, 2)], vec![(20_000, 2)]]
2518		);
2519	}
2520
2521	/// `cut()` flushes the current group immediately; the next write must be a keyframe.
2522	#[tokio::test]
2523	async fn cut_closes_immediately() {
2524		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2525		let consumer = track.subscribe(replay());
2526		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2527
2528		producer.write(frame(0, true)).unwrap();
2529		producer.write(frame(10_000, false)).unwrap();
2530		producer
2531			.cut(Some(moq_net::Timestamp::from_micros(15_000).unwrap()))
2532			.unwrap();
2533		producer.write(frame(20_000, true)).unwrap();
2534		let _finished = producer.finish().unwrap();
2535
2536		assert_eq!(collect_groups(consumer).await, vec![2, 1]);
2537	}
2538
2539	/// Writing a non-keyframe with no open group returns MissingKeyframe.
2540	#[test]
2541	fn first_frame_must_be_keyframe() {
2542		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2543		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Data));
2544
2545		let err = producer.write(frame(0, false)).unwrap_err();
2546		assert!(matches!(err, crate::Error::MissingKeyframe(_)));
2547	}
2548
2549	/// Drain all groups from a finished track, returning their starts.
2550	async fn collect_starts(consumer: moq_net::track::Subscriber) -> Vec<u64> {
2551		// Key order, oldest first, whatever the subscription's Group Order.
2552		let mut consumer = consumer.ordered();
2553		let mut starts = Vec::new();
2554		while let Some(group) = consumer.next_group().await.unwrap() {
2555			starts.push(group.start);
2556		}
2557		starts
2558	}
2559
2560	/// An overlapping splice moves a keyframe past the group a cut ended whole, so a later cut at
2561	/// the source's end, below that moved frame, ends the group at the frame instead of refusing.
2562	#[tokio::test]
2563	async fn cut_at_the_source_end_below_a_moved_keyframe() {
2564		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2565		let consumer = track.subscribe(replay());
2566		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2567
2568		for timestamp in [0, 20_000, 40_000, 60_000, 80_000] {
2569			producer.write(frame(timestamp, true)).unwrap();
2570		}
2571		producer.cut(Some(Timestamp::from_micros(100_000).unwrap())).unwrap();
2572		// Past the newest frame but inside the ended span, so it publishes at 100 ms.
2573		producer.write(frame(90_000, true)).unwrap();
2574		// A bound below the keyframe's source timestamp is still below a frame of the group.
2575		let below = producer.cut(Some(Timestamp::from_micros(85_000).unwrap()));
2576		assert!(matches!(below, Err(crate::Error::InvalidEnd(_))), "{below:?}");
2577		producer.cut(Some(Timestamp::from_micros(95_000).unwrap())).unwrap();
2578		producer.write(frame(120_000, true)).unwrap();
2579		let _finished = producer.finish().unwrap();
2580
2581		assert_eq!(
2582			collect_starts(consumer).await,
2583			vec![0, 20_000, 40_000, 60_000, 80_000, 100_000, 120_000]
2584		);
2585	}
2586
2587	/// A later frame below a moved keyframe still bounds its group's source end.
2588	#[tokio::test]
2589	async fn cut_below_a_later_frame_of_a_moved_group() {
2590		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2591		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2592
2593		producer.write(frame(0, true)).unwrap();
2594		producer.cut(Some(Timestamp::from_micros(40_000).unwrap())).unwrap();
2595		// Moved to 40 ms; the frame after it presents at its own 37 ms.
2596		producer.write(frame(30_000, true)).unwrap();
2597		producer.write(frame(37_000, false)).unwrap();
2598		let below = producer.cut(Some(Timestamp::from_micros(35_000).unwrap()));
2599		assert!(matches!(below, Err(crate::Error::InvalidEnd(_))), "{below:?}");
2600		producer.cut(Some(Timestamp::from_micros(42_000).unwrap())).unwrap();
2601		let _finished = producer.finish().unwrap();
2602	}
2603
2604	/// Records the frames handed to each `write`, so tests can inspect the
2605	/// durations the producer backfilled. Write-only.
2606	#[derive(Clone, Default)]
2607	struct Recording(std::rc::Rc<std::cell::RefCell<Vec<Vec<Frame>>>>);
2608
2609	impl super::Container for Recording {
2610		type Error = crate::Error;
2611
2612		fn write(&self, _group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
2613			self.0.borrow_mut().push(frames.to_vec());
2614			Ok(())
2615		}
2616
2617		fn decode(&self, _frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
2618			unreachable!("Recording is write-only")
2619		}
2620	}
2621
2622	/// The keyframe that rolls a group over backfills the duration of the previous
2623	/// group's last frame, without buffering an extra frame.
2624	#[tokio::test]
2625	async fn keyframe_backfills_batched_durations() {
2626		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2627		let recording = Recording::default();
2628		let mut producer = Producer::new(track, recording.clone()).with_buffer(std::time::Duration::from_secs(10));
2629
2630		producer.write(frame(0, true)).unwrap(); // group 0 opens
2631		producer.write(frame(33_000, false)).unwrap(); // buffered
2632		producer.write(frame(66_000, true)).unwrap(); // rolls group 0 over -> flush with next = 66ms
2633		let _finished = producer.finish().unwrap();
2634
2635		let writes = recording.0.borrow();
2636		let group0 = &writes[0];
2637		assert_eq!(group0.len(), 2);
2638		// The first sample's duration is the gap to the next buffered sample: 33ms - 0.
2639		assert_eq!(group0[0].duration, Some(Timestamp::from_micros(33_000).unwrap()));
2640		// The last sample's duration is backfilled from the next keyframe: 66ms - 33ms.
2641		assert_eq!(group0[1].duration, Some(Timestamp::from_micros(33_000).unwrap()));
2642	}
2643
2644	/// A `cut(None)` boundary is micro-scale (the estimated end), so without converting
2645	/// it into the frame's own scale the `checked_sub` refuses and the last frame
2646	/// silently keeps `duration: None`. 90 kHz frames, as the TS importer feeds them.
2647	#[tokio::test]
2648	async fn cut_none_backfills_the_last_frame_duration_at_native_scale() {
2649		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2650		let recording = Recording::default();
2651		let mut producer = Producer::new(track, recording.clone()).with_buffer(std::time::Duration::from_secs(10));
2652
2653		let scale = moq_net::Timescale::new(90_000).unwrap();
2654		let frame_at = |ticks: u64, keyframe: bool| Frame {
2655			timestamp: Timestamp::new(ticks, scale).unwrap(),
2656			decode: None,
2657			payload: Bytes::from_static(&[0xDE, 0xAD]),
2658			keyframe,
2659			duration: None,
2660		};
2661
2662		// 3003 ticks is not a whole number of micros, so the micro-scale estimate
2663		// truncates on the way through.
2664		producer.write(frame_at(0, true)).unwrap();
2665		producer.write(frame_at(3003, false)).unwrap();
2666		producer.write(frame_at(6006, false)).unwrap();
2667		producer.cut(None).unwrap();
2668		let _finished = producer.finish().unwrap();
2669
2670		let writes = recording.0.borrow();
2671		let group = &writes[0];
2672		assert_eq!(group.len(), 3);
2673		let duration = |ticks: u64| Timestamp::new(ticks, scale).unwrap();
2674		assert_eq!(group[0].duration, Some(duration(3003)));
2675		assert_eq!(group[1].duration, Some(duration(3003)));
2676		assert_eq!(
2677			group[2].duration,
2678			Some(duration(3002)),
2679			"the truncated estimate still lands on exact native ticks instead of going missing"
2680		);
2681
2682		// Every duration converts into the fMP4 track timescale without remainder;
2683		// a micros round-trip would refuse here with SampleDurationInexact.
2684		let info = crate::container::fmp4::FragmentInfo {
2685			track_id: 1,
2686			timescale: scale,
2687			sequence_number: 0,
2688			kind: crate::container::fmp4::Kind::Video,
2689		};
2690		crate::container::fmp4::encode_fragment(info, group).unwrap();
2691	}
2692
2693	/// Writes each frame onto the group at its own timescale, so the group's frames keep
2694	/// precision a microsecond container would drop.
2695	struct Stamped;
2696
2697	impl super::Container for Stamped {
2698		type Error = crate::Error;
2699
2700		fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
2701			for frame in frames {
2702				// A group's timestamps never decrease, as every real container stamps them.
2703				let transport = match group.latest() {
2704					Some(latest) if frame.timestamp < latest => latest,
2705					_ => frame.timestamp,
2706				};
2707				group.write_frame(transport, frame.payload.clone())?;
2708			}
2709			Ok(())
2710		}
2711
2712		fn decode(&self, _frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
2713			unreachable!("Stamped is write-only")
2714		}
2715
2716		fn kind(&self) -> Kind {
2717			Kind::Video
2718		}
2719	}
2720
2721	/// A cut bound below the newest frame by less than a microsecond is still below it in the
2722	/// track's timescale, where `finish_at` checks it, so the cut is refused and the group stays
2723	/// open. An estimate summed in microseconds would fall below it too, so it ends at the frame.
2724	#[tokio::test]
2725	async fn a_bound_below_a_frame_by_under_a_microsecond_is_refused() {
2726		let nanos = moq_net::Timescale::new(1_000_000_000).unwrap();
2727		let info = hang::container::track_info(hang::catalog::PRIORITY.video).with_timescale(nanos);
2728		let track = track_producer("test", info);
2729		let mut consumer = track.subscribe(replay());
2730		let mut producer = Producer::new(track, Stamped);
2731		let at = |nanoseconds: u64, keyframe: bool| Frame {
2732			timestamp: Timestamp::new(nanoseconds, nanos).unwrap(),
2733			decode: None,
2734			payload: Bytes::from_static(&[0xDE, 0xAD]),
2735			keyframe,
2736			duration: None,
2737		};
2738		producer.write(at(1_000_000, true)).unwrap();
2739		// Within one microsecond of the newest frame, which still counts as the newer.
2740		producer.write(at(2_000_001, false)).unwrap();
2741		producer.write(at(2_000_002, false)).unwrap();
2742		let below = producer.cut(Some(Timestamp::new(2_000_001, nanos).unwrap()));
2743		assert!(matches!(below, Err(crate::Error::InvalidEnd(_))), "{below:?}");
2744		assert!(!producer.needs_keyframe(), "the refused cut leaves the group open");
2745		producer.cut(None).unwrap();
2746
2747		let mut group = consumer.recv_group().await.unwrap().unwrap();
2748		let mut frames = 0;
2749		while group.read_frame().await.unwrap().is_some() {
2750			frames += 1;
2751		}
2752		assert_eq!(frames, 3);
2753		assert_eq!(group.end(), Some(2_000_002), "the estimate ends at the newest frame");
2754	}
2755
2756	#[tokio::test]
2757	async fn duration_marker_uses_cadence_not_batching_delay() {
2758		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2759		let consumer = track.subscribe(replay());
2760		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2761		producer.burst(std::time::Duration::from_secs(1)).unwrap();
2762		producer.write(frame(0, true)).unwrap();
2763		producer.write(frame(20_000, false)).unwrap();
2764		producer.write(frame(40_000, false)).unwrap();
2765		let _finished = producer.finish().unwrap();
2766		assert_eq!(collect_payloads(consumer).await[0].last(), Some(&(60_000, 0)));
2767	}
2768
2769	#[tokio::test]
2770	async fn reordered_group_does_not_mark_the_decode_tail_with_the_presentation_end() {
2771		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2772		let consumer = track.subscribe(replay());
2773		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2774		for (index, timestamp) in [0, 120_000, 40_000, 80_000].into_iter().enumerate() {
2775			producer.write(frame(timestamp, index == 0)).unwrap();
2776		}
2777		producer.write(frame(160_000, true)).unwrap();
2778		producer.write(frame(200_000, false)).unwrap();
2779		producer.cut(Some(Timestamp::from_micros(240_000).unwrap())).unwrap();
2780		let _finished = producer.finish().unwrap();
2781		let groups = collect_payloads(consumer).await;
2782		assert_eq!(groups[0], vec![(0, 2), (120_000, 2), (40_000, 2), (80_000, 2)]);
2783		assert_eq!(
2784			groups[1].last(),
2785			Some(&(240_000, 0)),
2786			"the next group can mark its tail"
2787		);
2788	}
2789
2790	#[tokio::test]
2791	async fn duration_marker_follows_a_slower_cadence() {
2792		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2793		let consumer = track.subscribe(replay());
2794		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2795		for (index, timestamp) in [0, 16_000, 32_000, 65_000, 98_000].into_iter().enumerate() {
2796			producer.write(frame(timestamp, index == 0)).unwrap();
2797		}
2798		let _finished = producer.finish().unwrap();
2799		assert_eq!(collect_payloads(consumer).await[0].last(), Some(&(131_000, 0)));
2800	}
2801
2802	#[tokio::test]
2803	async fn an_unknown_tail_at_the_previous_endpoint_uses_current_cadence() {
2804		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2805		let consumer = track.subscribe(replay());
2806		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2807		let mut first = frame(0, true);
2808		first.duration = Some(Timestamp::from_micros(40_000).unwrap());
2809		producer.write(first).unwrap();
2810		producer.write(frame(40_000, false)).unwrap();
2811		let _finished = producer.finish().unwrap();
2812		assert_eq!(collect_payloads(consumer).await[0].last(), Some(&(80_000, 0)));
2813	}
2814
2815	#[tokio::test(start_paused = true)]
2816	async fn backwards_cut_is_rejected_before_flushing_or_closing() {
2817		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2818		let mut consumer = track.subscribe(replay());
2819		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video))
2820			.with_buffer(std::time::Duration::from_secs(1));
2821		producer.write(frame(20_000, true)).unwrap();
2822		assert!(producer.cut(Some(Timestamp::from_micros(10_000).unwrap())).is_err());
2823		assert!(!producer.needs_keyframe());
2824		// Still buffered, so the group its first frame creates doesn't exist yet.
2825		assert!(
2826			kio::clock::timeout(std::time::Duration::from_millis(1), consumer.recv_group())
2827				.await
2828				.is_err()
2829		);
2830		producer.write(frame(30_000, false)).unwrap();
2831		producer.cut(Some(Timestamp::from_micros(35_000).unwrap())).unwrap();
2832		let mut group = consumer.recv_group().await.unwrap().unwrap();
2833		let mut timestamps = Vec::new();
2834		while let Some(frame) = group.read_frame().await.unwrap() {
2835			timestamps.push(
2836				hang::container::Frame::decode(frame.payload)
2837					.unwrap()
2838					.timestamp
2839					.as_micros()
2840					.unwrap(),
2841			);
2842		}
2843		assert_eq!(timestamps, vec![20_000, 30_000, 35_000]);
2844	}
2845
2846	#[tokio::test]
2847	async fn a_rewound_keyframe_is_refused() {
2848		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2849		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2850		producer.write(frame(20_000, true)).unwrap();
2851		producer.write(frame(30_000, false)).unwrap();
2852		let err = producer.write(frame(0, true)).unwrap_err();
2853		assert!(matches!(err, crate::Error::TimestampRewind(_)));
2854	}
2855
2856	/// The media frames of each group, without duration markers.
2857	fn media(groups: Vec<Vec<(u128, usize)>>) -> Vec<Vec<u128>> {
2858		groups
2859			.into_iter()
2860			.map(|group| {
2861				group
2862					.into_iter()
2863					.filter(|(_, len)| *len > 0)
2864					.map(|(ts, _)| ts)
2865					.collect()
2866			})
2867			.collect()
2868	}
2869
2870	/// #3798's join: an IDR one frame below the open group's newest frame, but above its start,
2871	/// continues that group, so every frame of the next group presents after it.
2872	#[tokio::test]
2873	async fn a_keyframe_overlapping_the_open_group_continues_it() {
2874		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2875		let consumer = track.subscribe(replay());
2876		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2877		producer.write(frame(100_000, true)).unwrap();
2878		producer.write(frame(133_000, false)).unwrap();
2879		producer.write(frame(166_000, false)).unwrap();
2880		producer.write(frame(150_000, true)).unwrap();
2881		producer.write(frame(183_000, false)).unwrap();
2882		producer.write(frame(216_000, true)).unwrap();
2883		let _finished = producer.finish().unwrap();
2884		assert_eq!(
2885			media(collect_payloads(consumer).await),
2886			[vec![100_000, 133_000, 166_000, 150_000, 183_000], vec![216_000]]
2887		);
2888	}
2889
2890	/// A splice whose keyframe lands just past the old content: a leading picture that would
2891	/// present at or before the old content's newest frame is dropped, with the keyframe's later
2892	/// leading pictures, which may reference it. The pictures presenting after the keyframe publish.
2893	#[tokio::test]
2894	async fn a_leading_picture_at_or_before_the_previous_group_is_dropped() {
2895		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2896		let consumer = track.subscribe(replay());
2897		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2898		producer.write(frame(100_000, true)).unwrap();
2899		producer.write(frame(166_000, false)).unwrap();
2900		producer.write(frame(133_000, false)).unwrap();
2901		producer.write(frame(200_000, true)).unwrap();
2902		producer.write(frame(150_000, false)).unwrap();
2903		producer.write(frame(166_000, false)).unwrap();
2904		producer.write(frame(183_000, false)).unwrap();
2905		producer.write(frame(233_000, false)).unwrap();
2906		let _finished = producer.finish().unwrap();
2907		assert_eq!(
2908			media(collect_payloads(consumer).await),
2909			[vec![100_000, 166_000, 133_000], vec![200_000, 233_000]]
2910		);
2911	}
2912
2913	/// After a cut there is no open group for a keyframe at or before the newest frame to continue,
2914	/// so it is dropped with the frames decoding from it, until a keyframe past the newest frame.
2915	#[tokio::test]
2916	async fn a_keyframe_overlapping_a_closed_group_is_dropped() {
2917		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2918		let consumer = track.subscribe(replay());
2919		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2920		producer.write(frame(100_000, true)).unwrap();
2921		producer.write(frame(133_000, false)).unwrap();
2922		producer.write(frame(166_000, false)).unwrap();
2923		producer.cut(None).unwrap();
2924		producer.write(frame(150_000, true)).unwrap();
2925		assert!(producer.needs_keyframe());
2926		producer.write(frame(183_000, false)).unwrap();
2927		producer.write(frame(200_000, true)).unwrap();
2928		let _finished = producer.finish().unwrap();
2929		assert_eq!(
2930			media(collect_payloads(consumer).await),
2931			[vec![100_000, 133_000, 166_000], vec![200_000]]
2932		);
2933	}
2934
2935	/// Group starts strictly increase, so a keyframe at the open group's start continues that group
2936	/// rather than opening one.
2937	#[tokio::test]
2938	async fn a_keyframe_at_the_previous_group_start_continues_it() {
2939		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
2940		let consumer = track.subscribe(replay());
2941		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
2942		producer.write(frame(100_000, true)).unwrap();
2943		producer.write(frame(100_000, true)).unwrap();
2944		producer.write(frame(120_000, true)).unwrap();
2945		let _finished = producer.finish().unwrap();
2946		assert_eq!(collect_starts(consumer).await, vec![100_000, 120_000]);
2947	}
2948
2949	/// A frame below the start of the group before its own reaches back past a whole group.
2950	#[tokio::test]
2951	async fn a_frame_below_the_previous_group_start_is_refused() {
2952		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2953		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2954		producer.write(frame(100_000, true)).unwrap();
2955		producer.write(frame(133_000, false)).unwrap();
2956		producer.write(frame(200_000, true)).unwrap();
2957		let err = producer.write(frame(90_000, false)).unwrap_err();
2958		assert!(matches!(err, crate::Error::TimestampRewind(_)));
2959	}
2960
2961	#[tokio::test]
2962	async fn b_frames_within_a_group_are_accepted() {
2963		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2964		let consumer = track.subscribe(replay());
2965		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2966		for (index, timestamp) in [0, 66_000, 33_000].into_iter().enumerate() {
2967			producer.write(frame(timestamp, index == 0)).unwrap();
2968		}
2969		let _finished = producer.finish().unwrap();
2970		let groups = collect_payloads(consumer).await;
2971		assert_eq!(groups[0][..3], [(0, 2), (66_000, 2), (33_000, 2)]);
2972	}
2973
2974	#[tokio::test]
2975	async fn open_gop_leading_pictures_above_the_previous_group_are_accepted() {
2976		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
2977		let consumer = track.subscribe(replay());
2978		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
2979		producer.write(frame(0, true)).unwrap();
2980		producer.write(frame(33_000, false)).unwrap();
2981		producer.write(frame(66_000, true)).unwrap();
2982		producer.write(frame(50_000, false)).unwrap();
2983		let _finished = producer.finish().unwrap();
2984		let groups = collect_payloads(consumer).await;
2985		assert_eq!(groups[1][0], (66_000, 2));
2986		assert_eq!(groups[1][1], (50_000, 2));
2987	}
2988
2989	/// Random reordering, splices, and cuts: every frame of a group presents after every frame of
2990	/// the groups before it, and a frame is dropped only when it presents at or before a frame
2991	/// published ahead of it.
2992	#[test]
2993	fn groups_never_overlap_on_random_streams() {
2994		use proptest::prelude::*;
2995		use proptest::test_runner::{Config, TestRunner};
2996
2997		let mut runner = TestRunner::new(Config {
2998			cases: 256,
2999			failure_persistence: None,
3000			..Default::default()
3001		});
3002		// Per frame: its offset from a 33ms cadence, whether it is a keyframe, and whether a cut
3003		// precedes it.
3004		let stream = proptest::collection::vec(
3005			(
3006				-150_000i64..150_000,
3007				proptest::bool::weighted(0.2),
3008				proptest::bool::weighted(0.03),
3009			),
3010			1..120,
3011		);
3012		runner
3013			.run(&stream, |frames| {
3014				let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3015				let mut consumer = track.subscribe(replay());
3016				let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3017				let mut accepted = Vec::new();
3018				for (index, (offset, keyframe, cut)) in frames.into_iter().enumerate() {
3019					if cut {
3020						producer.cut(None).unwrap();
3021					}
3022					let timestamp = (1_000_000 + 33_000 * index as i64 + offset) as u64;
3023					let written = producer.write(Frame {
3024						timestamp: Timestamp::from_micros(timestamp).unwrap(),
3025						decode: None,
3026						payload: Bytes::copy_from_slice(&(index as u32).to_be_bytes()),
3027						keyframe,
3028						duration: None,
3029					});
3030					if written.is_ok() {
3031						accepted.push((index as u32, timestamp as u128, keyframe));
3032					}
3033				}
3034				let _finished = producer.finish().unwrap();
3035
3036				let mut groups: Vec<Vec<(u32, u128)>> = Vec::new();
3037				let mut spans = Vec::new();
3038				futures::executor::block_on(async {
3039					while let Some(mut group) = consumer.recv_group().await.unwrap() {
3040						let mut frames = Vec::new();
3041						while let Some(frame) = group.read_frame().await.unwrap() {
3042							let decoded = hang::container::Frame::decode(frame.payload).unwrap();
3043							if let Ok(index) = <[u8; 4]>::try_from(decoded.payload.as_ref()) {
3044								frames.push((u32::from_be_bytes(index), decoded.timestamp.as_micros().unwrap()));
3045							}
3046						}
3047						groups.push(frames);
3048						spans.push((group.start, group.end()));
3049					}
3050				});
3051
3052				// No group starts inside the span of a group that ended whole.
3053				for pair in spans.windows(2) {
3054					let ((_, end), (next, _)) = (pair[0], pair[1]);
3055					prop_assert!(end.is_none_or(|end| next >= end), "{spans:?}");
3056				}
3057
3058				let mut ceiling = None;
3059				for group in &groups {
3060					for &(_, timestamp) in group {
3061						prop_assert!(ceiling.is_none_or(|ceiling| timestamp > ceiling), "{groups:?}");
3062					}
3063					ceiling = group.iter().map(|&(_, timestamp)| timestamp).max().max(ceiling);
3064				}
3065
3066				// Published frames are the accepted ones in order, less those at or before a frame
3067				// published ahead of them, those after a dropped keyframe until one is published, and
3068				// the leading pictures of a keyframe after one of them was dropped.
3069				let published: Vec<(u32, u128)> = groups.concat();
3070				let mut next = published.iter().peekable();
3071				let (mut newest, mut skipping) = (None, false);
3072				let (mut latest, mut tainted) = (None, false);
3073				for &(index, timestamp, keyframe) in &accepted {
3074					if let Some(&(_, stamped)) = next.next_if(|&&(published, _)| published == index) {
3075						// A keyframe opening a group past a whole group's End is stamped there.
3076						prop_assert!(stamped >= timestamp && (keyframe || stamped == timestamp));
3077						newest = newest.max(Some(stamped));
3078						skipping &= !keyframe;
3079						if keyframe {
3080							(latest, tainted) = (Some(stamped), false);
3081						}
3082						prop_assert!(
3083							keyframe || !tainted || latest.is_none_or(|latest| timestamp >= latest),
3084							"frame {index} at {timestamp} kept after a leading picture of {latest:?} was dropped"
3085						);
3086					} else {
3087						let leading = tainted && !keyframe && latest.is_some_and(|latest| timestamp < latest);
3088						prop_assert!(
3089							newest.is_some_and(|newest| timestamp <= newest) || (skipping && !keyframe) || leading,
3090							"frame {index} at {timestamp} was dropped above {newest:?}"
3091						);
3092						skipping |= keyframe;
3093						tainted |= !keyframe && latest.is_some_and(|latest| timestamp < latest);
3094					}
3095				}
3096				prop_assert!(next.peek().is_none(), "published a frame never accepted");
3097				Ok(())
3098			})
3099			.unwrap();
3100	}
3101
3102	#[tokio::test]
3103	async fn duration_marker_resets_after_discontinuity() {
3104		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3105		let consumer = track.subscribe(replay());
3106		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3107		producer.write(frame(1_000_000, true)).unwrap();
3108		producer.write(frame(1_010_000, false)).unwrap();
3109		producer.discontinuity().unwrap();
3110		producer.write(frame(1_020_000, true)).unwrap();
3111		producer.write(frame(1_040_000, false)).unwrap();
3112		let _finished = producer.finish().unwrap();
3113		let groups = collect_payloads(consumer).await;
3114		assert_eq!(groups.last().unwrap().last(), Some(&(1_060_000, 0)));
3115	}
3116
3117	/// A capture that reopens at once resumes sooner than one frame after the break. Guessing
3118	/// the closing group's end from its cadence would put a duration marker past the resumed
3119	/// keyframe, which a consumer reads as a rewind and refuses.
3120	#[tokio::test]
3121	async fn a_prompt_resume_after_a_discontinuity_is_not_a_rewind() {
3122		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3123		let subscriber = track.subscribe(replay());
3124		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3125		producer.write(frame(1_000_000, true)).unwrap();
3126		producer.write(frame(1_040_000, false)).unwrap();
3127		producer.discontinuity().unwrap();
3128		// Resumed 10ms later, inside the 40ms cadence measured before the break.
3129		producer.write(frame(1_050_000, true)).unwrap();
3130		let _finished = producer.finish().unwrap();
3131
3132		let mut consumer = crate::container::Consumer::new(subscriber, Wire::legacy(crate::container::Kind::Video));
3133		let mut timestamps = Vec::new();
3134		while let Some(frame) = consumer.read_frame().await.unwrap() {
3135			timestamps.push(frame.timestamp.as_micros().unwrap());
3136		}
3137		assert_eq!(timestamps, [1_000_000, 1_040_000, 1_050_000]);
3138	}
3139
3140	/// A published group as a copy receives it: its start, its frames, and its End.
3141	type Published = (u64, Vec<moq_net::frame::Frame>, Option<u64>);
3142
3143	/// Every group `consumer` reads, with its frames and End.
3144	async fn collect_published(consumer: moq_net::track::Subscriber) -> Vec<Published> {
3145		// Key order, oldest first, whatever the subscription's Group Order.
3146		let mut consumer = consumer.ordered();
3147		let mut groups = Vec::new();
3148		while let Some(mut group) = consumer.next_group().await.unwrap() {
3149			let mut frames = Vec::new();
3150			while let Some(frame) = group.read_frame().await.unwrap() {
3151				frames.push(frame);
3152			}
3153			groups.push((group.start, frames, group.end()));
3154		}
3155		groups
3156	}
3157
3158	/// Replay `groups` into a fresh copy in `order`, as a lite-07 relay creates what arrives,
3159	/// returning what the copy refused. A GROUP_END accounts for the starts inside its span, which
3160	/// the copy then refuses, as the relay's subscription does.
3161	fn copy(groups: &[Published], order: impl IntoIterator<Item = usize>) -> moq_net::Result<()> {
3162		let copy = track_producer("copy", hang::container::track_info(hang::catalog::PRIORITY.video));
3163		for index in order {
3164			let (start, frames, end) = &groups[index];
3165			let (first, rest) = frames.split_first().expect("a group holds its first frame");
3166			let mut group = copy.create_group(moq_net::frame::Frame::new(first.timestamp, first.payload.clone()))?;
3167			assert_eq!(group.start, *start, "a group is keyed by its first frame");
3168			for frame in rest {
3169				group.write_frame(moq_net::frame::Frame::new(frame.timestamp, frame.payload.clone()))?;
3170			}
3171			match end {
3172				Some(end) => {
3173					group.finish_at(*end)?;
3174					copy.skip_groups(start + 1..*end);
3175				}
3176				None => drop(group.finish()?),
3177			}
3178		}
3179		Ok(())
3180	}
3181
3182	/// The marker a discontinuity publishes after a cut starts at the End the cut gave its group,
3183	/// outside that group's span, so a lite-07 copy takes it whichever arrives first. One a unit
3184	/// inside the span is refused when it arrives second. Media resuming right at the marker is
3185	/// stamped one unit past it.
3186	#[tokio::test]
3187	async fn a_marker_after_a_cut_lands_outside_the_span_it_ended() {
3188		for (end, at) in [(Some(25_000), 25_000), (None, 20_000)] {
3189			let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3190			let consumer = track.subscribe(replay());
3191			let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3192			producer.write(frame(0, true)).unwrap();
3193			producer.write(frame(10_000, false)).unwrap();
3194			producer.cut(end.map(|us| Timestamp::from_micros(us).unwrap())).unwrap();
3195			producer.discontinuity().unwrap();
3196			producer.write(frame(at, true)).unwrap();
3197			producer.write(frame(at + 10_000, false)).unwrap();
3198			let _finished = producer.finish().unwrap();
3199
3200			let groups = collect_published(consumer).await;
3201			let starts: Vec<_> = groups.iter().map(|(start, _, _)| *start).collect();
3202			assert_eq!(starts, [0, at, at + 1], "cut({end:?})");
3203			assert_eq!(groups[0].2, Some(at), "the cut ends its group whole");
3204			let resumed = groups[2].1[0].timestamp.as_micros().unwrap();
3205			assert_eq!(
3206				resumed,
3207				u128::from(at + 1),
3208				"the resumed keyframe is stamped past the marker"
3209			);
3210
3211			for order in [[0, 1, 2], [1, 0, 2], [2, 1, 0]] {
3212				copy(&groups, order).unwrap_or_else(|err| panic!("cut({end:?}) in {order:?}: {err}"));
3213			}
3214			let mut marker = groups[1].1[0].clone();
3215			marker.timestamp = Timestamp::from_micros(at - 1).unwrap();
3216			let inside = [groups[0].clone(), (at - 1, vec![marker], None)];
3217			assert!(
3218				copy(&inside, [0, 1]).is_err(),
3219				"a marker inside the span arriving second"
3220			);
3221		}
3222	}
3223
3224	/// An explicit end below a frame the group holds is refused for every kind, without closing
3225	/// the group, rather than closing it without the End it meant.
3226	#[tokio::test]
3227	async fn a_cut_below_a_written_frame_is_refused_for_every_kind() {
3228		use crate::container::Kind;
3229		let cases: [(Kind, &[u64], u64, u64); 4] = [
3230			(Kind::Audio, &[0, 20_000], 10_000, 40_000),
3231			(Kind::Data, &[0, 20_000], 10_000, 20_000),
3232			(Kind::Video, &[0, 40_000], 20_000, 80_000),
3233			// Reordered: the newest frame presents before the last one decoded.
3234			(Kind::Video, &[0, 120_000, 40_000, 80_000], 100_000, 120_000),
3235		];
3236		for (kind, timestamps, below, end) in cases {
3237			let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3238			let consumer = track.subscribe(replay());
3239			let mut producer = Producer::new(track, Wire::legacy(kind));
3240			for (index, timestamp) in timestamps.iter().enumerate() {
3241				producer.write(frame(*timestamp, index == 0)).unwrap();
3242			}
3243			let refused = producer.cut(Some(Timestamp::from_micros(below).unwrap()));
3244			assert!(
3245				matches!(refused, Err(crate::Error::InvalidEnd(_))),
3246				"{kind:?}: {refused:?}"
3247			);
3248			assert!(!producer.needs_keyframe(), "{kind:?}: the group stays open");
3249			producer.cut(Some(Timestamp::from_micros(end).unwrap())).unwrap();
3250			let _finished = producer.finish().unwrap();
3251
3252			let groups = collect_published(consumer).await;
3253			assert_eq!(groups.len(), 1, "{kind:?}");
3254			assert_eq!(
3255				groups[0].2,
3256				Some(end),
3257				"{kind:?}: the group ends whole where it was cut"
3258			);
3259		}
3260	}
3261
3262	/// A keyframe past the newest frame but below the End a cut estimated from the cadence, as a
3263	/// faster cadence or a duration rounded up overshoots, starts at that End rather than inside
3264	/// the span it closed, and the rest of its group follows.
3265	#[tokio::test]
3266	async fn a_keyframe_below_an_estimated_end_starts_at_it() {
3267		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3268		let consumer = track.subscribe(replay());
3269		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3270		producer.write(frame(100_000, true)).unwrap();
3271		producer.write(frame(166_000, false)).unwrap();
3272		producer.cut(None).unwrap();
3273		producer.write(frame(200_000, true)).unwrap();
3274		producer.write(frame(233_000, false)).unwrap();
3275		producer.write(frame(266_000, false)).unwrap();
3276		let _finished = producer.finish().unwrap();
3277
3278		let groups = collect_published(consumer).await;
3279		assert_eq!(
3280			groups[0].2,
3281			Some(232_000),
3282			"the cut estimates one 66ms frame past the last"
3283		);
3284		assert_eq!(groups[1].0, 232_000, "the keyframe starts at the End");
3285		let decoded: Vec<_> = (groups[1].1.iter())
3286			.map(|frame| hang::container::Frame::decode(frame.payload.clone()).unwrap())
3287			.filter(|frame| !frame.payload.is_empty())
3288			.map(|frame| frame.timestamp.as_micros().unwrap())
3289			.collect();
3290		assert_eq!(decoded, [232_000, 233_000, 266_000]);
3291		copy(&groups, [1, 0]).unwrap();
3292	}
3293
3294	/// A source whose stated durations overshoot its spacing moves each keyframe at most by that
3295	/// overshoot: the next End is estimated from where the source put the frame, not where its
3296	/// group start moved it, so the moves never add up into a rewind. Past twice the spacing, a
3297	/// keyframe at or below the newest frame is dropped rather than refused.
3298	#[tokio::test]
3299	async fn moved_keyframes_never_add_up_across_groups() {
3300		for (duration, starts) in [
3301			(144_000, vec![0, 144_000, 244_000, 344_000, 444_000, 544_000]),
3302			(250_000, vec![0, 250_000, 350_000, 550_000]),
3303		] {
3304			let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio));
3305			let consumer = track.subscribe(replay());
3306			let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Audio));
3307			for i in 0..6 {
3308				let frame = Frame {
3309					duration: Some(Timestamp::from_micros(duration).unwrap()),
3310					..frame(i * 100_000, true)
3311				};
3312				producer.write(frame).unwrap();
3313				producer.cut(None).unwrap();
3314			}
3315			let _finished = producer.finish().unwrap();
3316
3317			let groups = collect_published(consumer).await;
3318			let published: Vec<_> = groups.iter().map(|(start, _, _)| *start).collect();
3319			assert_eq!(published, starts, "{duration}us frames every 100ms");
3320			copy(&groups, (0..groups.len()).rev()).unwrap();
3321		}
3322	}
3323
3324	/// Parameter sets written as a keyframe ahead of their picture at one timestamp move with it:
3325	/// the picture continues the group the parameter sets opened, at the same moved start.
3326	#[tokio::test]
3327	async fn a_frame_at_a_moved_keyframes_timestamp_moves_with_it() {
3328		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3329		let consumer = track.subscribe(replay());
3330		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3331		producer.write(frame(100_000, true)).unwrap();
3332		producer.write(frame(166_000, false)).unwrap();
3333		producer.cut(None).unwrap();
3334		// The parameter sets, then their picture.
3335		producer.write(frame(200_000, true)).unwrap();
3336		producer.write(frame(200_000, true)).unwrap();
3337		producer.write(frame(233_000, false)).unwrap();
3338		let _finished = producer.finish().unwrap();
3339
3340		assert_eq!(
3341			media(collect_payloads(consumer).await),
3342			[vec![100_000, 166_000], vec![232_000, 232_000, 233_000]]
3343		);
3344	}
3345
3346	/// Published order is compared at the track's own precision: on a nanosecond track, a frame a
3347	/// nanosecond below its moved keyframe reorders the group though both share a microsecond.
3348	#[tokio::test]
3349	async fn a_frame_a_nanosecond_below_a_moved_keyframe_reorders_its_group() {
3350		let nanos = moq_net::Timescale::new(1_000_000_000).unwrap();
3351		let info = hang::container::track_info(hang::catalog::PRIORITY.video).with_timescale(nanos);
3352		let track = track_producer("test", info);
3353		let consumer = track.subscribe(replay());
3354		let mut producer = Producer::new(track, Stamped);
3355		let at = |nanoseconds: u64, keyframe: bool| Frame {
3356			timestamp: Timestamp::new(nanoseconds, nanos).unwrap(),
3357			decode: None,
3358			payload: Bytes::from_static(&[0xDE, 0xAD]),
3359			keyframe,
3360			duration: None,
3361		};
3362		producer.write(at(1_000_000, true)).unwrap();
3363		producer.write(at(1_500_000, false)).unwrap();
3364		producer.cut(Some(Timestamp::new(2_000_002, nanos).unwrap())).unwrap();
3365		// Below the End the cut set, so moved to it, while the frame after it presents a nanosecond
3366		// below and rides at the keyframe's time, since a group's timestamps never decrease.
3367		producer.write(at(1_900_000, true)).unwrap();
3368		producer.write(at(2_000_001, false)).unwrap();
3369		producer.cut(None).unwrap();
3370		let _finished = producer.finish().unwrap();
3371
3372		let groups = collect_published(consumer).await;
3373		let timestamps: Vec<_> = groups[1].1.iter().map(|frame| frame.timestamp.value()).collect();
3374		assert_eq!(timestamps, [2_000_002, 2_000_002]);
3375		assert_eq!(groups[1].2, None, "a reordered group ends without an estimated End");
3376	}
3377
3378	/// A frame after a moved keyframe that publishes below it reorders the group as published, so
3379	/// the group's presentation end no longer bounds its decode-order tail and no marker says so.
3380	#[tokio::test]
3381	async fn a_frame_published_below_a_moved_keyframe_reorders_its_group() {
3382		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3383		let consumer = track.subscribe(replay());
3384		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3385		producer.write(frame(0, true)).unwrap();
3386		producer.write(frame(100_000, false)).unwrap();
3387		producer.cut(Some(Timestamp::from_micros(232_000).unwrap())).unwrap();
3388		// Below the End the cut set, so moved to it, while the frame after it stays.
3389		producer.write(frame(200_000, true)).unwrap();
3390		producer.write(frame(220_000, false)).unwrap();
3391		producer.cut(None).unwrap();
3392		let _finished = producer.finish().unwrap();
3393
3394		let groups = collect_payloads(consumer).await;
3395		assert_eq!(groups[1], vec![(232_000, 2), (220_000, 2)]);
3396	}
3397
3398	/// An open GOP's leading pictures present after every frame of the group before theirs but
3399	/// before their keyframe, so inside the span of that group, which ends whole at the keyframe.
3400	/// That breaks nothing: each span holds no other group's start, and every frame of a group
3401	/// presents before every frame of a higher one.
3402	#[tokio::test]
3403	async fn open_gop_spans_hold_no_other_start() {
3404		let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video));
3405		let consumer = track.subscribe(replay());
3406		let mut producer = Producer::new(track, Wire::legacy(crate::container::Kind::Video));
3407		// Decode order, in milliseconds: each keyframe's leading pictures reference the P-frame
3408		// before it.
3409		let decode_order = [
3410			(0, true),
3411			(90, false),
3412			(30, false),
3413			(60, false),
3414			(180, false),
3415			(120, false),
3416			(150, false),
3417			(270, true),
3418			(210, false),
3419			(240, false),
3420			(360, false),
3421			(300, false),
3422			(330, false),
3423			(450, true),
3424			(390, false),
3425		];
3426		for (millis, keyframe) in decode_order {
3427			producer.write(frame(millis * 1_000, keyframe)).unwrap();
3428		}
3429		let _finished = producer.finish().unwrap();
3430
3431		let groups = collect_published(consumer).await;
3432		let starts: Vec<_> = groups.iter().map(|(start, _, _)| *start).collect();
3433		assert_eq!(starts, [0, 270_000, 450_000]);
3434		assert_eq!(groups[0].2, Some(270_000), "a group ends whole at the next keyframe");
3435		for (start, _, end) in &groups {
3436			let Some(end) = end else { continue };
3437			assert!(
3438				!starts.iter().any(|other| other > start && other < end),
3439				"[{start}, {end}) holds another start: {starts:?}"
3440			);
3441		}
3442		// The prefix keeps each presentation time; the transport keeps the newest so far.
3443		let presented: Vec<Vec<u128>> = (groups.iter())
3444			.map(|(_, frames, _)| {
3445				frames
3446					.iter()
3447					.map(|frame| {
3448						let decoded = hang::container::Frame::decode(frame.payload.clone()).unwrap();
3449						decoded.timestamp.as_micros().unwrap()
3450					})
3451					.collect()
3452			})
3453			.collect();
3454		assert_eq!(presented[1], [270_000, 210_000, 240_000, 360_000, 300_000, 330_000]);
3455		for pair in presented.windows(2) {
3456			let (lower, higher) = (pair[0].iter().max().unwrap(), pair[1].iter().min().unwrap());
3457			assert!(lower < higher, "{presented:?}");
3458		}
3459		copy(&groups, [2, 1, 0]).unwrap();
3460	}
3461}