Skip to main content

moq_mux/container/ts/
import.rs

1//! MPEG-TS demuxer.
2//!
3//! [`Import`] reads a TS byte stream, reassembles PES packets per PID, and
4//! routes their payloads to the codec importers (H.264/H.265/AAC, plus the
5//! legacy MP2/AC-3/E-AC-3 verbatim path), which own their broadcast tracks and
6//! catalog entries. Elementary streams we don't decode are carried verbatim, one
7//! MoQ track per PID, described in the `mpegts` catalog section: PES streams ride
8//! the normal PES reassembly and travel as whole PES packets at their placement on
9//! the program clock, while section-framed streams (SCTE-35 and other private
10//! sections, which are not PES) are reassembled as sections, as the PAT and PMT
11//! are. TS adds PAT/PMT discovery, PES reassembly, the
12//! private-section path, and the 90 kHz PTS conversion across its 33-bit wrap. The service
13//! layer is captured too: the identity parsed from the PAT as a
14//! [`Program`](catalog::Program) record in the `mpegts` catalog section, and the
15//! standalone SI PIDs as opaque sections on per-`(PID, table_id)` snapshot tracks
16//! (see [`si`](super::si)), so both survive the round-trip.
17
18use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
19use std::sync::Arc;
20use std::sync::atomic::{AtomicUsize, Ordering};
21
22use mpeg2ts::es::StreamType;
23use mpeg2ts::ts::{Pid, TsPacket};
24
25use super::adts;
26use super::catalog;
27use super::demux::{Demux, Packet};
28use super::error::{Context, Error, Result, bail, bail_unsupported, ensure, malformed};
29use super::health::{Continuation, Continuity, Health};
30use super::mux_rate::PCR_WRAP;
31use super::passthrough::{PCR_HZ, PCR_OFFSET, Sample, locate};
32use super::psi::{self, PesStart, Pmt};
33use super::stats;
34use crate::catalog::Offset;
35use crate::catalog::hang::CatalogExt;
36use crate::codec::{aac, ac3, eac3, h264, h265, legacy, mp2, opus};
37use moq_net::Timestamp;
38
39#[path = "video.rs"]
40mod video;
41
42/// Demuxes an MPEG-TS byte stream into a MoQ broadcast.
43///
44/// Decodes H.264 (stream type 0x1B), H.265 (0x24), ADTS AAC (0x0F), MP2
45/// (0x03/0x04), AC-3 (0x81), and E-AC-3 (0x87). Each codec stream is fed to its importer, which
46/// manages the track, catalog config, and keyframe-based group boundaries. MPEG-1/2 video
47/// (0x01/0x02) is not decoded but still paces the program: its PTS anchors the timebase while
48/// its PES ride whole as below.
49///
50/// Video access units can span PES packets, and one PES can contain several. Its PTS
51/// stamps the AU whose required start-code prefix begins there, once. Later AUs need
52/// anchored POC and proportional timing: AVC's TS timing descriptor plus fixed-rate
53/// SPS VUI, or HEVC's `poc_proportional_to_timing_flag`. Missing timing ends the import;
54/// it is not recoverable packet damage. Raw elementary-stream import keeps its
55/// caller-supplied timestamp mode.
56///
57/// Partial header contents hold at most 264 bytes per PID. PES payloads, retained video
58/// AUs, and sections awaiting a timestamp share a 16 MiB budget, and at most 4096 units are
59/// buffered, the raw TS accumulator's group roll triggers. Exceeding either limit refuses the input
60/// instead of retaining more bytes.
61///
62/// Elementary streams we don't decode are carried verbatim, one MoQ track per
63/// PID, when the catalog `E` carries the [`mpegts`](super::Mpegts) section: section-framed
64/// streams (private sections 0x05, the ISO 13818-6 DSM-CC types 0x0A to 0x0D, and SCTE-35 0x86
65/// marked by a program-level 'CUEI' registration descriptor) are reassembled as sections, and
66/// any other stream travels as whole PES packets ([`PesPacket`](super::PesPacket)), LATM/LOAS
67/// AAC (0x11) included. A 0x86 stream without 'CUEI', which may be DTS audio or SCTE-35, is not
68/// carried. With a base `Catalog<()>` no undecoded stream is carried.
69///
70/// Every PID is accounted for. A listed stream that is not carried counts once in
71/// [`stats::Stream::refused`] with a warning, and so does each TS-scrambled packet on a carried
72/// one and each PES-scrambled PES on a decoded one. Once the PMT is in, a packet on a PID no table claims (the null PID aside) counts in its
73/// own row: see [`stats::Snapshot::streams`]. That holds when the PAT lists only the imported
74/// program; a [`with_program`](Self::with_program) import of a multiplex cannot tell another
75/// program's PIDs from unclaimed ones, so it leaves them to [`Programs`](super::Programs).
76///
77/// A whole PES or section is timestamped with its placement: the program clock at its first byte,
78/// interpolated between the PCRs either side of it (ISO 13818-1 2.4.2.2) and shifted onto the
79/// catalog clock as the media is. It waits for the PCR after it, and for the first media PTS
80/// to anchor the timebase, or the first PCR when the PMT declares no media stream, within the
81/// staging bound below; one that starts past the last PCR before a
82/// clock break or the end of input is extrapolated from the last two. One before the first PCR,
83/// or with no interval to extrapolate from, is dropped and counted in
84/// [`stats::Stream::unplaced`]. A section's SCTE-35 splice times absorb the media's offset in
85/// `pts_adjustment`; a whole PES's PTS and DTS move by that offset, and every other byte is kept.
86/// A stream whose PES carry a clock only the PTS and DTS of are rebased (ESCR, a
87/// `pack_header_field`, a TREF), PES-level scrambling, an unbounded non-video PES, or a header
88/// export would refuse is refused rather than altered. A program with no PCR refuses both
89/// whole PES and section streams: [`stats::Stream::refused`]. A PMT that moves the PCR PID ends the
90/// placement timebase, as a clock break does; one that drops the PCR refuses those streams, and
91/// one that names it again carries them.
92///
93/// The PAT and every PMT are reassembled the same way, so a table that spans packets or
94/// sits behind a nonzero pointer_field is read whole. A PAT or PMT section whose CRC-32
95/// fails is dropped and counted in [`stats::Snapshot::crc_error`]; the last good table stays
96/// in force.
97///
98/// With the `mpegts` catalog extension, the catalog goes out with the first media and gains
99/// `mpegts.muxRate` as an update once a two-second PCR window measures a constant rate, which
100/// a variable-rate source never does. An export that pads waits for that update. A restarted
101/// import's catalog carries its predecessor's measurement of the same multiplex
102/// ([`Republish`](super::Republish)), which the measurement then refines as usual.
103///
104/// The selected container applies only to decoded media renditions. Verbatim tracks in the
105/// `mpegts` catalog section continue to use the legacy Hang container.
106///
107/// PTS values follow the program's timestamp history across their 33-bit wrap,
108/// including the PCR history before a data-only program gains media.
109pub struct Import<E: catalog::Catalog = ()> {
110	broadcast: moq_net::broadcast::Producer,
111	catalog: crate::catalog::Producer<E>,
112	container: hang::catalog::Container,
113
114	/// Held until the first media PTS or data-only PCR anchors the clock, withholding the catalog
115	/// until every stream in the initial program has reserved its rendition and the root `clock` is
116	/// final. A one-shot muxer (fMP4, TS re-export) sees the complete track list in the first
117	/// snapshot rather than a half-converged one. See [`Reserved`](crate::catalog::Reserved).
118	initial_reservation: Option<crate::catalog::Reserved<E>>,
119
120	/// Whether the current PMT declares a media stream that can anchor the program clock.
121	media_clock: bool,
122	/// Whether video paces the audio bursts, fixed by the PMT.
123	has_video: bool,
124
125	/// The program's timestamp base: the first media PTS, or a data-only PCR, anchors it; every PTS shifts by
126	/// its offset onto the catalog clock.
127	timebase: crate::catalog::Timebase<E>,
128
129	/// Frames the input [`decode`](Self::decode) reads. [`Programs`](super::Programs) runs one
130	/// parser for every program instead and hands each its packets.
131	demux: Demux,
132	/// Watches the input [`decode`](Self::decode) reads for a clock step that ends the identity.
133	steps: super::step::Steps,
134	/// PIDs whose route changed while handling the current packet, for the parser to restart.
135	restarts: Vec<u16>,
136	/// Whether a PAT moved the PMT, or a PMT was handled, since
137	/// [`claims_changed`](Self::claims_changed) last said so.
138	claims_changed: bool,
139	/// The PMT PID the latest PAT names for the imported program, with its reassembler.
140	/// Several programs' PMTs may share one.
141	pmt: Option<(Pid, SectionReassembler)>,
142	/// PMT sections dropped for a CRC mismatch, keyed by PID.
143	crc_errors: BTreeMap<u16, u64>,
144	/// Per elementary-stream-PID codec routing.
145	streams: HashMap<Pid, Stream<E>>,
146	/// Counters from routes a later PMT replaced, keyed by PID.
147	retired_stats: BTreeMap<u16, stats::Stream>,
148	/// Damaged packets, PES, or access units refused, cumulative across PID remaps.
149	damaged: BTreeMap<u16, u64>,
150	damage_log: super::damage::Log,
151	/// Access units per elementary stream, timed on the program clock.
152	liveness: Liveness,
153	/// In-progress PES reassembly, keyed by elementary PID.
154	pending: HashMap<Pid, Pending>,
155	/// PES with new payload since the last batch, so decoded units need not wait for the PES end.
156	partial: Vec<Pid>,
157	/// Partial clear PES headers, at most 9 + 255 bytes per elementary PID, each with where its
158	/// start code sits on the program clock ([`Placement::span`]).
159	headers: HashMap<Pid, (Option<Span>, Vec<u8>)>,
160	/// The program clock at each input byte, which places whole PES packets and sections.
161	placement: Placement,
162	/// Whole PES and sections dropped for want of a clock to place them, keyed by PID.
163	unplaced: BTreeMap<u16, u64>,
164	/// Undecoded streams refused rather than carried altered, keyed by PID.
165	refused: BTreeMap<u16, u64>,
166	/// The `stream_type` of each undecoded stream refused only for want of a PCR, routed again
167	/// once a PMT names one or gives the PID another type.
168	unclocked: HashMap<Pid, u8>,
169	/// One program-wide budget for PES payloads and sections awaiting their clock.
170	staging: Arc<Staging>,
171	/// The TR 101 290 checks timed on the program clock.
172	health: Health,
173	/// PID the PMT designates as carrying the program clock reference. An
174	/// adaptation-field `discontinuity_indicator` means a *system time-base*
175	/// discontinuity only here; on any other PID it says nothing but that the
176	/// continuity counter jumped ([`Continuation::Broken`]).
177	pcr_pid: Option<Pid>,
178	/// The input offset from which a PCR may start the clock a PMT names, while none does.
179	/// Exporters may lead their first PAT/PMT with PCR, which the parser keeps per PID.
180	unclocked_since: Option<u64>,
181	/// The multiplex rate measured off the PCR PID, recorded in the `mpegts` section
182	/// while the source holds one. Only fed with `mpegts` catalog support.
183	mux_rate: super::mux_rate::Meter,
184	/// Whether any media or section has been published since the last timebase break, so
185	/// consecutive markers (a repeated flag, a retransmitted clock packet) declare one
186	/// break rather than one each.
187	published: bool,
188	/// True once a PMT with at least one supported stream has been parsed.
189	initialized: bool,
190
191	/// Section-framed verbatim PIDs. Private sections (SCTE-35 table_id 0xFC and others)
192	/// are not PES, so they are reassembled as sections rather than PES-parsed. Keyed by
193	/// PID. SCTE-35 is detected via the PMT 'CUEI' registration descriptor.
194	sections: HashMap<u16, SectionStream<E>>,
195	/// Whether the catalog can carry the `mpegts` section, sampled once at construction.
196	/// A base `Catalog<()>` can't, so its undecoded PIDs route to `Stream::Ignored`.
197	supports_mpegts: bool,
198	/// PMT ES-level descriptors per PID, stashed when a PMT is parsed so a decoded
199	/// media track can record them (language, registration, ...) once its track exists.
200	es_descriptors: HashMap<u16, Vec<catalog::Descriptor>>,
201	/// Decoded media PIDs already recorded into `mpegts.tracks`, by the track name recorded, so the
202	/// reconcile in [`Self::flush`] runs once per track rather than on every frame, and moves the
203	/// entry when a format change publishes the PID under a new name.
204	recorded_media: HashMap<Pid, String>,
205	/// The program-level descriptors the catalog advertises, rewritten in place as the PMT
206	/// revises them.
207	program_info: Vec<catalog::Descriptor>,
208	/// What the PMT in force says of each PID it lists, so a revision that says otherwise ends
209	/// the route rather than carrying the new stream under the old name.
210	listed: HashMap<Pid, Listing>,
211	/// The SI store: buffers each sub-table to a complete generation, publishes the
212	/// per-`(PID, table_id)` snapshot tracks, and advertises them in the catalog.
213	si: super::si::Capture<E>,
214	/// The `(transport_stream_id, program_number)` the first PAT named, also captured into the
215	/// catalog service record with the PMT PID. A PAT naming another refuses the import: the
216	/// carried SI describes this one.
217	identity: Option<(u16, u16)>,
218	/// Latest video PTS, used to timestamp service-information snapshots.
219	last_pts: Option<Timestamp>,
220	/// The program's PTS history, which picks each value's 33-bit wrap.
221	pts: PtsUnwrap,
222	/// The program number chosen by [`with_program`](Self::with_program). `None` imports the
223	/// multiplex's only program and refuses a PAT that lists more than one.
224	program: Option<u16>,
225	/// The packets on PIDs no table claims, counted once [`alone`](Self::alone) and
226	/// [`described`](Self::described). Under [`Programs`](super::Programs) this importer reads only
227	/// the PIDs it claims, so `Programs` counts them instead, once for the multiplex.
228	unclaimed: super::unclaimed::Unclaimed,
229	/// The last PAT lists only the imported program, so a PID it does not claim is no other's.
230	alone: bool,
231	/// A PMT has described the program, so a PID it does not claim is not one still to come.
232	described: bool,
233	/// Carried PIDs already warned about a TS-scrambled packet.
234	scrambled: HashSet<u16>,
235	/// Whether input is still accepted: [`finish`](Self::finish) or [`abort`](Self::abort) ends it.
236	input: crate::container::Input,
237}
238
239impl<E: catalog::Catalog> Import<E> {
240	/// Import a byte stream into the broadcast using its reserved catalog producer.
241	pub fn new(broadcast: moq_net::broadcast::Producer, reserved: crate::catalog::Reserved<E>) -> Self {
242		let container = hang::catalog::Container::default();
243		// A long-lived producer handle for catalog edits (mpegts sections, later PMTs); the passed
244		// reservation gates the initial publish and is dropped once the first PES anchors.
245		let catalog = reserved.producer();
246		// Sample the real catalog once at construction, not E::default(): an extension
247		// may carry the section by value, and a snapshot clones under the mutex (no publish).
248		let mut snapshot = catalog.snapshot();
249		let mpegts = snapshot.ext.mpegts_mut();
250		let supports_mpegts = mpegts.is_some();
251		// A rate the catalog already records measured this multiplex, so the catalog needn't wait.
252		let measured = mpegts.as_deref().and_then(|mpegts| mpegts.mux_rate);
253		// What the catalog already advertises, so the first PMT republishes only a difference.
254		let program_info = mpegts
255			.map(|mpegts| std::mem::take(&mut mpegts.program_descriptors))
256			.unwrap_or_default();
257		if supports_mpegts {
258			catalog.count_ext_tracks(|ext: &mut E| ext.mpegts_mut().is_some_and(|mpegts| mpegts.has_track()));
259		}
260		let si = super::si::Capture::new(broadcast.clone(), catalog.clone());
261		let timebase = catalog.timebase();
262		Self {
263			broadcast,
264			catalog,
265			container,
266			media_clock: false,
267			has_video: false,
268			timebase,
269			initial_reservation: Some(reserved),
270			demux: Demux::new(supports_mpegts),
271			steps: Default::default(),
272			restarts: Vec::new(),
273			claims_changed: false,
274			pmt: None,
275			crc_errors: BTreeMap::new(),
276			streams: HashMap::new(),
277			retired_stats: BTreeMap::new(),
278			damaged: BTreeMap::new(),
279			damage_log: Default::default(),
280			liveness: Liveness::default(),
281			pending: HashMap::new(),
282			partial: Vec::new(),
283			headers: HashMap::new(),
284			placement: Placement::default(),
285			unplaced: BTreeMap::new(),
286			refused: BTreeMap::new(),
287			unclocked: HashMap::new(),
288			staging: Arc::default(),
289			health: Health::default(),
290			pcr_pid: None,
291			unclocked_since: Some(0),
292			mux_rate: super::mux_rate::Meter::measured(measured),
293			published: false,
294			initialized: false,
295			sections: HashMap::new(),
296			supports_mpegts,
297			es_descriptors: HashMap::new(),
298			recorded_media: HashMap::new(),
299			program_info,
300			listed: HashMap::new(),
301			si,
302			identity: None,
303			last_pts: None,
304			pts: PtsUnwrap::default(),
305			program: None,
306			unclaimed: Default::default(),
307			alone: false,
308			described: false,
309			scrambled: HashSet::new(),
310			input: crate::container::Input::Open,
311		}
312	}
313
314	/// Shift this program's timestamps through `timebase`, a timestamp base of the catalog `reserved`
315	/// belongs to, instead of a fresh one: importers of one source share its offset.
316	///
317	/// Set it before the first [`decode`](Self::decode), which may anchor the timebase.
318	pub fn with_timebase(mut self, timebase: crate::catalog::Timebase<E>) -> Self {
319		self.timebase = timebase;
320		self
321	}
322
323	/// Import only the program numbered `program` in the PAT, ignoring the rest of the multiplex.
324	///
325	/// Without this, a PAT that lists more than one program fails the import with
326	/// [`MultiplePrograms`](Error::MultiplePrograms) rather than merging them onto one clock. A PAT that does not
327	/// list `program` fails it too. The SI describes only this program's service: other
328	/// services' EIT actual is dropped and the SDT actual lists this service alone.
329	pub fn with_program(mut self, program: u16) -> Self {
330		self.program = Some(program);
331		self.si.select(program);
332		self
333	}
334
335	/// Select the container this importer wraps decoded media renditions in.
336	///
337	/// [`Legacy`](hang::catalog::Container::Legacy) unless selected. It applies to every rendition
338	/// this input demuxes, since the tracks are discovered rather than named by the caller.
339	pub fn with_container(mut self, container: hang::catalog::Container) -> Self {
340		self.container = container;
341		self
342	}
343
344	/// Carry on the PMT `sections` began on `pid`, for an importer that starts mid-stream on the
345	/// packet after the ones `sections` read.
346	pub(super) fn with_pmt(mut self, pid: Pid, sections: SectionReassembler) -> Self {
347		self.pmt = Some((pid, sections));
348		self
349	}
350
351	/// The PID this importer reads its PMT from.
352	pub(super) fn pmt_pid(&self) -> Option<u16> {
353		self.pmt.as_ref().map(|(pid, _)| pid.as_u16())
354	}
355
356	/// The PID this importer takes its program clock from.
357	pub(super) fn pcr_pid(&self) -> Option<u16> {
358		self.pcr_pid.map(|pid| pid.as_u16())
359	}
360
361	/// Whether this importer reassembles the PMT sections on `pid`.
362	fn reads_pmt(&self, pid: u16) -> bool {
363		self.pmt.as_ref().is_some_and(|(pmt, _)| pmt.as_u16() == pid)
364	}
365
366	/// Whether a route of this importer delivers what arrives on `pid`.
367	pub(super) fn carries(&self, pid: u16) -> bool {
368		self.sections.contains_key(&pid) || Pid::new(pid).is_ok_and(|pid| self.streams.contains_key(&pid))
369	}
370
371	/// The TR 101 290 intervals this importer times, for another to take over.
372	pub(super) fn timing(&self) -> &Health {
373		&self.health
374	}
375
376	/// Input bytes held for a later call, such as behind a suspected clock step.
377	#[cfg(test)]
378	pub(super) fn held(&self) -> usize {
379		self.demux.held()
380	}
381
382	/// The TR 101 290 intervals, for a caller to advance while no packet routes to this program.
383	pub(super) fn timing_mut(&mut self) -> &mut Health {
384		&mut self.health
385	}
386
387	/// Take over the TR 101 290 intervals `health` timed on `pid`, from a
388	/// program that read the same packets, to count the PID from here on. See
389	/// [`Health::hand_over`].
390	pub(super) fn take_over(&mut self, pid: u16, health: &Health) {
391		let cadenced = Pid::new(pid)
392			.ok()
393			.and_then(|pid| self.streams.get(&pid))
394			.is_some_and(Stream::cadenced);
395		health.hand_over(pid, &mut self.health, cadenced);
396	}
397
398	/// A reservation for one of this program's streams, which the program's timebase shifts.
399	fn reserve(&self) -> crate::catalog::Reserved<E> {
400		self.catalog.reserve()
401	}
402
403	/// The video hint for a decoded rendition: this importer's container, nothing else.
404	fn video_hint(&self) -> crate::catalog::VideoHint {
405		crate::catalog::VideoHint {
406			container: self.container.clone(),
407			..Default::default()
408		}
409	}
410
411	/// Append `buf` to the internal scratch and demux every whole TS packet it
412	/// now completes. The buffer is fully consumed; a trailing partial packet
413	/// (< 188 bytes) is retained for the next call.
414	///
415	/// A step of the source's clock onto another timeline ends the identity, failing with
416	/// [`Restarted`](Error::Restarted): the program clock and every timed stream stepping
417	/// together without `discontinuity_indicator`, forward by more than 10 s or back, or the
418	/// streams stepping back after a flagged break. Until the streams have spoken, which a
419	/// cadenced one does within 0.7 s, the input after a suspected step is held rather than
420	/// published, up to half a group's bytes. A PAT naming another `transport_stream_id` or
421	/// program number restarts too, at that PAT. Every later call fails the same way;
422	/// [`finish`](Self::finish) ends the identity before the step.
423	///
424	/// A PAT listing several programs fails with [`MultiplePrograms`](Error::MultiplePrograms)
425	/// unless [`with_program`](Self::with_program) picked one. Input after
426	/// [`finish`](Self::finish) is refused with [`Finished`](crate::Error::Finished), or with the
427	/// cause of a finish that failed.
428	///
429	/// [`Republish`](super::Republish) carries on past each restart into a new identity, on a
430	/// path of an origin.
431	pub fn decode(&mut self, data: &[u8]) -> Result<()> {
432		match self.decode_or_restart(data)? {
433			None => Ok(()),
434			Some(restart) => Err(Error::Restarted(restart.step)),
435		}
436	}
437
438	/// No input follows: read what a step still being judged held, returning a restart it
439	/// reaches, as [`decode_or_restart`](Self::decode_or_restart) does.
440	pub(super) fn settle(&mut self) -> Result<Option<super::Restart>> {
441		match self.steps.settle() {
442			true => self.decode_or_restart(&[]),
443			false => Ok(None),
444		}
445	}
446
447	/// [`decode`](Self::decode), returning a restart as a value with the input from the step on,
448	/// for [`Republish`](super::Republish) to read into a new identity.
449	pub(super) fn decode_or_restart(&mut self, data: &[u8]) -> Result<Option<super::Restart>> {
450		self.input.check()?;
451		let mut demux = std::mem::take(&mut self.demux);
452		let result = self.decode_with(&mut demux, data);
453		self.demux = demux;
454		result
455	}
456
457	fn decode_with(&mut self, demux: &mut Demux, data: &[u8]) -> Result<Option<super::Restart>> {
458		demux.push(data);
459		// Route one whole packet at a time, so a PMT is parsed (and any PID it declares
460		// registered) before the packets that follow it in the same chunk route.
461		loop {
462			for pid in self.restarts.drain(..) {
463				demux.restart(pid);
464				self.steps.forget(pid);
465			}
466			let streams = &self.streams;
467			let timed = |pid: u16| {
468				Pid::new(pid)
469					.ok()
470					.and_then(|pid| streams.get(&pid))
471					.is_some_and(|stream| !matches!(stream, Stream::Ignored))
472			};
473			let (program, identity) = (self.program, self.identity);
474			// A PAT whose selection fails switches nothing; routing it reports the failure.
475			let switched = |pat: &psi::Pat| {
476				let entry = select(program, pat).ok().flatten()?.0;
477				let (transport_stream_id, program_number) = (pat.transport_stream_id, entry.program_number);
478				(identity? != (transport_stream_id, program_number)).then_some(super::Step::Identity {
479					transport_stream_id,
480					program_number,
481				})
482			};
483			let routes = super::step::Routes {
484				pcr_pid: self.pcr_pid.map(|pid| pid.as_u16()),
485				timed: &timed,
486				now: self.liveness.now(),
487				switched: &switched,
488			};
489			match self.steps.judge(demux, &routes) {
490				super::step::Verdict::Route => {}
491				// Held input keeps its arrival, and is graded once routed.
492				super::step::Verdict::Hold => {
493					demux.drain();
494					self.flush_batch()?;
495					return Ok(None);
496				}
497				super::step::Verdict::Restart(step) => {
498					let remainder = demux.remainder();
499					demux.drain();
500					self.flush_batch()?;
501					return Ok(Some(super::Restart { step, remainder }));
502				}
503			}
504			let Some(packet) = demux.next() else { break };
505			self.packet(&packet)?;
506		}
507		// Every packet this chunk completed is read: grade the input through its arrival.
508		self.health.flush();
509		demux.drain();
510		self.flush_batch()?;
511		Ok(None)
512	}
513
514	/// Cut the snapshot groups for whatever SI committed since the last call, and flush the
515	/// damage log. Batching per decode call (plus the store's own host-clock debounce)
516	/// coalesces a junction's burst of sub-table commits into few groups instead of one per
517	/// commit.
518	pub(super) fn flush_batch(&mut self) -> Result<()> {
519		self.flush_partial()?;
520		self.damage_log.flush(kio::clock::now());
521		self.si.flush(self.last_pts.unwrap_or(Timestamp::ZERO), false)
522	}
523
524	/// Parse available decoded units before their arrival clock advances.
525	fn flush_partial(&mut self) -> Result<()> {
526		let mut partial = std::mem::take(&mut self.partial);
527		for pid in partial.drain(..) {
528			if !self.streams.get(&pid).is_some_and(Stream::salvages_partial_pes) {
529				continue;
530			}
531			let Some(pending) = self.pending.get_mut(&pid).filter(|pending| !pending.data.is_empty()) else {
532				continue;
533			};
534			let mut next = Pending::empty();
535			next.retained = Retained::new(self.staging.clone());
536			next.offset = pending.offset;
537			next.continuation = true;
538			next.data_len = pending.data_len.map(|len| len - pending.data.len());
539			let mut piece = std::mem::replace(pending, next);
540			// This is a piece of a PES, not a truncated end. The remaining length stays in `next`.
541			piece.data_len = None;
542			self.write_pending(pid, piece)?;
543		}
544		self.partial = partial;
545		Ok(())
546	}
547
548	/// The PIDs this program reads besides the PAT and the standalone SI PIDs: its PMTs, its
549	/// elementary streams and its clock.
550	pub(super) fn claims(&self) -> Vec<u16> {
551		let mut pids: Vec<u16> = self
552			.pmt
553			.iter()
554			.map(|(pid, _)| pid)
555			.chain(self.streams.keys())
556			.chain(self.pcr_pid.iter())
557			.map(Pid::as_u16)
558			.chain(self.sections.keys().copied())
559			.collect();
560		pids.sort_unstable();
561		pids.dedup();
562		pids
563	}
564
565	/// Whether this program reads `pid`: one it [`claims`](Self::claims), or one claimed whatever
566	/// the PMT says.
567	fn claims_pid(&self, pid: u16) -> bool {
568		super::unclaimed::Unclaimed::fixed(pid, self.supports_mpegts)
569			|| self.sections.contains_key(&pid)
570			|| Pid::new(pid).is_ok_and(|pid| {
571				self.reads_pmt(pid.as_u16()) || self.streams.contains_key(&pid) || self.pcr_pid == Some(pid)
572			})
573	}
574
575	/// The program clock: PCR ticks since its first PCR, or `None` before one.
576	pub(super) fn now(&self) -> Option<u64> {
577		self.liveness.now()
578	}
579
580	/// Whether [`claims`](Self::claims) may have changed since the last call.
581	pub(super) fn claims_changed(&mut self) -> bool {
582		std::mem::take(&mut self.claims_changed)
583	}
584
585	/// Drain the PIDs whose route changed since the last call, for the parser to restart.
586	pub(super) fn restarts(&mut self) -> std::vec::Drain<'_, u16> {
587		self.restarts.drain(..)
588	}
589
590	/// Route one packet the parser framed. Packets on PIDs this program does not
591	/// [`claim`](Self::claims) may be skipped, except the PAT's and the SI PIDs' whole sections.
592	pub(super) fn packet(&mut self, packet: &Packet) -> Result<()> {
593		let Packet {
594			pkt,
595			pid,
596			offset,
597			continuation,
598			..
599		} = *packet;
600		// A packet flagged corrupt may carry another PID's number.
601		if self.alone && self.described && pkt[1] & 0x80 == 0 && !self.claims_pid(pid) {
602			self.unclaimed.packet(pid);
603		}
604		// Every packet is graded, but only the media PIDs and the clock route on the
605		// verdict: PSI and section PIDs keep their reassemblers' own.
606		let at = super::health::At {
607			count: packet.count,
608			arrival: packet.arrival,
609		};
610		self.health.packet(pkt, continuation, at);
611		let continuation = Pid::new(pid)
612			.ok()
613			.filter(|pid| self.streams.contains_key(pid) || self.pcr_pid == Some(*pid))
614			.map(|_| continuation);
615		// A retransmitted payload must not repeat the clock reset it carried.
616		if matches!(continuation, Some(Continuation::Duplicate)) {
617			return Ok(());
618		}
619		// A media or PCR packet whose adaptation field overruns itself ends the import before
620		// its clock bits can reach the program clock: it arrived whole and unflagged, so the
621		// muxer wrote it wrong.
622		if let Ok(pid) = Pid::new(pid)
623			&& (self
624				.streams
625				.get(&pid)
626				.is_some_and(|stream| !matches!(stream, Stream::Ignored))
627				|| self.pcr_pid == Some(pid))
628			&& pkt[1] & 0x80 == 0
629			&& !adaptation_valid(pkt)
630		{
631			return Err(malformed!("malformed TS adaptation field on PID {}", pid.as_u16()));
632		}
633		// Read the clock's own flag before routing, so the break lands between the media
634		// either side of it. The PCR PID can be a dedicated one nothing below routes, and
635		// the flag rides an adaptation-only packet as readily as a payload one.
636		// A packet the demodulator flagged corrupt (`transport_error_indicator`) is not
637		// read: its adaptation field is as untrustworthy as its payload, and taking a bit
638		// out of it would break every track in the program on line noise.
639		if self.pcr_pid.is_some_and(|p| p.as_u16() == pid) && pkt[1] & 0x80 == 0 {
640			if pcr(pkt).is_some() {
641				self.flush_partial()?;
642			}
643			if discontinuity_indicator(pkt) {
644				// A PES this packet starts ends the one before it on its PID whole, on the old
645				// clock; only the other PIDs' are cut short by the break. An adaptation-only
646				// packet starts none whatever its PUSI says, as `pes_packet` treats it.
647				if pkt[1] & 0x40 != 0
648					&& matches!(payload(pkt), Payload::Bytes(_))
649					&& let Ok(pid) = Pid::new(pid)
650				{
651					self.flush(pid)?;
652				}
653				self.timebase_break()?;
654				// The new timebase starts with the PCR the flag rides, if it rides one.
655				if let Some(pcr) = pcr(pkt) {
656					self.place_pcr(pcr, offset)?;
657					self.si.pcr(pcr, packet.count);
658				}
659			} else if let Some(pcr) = pcr(pkt) {
660				self.place_pcr(pcr, offset)?;
661				self.liveness.pcr(pcr);
662				self.si.pcr(pcr, packet.count);
663				if self.supports_mpegts && self.mux_rate.pcr(pcr, packet.count) {
664					self.record_mux_rate()?;
665				}
666			}
667		}
668		// TS-level scrambling hides a payload from all but a descrambler, so the semantic lane
669		// cannot carry it where the raw lane can. Its adaptation field stays clear: the clock
670		// above has read it.
671		if pkt[1] & 0x80 == 0
672			&& pkt[3] & 0xc0 != 0
673			&& let Ok(pid) = Pid::new(pid)
674			&& (self.sections.contains_key(&pid.as_u16())
675				|| self
676					.streams
677					.get(&pid)
678					.is_some_and(|stream| !matches!(stream, Stream::Ignored)))
679		{
680			return self.scrambled(pid);
681		}
682		if let Some(section) = self.sections.get_mut(&pid) {
683			let unplaced = section.packet(pkt, offset, &self.placement)?;
684			let (units, dropped) = section.release(&self.timebase, &self.pts, self.placement.generation)?;
685			let unplaced = unplaced + dropped;
686			if unplaced > 0 {
687				*self.unplaced.entry(pid).or_default() += unplaced;
688			}
689			self.published |= units > 0;
690			self.liveness.delivered(pid, units);
691			return Ok(());
692		}
693		// The standalone SI PIDs carry the service layer, not media, and no PAT or PMT
694		// names them. The parser reassembled their sections, each captured whatever its
695		// `table_id`.
696		if self.supports_mpegts && catalog::SI_PIDS.contains(&pid) {
697			for section in packet.sections {
698				if !self.si.section(pid, section.clone(), packet.count) {
699					*self.unplaced.entry(pid).or_default() += 1;
700				}
701			}
702			return Ok(());
703		}
704		// An elementary stream's PES is as vulnerable to a break as a section is. A
705		// looping publisher wraps with its last PES still open and short of its declared
706		// length, so the next loop's leading packets would otherwise complete it and hand
707		// the codec one buffer straddling the cut.
708		if let Ok(pid) = Pid::new(pid)
709			&& self.streams.contains_key(&pid)
710		{
711			match continuation.expect("media PID continuity was classified") {
712				Continuation::Duplicate => return Ok(()),
713				// Flagged corrupt, so the packet joins the partial rather than opening a
714				// new PES out of bytes the demodulator already disowned.
715				Continuation::Corrupt => {
716					self.damage(pid, &malformed!("transport error indicator"))?;
717					return Ok(());
718				}
719				Continuation::Broken => {
720					self.broken(pid)?;
721					// This packet still routes normally: a PUSI opens a fresh PES, while a
722					// continuation finds no pending entry and is dropped, so the stream
723					// resumes at the next PES start rather than mid-frame.
724				}
725				Continuation::Contiguous => {}
726			}
727		}
728		let Ok(pid) = Pid::new(pid) else {
729			return Ok(());
730		};
731		if pid.as_u16() == Pid::PAT {
732			if let Some(pat) = &packet.pat {
733				self.handle_pat(pat)?;
734			}
735		} else if self.pmt.as_ref().is_some_and(|(pmt, _)| *pmt == pid) {
736			self.pmt_packet(pid, packet)?;
737		} else {
738			// PIDs we don't carry (`Stream::Ignored`, counted when refused) are dropped, as is
739			// every PID no table claims (counted by `claims` above) and every PID before the
740			// PSI that declares it: a live capture joins mid-stream, so PES arrive before
741			// their PMT.
742			match self.streams.get(&pid) {
743				None | Some(Stream::Ignored) => {}
744				Some(_) => self.pes_packet(pid, pkt, offset)?,
745			}
746		}
747		Ok(())
748	}
749
750	/// Feed one packet on the PMT PID to its reassembler, applying every good PMT section.
751	fn pmt_packet(&mut self, pid: Pid, packet: &Packet) -> Result<()> {
752		let mut sections = Vec::new();
753		if let Some((_, reassembler)) = &mut self.pmt {
754			reassembler.push(packet.pkt, &mut sections);
755		}
756		for section in sections {
757			// Other tables may share the PID; only a PMT is this path's to check.
758			if section.first() != Some(&psi::PMT_TABLE_ID) {
759				continue;
760			}
761			if !psi::crc_ok(&section) {
762				self.crc_error(pid);
763				continue;
764			}
765			if let Some(pmt) = Pmt::parse(&section) {
766				self.handle_pmt(pmt)?;
767				self.seed_clock(packet)?;
768			}
769		}
770		Ok(())
771	}
772
773	/// Start a clock a PMT just named from its latest PCR, if one arrived since the program
774	/// last had none, or note from when one may start it.
775	fn seed_clock(&mut self, packet: &Packet) -> Result<()> {
776		match self.pcr_pid {
777			Some(pid) => {
778				if let Some(since) = self.unclocked_since.take()
779					&& let Some(&sample) = packet.pcrs.get(&pid.as_u16())
780					&& sample.at - PCR_OFFSET >= since
781				{
782					self.place_pcr(sample.ticks, sample.at - PCR_OFFSET)?;
783				}
784			}
785			None => {
786				self.unclocked_since
787					.get_or_insert(packet.offset + TsPacket::SIZE as u64);
788			}
789		}
790		Ok(())
791	}
792
793	/// A PMT section failed its CRC: it is dropped whole, and the table already in
794	/// force stays.
795	fn crc_error(&mut self, pid: Pid) {
796		*self.crc_errors.entry(pid.as_u16()).or_default() += 1;
797		tracing::warn!(pid = pid.as_u16(), "dropped a PSI section with a bad CRC");
798	}
799
800	fn handle_pmt(&mut self, pmt: Pmt) -> Result<()> {
801		// PMTs of several programs may share one PID; only the chosen one maps streams.
802		if self.program.is_some_and(|program| program != pmt.program_number) {
803			return Ok(());
804		}
805		self.claims_changed = true;
806		// Which PID speaks for the program clock, so a `discontinuity_indicator` there
807		// can be read as a timebase reset rather than a counter jump.
808		if self.pcr_pid != pmt.pcr_pid {
809			// The first clock a PMT names measured nothing yet, but may keep a rate it was given.
810			let changed = self.pcr_pid.is_some();
811			self.pcr_pid = pmt.pcr_pid;
812			self.health.pcr_pid(pmt.pcr_pid.map(|pid| pid.as_u16()));
813			// A new clock: the intervals straddling the switch measure nothing, and the whole PES
814			// the old one began are placed on its timebase, never between its PCRs and the new.
815			self.liveness.discontinuity();
816			self.si.discontinuity();
817			if changed {
818				self.reset_mux_rate()?;
819			}
820			self.settle_placement()?;
821		}
822
823		// SCTE-35 is announced by a program-level registration descriptor with
824		// format_identifier 'CUEI' (ITU-T J.181). The stream itself uses
825		// stream_type 0x86, which is also a DTS audio variant, so detection keys
826		// off the CUEI descriptor, not the stream type alone.
827		let cuei = pmt
828			.program_info
829			.iter()
830			.any(|d| d.tag == 0x05 && d.data.len() >= 4 && &d.data[0..4] == b"CUEI");
831
832		// Record the program-level descriptors as the PMT revises them; export re-emits them
833		// verbatim, including the original CUEI.
834		if self.supports_mpegts && self.program_info != pmt.program_info {
835			if let Some(mpegts) = self.catalog.edit()?.ext.mpegts_mut() {
836				mpegts.program_descriptors = pmt.program_info.clone();
837			}
838			self.program_info = pmt.program_info.clone();
839		}
840
841		// A stream the PMT no longer lists, or lists as something else, ends here, so every
842		// track name keeps meaning one elementary stream; a revised one opens under a new name.
843		let listed: HashMap<Pid, Listing> = pmt
844			.streams
845			.iter()
846			.map(|es| {
847				let listing = Listing {
848					stream_type: es.stream_type,
849					descriptors: es.descriptors.clone(),
850					sections: section_framed(es.stream_type, cuei),
851				};
852				(es.pid, listing)
853			})
854			.collect();
855		let mut ended: Vec<Pid> = self
856			.listed
857			.iter()
858			.filter(|(pid, listing)| listed.get(pid) != Some(listing))
859			.map(|(&pid, _)| pid)
860			.collect();
861		ended.sort_by_key(Pid::as_u16);
862		for pid in ended {
863			self.end_route(pid)?;
864			if !listed.contains_key(&pid) {
865				tracing::info!(pid = pid.as_u16(), "TS elementary stream left the PMT");
866			}
867		}
868		self.listed = listed;
869
870		for es in &pmt.streams {
871			let before = self.route(es.pid);
872			// Stash ES descriptors so a decoded media track can record them once its
873			// (lazily created) track exists; verbatim streams record their own.
874			if self.supports_mpegts {
875				self.es_descriptors.insert(es.pid.as_u16(), es.descriptors.clone());
876			}
877			// Section-framed data is reassembled as sections, never PES-parsed. Everything else
878			// routes through ensure_stream (a decoded codec, whole PES, or refused).
879			if section_framed(es.stream_type, cuei) {
880				self.ensure_section(es.pid, es.stream_type, &es.descriptors)?;
881			} else {
882				self.ensure_stream(es.pid, es.stream_type, &es.descriptors)?;
883			}
884			// Tracks configured by the PMT must carry their PID before the clock releases the catalog.
885			self.record_media_track(es.pid)?;
886			// Report a new PID or a changed route once; a repeated PMT stays quiet.
887			if let Some((outcome, carriage)) = self.route(es.pid)
888				&& before != Some((outcome, carriage))
889			{
890				tracing::info!(
891					pid = es.pid.as_u16(),
892					stream_type = es.stream_type,
893					outcome,
894					carriage,
895					"TS elementary stream"
896				);
897			}
898		}
899		self.has_video = self.streams.values().any(Stream::video);
900		self.media_clock = pmt.streams.iter().any(|es| {
901			self.streams.get(&es.pid).is_some_and(|stream| {
902				stream.video() || matches!(stream, Stream::Aac(_) | Stream::Opus(_) | Stream::Legacy(_))
903			})
904		});
905		let pids: Vec<u16> = pmt.streams.iter().map(|es| es.pid.as_u16()).collect();
906		self.health.pmt_streams(&pids);
907		self.described = true;
908		Ok(())
909	}
910
911	/// How a PID's elementary stream is carried, as `(outcome, carriage)`, or `None` if unrouted.
912	fn route(&self, pid: Pid) -> Option<(&'static str, &'static str)> {
913		Some(match self.streams.get(&pid) {
914			Some(Stream::H264 { .. } | Stream::H265 { .. } | Stream::Aac(_) | Stream::Opus(_) | Stream::Legacy(_)) => {
915				("track", "decoded")
916			}
917			Some(Stream::PesPacket(_)) => ("verbatim", "pesPacket"),
918			Some(Stream::Clock) => ("dropped", "clock only"),
919			Some(Stream::Ignored) => ("dropped", "none"),
920			None if self.sections.contains_key(&pid.as_u16()) => ("verbatim", "section"),
921			None => return None,
922		})
923	}
924
925	/// Route one packet on an elementary stream PID, at input offset `offset`, into its PES
926	/// reassembly.
927	fn pes_packet(&mut self, pid: Pid, pkt: &[u8; TsPacket::SIZE], offset: u64) -> Result<()> {
928		let payload = match payload(pkt) {
929			Payload::None => return Ok(()),
930			Payload::Bytes(payload) => payload,
931			Payload::Malformed => {
932				return Err(malformed!("malformed TS adaptation field on PID {}", pid.as_u16()));
933			}
934		};
935		if pkt[1] & 0x40 != 0 {
936			// Loss, a flagged packet, and scrambling all drop a partial header, so one still here
937			// is a header the muxer cut short.
938			if self.headers.contains_key(&pid) {
939				return Err(malformed!(
940					"PES header on PID {} truncated at the next start",
941					pid.as_u16()
942				));
943			}
944			self.flush(pid)?;
945			// The payload ends the packet, so this is where its start code sits in the input.
946			let at = offset + (TsPacket::SIZE - payload.len()) as u64;
947			// Taken here, not once the header is whole, so a PCR landing before the header's
948			// continuation is the one after it.
949			let span = self.placement.span(at);
950			return self.pes_header(pid, span, payload.to_vec());
951		}
952		if let Some((span, mut header)) = self.headers.remove(&pid) {
953			header.extend_from_slice(payload);
954			self.pes_header(pid, span, header)
955		} else {
956			self.handle_pes_continuation(pid, payload)
957		}
958	}
959
960	/// Open the PES whose header `header` begins, placed by `span` from its start code, or hold
961	/// the header until the packets after it complete it. A header that arrived intact but does
962	/// not parse ends the import.
963	fn pes_header(&mut self, pid: Pid, span: Option<Span>, header: Vec<u8>) -> Result<()> {
964		let malformed = |err| malformed!("PES header on PID {}: {err}", pid.as_u16());
965		let len = PesStart::header_len(&header).map_err(malformed)?;
966		if header.len() < len {
967			self.headers.insert(pid, (span, header));
968			return Ok(());
969		}
970		let pes = PesStart::parse(&header).map_err(malformed)?;
971		self.handle_pes_start(pid, pes, span)
972	}
973
974	fn ensure_stream(&mut self, pid: Pid, stream_type: u8, descriptors: &[catalog::Descriptor]) -> Result<()> {
975		let temporal_poc = if stream_type == StreamType::H264 as u8 {
976			video::temporal_poc(descriptors)?
977		} else {
978			false
979		};
980		if let Some(Stream::H264 { assembly, .. }) = self.streams.get_mut(&pid) {
981			assembly.clock.temporal_poc = temporal_poc;
982		}
983
984		// A later PMT can remap a PID that was section-framed (intercepted in
985		// `decode`) to a PES codec/verbatim stream. Drop the stale section route first,
986		// or it would keep intercepting the PID and the new stream would never get data.
987		// This only fires on a genuine remap: section PIDs otherwise route to
988		// `ensure_section`, never here.
989		if let Some(mut section) = self.retire_section(pid) {
990			section.finish()?;
991			self.pending.remove(&pid);
992			self.headers.remove(&pid);
993			drop(section);
994		}
995		// A private PES stream follows the PMT's PCR_PID: refused while there is none to place
996		// its PES by, and routed again once there is, or once the PID carries another type.
997		match self.streams.get(&pid) {
998			Some(Stream::PesPacket(stream)) if self.pcr_pid.is_none() => {
999				let carried = stream.stream_type;
1000				self.refuse(pid, "the program lost the PCR that placed it")?;
1001				self.unclocked.insert(pid, carried);
1002				return Ok(());
1003			}
1004			Some(Stream::Ignored | Stream::Clock)
1005				if self
1006					.unclocked
1007					.get(&pid)
1008					.is_some_and(|&refused| self.pcr_pid.is_some() || refused != stream_type) =>
1009			{
1010				self.unclocked.remove(&pid);
1011				self.streams.remove(&pid);
1012			}
1013			Some(_) => return Ok(()),
1014			None => {}
1015		}
1016
1017		let stream = match StreamType::from_u8(stream_type).ok() {
1018			Some(StreamType::H264) => {
1019				let track = self
1020					.broadcast
1021					.unique_track(".avc3", self.catalog.track_info(hang::catalog::PRIORITY.video));
1022				Stream::H264 {
1023					split: h264::Split::new(),
1024					assembly: {
1025						let mut assembly = video::Assembly::new(video::Codec::Avc);
1026						assembly.clock.temporal_poc = temporal_poc;
1027						assembly
1028					},
1029					import: Box::new(h264::Import::new(track, self.reserve(), self.video_hint())?),
1030				}
1031			}
1032			Some(StreamType::H265) => {
1033				let track = self
1034					.broadcast
1035					.unique_track(".hev1", self.catalog.track_info(hang::catalog::PRIORITY.video));
1036				Stream::H265 {
1037					split: h265::Split::new(),
1038					assembly: video::Assembly::new(video::Codec::Hevc),
1039					import: Box::new(h265::Import::new(track, self.reserve(), self.video_hint())?),
1040				}
1041			}
1042			// Only ADTS-framed AAC (0x0F). 0x11 is LATM/LOAS, which uses a different
1043			// framing and syncword, so it rides whole like any other undecoded stream.
1044			Some(StreamType::AdtsAac) => Stream::Aac(Box::new(AacStream {
1045				import: None,
1046				asc: bytes::Bytes::new(),
1047				format: (0, 0, 0),
1048				broadcast: self.broadcast.clone(),
1049				reserved: Some(self.reserve()),
1050				catalog: self.catalog.clone(),
1051				container: self.container.clone(),
1052				tail: Vec::new(),
1053				tail_pts: None,
1054				tail_pes: PesStarts::default(),
1055				resync: Resync::new(pid.as_u16(), ".aac"),
1056				burst: std::time::Duration::ZERO,
1057				last: None,
1058				group: AudioGroup::default(),
1059			})),
1060			// Legacy broadcast audio, carried verbatim. Both MP2 stream types
1061			// (0x03 MPEG-1, 0x04 MPEG-2 half rate) share one parser; sample rate and
1062			// channels always come from the frame header, not the PMT.
1063			Some(StreamType::Mpeg1Audio | StreamType::Mpeg2HalvedSampleRateAudio) => {
1064				self.legacy_stream(pid, &mp2::DESCRIPTOR)
1065			}
1066			Some(StreamType::DolbyDigitalUpToSixChannelAudio) => self.legacy_stream(pid, &ac3::DESCRIPTOR),
1067			Some(StreamType::DolbyDigitalPlusUpTo16ChannelAudioForAtsc) => self.legacy_stream(pid, &eac3::DESCRIPTOR),
1068			// Opus rides private-data PES (0x06), distinguished from other private streams
1069			// by an 'Opus' registration descriptor. Channels and the (always 48 kHz) rate
1070			// come from the descriptors, so the importer is built up front. A channel code
1071			// the descriptor cannot justify drops this PID; the rest of the program stays.
1072			Some(StreamType::Mpeg2PacketizedData) if registration_format(descriptors) == Some(*b"Opus") => {
1073				match opus_config(descriptors) {
1074					Ok(config) => {
1075						let track = self
1076							.broadcast
1077							.unique_track(".opus", self.catalog.track_info(hang::catalog::PRIORITY.audio));
1078						let mut config: hang::catalog::AudioConfig = config.into();
1079						config.container = self.container.clone();
1080						Stream::Opus(Box::new(OpusStream {
1081							import: opus::Import::new(track, self.reserve(), config)?,
1082							last: None,
1083							group: AudioGroup::default(),
1084						}))
1085					}
1086					Err(err) => self.uncarried(
1087						pid,
1088						stream_type,
1089						&format!("unsupported Opus channel configuration: {err:#}"),
1090					),
1091				}
1092			}
1093			// 0x86 is ambiguous: DTS audio, or a non-conformant SCTE-35 mux without CUEI, which is
1094			// sections a PES parse would abort on. Refuse it rather than guess.
1095			_ if stream_type == StreamType::Dts8ChannelLosslessAudio as u8 => self.uncarried(
1096				pid,
1097				stream_type,
1098				"0x86 without a CUEI registration may be DTS or SCTE-35",
1099			),
1100			// A codec we don't decode, named or not, MPEG-1/2 video included, rides as whole PES
1101			// packets when the catalog supports the `mpegts` section.
1102			_ if !self.supports_mpegts => self.uncarried(pid, stream_type, "the catalog has no mpegts section"),
1103			_ if self.pcr_pid.is_none() => {
1104				// Nothing could place its PES, so no track is advertised.
1105				self.unclocked.insert(pid, stream_type);
1106				self.uncarried(pid, stream_type, "the program has no PCR to place it by")
1107			}
1108			_ => Stream::PesPacket(Box::new(PesPacketStream::new(
1109				self.broadcast.clone(),
1110				self.catalog.clone(),
1111				pid.as_u16(),
1112				stream_type,
1113				descriptors.to_vec(),
1114			)?)),
1115		};
1116
1117		// Clock is not a decodable track, so it doesn't initialize the importer.
1118		if !matches!(stream, Stream::Ignored | Stream::Clock) {
1119			self.initialized = true;
1120		}
1121		if !matches!(stream, Stream::Ignored) {
1122			self.liveness.register(pid.as_u16());
1123		}
1124		self.streams.insert(pid, stream);
1125		self.health.restart(pid.as_u16());
1126		self.restarts.push(pid.as_u16());
1127		Ok(())
1128	}
1129
1130	/// The route of a listed stream this import does not carry, counted once as refused. MPEG-1/2
1131	/// video still paces the program by its PTS.
1132	fn uncarried(&mut self, pid: Pid, stream_type: u8, why: &str) -> Stream<E> {
1133		*self.refused.entry(pid.as_u16()).or_default() += 1;
1134		tracing::warn!(pid = pid.as_u16(), stream_type, why, "refused a listed stream");
1135		match mpeg_video(stream_type) {
1136			true => Stream::Clock,
1137			false => Stream::Ignored,
1138		}
1139	}
1140
1141	fn legacy_stream(&self, pid: Pid, descriptor: &'static legacy::Descriptor) -> Stream<E> {
1142		Stream::Legacy(Box::new(LegacyStream {
1143			descriptor,
1144			import: None,
1145			broadcast: self.broadcast.clone(),
1146			reserved: Some(self.reserve()),
1147			catalog: self.catalog.clone(),
1148			format: (0, 0),
1149			container: self.container.clone(),
1150			tail: Vec::new(),
1151			tail_pts: None,
1152			tail_pes: PesStarts::default(),
1153			resync: Resync::new(pid.as_u16(), descriptor.track_suffix),
1154			last: None,
1155			group: AudioGroup::default(),
1156		}))
1157	}
1158
1159	/// Register a section-framed verbatim PID (SCTE-35 or other private sections):
1160	/// intercepted (see [`Self::decode`]) with a verbatim track when the catalog
1161	/// carries the `mpegts` section, dropped as `Ignored` when it can't.
1162	fn ensure_section(&mut self, pid: Pid, stream_type: u8, descriptors: &[catalog::Descriptor]) -> Result<()> {
1163		if self.supports_mpegts && self.pcr_pid.is_none() {
1164			if self.unclocked.get(&pid) != Some(&stream_type) {
1165				self.refuse(pid, "the program has no PCR to place it by")?;
1166				self.unclocked.insert(pid, stream_type);
1167			}
1168			self.liveness.register(pid.as_u16());
1169			self.initialized = true;
1170			return Ok(());
1171		}
1172		if self.sections.contains_key(&pid.as_u16()) {
1173			return Ok(());
1174		}
1175		// This PID is becoming section-framed; drop any partial PES a prior codec left pending.
1176		self.pending.remove(&pid);
1177		self.headers.remove(&pid);
1178		self.health.restart(pid.as_u16());
1179		self.restarts.push(pid.as_u16());
1180		if !self.supports_mpegts {
1181			// Always route to Ignored, replacing any prior codec on this PID (a later PMT
1182			// can reassign it), so a private section is never PES-parsed. Counted once.
1183			let stream = match self.retire_stream(pid) {
1184				Some(Stream::Ignored) => Stream::Ignored,
1185				_ => self.uncarried(pid, stream_type, "the catalog has no mpegts section"),
1186			};
1187			self.streams.insert(pid, stream);
1188			return Ok(());
1189		}
1190		// A prior PMT may have routed this PID to Ignored; drop it so the PID has one route.
1191		self.retire_stream(pid);
1192		let descriptors = descriptors.to_vec();
1193		let mut stream = SectionStream::new(
1194			self.broadcast.clone(),
1195			self.catalog.clone(),
1196			pid.as_u16(),
1197			stream_type,
1198			descriptors,
1199		)?;
1200		stream.staging = self.staging.clone();
1201		self.sections.insert(pid.as_u16(), stream);
1202		self.liveness.register(pid.as_u16());
1203		self.initialized = true;
1204		tracing::debug!(
1205			pid = pid.as_u16(),
1206			stream_type,
1207			"private section stream detected; reassembling its sections"
1208		);
1209		Ok(())
1210	}
1211
1212	/// Remove a PES route while keeping the counters it accumulated for this importer.
1213	fn retire_stream(&mut self, pid: Pid) -> Option<Stream<E>> {
1214		self.unclocked.remove(&pid);
1215		let stream = self.streams.remove(&pid)?;
1216		self.keep_stats(pid, stream.stats());
1217		Some(stream)
1218	}
1219
1220	/// Keep a retired route's counters for this importer, naming it the PID's latest route.
1221	fn keep_stats(&mut self, pid: Pid, current: Option<stats::Stream>) {
1222		if let Some(current) = current {
1223			self.retired_stats
1224				.entry(pid.as_u16())
1225				.and_modify(|retired| retired.merge(&current))
1226				.or_insert(current);
1227		}
1228	}
1229
1230	/// End the route on `pid` for a PMT that dropped or revised its stream, as the end of input
1231	/// ends every route: the PES it began goes out, what waits on the clock is placed from the
1232	/// PCRs so far or counted unplaced (refusing the import, as end of input does, if no media
1233	/// timestamp anchored it), and its track finishes and leaves the catalog.
1234	fn end_route(&mut self, pid: Pid) -> Result<()> {
1235		if self.headers.remove(&pid).is_some() {
1236			self.damage(pid, &malformed!("PES header truncated by a PMT revision"))?;
1237		}
1238		self.flush(pid)?;
1239		// Released as if its timebase ended here, so a unit no later PCR will bracket for it is
1240		// unplaced rather than held.
1241		let generation = self.placement.generation + 1;
1242		let (mut units, mut unplaced) = (0, 0);
1243		// Each route stays in its map until it has finished, so a failure on the way leaves it
1244		// for `abort` to end with the cause.
1245		if let Some(section) = self.sections.get_mut(&pid.as_u16()) {
1246			section.settle(&self.placement);
1247			(units, unplaced) = section.release(&self.timebase, &self.pts, generation)?;
1248			ensure!(
1249				section.held.is_empty(),
1250				"TS sections reached a PMT revision without a media timestamp"
1251			);
1252			section.finish()?;
1253		}
1254		if let Some(section) = self.sections.remove(&pid.as_u16()) {
1255			self.keep_stats(pid, Some(stats::Stream::new(".ts", stats::Class::Data)));
1256			drop(section);
1257		}
1258		self.unclocked.remove(&pid);
1259		if let Some(stream) = self.streams.get_mut(&pid)
1260			&& let Stream::PesPacket(stream) = &mut *stream
1261		{
1262			stream.end();
1263			stream.settle(&self.placement);
1264			let (published, dropped) = stream.release(&self.timebase, &self.pts, generation)?;
1265			units += published;
1266			unplaced += dropped;
1267			ensure!(
1268				stream.held.is_empty(),
1269				"TS private PES reached a PMT revision without a media timestamp"
1270			);
1271		}
1272		units += self.finish_stream(pid)?;
1273		if let Some(stream) = self.streams.get(&pid) {
1274			// A verbatim entry leaves with its stream; a decoded track's is recorded here.
1275			if let Some(name) = self.recorded_media.remove(&pid)
1276				&& stream.media_track_name().is_some()
1277				&& let Some(mpegts) = self.catalog.edit()?.ext.mpegts_mut()
1278			{
1279				mpegts.tracks.remove(&name);
1280			}
1281		}
1282		if let Some(stream) = self.streams.remove(&pid) {
1283			// Finishing can publish a held frame, which its counters then include.
1284			self.keep_stats(pid, stream.stats());
1285			drop(stream);
1286		}
1287		if unplaced > 0 {
1288			*self.unplaced.entry(pid.as_u16()).or_default() += unplaced;
1289		}
1290		self.published |= units > 0;
1291		self.liveness.delivered(pid.as_u16(), units);
1292		self.liveness.retire(pid.as_u16());
1293		self.es_descriptors.remove(&pid.as_u16());
1294		Ok(())
1295	}
1296
1297	/// Remove the section route on `pid`, keeping the row of the track it published.
1298	fn retire_section(&mut self, pid: Pid) -> Option<SectionStream<E>> {
1299		let section = self.sections.remove(&pid.as_u16())?;
1300		self.retired_stats
1301			.entry(pid.as_u16())
1302			.or_insert_with(|| stats::Stream::new(".ts", stats::Class::Data));
1303		Some(section)
1304	}
1305
1306	/// Open the PES whose header `pes` begins where `span` says, if any PCR came before it.
1307	fn handle_pes_start(&mut self, pid: Pid, pes: PesStart, span: Option<Span>) -> Result<()> {
1308		// Finish the preceding PES before accepting another header.
1309		if self.pending.contains_key(&pid) {
1310			self.flush(pid)?;
1311		}
1312
1313		let Some(stream) = self.streams.get(&pid) else {
1314			// PES before its PMT entry; ignore until the layout is known.
1315			return Ok(());
1316		};
1317
1318		// Conditional access, like TS-level scrambling: refused while it lasts, on any carriage.
1319		if pes.scrambled() {
1320			return self.scrambled(pid);
1321		}
1322		let whole = match stream {
1323			Stream::PesPacket(stream) => Some(stream.stream_type),
1324			_ => None,
1325		};
1326		if let Some(stream_type) = whole
1327			&& let Some(why) = refusal(&pes, stream_type)
1328		{
1329			return self.refuse(pid, &why);
1330		}
1331		let stream = &self.streams[&pid];
1332
1333		let is_video = stream.video();
1334		let is_clock = matches!(stream, Stream::Clock);
1335		if pes.pts.is_some() && stream.cadenced() {
1336			self.health.pts(pid.as_u16(), self.health.now());
1337		}
1338		// Resolve the wrap at PES start so every elementary stream and private section shares
1339		// the program timeline, including streams discovered after a wrap.
1340		let (pts, offset) = match pes.pts {
1341			Some(raw) => {
1342				// Only a stream still behind a wrap the first PTS crossed reads as negative.
1343				let Ok(ticks) = u64::try_from(self.pts.unwrap(raw)) else {
1344					*self.unplaced.entry(pid.as_u16()).or_default() += 1;
1345					return Ok(());
1346				};
1347				let offset = self.timebase.anchor(Timestamp::from_scale(ticks, 90_000)?)?;
1348				(Some(ticks), offset)
1349			}
1350			None => (None, Offset::default()),
1351		};
1352		if is_video {
1353			for stream in self.streams.values_mut() {
1354				if let Stream::Aac(audio) = stream {
1355					audio.burst = std::time::Duration::ZERO;
1356				}
1357			}
1358			// Service-information snapshots follow the current video presentation time.
1359			if pts.is_some() {
1360				self.last_pts = on_clock(pts, offset)?;
1361			}
1362		}
1363		if pts.is_some() {
1364			// The clock is final. Configured tracks need not wait for this PES's payload.
1365			self.initial_reservation = None;
1366			self.release_placed()?;
1367		}
1368
1369		if is_clock {
1370			// Nothing is published, but each PES is a picture the source delivered.
1371			self.liveness.delivered(pid.as_u16(), 1);
1372			return Ok(());
1373		}
1374
1375		// A whole PES keeps its header, and is placed by the PCR before it and the one after.
1376		let (header, data_len, span) = match whole {
1377			Some(_) => {
1378				// A span whose timebase ended while its header assembled was settled with it, or
1379				// is dropped as unplaced at release.
1380				let Some(span) = span else {
1381					// Before the first PCR on this timebase nothing places it.
1382					*self.unplaced.entry(pid.as_u16()).or_default() += 1;
1383					return Ok(());
1384				};
1385				let len = pes.data_len.map(|len| pes.header.len() + len);
1386				(pes.header, len, Some(span))
1387			}
1388			None => (&[][..], pes.data_len, None),
1389		};
1390		let data = &pes.data[..pes.data_len.unwrap_or(pes.data.len()).min(pes.data.len())];
1391		let mut retained = Retained::new(self.staging.clone());
1392		// A whole PES is held as a unit until placed, so tiny ones count against the unit bound
1393		// as sections do, not the byte bound alone.
1394		retained.grow(header.len() + data.len(), usize::from(span.is_some()))?;
1395		let mut pending = Pending {
1396			retained,
1397			pts,
1398			offset,
1399			dts: pes.dts,
1400			data: Vec::with_capacity(header.len() + data.len()),
1401			data_len,
1402			span,
1403			continuation: false,
1404		};
1405		pending.data.extend_from_slice(header);
1406		pending.data.extend_from_slice(data);
1407		let complete = matches!(data_len, Some(len) if pending.data.len() >= len);
1408		self.pending.insert(pid, pending);
1409		self.partial.push(pid);
1410
1411		if complete {
1412			self.flush(pid)?;
1413		}
1414		Ok(())
1415	}
1416
1417	fn handle_pes_continuation(&mut self, pid: Pid, data: &[u8]) -> Result<()> {
1418		let Some(pending) = self.pending.get_mut(&pid) else {
1419			return Ok(());
1420		};
1421		let len = pending
1422			.data_len
1423			.map_or(data.len(), |len| len - pending.data.len())
1424			.min(data.len());
1425		if pending.data.is_empty() && len != 0 {
1426			self.partial.push(pid);
1427		}
1428		pending.retained.grow(len, 0)?;
1429		pending.data.extend_from_slice(&data[..len]);
1430		if matches!(pending.data_len, Some(len) if pending.data.len() >= len) {
1431			self.flush(pid)?;
1432		}
1433		Ok(())
1434	}
1435
1436	/// Refuse the PES a damaged packet breaks (loss, the transport error indicator, or a header
1437	/// cut short by either, a PMT revision, or the end of input) without changing any other PID
1438	/// or the program clock.
1439	fn damage(&mut self, pid: Pid, err: &Error) -> Result<()> {
1440		// Complete AUs ahead of the damaged packet remain valid, including those
1441		// in an unbounded PES. Its final NAL/AU is never flushed at a loss boundary.
1442		if let Some(pending) = self.pending.remove(&pid)
1443			&& let Some(stream @ (Stream::H264 { .. } | Stream::H265 { .. })) = self.streams.get_mut(&pid)
1444		{
1445			let units = stream.write(pending, false)?;
1446			self.published |= units > 0;
1447			self.liveness.delivered(pid.as_u16(), units);
1448			self.record_media_track(pid)?;
1449		}
1450		self.headers.remove(&pid);
1451		match self.streams.get_mut(&pid) {
1452			// Nothing is imported from it, so there is nothing to refuse or report.
1453			Some(Stream::Ignored) => return Ok(()),
1454			Some(stream) => stream.lost()?,
1455			None => {}
1456		}
1457		*self.damaged.entry(pid.as_u16()).or_default() += 1;
1458		self.damage_log.record(pid.as_u16(), err);
1459		Ok(())
1460	}
1461
1462	fn flush(&mut self, pid: Pid) -> Result<()> {
1463		let Some(pending) = self.pending.remove(&pid) else {
1464			return Ok(());
1465		};
1466
1467		self.write_pending(pid, pending)
1468	}
1469
1470	fn write_pending(&mut self, pid: Pid, pending: Pending) -> Result<()> {
1471		let batched = self.has_video;
1472		let Some(stream) = self.streams.get_mut(&pid) else {
1473			return Ok(());
1474		};
1475		let truncated = pending.data_len.is_some_and(|len| pending.data.len() < len);
1476		if truncated && !stream.salvages_partial_pes() {
1477			return self.damage(pid, &malformed!("PES payload truncated before its declared length"));
1478		}
1479
1480		let units = stream.write(pending, batched)?;
1481		if truncated {
1482			if matches!(self.streams.get(&pid), Some(Stream::H264 { .. } | Stream::H265 { .. })) {
1483				self.damage(pid, &malformed!("PES payload truncated before its declared length"))?;
1484			} else {
1485				self.streams.get_mut(&pid).expect("existing route").lost()?;
1486			}
1487		}
1488		self.published |= units > 0;
1489		self.liveness.delivered(pid.as_u16(), units);
1490		if matches!(self.streams.get(&pid), Some(Stream::PesPacket(_))) {
1491			self.release_placed()?;
1492		}
1493
1494		// Record the decoded media track's PID + PMT descriptors (language, ...) once
1495		// its lazily created track exists, so export can preserve them.
1496		self.record_media_track(pid)
1497	}
1498
1499	/// A PCR at input offset `offset`, its packet's, on the program's clock PID: it places every
1500	/// whole PES and section begun since the last, and releases those complete.
1501	fn place_pcr(&mut self, raw: u64, offset: u64) -> Result<()> {
1502		if self.placement.rewinds(raw) {
1503			// The clock stepped back without saying so: what it placed so far is placed by the
1504			// old timebase, and the new one starts here.
1505			self.settle_placement()?;
1506		}
1507		if !self.media_clock {
1508			// PCR and PTS share one era. Advance it from PCR while no media can do so,
1509			// including across a wrap before a later PMT adds a media stream.
1510			self.pts.unwrap(raw / 300);
1511			let ticks = u64::try_from(self.pts.pcr(raw)).map_err(|_| moq_net::TimeOverflow)?;
1512			self.timebase.anchor(Timestamp::from_scale(ticks, PCR_HZ)?)?;
1513			self.initial_reservation = None;
1514		}
1515		let sample = self.placement.pcr(raw, offset + PCR_OFFSET);
1516		let generation = self.placement.generation;
1517		// A PES still assembling its header is bracketed too, so the first PCR past its start
1518		// code places it however many arrive before the header is whole.
1519		let spans = self.pending.values_mut().filter_map(|pending| pending.span.as_mut());
1520		for span in spans.chain(self.headers.values_mut().filter_map(|(span, _)| span.as_mut())) {
1521			span.bracket(generation, sample);
1522		}
1523		for stream in self.streams.values_mut() {
1524			if let Stream::PesPacket(stream) = stream {
1525				stream.bracket(generation, sample);
1526			}
1527		}
1528		for section in self.sections.values_mut() {
1529			section.bracket(generation, sample);
1530		}
1531		self.release_placed()
1532	}
1533
1534	/// End the placement timebase: extrapolate every PES or section begun past its last PCR from its
1535	/// last two, and publish what that places.
1536	fn settle_placement(&mut self) -> Result<()> {
1537		let spans = self.pending.values_mut().filter_map(|pending| pending.span.as_mut());
1538		for span in spans.chain(self.headers.values_mut().filter_map(|(span, _)| span.as_mut())) {
1539			span.settle(&self.placement);
1540		}
1541		for stream in self.streams.values_mut() {
1542			if let Stream::PesPacket(stream) = stream {
1543				stream.settle(&self.placement);
1544			}
1545		}
1546		for section in self.sections.values_mut() {
1547			section.settle(&self.placement);
1548		}
1549		self.placement.reset();
1550		self.release_placed()
1551	}
1552
1553	/// Publish every held PES or section that is placed, once the timebase has its offset.
1554	fn release_placed(&mut self) -> Result<()> {
1555		for (pid, stream) in &mut self.streams {
1556			let Stream::PesPacket(stream) = stream else {
1557				continue;
1558			};
1559			let (units, unplaced) = stream.release(&self.timebase, &self.pts, self.placement.generation)?;
1560			if unplaced > 0 {
1561				*self.unplaced.entry(pid.as_u16()).or_default() += unplaced;
1562			}
1563			self.published |= units > 0;
1564			self.liveness.delivered(pid.as_u16(), units);
1565		}
1566		for (pid, section) in &mut self.sections {
1567			let (units, unplaced) = section.release(&self.timebase, &self.pts, self.placement.generation)?;
1568			if unplaced > 0 {
1569				*self.unplaced.entry(*pid).or_default() += unplaced;
1570			}
1571			self.published |= units > 0;
1572			self.liveness.delivered(*pid, units);
1573		}
1574		Ok(())
1575	}
1576
1577	/// Refuse the undecoded stream on `pid` rather than carry it altered: its track ends with an
1578	/// error and leaves the catalog, and the PID is dropped from here on.
1579	fn refuse(&mut self, pid: Pid, why: &str) -> Result<()> {
1580		self.pending.remove(&pid);
1581		self.headers.remove(&pid);
1582		if let Some(section) = self.retire_section(pid) {
1583			section.abort(moq_net::Error::Unsupported);
1584		}
1585		// MPEG-1/2 video still paces the program once its PES are refused.
1586		let clock = match self.retire_stream(pid) {
1587			Some(stream) => {
1588				let video = stream.video();
1589				stream.abort(moq_net::Error::Unsupported);
1590				video
1591			}
1592			None => false,
1593		};
1594		self.streams
1595			.insert(pid, if clock { Stream::Clock } else { Stream::Ignored });
1596		*self.refused.entry(pid.as_u16()).or_default() += 1;
1597		tracing::warn!(pid = pid.as_u16(), why, "refused an undecoded stream");
1598		Ok(())
1599	}
1600
1601	/// A TS-scrambled packet or PES-scrambled PES on the carried `pid`: refused, and the unit it
1602	/// interrupts lost with it. The route stays, so the stream resumes once it is clear again.
1603	fn scrambled(&mut self, pid: Pid) -> Result<()> {
1604		self.pending.remove(&pid);
1605		self.headers.remove(&pid);
1606		if let Some(stream) = self.streams.get_mut(&pid) {
1607			stream.lost()?;
1608		}
1609		// A section's continuity counter never sees the packet, so after 16 the next clear one
1610		// would look contiguous and complete the partial with bytes from another section.
1611		if let Some(section) = self.sections.get_mut(&pid.as_u16()) {
1612			section.reassembler = SectionReassembler::default();
1613		}
1614		*self.refused.entry(pid.as_u16()).or_default() += 1;
1615		if self.scrambled.insert(pid.as_u16()) {
1616			tracing::warn!(
1617				pid = pid.as_u16(),
1618				"refusing scrambled payloads; carry the multiplex whole to keep them"
1619			);
1620		}
1621		Ok(())
1622	}
1623
1624	/// The packet chain on `pid` was cut: salvage the truncated PES, and treat the bytes
1625	/// after it as [lost](Stream::lost).
1626	fn broken(&mut self, pid: Pid) -> Result<()> {
1627		self.salvage(pid)?;
1628		if let Some(stream) = self.streams.get_mut(&pid) {
1629			stream.lost()?;
1630		}
1631		Ok(())
1632	}
1633
1634	/// Publish the truncated PES on `pid` only where its bytes stand on their own, and drop
1635	/// whatever is left mid-unit.
1636	fn salvage(&mut self, pid: Pid) -> Result<()> {
1637		if self.headers.remove(&pid).is_some() {
1638			self.damage(pid, &malformed!("PES header truncated by packet loss"))?;
1639		}
1640		if self.streams.get(&pid).is_some_and(Stream::salvages_partial_pes) {
1641			self.flush(pid)
1642		} else {
1643			self.pending.remove(&pid);
1644			self.headers.remove(&pid);
1645			Ok(())
1646		}
1647	}
1648
1649	/// A system time-base discontinuity: the PCR PID declared that the clock every
1650	/// timestamp downstream is measured against restarts here.
1651	///
1652	/// Publish it as a break on every track, which is what carries it across MoQ (an empty
1653	/// group per track) and back out of the exporter as a set `discontinuity_indicator`.
1654	/// Whatever the source does next -- restart at zero, leap half a minute ahead -- is a new
1655	/// timeline rather than the old one continuing, and a consumer that splices the two gets
1656	/// the whole jump as a frame duration.
1657	///
1658	/// Scoped to the PCR PID on purpose. A counter jump (the same flag on an elementary PID,
1659	/// or a gap with no flag at all) loses bytes without moving the clock, and the 33-bit
1660	/// PCR/PTS rollover sets nothing and only moves the next PTS into the next era; neither is
1661	/// a program break and neither reaches here.
1662	fn timebase_break(&mut self) -> Result<()> {
1663		// The bytes still accumulating belong to the old clock, and their continuation is
1664		// stamped on the new one, so cut every PES here rather than splicing across. This
1665		// runs before the marker so a salvaged tail lands in the closing group, which the
1666		// marker closes without guessing an end.
1667		for pid in self.streams.keys().copied().collect::<Vec<_>>() {
1668			self.salvage(pid)?;
1669		}
1670		// Whole PES the old clock began go out on its timeline, ahead of the marker, so none waits
1671		// for a PES on the new one to complete a start code.
1672		for stream in self.streams.values_mut() {
1673			stream.end();
1674		}
1675		self.settle_placement()?;
1676		ensure!(
1677			self.sections.values().all(|section| section.held.is_empty()),
1678			"TS sections reached a clock break without a media timestamp"
1679		);
1680		ensure!(
1681			self.streams.values().all(Stream::placed),
1682			"TS private PES reached a clock break without a media timestamp"
1683		);
1684		for stream in self.streams.values_mut() {
1685			stream.desync();
1686			stream.discontinuity(self.published)?;
1687		}
1688		for section in self.sections.values_mut() {
1689			section.discontinuity(self.published)?;
1690		}
1691		self.last_pts = None;
1692		self.published = false;
1693		self.liveness.discontinuity();
1694		self.si.discontinuity();
1695		self.reset_mux_rate()?;
1696		tracing::debug!("MPEG-TS system time-base discontinuity");
1697		Ok(())
1698	}
1699
1700	/// The program clock changed, so the measured rate no longer holds. A leading flag starts this
1701	/// identity's clock and cannot invalidate a window not begun.
1702	fn reset_mux_rate(&mut self) -> Result<()> {
1703		if !self.mux_rate.started() {
1704			return Ok(());
1705		}
1706		if self.mux_rate.discontinuity() {
1707			self.record_mux_rate()?;
1708		}
1709		Ok(())
1710	}
1711
1712	/// Copy the measured multiplex rate into the `mpegts` section, publishing the
1713	/// catalog. Called only when the measurement changed, so a steady source republishes
1714	/// only when a window sets a new high, ever more rarely.
1715	fn record_mux_rate(&mut self) -> Result<()> {
1716		let rate = self.mux_rate.published();
1717		if let Some(mpegts) = self.catalog.edit()?.ext.mpegts_mut() {
1718			mpegts.mux_rate = rate;
1719		}
1720		Ok(())
1721	}
1722
1723	/// Record a decoded media stream's PID and ES descriptors into `mpegts.tracks`,
1724	/// once per track. No-op without the `mpegts` section, before the track exists,
1725	/// or for verbatim streams (which self-register).
1726	fn record_media_track(&mut self, pid: Pid) -> Result<()> {
1727		if !self.supports_mpegts {
1728			return Ok(());
1729		}
1730		let Some(name) = self.streams.get(&pid).and_then(|s| s.media_track_name()) else {
1731			return Ok(());
1732		};
1733		if self.recorded_media.get(&pid) == Some(&name) {
1734			return Ok(());
1735		}
1736		let descriptors = self.es_descriptors.get(&pid.as_u16()).cloned().unwrap_or_default();
1737		if let Some(mpegts) = self.catalog.edit()?.ext.mpegts_mut() {
1738			// A format change moved the PID to a new track, whose entry replaces the ended one's.
1739			if let Some(previous) = self.recorded_media.get(&pid) {
1740				mpegts.tracks.remove(previous);
1741			}
1742			let entry = mpegts
1743				.tracks
1744				.entry(name.clone())
1745				.or_insert_with(|| catalog::Track::new(pid.as_u16()));
1746			entry.pid = pid.as_u16();
1747			entry.descriptors = descriptors;
1748		}
1749		self.recorded_media.insert(pid, name);
1750		Ok(())
1751	}
1752
1753	/// Pick the imported program from a whole PAT and learn its PMT PID, so `decode`
1754	/// reassembles that PMT and no other. A PAT naming another PID for the program moves the
1755	/// reassembler there, and the catalog's `program.pmtPid` with it.
1756	///
1757	/// Every PAT is checked, so a program added mid-stream ends an unselected import, a
1758	/// selected program that disappears ends a selected one; media already published stays. A
1759	/// PAT naming the program under another identity never reaches a [`decode`](Self::decode),
1760	/// which restarts at it, so only an import reading one program of several refuses it.
1761	pub(super) fn handle_pat(&mut self, pat: &psi::Pat) -> Result<()> {
1762		let Some((entry, alone)) = select(self.program, pat)? else {
1763			return Ok(());
1764		};
1765		let identity = (pat.transport_stream_id, entry.program_number);
1766		if let Some((transport_stream_id, program_number)) = self.identity
1767			&& (transport_stream_id, program_number) != identity
1768		{
1769			bail_unsupported!(
1770				"the PAT changed the program's identity from transport_stream_id {transport_stream_id} program {program_number} to transport_stream_id {} program {}, which the carried service information does not describe",
1771				identity.0,
1772				identity.1
1773			);
1774		}
1775		let first = self.identity.replace(identity).is_none();
1776		self.health.pmt_pids(&[entry.pmt_pid.as_u16()], self.health.now());
1777		let moved = self.pmt.as_ref().is_none_or(|(pid, _)| *pid != entry.pmt_pid);
1778		if moved {
1779			if let Some((from, _)) = &self.pmt {
1780				tracing::info!(
1781					program = entry.program_number,
1782					from = from.as_u16(),
1783					to = entry.pmt_pid.as_u16(),
1784					"TS PMT moved to another PID"
1785				);
1786			}
1787			// A section begun on the old PID no longer speaks for the program.
1788			self.pmt = Some((entry.pmt_pid, SectionReassembler::default()));
1789			self.claims_changed = true;
1790		}
1791		// Alongside another program, a PID could be that program's.
1792		self.alone = alone;
1793		if first || moved {
1794			self.record_program_identity(pat.transport_stream_id, &entry)?;
1795		}
1796		Ok(())
1797	}
1798
1799	/// Capture the transport/service identity (TSID, service number, PMT PID) from the
1800	/// PAT into the catalog service record. No-op without `mpegts` support.
1801	fn record_program_identity(&mut self, transport_stream_id: u16, entry: &psi::Association) -> Result<()> {
1802		if !self.supports_mpegts {
1803			return Ok(());
1804		}
1805		if let Some(mpegts) = self.catalog.edit()?.ext.mpegts_mut() {
1806			let program = mpegts.program.get_or_insert_with(Default::default);
1807			program.transport_stream_id = transport_stream_id;
1808			program.program_number = entry.program_number;
1809			program.pmt_pid = entry.pmt_pid.as_u16();
1810		}
1811		Ok(())
1812	}
1813
1814	fn finish_stream(&mut self, pid: Pid) -> Result<u64> {
1815		match self.streams.get_mut(&pid) {
1816			Some(stream) => stream.finish(),
1817			None => Ok(0),
1818		}
1819	}
1820
1821	/// Flush any buffered PES, finish every track, and return the [`Finished`] import.
1822	///
1823	/// Input held while a step was judged is read first, failing with
1824	/// [`Restarted`](Error::Restarted) if it reaches one, since this import would drop the
1825	/// broadcast after it. A step [`decode`](Self::decode) already reported ends the identity
1826	/// there instead. A finish that fails aborts every track with the cause, so it can't be
1827	/// retried.
1828	pub fn finish(mut self) -> Result<Finished<E>> {
1829		self.finish_in_place()?;
1830		Ok(Finished { import: self })
1831	}
1832
1833	/// [`finish`](Self::finish) for an owner that keeps the importer, as
1834	/// [`Programs`](super::Programs) keeps each program's. A finish that fails returns the cause to
1835	/// every later call; one that succeeded does nothing when called again.
1836	pub(super) fn finish_in_place(&mut self) -> Result<()> {
1837		match &self.input {
1838			crate::container::Input::Open => {}
1839			crate::container::Input::Finished => return Ok(()),
1840			crate::container::Input::Refused(err) | crate::container::Input::Failed(err) => {
1841				return Err(err.clone().into());
1842			}
1843		}
1844		let result = self.end();
1845		match &result {
1846			Ok(()) => self.input = crate::container::Input::Finished,
1847			Err(err) => self.fail(err.clone().into()),
1848		}
1849		result
1850	}
1851
1852	/// Flush the input and finish every track, stopping at the first failure.
1853	fn end(&mut self) -> Result<()> {
1854		// A step still being judged never completed: what it held routes as read. A step that
1855		// routing reaches fails the finish rather than drop the broadcast after it; `Republish`
1856		// settles first, so it republishes that broadcast instead.
1857		if let Some(restart) = self.settle()? {
1858			return Err(Error::Restarted(restart.step));
1859		}
1860		self.demux.finish();
1861		for pid in self.headers.keys().copied().collect::<Vec<_>>() {
1862			self.damage(pid, &malformed!("PES header truncated at end of input"))?;
1863		}
1864		let pids: Vec<Pid> = self.pending.keys().copied().collect();
1865		for pid in pids {
1866			self.flush(pid)?;
1867		}
1868		for stream in self.streams.values_mut() {
1869			stream.end();
1870		}
1871		self.settle_placement()?;
1872		ensure!(
1873			self.sections.values().all(|section| section.held.is_empty()),
1874			"TS sections reached end of input without a media timestamp"
1875		);
1876		ensure!(
1877			self.streams.values().all(Stream::placed),
1878			"TS private PES reached end of input without a media timestamp"
1879		);
1880		// EOF releases the decoder reservations of a short source.
1881		self.initial_reservation = None;
1882		for pid in self.streams.keys().copied().collect::<Vec<_>>() {
1883			let units = self.finish_stream(pid)?;
1884			self.published |= units > 0;
1885			self.liveness.delivered(pid.as_u16(), units);
1886			self.record_media_track(pid)?;
1887		}
1888		for section in self.sections.values_mut() {
1889			section.finish()?;
1890		}
1891		self.si.finish(self.last_pts.unwrap_or(Timestamp::ZERO))?;
1892		Ok(())
1893	}
1894
1895	/// Snapshot what every elementary stream has delivered, the audio frame sync lost on the
1896	/// way, damaged units refused, and the PAT and PMT sections dropped for a bad CRC.
1897	///
1898	/// Cheap: it reads counters the demuxer already keeps, so a caller can poll it per
1899	/// chunk and report the delta.
1900	pub fn stats(&self) -> stats::Snapshot {
1901		let mut streams = self.retired_stats.clone();
1902		let routes = self
1903			.streams
1904			.iter()
1905			.filter_map(|(pid, stream)| Some((pid.as_u16(), stream.stats()?)))
1906			.chain(
1907				self.sections
1908					.keys()
1909					.map(|&pid| (pid, stats::Stream::new(".ts", stats::Class::Data))),
1910			);
1911		for (pid, current) in routes {
1912			streams
1913				.entry(pid)
1914				.and_modify(|retired| retired.merge(&current))
1915				.or_insert(current);
1916		}
1917		// A dedicated PCR PID routes no stream, so its damage gets a clock-only row.
1918		for (&pid, &damaged) in &self.damaged {
1919			streams
1920				.entry(pid)
1921				.or_insert_with(|| stats::Stream::new("", stats::Class::Data))
1922				.damaged = damaged;
1923		}
1924		// A stream refused before it had a track has no row of its own either, nor does an
1925		// SI PID.
1926		for (&pid, &unplaced) in &self.unplaced {
1927			let track = if catalog::SI_PIDS.contains(&pid) { ".si" } else { "" };
1928			streams
1929				.entry(pid)
1930				.or_insert_with(|| stats::Stream::new(track, stats::Class::Data))
1931				.unplaced = unplaced;
1932		}
1933		for (&pid, &refused) in &self.refused {
1934			streams
1935				.entry(pid)
1936				.or_insert_with(|| stats::Stream::new("", stats::Class::Data))
1937				.refused = refused;
1938		}
1939		self.unclaimed.report(&mut streams, |pid| self.claims_pid(pid));
1940		for (pid, stats) in &mut streams {
1941			(stats.units, stats.quiet) = self.liveness.stream(*pid);
1942		}
1943		let mut stats = stats::Snapshot {
1944			streams,
1945			crc_error: self.crc_errors.values().sum::<u64>() + self.demux.pat_crc_error(),
1946			..Default::default()
1947		};
1948		let mut errors = self.demux.errors().clone();
1949		errors.max(self.health.errors());
1950		errors.report(&mut stats);
1951		stats
1952	}
1953
1954	/// The TR 101 290 counts this program timed, for [`Programs`](super::Programs) to count each
1955	/// PID once.
1956	pub(super) fn errors(&self) -> &super::health::Errors {
1957		self.health.errors()
1958	}
1959
1960	/// PMT sections dropped for a bad CRC per PID.
1961	#[cfg(test)]
1962	pub(super) fn crc_errors(&self) -> &BTreeMap<u16, u64> {
1963		&self.crc_errors
1964	}
1965
1966	/// Abort every track with `err` instead of finishing, so subscribers see the
1967	/// real cause rather than [`moq_net::Error::Dropped`]. Buffered PES is discarded.
1968	/// Consumes the importer.
1969	///
1970	/// Unlike a drop, this leaves the tracks' HLS records to the catalog, whose abort fails them
1971	/// rather than ending them as a complete recording.
1972	pub fn abort(mut self, err: moq_net::Error) {
1973		self.fail(err.into());
1974	}
1975
1976	/// Abort every track with `cause`, which later calls report, and release the catalog: nothing
1977	/// is left to wait for.
1978	pub(super) fn fail(&mut self, cause: crate::Error) {
1979		let err = cause.reason();
1980		self.input = crate::container::Input::Failed(cause);
1981		for stream in std::mem::take(&mut self.streams).into_values() {
1982			stream.abort(err.clone());
1983		}
1984		for section in std::mem::take(&mut self.sections).into_values() {
1985			section.abort(err.clone());
1986		}
1987		let si = std::mem::replace(
1988			&mut self.si,
1989			super::si::Capture::new(self.broadcast.clone(), self.catalog.clone()),
1990		);
1991		si.abort(err);
1992		self.initial_reservation = None;
1993	}
1994}
1995
1996/// A TS import that [finished](Import::finish): every track has ended, and they can still be
1997/// read or aborted, but it takes no more input.
1998///
1999/// Dropping it releases the tracks and their catalog renditions, as dropping the [`Import`] does.
2000///
2001/// ```compile_fail,E0599
2002/// # fn cannot_decode(mut import: moq_mux::container::ts::Finished) {
2003/// import.decode(b"").unwrap();
2004/// # }
2005/// ```
2006#[must_use = "dropping it releases the tracks and their catalog renditions"]
2007pub struct Finished<E: catalog::Catalog = ()> {
2008	import: Import<E>,
2009}
2010
2011impl<E: catalog::Catalog> Finished<E> {
2012	/// What every elementary stream delivered; see [`Import::stats`].
2013	pub fn stats(&self) -> stats::Snapshot {
2014		self.import.stats()
2015	}
2016
2017	/// Abort every track with `err`; see [`Import::abort`]. Readers still draining a track get its
2018	/// clean end instead once every group below its end finished.
2019	pub fn abort(self, err: moq_net::Error) {
2020		self.import.abort(err);
2021	}
2022}
2023
2024impl<E: catalog::Catalog> Drop for Import<E> {
2025	/// End the input unless it already ended.
2026	fn drop(&mut self) {
2027		if matches!(self.input, crate::container::Input::Open)
2028			&& let Err(err) = self.finish_in_place()
2029		{
2030			tracing::warn!(%err, "failed to finish a dropped TS import");
2031		}
2032	}
2033}
2034
2035/// The entry `pat` lists for `program`, or for its only program when none is selected, and
2036/// whether it is the only one. `None` while an unselected PAT lists no program.
2037fn select(program: Option<u16>, pat: &psi::Pat) -> Result<Option<(psi::Association, bool)>> {
2038	// program_number 0 is the network PID association, not a program.
2039	let programs: Vec<_> = pat.programs.iter().filter(|entry| entry.program_number != 0).collect();
2040	let numbers = || programs.iter().map(|entry| entry.program_number).collect::<Vec<_>>();
2041	let entry = match program {
2042		Some(program) => match programs.iter().find(|entry| entry.program_number == program) {
2043			Some(entry) => entry,
2044			None => {
2045				return Err(Error::MissingProgram {
2046					program,
2047					programs: numbers(),
2048				});
2049			}
2050		},
2051		None => match programs.as_slice() {
2052			[] => return Ok(None),
2053			[entry] => entry,
2054			_ => return Err(Error::MultiplePrograms { programs: numbers() }),
2055		},
2056	};
2057	Ok(Some((**entry, programs.len() == 1)))
2058}
2059
2060/// What a PMT says of one elementary stream. A route lasts as long as its PID's listing does.
2061#[derive(Clone, Debug, PartialEq, Eq)]
2062struct Listing {
2063	stream_type: u8,
2064	descriptors: Vec<catalog::Descriptor>,
2065	/// Reassembled as sections: [`section_framed`] under the program descriptors it came with.
2066	sections: bool,
2067}
2068
2069/// Whether a stream of `stream_type` carries sections rather than PES: private sections (0x05),
2070/// the ISO 13818-6 DSM-CC types, each of which rides DSM-CC sections (0x0A multiprotocol
2071/// encapsulation, 0x0B U-N messages and carousels, 0x0C stream descriptors, 0x0D any DSM-CC
2072/// section), and SCTE-35 (0x86) in a program whose descriptors carry the 'CUEI' registration.
2073/// 0x86 is also a DTS audio type, so without it the stream is not read as cues.
2074fn section_framed(stream_type: u8, cuei: bool) -> bool {
2075	matches!(stream_type, 0x05 | 0x0a..=0x0d) || (cuei && stream_type == StreamType::Dts8ChannelLosslessAudio as u8)
2076}
2077
2078// Match the raw TS accumulator's group roll triggers: they bound one program's staged input.
2079pub(super) const STAGING_BYTES_MAX: usize = super::passthrough::GROUP_BYTES_MAX as usize;
2080const STAGING_UNITS_MAX: usize = super::passthrough::GROUP_OBJECTS_MAX;
2081
2082#[derive(Default)]
2083struct Staging {
2084	bytes: AtomicUsize,
2085	units: AtomicUsize,
2086}
2087
2088/// Accounting follows ownership through flush, loss, remapping, and importer drop.
2089struct Retained {
2090	staging: Arc<Staging>,
2091	bytes: usize,
2092	units: usize,
2093}
2094
2095impl Retained {
2096	fn new(staging: Arc<Staging>) -> Self {
2097		Self {
2098			staging,
2099			bytes: 0,
2100			units: 0,
2101		}
2102	}
2103
2104	fn grow(&mut self, bytes: usize, units: usize) -> Result<()> {
2105		let reserve = |used: &AtomicUsize, add: usize, max: usize| {
2106			if add == 0 {
2107				return true;
2108			}
2109			used.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
2110				used.checked_add(add).filter(|&sum| sum <= max)
2111			})
2112			.is_ok()
2113		};
2114		ensure!(
2115			reserve(&self.staging.bytes, bytes, STAGING_BYTES_MAX),
2116			"TS staging exceeds {STAGING_BYTES_MAX} bytes while waiting for a PES boundary or timestamp"
2117		);
2118		if !reserve(&self.staging.units, units, STAGING_UNITS_MAX) {
2119			self.staging.bytes.fetch_sub(bytes, Ordering::Relaxed);
2120			bail!("TS staging exceeds {STAGING_UNITS_MAX} buffered units while waiting for a boundary or timestamp");
2121		}
2122		self.bytes += bytes;
2123		self.units += units;
2124		Ok(())
2125	}
2126
2127	fn resize(&mut self, bytes: usize, units: usize) -> Result<()> {
2128		self.grow(bytes.saturating_sub(self.bytes), units.saturating_sub(self.units))?;
2129		self.staging.bytes.fetch_sub(self.bytes - bytes, Ordering::Relaxed);
2130		self.staging.units.fetch_sub(self.units - units, Ordering::Relaxed);
2131		self.bytes = bytes;
2132		self.units = units;
2133		Ok(())
2134	}
2135
2136	fn take(&mut self, bytes: usize, units: usize) -> Self {
2137		self.bytes -= bytes;
2138		self.units -= units;
2139		Self {
2140			staging: self.staging.clone(),
2141			bytes,
2142			units,
2143		}
2144	}
2145
2146	fn clear(&mut self) {
2147		self.staging.bytes.fetch_sub(self.bytes, Ordering::Relaxed);
2148		self.staging.units.fetch_sub(self.units, Ordering::Relaxed);
2149		self.bytes = 0;
2150		self.units = 0;
2151	}
2152}
2153
2154impl Drop for Retained {
2155	fn drop(&mut self) {
2156		self.clear();
2157	}
2158}
2159
2160/// A reassembled PES packet awaiting routing to its codec importer.
2161struct Pending {
2162	retained: Retained,
2163	/// The unwrapped 90 kHz PTS,
2164	/// before the offset.
2165	pts: Option<u64>,
2166	/// The timebase's offset, which the PTS shifts by onto the catalog clock.
2167	offset: Offset,
2168	/// Raw 90 kHz DTS, still wrapped. Present on reordered (B-frame) video; its distance below
2169	/// the PTS, modulo the wrap, is the reorder delay published as the catalog jitter.
2170	dts: Option<u64>,
2171	/// The payload, or the whole packet, header included, for a [`PesPacketStream`].
2172	data: Vec<u8>,
2173	/// Bytes left in a bounded PES, including `data`, else `None` (unbounded video).
2174	data_len: Option<usize>,
2175	/// Where a whole PES sits on the program clock; `None` for every other stream.
2176	span: Option<Span>,
2177	/// This payload continues the current PES, so audio keeps its next frame timestamp.
2178	continuation: bool,
2179}
2180
2181impl Pending {
2182	/// A PES carrying nothing, used to drain a stream's carried tail at end of stream.
2183	fn empty() -> Self {
2184		Self {
2185			retained: Retained::new(Arc::default()),
2186			pts: None,
2187			offset: Offset::default(),
2188			dts: None,
2189			data: Vec::new(),
2190			data_len: None,
2191			span: None,
2192			continuation: false,
2193		}
2194	}
2195}
2196
2197/// Create a track for an undecoded stream and record `entry`, its carriage record, under its
2198/// name in the `mpegts` catalog section. Shared by the section and whole-PES paths.
2199fn register_verbatim<E: catalog::Catalog>(
2200	broadcast: &mut moq_net::broadcast::Producer,
2201	catalog: &mut crate::catalog::Producer<E>,
2202	entry: catalog::Track,
2203) -> Result<crate::container::Producer<crate::catalog::hang::Wire>> {
2204	// Verbatim payloads ride the legacy container, which normalizes the per-frame
2205	// timestamp to microseconds on the wire (see `hang::container::Frame::encode`),
2206	// so the track declares that timescale to match.
2207	//
2208	// Priority follows text rather than the media tiers: an undecoded elementary
2209	// stream (SCTE-35 cues, teletext, DVB subtitles) is tiny and timing-critical, so
2210	// it should never queue behind a media backlog, and it's too small to starve
2211	// anything by sitting above one.
2212	let track = broadcast.unique_track(".ts", catalog.track_info(hang::catalog::PRIORITY.text));
2213	let name = track.name().to_string();
2214
2215	// Build the media producer before advertising the track. It is fallible (its
2216	// timeline track can collide), and the `VerbatimEntry` that removes this catalog
2217	// entry on drop only exists once this function returns successfully, so an entry
2218	// published first would be stranded.
2219	let media = catalog.media_raw(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data))?;
2220
2221	let mut guard = catalog.edit()?;
2222	let Some(mpegts) = guard.ext.mpegts_mut() else {
2223		// supports_mpegts was true when sampled at construction; None here means the
2224		// catalog dropped the section since.
2225		bail!("catalog extension no longer carries an mpegts section");
2226	};
2227	mpegts.tracks.insert(name, entry);
2228	drop(guard);
2229
2230	Ok(media)
2231}
2232
2233/// Remove a verbatim track's entry from the `mpegts` catalog section on drop.
2234fn unregister_verbatim<E: catalog::Catalog>(catalog: &mut crate::catalog::Producer<E>, name: &str) {
2235	// A closed catalog has nothing left to unregister from.
2236	let Ok(mut catalog) = catalog.edit() else {
2237		return;
2238	};
2239	if let Some(mpegts) = catalog.ext.mpegts_mut() {
2240		mpegts.tracks.remove(name);
2241	}
2242}
2243
2244/// Owns a verbatim track's `mpegts` catalog entry, removing it however the stream ends.
2245struct VerbatimEntry<E: catalog::Catalog> {
2246	catalog: crate::catalog::Producer<E>,
2247	name: String,
2248}
2249
2250impl<E: catalog::Catalog> Drop for VerbatimEntry<E> {
2251	fn drop(&mut self) {
2252		unregister_verbatim(&mut self.catalog, &self.name);
2253	}
2254}
2255
2256/// Publishes reassembled private sections (SCTE-35 and others) as verbatim frames
2257/// on a track described in the `mpegts` catalog section.
2258///
2259/// Private sections (e.g. SCTE-35 table_id 0xFC) are not PES, so this PID is
2260/// intercepted before the mpeg2ts reader (which would PES-parse it and abort).
2261/// The byte-level reassembly lives in [`SectionReassembler`]; this type owns the
2262/// track and catalog entry and places each section on the PCR clock.
2263struct SectionStream<E: catalog::Catalog> {
2264	track: crate::container::Producer<crate::catalog::hang::Wire>,
2265	/// Clears this track's catalog entry on drop.
2266	_entry: VerbatimEntry<E>,
2267	reassembler: SectionReassembler,
2268	/// Sections waiting for the next PCR or the timebase's offset, in input order.
2269	held: VecDeque<Held>,
2270	staging: Arc<Staging>,
2271}
2272
2273impl<E: catalog::Catalog> SectionStream<E> {
2274	fn new(
2275		mut broadcast: moq_net::broadcast::Producer,
2276		mut catalog: crate::catalog::Producer<E>,
2277		pid: u16,
2278		stream_type: u8,
2279		descriptors: Vec<catalog::Descriptor>,
2280	) -> Result<Self> {
2281		let entry = catalog::Track {
2282			pid,
2283			descriptors,
2284			verbatim: Some(catalog::Verbatim::new(stream_type, catalog::Framing::Section)),
2285			pes_packet: None,
2286		};
2287		let track = register_verbatim(&mut broadcast, &mut catalog, entry)?;
2288		let entry = VerbatimEntry {
2289			name: track.name().to_string(),
2290			catalog,
2291		};
2292		Ok(Self {
2293			track,
2294			_entry: entry,
2295			reassembler: SectionReassembler::default(),
2296			held: VecDeque::new(),
2297			staging: Arc::default(),
2298		})
2299	}
2300
2301	/// Reassemble sections, retaining their first byte's placement across PCRs and fragments.
2302	/// Returns how many began before the first PCR and cannot be placed.
2303	fn packet(&mut self, pkt: &[u8], at: u64, placement: &Placement) -> Result<u64> {
2304		let mut completed = Vec::new();
2305		self.reassembler.push_at(pkt, Some((at, placement)), &mut completed);
2306		let mut unplaced = 0;
2307		for (span, section) in completed {
2308			let Some(span) = span else {
2309				unplaced += 1;
2310				continue;
2311			};
2312			let mut retained = Retained::new(self.staging.clone());
2313			retained.grow(section.len(), 1)?;
2314			self.held.push_back(Held {
2315				payload: section,
2316				span,
2317				_retained: retained,
2318			});
2319		}
2320		Ok(unplaced)
2321	}
2322
2323	fn bracket(&mut self, generation: u64, after: Sample) {
2324		for span in self
2325			.reassembler
2326			.span
2327			.iter_mut()
2328			.chain(self.held.iter_mut().map(|held| &mut held.span))
2329		{
2330			span.bracket(generation, after);
2331		}
2332	}
2333
2334	fn settle(&mut self, placement: &Placement) {
2335		for span in self
2336			.reassembler
2337			.span
2338			.iter_mut()
2339			.chain(self.held.iter_mut().map(|held| &mut held.span))
2340		{
2341			span.settle(placement);
2342		}
2343	}
2344
2345	/// Publish sections with the same placement and unplaceable handling as whole PES.
2346	fn release(
2347		&mut self,
2348		timebase: &crate::catalog::Timebase<E>,
2349		pts: &PtsUnwrap,
2350		generation: u64,
2351	) -> Result<(u64, u64)> {
2352		let Some(offset) = timebase.offset() else {
2353			return Ok((0, 0));
2354		};
2355		let (mut published, mut unplaced) = (0, 0);
2356		while let Some(timestamp) = self
2357			.held
2358			.front()
2359			.and_then(|held| held.timestamp(pts, offset, generation))
2360		{
2361			let mut held = self.held.pop_front().expect("a front");
2362			let Some(timestamp) = timestamp else {
2363				unplaced += 1;
2364				continue;
2365			};
2366			adjust_splice(&mut held.payload, offset);
2367			self.track.write(crate::container::Frame {
2368				timestamp,
2369				decode: None,
2370				duration: None,
2371				payload: bytes::Bytes::from(held.payload),
2372				keyframe: true,
2373			})?;
2374			self.track.cut(None)?;
2375			published += 1;
2376		}
2377		Ok((published, unplaced))
2378	}
2379
2380	fn discontinuity(&mut self, published: bool) -> Result<()> {
2381		// The half-reassembled section is stamped with the clock that just ended.
2382		self.reassembler = SectionReassembler::default();
2383		if published {
2384			self.track.discontinuity()?;
2385		}
2386		Ok(())
2387	}
2388
2389	fn finish(&mut self) -> Result<()> {
2390		self.track.end_with(None)?;
2391		Ok(())
2392	}
2393
2394	fn abort(self, err: moq_net::Error) {
2395		self.track.abort(err);
2396	}
2397}
2398
2399/// Shift a SCTE-35 `splice_info_section`'s splice times by `offset`, the shift its media took
2400/// onto the catalog clock.
2401///
2402/// Its `pts_time` fields name the source's PTS base, which nothing downstream can recover once
2403/// the media moved, so the section's `pts_adjustment` (added to every `pts_time`, modulo 2^33)
2404/// absorbs the offset and the `CRC_32` is recomputed. The field is outside the encrypted part, so
2405/// an encrypted section is adjusted alike. Any other section, one too short to be a SCTE-35
2406/// section, or one failing its CRC is left alone.
2407fn adjust_splice(section: &mut [u8], offset: Offset) {
2408	const TABLE_ID: u8 = 0xFC;
2409	const FIELD: i128 = 1 << 33;
2410	// table_id through cw_index, plus the CRC_32: the shortest section carrying the field.
2411	if offset == Offset::default() || section.len() < 14 || section[0] != TABLE_ID {
2412		return;
2413	}
2414	// A corrupt section stays corrupt rather than gaining a CRC that vouches for it.
2415	if psi::CRC.checksum(section) != 0 {
2416		return;
2417	}
2418
2419	// pts_adjustment: the low bit of byte 4, then bytes 5..9.
2420	let field = ((section[4] as u64 & 1) << 32) | u32::from_be_bytes(section[5..9].try_into().unwrap()) as u64;
2421	let adjusted = (field as i128 + offset.ticks(90_000)).rem_euclid(FIELD) as u64;
2422	section[4] = (section[4] & !1) | (adjusted >> 32) as u8;
2423	section[5..9].copy_from_slice(&(adjusted as u32).to_be_bytes());
2424
2425	let body = section.len() - 4;
2426	let crc = psi::CRC.checksum(&section[..body]);
2427	section[body..].copy_from_slice(&crc.to_be_bytes());
2428}
2429
2430/// Publishes each PES of an elementary stream we don't decode (private data, teletext, DVB
2431/// subtitles, DVB AC-3, DTS, ...) whole, as one frame on a track described by a
2432/// [`PesPacket`](catalog::PesPacket) record in the `mpegts` catalog section.
2433///
2434/// A frame is the packet from its start code through its payload, its PTS and DTS moved onto the
2435/// catalog clock and every other byte as received, timestamped with its placement on the program
2436/// clock. A PES without a PTS keeps none. See [`Import`] for when one is held, dropped, or refuses
2437/// its stream.
2438///
2439/// Each PES is a group of its own, except MPEG-1/2 video's: a PES in which a sequence header
2440/// begins opens a group, where a decoder can start, and the pictures after it join that group.
2441/// Those before the first sequence header, or after a loss until the next, are dropped, since
2442/// they depend on pictures a subscriber never gets. A video PES ending in part of a start code
2443/// waits for the next PES on the stream, or for the stream to end, to tell whether a sequence
2444/// header begins in it.
2445struct PesPacketStream<E: catalog::Catalog> {
2446	track: crate::container::Producer<crate::catalog::hang::Wire>,
2447	/// Clears this track's catalog entry on drop.
2448	_entry: VerbatimEntry<E>,
2449	/// The PMT `stream_type`, which says whether an unbounded PES is video.
2450	stream_type: u8,
2451	/// Whole PES waiting for the PCR after them or the timebase's offset, in input order, each
2452	/// with where it falls in the groups.
2453	held: VecDeque<(Held, Join)>,
2454	/// The stream lost a unit since the last PES held, so the next joins no group.
2455	lost: bool,
2456	/// The PES at the back of `held` ends in part of a start code, so whether it opens a group
2457	/// waits for the PES after it; [`Self::release`] stops before it meanwhile.
2458	straddles: bool,
2459}
2460
2461/// Where a whole PES falls in its track's groups.
2462#[derive(Clone, Copy, PartialEq, Eq)]
2463enum Join {
2464	/// It opens a group: every PES of a stream other than MPEG-1/2 video, and one of that video
2465	/// carrying a sequence header.
2466	Opens,
2467	/// It joins the group open before it.
2468	Continues,
2469	/// It follows a loss, so the group before it ends and it is dropped with the PES after it
2470	/// until one opens a group.
2471	Resyncs,
2472}
2473
2474/// A whole PES or section waiting to be placed.
2475struct Held {
2476	payload: Vec<u8>,
2477	span: Span,
2478	/// Held for its `Drop`, which returns the bytes to the staging budget.
2479	_retained: Retained,
2480}
2481
2482impl Held {
2483	/// `None` waits for a PCR; `Some(None)` drops a unit its timebase could not place.
2484	fn timestamp(&self, pts: &PtsUnwrap, offset: Offset, generation: u64) -> Option<Option<Timestamp>> {
2485		match self.span.ticks {
2486			Some(ticks) => Some(placement(pts, offset, ticks)),
2487			None if self.span.generation != generation => Some(None),
2488			None => None,
2489		}
2490	}
2491}
2492
2493impl<E: catalog::Catalog> PesPacketStream<E> {
2494	fn new(
2495		mut broadcast: moq_net::broadcast::Producer,
2496		mut catalog: crate::catalog::Producer<E>,
2497		pid: u16,
2498		stream_type: u8,
2499		descriptors: Vec<catalog::Descriptor>,
2500	) -> Result<Self> {
2501		let entry = catalog::Track {
2502			pid,
2503			descriptors,
2504			verbatim: None,
2505			pes_packet: Some(catalog::PesPacket::new(stream_type)),
2506		};
2507		let track = register_verbatim(&mut broadcast, &mut catalog, entry)?;
2508		let entry = VerbatimEntry {
2509			name: track.name().to_string(),
2510			catalog,
2511		};
2512		Ok(Self {
2513			track,
2514			_entry: entry,
2515			stream_type,
2516			held: VecDeque::new(),
2517			lost: false,
2518			straddles: false,
2519		})
2520	}
2521
2522	/// Hold one complete PES until it can be placed: [`Self::release`] publishes it.
2523	fn hold(&mut self, pending: Pending) {
2524		let span = pending.span.expect("a whole PES is spanned at its start");
2525		let join = match mpeg_video(self.stream_type) {
2526			false => Join::Opens,
2527			true => {
2528				let payload = es_payload(&pending.data);
2529				if std::mem::take(&mut self.straddles) {
2530					let (before, join) = self.held.back_mut().expect("a straddling PES is held");
2531					if straddled_header(es_payload(&before.payload), payload) {
2532						*join = Join::Opens;
2533					}
2534				}
2535				let join = match () {
2536					_ if memchr::memmem::find(payload, &SEQUENCE_HEADER).is_some() => Join::Opens,
2537					_ if self.lost => Join::Resyncs,
2538					_ => Join::Continues,
2539				};
2540				self.straddles = join != Join::Opens && partial_start_code(payload);
2541				join
2542			}
2543		};
2544		self.lost = false;
2545		let held = Held {
2546			payload: pending.data,
2547			span,
2548			_retained: pending.retained,
2549		};
2550		self.held.push_back((held, join));
2551	}
2552
2553	/// The unit in progress was lost: an MPEG-1/2 picture after it may reference it, and no
2554	/// sequence header continues from the PES before it.
2555	fn lost(&mut self) {
2556		self.lost = true;
2557		self.straddles = false;
2558	}
2559
2560	/// No PES follows the last held on its clock, so a start code its end began completes nothing.
2561	fn end(&mut self) {
2562		self.straddles = false;
2563	}
2564
2565	/// The PCR `after` arrived on timebase `generation`: every PES held since the last is
2566	/// bracketed.
2567	fn bracket(&mut self, generation: u64, after: Sample) {
2568		for (held, _) in &mut self.held {
2569			held.span.bracket(generation, after);
2570		}
2571	}
2572
2573	/// The timebase of `placement` ends: extrapolate the PES held past its last PCR.
2574	fn settle(&mut self, placement: &Placement) {
2575		for (held, _) in &mut self.held {
2576			held.span.settle(placement);
2577		}
2578	}
2579
2580	/// Publish the placed PES at the front, grouped as [`Join`] says, once `timebase` has its
2581	/// offset, and drop those no PCR on their own timebase can place: one ended before them, now
2582	/// that `generation` is the timebase running. `pts` is the program's PTS history, which
2583	/// picks each PCR's wrap. Returns how many went each way; a picture no group takes is
2584	/// neither.
2585	fn release(
2586		&mut self,
2587		timebase: &crate::catalog::Timebase<E>,
2588		pts: &PtsUnwrap,
2589		generation: u64,
2590	) -> Result<(u64, u64)> {
2591		let Some(offset) = timebase.offset() else {
2592			return Ok((0, 0));
2593		};
2594		let (mut published, mut unplaced) = (0, 0);
2595		while let Some(timestamp) = self
2596			.held
2597			.front()
2598			.filter(|_| !(self.straddles && self.held.len() == 1))
2599			.and_then(|(held, _)| held.timestamp(pts, offset, generation))
2600		{
2601			let (mut held, join) = self.held.pop_front().expect("a front");
2602			let Some(timestamp) = timestamp else {
2603				unplaced += 1;
2604				continue;
2605			};
2606			rebase(&mut held.payload, offset);
2607			if join == Join::Resyncs {
2608				self.track.cut(None)?;
2609			}
2610			let frame = crate::container::Frame {
2611				timestamp,
2612				decode: None,
2613				duration: None,
2614				payload: bytes::Bytes::from(held.payload),
2615				keyframe: join == Join::Opens,
2616			};
2617			match self.track.write(frame) {
2618				Ok(()) => published += 1,
2619				// A picture with no group open: before the first sequence header, or after a loss.
2620				Err(crate::Error::MissingKeyframe(_)) => continue,
2621				Err(err) => return Err(err.into()),
2622			}
2623			if !mpeg_video(self.stream_type) {
2624				self.track.cut(None)?;
2625			}
2626		}
2627		Ok((published, unplaced))
2628	}
2629
2630	fn discontinuity(&mut self, published: bool) -> Result<()> {
2631		if published {
2632			self.track.discontinuity()?;
2633		}
2634		Ok(())
2635	}
2636
2637	fn finish(&mut self) -> Result<()> {
2638		self.track.end_with(None)?;
2639		Ok(())
2640	}
2641
2642	fn abort(self, err: moq_net::Error) {
2643		self.track.abort(err);
2644	}
2645}
2646
2647/// Why a whole-PES track cannot carry `pes` unaltered, if it cannot: a header export refuses
2648/// ([`PesStart::whole`]), or a clock field only the PTS and DTS of are rebased.
2649fn refusal(pes: &PesStart, stream_type: u8) -> Option<String> {
2650	match pes.whole(stream_type) {
2651		Err(err) => Some(format!("{err:#}")),
2652		Ok(clock) => clock.map(|clock| clock.to_string()),
2653	}
2654}
2655
2656/// The catalog time of the program clock reading `ticks`, a 27 MHz count, on a timebase shifted
2657/// by `offset`: its PCR in the wrap nearest the program's PTS history, floored to microseconds.
2658/// `None` for a reading before the broadcast clock's zero.
2659fn placement(pts: &PtsUnwrap, offset: Offset, ticks: u64) -> Option<Timestamp> {
2660	let pcr = pts.pcr(ticks % PCR_WRAP);
2661	let micros = pcr.div_euclid(i128::from(PCR_HZ / 1_000_000)) + offset.ticks(1_000_000);
2662	Timestamp::from_micros(u64::try_from(micros).ok()?).ok()
2663}
2664
2665/// Move a whole PES's PTS and DTS onto the catalog clock in place, modulo 2^33 as a media PTS
2666/// moves, leaving their prefix and marker bits and every other byte as they were. The PES CRC
2667/// covers the previous packet's data bytes, not this header, so it stays valid.
2668fn rebase(pes: &mut [u8], offset: Offset) {
2669	const FIELD: i128 = 1 << 33;
2670	if offset == Offset::default() || !psi::has_optional_header(pes[3]) {
2671		return;
2672	}
2673	let fields = match pes[7] >> 6 {
2674		0b10 => 1,
2675		0b11 => 2,
2676		_ => 0,
2677	};
2678	for field in pes[9..9 + 5 * fields].as_chunks_mut::<5>().0 {
2679		let value = (u64::from(field[0] >> 1) & 0x07) << 30
2680			| u64::from(field[1]) << 22
2681			| u64::from(field[2] >> 1) << 15
2682			| u64::from(field[3]) << 7
2683			| u64::from(field[4] >> 1);
2684		let value = (i128::from(value) + offset.ticks(90_000)).rem_euclid(FIELD) as u64;
2685		field[0] = (field[0] & 0xf1) | ((value >> 29) & 0x0e) as u8;
2686		field[1] = (value >> 22) as u8;
2687		field[2] = (field[2] & 0x01) | ((value >> 14) & 0xfe) as u8;
2688		field[3] = (value >> 7) as u8;
2689		field[4] = (field[4] & 0x01) | ((value << 1) & 0xfe) as u8;
2690	}
2691}
2692
2693/// The program clock at each input byte, from the PCRs of the current timebase, which places
2694/// whole PES and sections: a byte is interpolated at the rate between the PCRs either side of it, as
2695/// [`Passthrough`](super::Passthrough) times its objects.
2696#[derive(Default)]
2697struct Placement {
2698	/// The last two PCRs of the timebase, newest last, unwrapped from its first.
2699	samples: VecDeque<Sample>,
2700	/// The last PCR, raw.
2701	raw: u64,
2702	/// Counts the timebases ended, so a PES never takes a PCR from one it did not start in.
2703	generation: u64,
2704}
2705
2706impl Placement {
2707	/// A PCR of `raw` 27 MHz ticks whose reference byte sits at input offset `at`.
2708	fn pcr(&mut self, raw: u64, at: u64) -> Sample {
2709		let ticks = match self.samples.back() {
2710			Some(last) => last.ticks + (raw + PCR_WRAP - self.raw) % PCR_WRAP,
2711			None => raw,
2712		};
2713		let sample = Sample { at, ticks };
2714		self.samples.push_back(sample);
2715		if self.samples.len() > 2 {
2716			self.samples.pop_front();
2717		}
2718		self.raw = raw;
2719		sample
2720	}
2721
2722	/// Whether `raw` steps back from the last PCR, modulo the wrap.
2723	fn rewinds(&self, raw: u64) -> bool {
2724		!self.samples.is_empty() && (raw + PCR_WRAP - self.raw) % PCR_WRAP >= PCR_WRAP / 2
2725	}
2726
2727	/// The timebase's last PCR.
2728	fn last(&self) -> Option<Sample> {
2729		self.samples.back().copied()
2730	}
2731
2732	/// A PES or section whose first byte sits at input offset `at`, after the last PCR;
2733	/// `None` before the first.
2734	fn span(&self, at: u64) -> Option<Span> {
2735		Some(Span {
2736			at,
2737			before: self.last()?,
2738			generation: self.generation,
2739			ticks: None,
2740		})
2741	}
2742
2743	/// The program clock at input offset `at`, past the last PCR, at the rate of the interval
2744	/// before it; `None` without one.
2745	fn extrapolate(&self, at: u64) -> Option<u64> {
2746		(self.samples.len() == 2).then(|| locate(at, &self.samples))
2747	}
2748
2749	/// End the timebase.
2750	fn reset(&mut self) {
2751		self.samples.clear();
2752		self.generation += 1;
2753	}
2754}
2755
2756/// Where a PES or section starts in the input, and the program clock there once known.
2757#[derive(Clone, Copy)]
2758struct Span {
2759	/// The input offset of its first byte.
2760	at: u64,
2761	/// The last PCR before it.
2762	before: Sample,
2763	/// The [`Placement::generation`] it started in.
2764	generation: u64,
2765	/// The program clock at its first byte, in its timebase's unwrapped 27 MHz ticks.
2766	ticks: Option<u64>,
2767}
2768
2769impl Span {
2770	/// Interpolate with `after`, the first PCR past it on its timebase.
2771	fn bracket(&mut self, generation: u64, after: Sample) {
2772		if self.ticks.is_none() && self.generation == generation {
2773			self.ticks = Some(locate(self.at, &VecDeque::from([self.before, after])));
2774		}
2775	}
2776
2777	/// Its timebase ended with no PCR after it: extrapolate from the last two.
2778	fn settle(&mut self, placement: &Placement) {
2779		if self.ticks.is_none() && self.generation == placement.generation {
2780			self.ticks = placement.extrapolate(self.at);
2781		}
2782	}
2783}
2784
2785/// Whether a packet's adaptation field sets `discontinuity_indicator`.
2786///
2787/// What that declares depends on the PID: a continuity-counter break on an elementary
2788/// stream, and additionally a system time-base break on the program's PCR PID. It rides an
2789/// adaptation-only packet (a clock packet with no payload) as readily as a payload one.
2790pub(super) fn discontinuity_indicator(pkt: &[u8; 188]) -> bool {
2791	pkt[3] & 0x20 != 0 && pkt[4] > 0 && pkt[5] & 0x80 != 0
2792}
2793
2794/// The PCR a packet's adaptation field carries, in 27 MHz ticks, so below the 2^33 * 300
2795/// wrap. `None` for an extension past 299, which no clock counts to.
2796pub(super) fn pcr(pkt: &[u8; 188]) -> Option<u64> {
2797	if pkt[3] & 0x20 == 0 || pkt[4] < 7 || pkt[5] & 0x10 == 0 {
2798		return None;
2799	}
2800	let base = (u64::from(pkt[6]) << 25)
2801		| (u64::from(pkt[7]) << 17)
2802		| (u64::from(pkt[8]) << 9)
2803		| (u64::from(pkt[9]) << 1)
2804		| (u64::from(pkt[10]) >> 7);
2805	let ext = (u64::from(pkt[10] & 0x01) << 8) | u64::from(pkt[11]);
2806	(ext < 300).then_some(base * 300 + ext)
2807}
2808
2809/// How long each elementary stream has gone without delivering an access unit.
2810///
2811/// Measured on the program clock, the PCR summed interval by interval, so it runs straight
2812/// through the 33-bit wrap, a signalled time-base reset and a corrupt PCR instead of jumping
2813/// with them. Not the media clock: that follows the video PTS, and stops with the very stream
2814/// this catches. [`Export`](super::Export) runs the same meter on the PCR it writes.
2815#[derive(Default)]
2816pub(super) struct Liveness {
2817	/// The last PCR in 27 MHz ticks, forgotten at a reset so no interval spans one.
2818	pcr: Option<u64>,
2819	/// PCR ticks elapsed since the first PCR, if one has arrived.
2820	elapsed: Option<u64>,
2821	/// Per PID: access units delivered, and `elapsed` at the last one, or at registration.
2822	/// Kept per PID rather than per route, so a PMT remap carries it like `retired_stats`.
2823	streams: HashMap<u16, (u64, u64)>,
2824	/// PIDs the PMT stopped listing: their counts stay, but they are not quiet.
2825	retired: HashSet<u16>,
2826}
2827
2828impl Liveness {
2829	/// A PCR arrived on the program's clock PID.
2830	///
2831	/// Stepped one interval at a time, so a corrupt PCR, or the clock stepping back without a
2832	/// flag, costs one interval rather than inventing hours of silence on every PID. The bound
2833	/// is the mux-rate meter's.
2834	pub(super) fn pcr(&mut self, pcr: u64) {
2835		self.step(pcr, super::mux_rate::MAX_INTERVAL);
2836	}
2837
2838	/// A PCR the caller wrote itself. Its clock breaks only where the caller flags a
2839	/// discontinuity, so every forward step counts, including the jump across a media gap
2840	/// longer than the backfill covers.
2841	pub(super) fn written_pcr(&mut self, pcr: u64) {
2842		self.step(pcr, super::mux_rate::PCR_WRAP);
2843	}
2844
2845	fn step(&mut self, pcr: u64, max: u64) {
2846		let elapsed = self.elapsed.get_or_insert(0);
2847		if let Some(last) = self.pcr.replace(pcr) {
2848			let step = (pcr + super::mux_rate::PCR_WRAP - last) % super::mux_rate::PCR_WRAP;
2849			if step <= max {
2850				*elapsed += step;
2851			}
2852		}
2853	}
2854
2855	/// PCR ticks elapsed on the program clock since its first PCR, or `None` before one.
2856	pub(super) fn now(&self) -> Option<u64> {
2857		self.elapsed
2858	}
2859
2860	/// The clock restarted or changed PID: the next interval measures nothing.
2861	pub(super) fn discontinuity(&mut self) {
2862		self.pcr = None;
2863	}
2864
2865	/// The PMT declared `pid`. Its silence counts from here until it delivers.
2866	pub(super) fn register(&mut self, pid: u16) {
2867		let now = self.elapsed.unwrap_or(0);
2868		let entry = self.streams.entry(pid).or_insert((0, now));
2869		if self.retired.remove(&pid) {
2870			entry.1 = now;
2871		}
2872	}
2873
2874	/// The route on `pid` ended. Until a PMT declares it again it is not silent, only gone.
2875	pub(super) fn retire(&mut self, pid: u16) {
2876		if self.streams.contains_key(&pid) {
2877			self.retired.insert(pid);
2878		}
2879	}
2880
2881	/// `pid` delivered `units` access units just now.
2882	pub(super) fn delivered(&mut self, pid: u16, units: u64) {
2883		if units == 0 {
2884			return;
2885		}
2886		let now = self.elapsed.unwrap_or(0);
2887		if let Some((count, last)) = self.streams.get_mut(&pid) {
2888			*count += units;
2889			*last = now;
2890		}
2891	}
2892
2893	/// `pid`'s access units and how long it has been quiet. See [`stats::Stream`].
2894	pub(super) fn stream(&self, pid: u16) -> (u64, Option<std::time::Duration>) {
2895		let Some(&(units, last)) = self.streams.get(&pid) else {
2896			return (0, None);
2897		};
2898		if self.retired.contains(&pid) {
2899			return (units, None);
2900		}
2901		let quiet = self
2902			.elapsed
2903			.map(|now| std::time::Duration::from_nanos((now - last) * 1_000 / 27));
2904		(units, quiet)
2905	}
2906}
2907
2908/// Locks onto the 188-byte packet grid of a TS byte stream.
2909///
2910/// 0x47 is the packet sync byte but also occurs freely in payload (TS has no byte
2911/// stuffing), so a lone 0x47 isn't a boundary.
2912#[derive(Clone, Copy, Default)]
2913pub(super) struct Framer {
2914	/// False until a candidate is confirmed by the next packet's sync byte; once true we
2915	/// stride 188 at a time and trust the per-packet check. Persists across calls so a
2916	/// candidate pending confirmation at a buffer tail is re-confirmed, not trusted blindly.
2917	synced: bool,
2918}
2919
2920impl Framer {
2921	/// Where the next whole packet in `buf` at or after `*off` starts, advancing `*off` past
2922	/// it. `None` once no confirmed packet remains, with `*off` at the first byte the next
2923	/// call still needs.
2924	pub(super) fn next(&mut self, buf: &[u8], off: &mut usize) -> Option<usize> {
2925		while *off + TsPacket::SIZE <= buf.len() {
2926			if self.synced && buf[*off] == 0x47 {
2927				let at = *off;
2928				*off += TsPacket::SIZE;
2929				return Some(at);
2930			}
2931			self.synced = false;
2932			// Scan (SIMD via memchr) for a candidate whose next packet also begins with 0x47,
2933			// confirming the 188 stride before locking onto it. Striding past a false
2934			// candidate would route one bogus packet; jumping a flat 188 instead would only
2935			// re-align on exact multiples and could desync forever.
2936			loop {
2937				let Some(rel) = memchr::memchr(0x47, &buf[*off..]) else {
2938					// No sync byte left: the buffer is junk, drop it.
2939					*off = buf.len();
2940					break;
2941				};
2942				*off += rel;
2943				match buf.get(*off + TsPacket::SIZE) {
2944					// Next packet also starts with a sync byte: lock onto this candidate.
2945					Some(&0x47) => {
2946						self.synced = true;
2947						break;
2948					}
2949					// The byte 188 ahead isn't a sync byte: this 0x47 was payload, keep scanning.
2950					Some(_) => *off += 1,
2951					// Can't confirm yet (candidate is near the buffer tail). Stay unsynced so
2952					// it's re-confirmed next call (with the trailing bytes) instead of trusted.
2953					None => break,
2954				}
2955			}
2956			// Unsynced means the buffer had no confirmable sync byte, or the candidate is
2957			// pending confirmation; either way there's nothing to route until more arrives.
2958			if !self.synced {
2959				return None;
2960			}
2961		}
2962		None
2963	}
2964}
2965
2966/// Reads whole PATs off PID 0: reassembles its sections, drops any whose CRC fails, and
2967/// collects the rest until every section of a version is in.
2968#[derive(Clone, Default)]
2969pub(super) struct PatReader {
2970	sections: SectionReassembler,
2971	table: psi::PatAssembler,
2972}
2973
2974impl PatReader {
2975	/// Consume one packet on PID 0, counting each section dropped for a bad CRC into
2976	/// `crc_error`. Returns the whole PAT if this packet completed one.
2977	pub(super) fn push(&mut self, pkt: &[u8; TsPacket::SIZE], crc_error: &mut u64) -> Option<psi::Pat> {
2978		let mut sections = Vec::new();
2979		self.sections.push(pkt, &mut sections);
2980		let mut pat = None;
2981		for section in sections {
2982			if section.first() != Some(&psi::PAT_TABLE_ID) {
2983				continue;
2984			}
2985			if !psi::crc_ok(&section) {
2986				*crc_error += 1;
2987				tracing::warn!(pid = Pid::PAT, "dropped a PSI section with a bad CRC");
2988				continue;
2989			}
2990			pat = self.table.section(&section).or(pat);
2991		}
2992		pat
2993	}
2994}
2995
2996/// Whether every adaptation field fits inside the length its packet declares, and a PCR
2997/// it carries is one.
2998pub(super) fn adaptation_valid(pkt: &[u8; TsPacket::SIZE]) -> bool {
2999	if pkt[3] & 0x20 == 0 {
3000		return true;
3001	}
3002	// Without payload the adaptation field fills the packet; with payload it leaves a byte.
3003	let length = usize::from(pkt[4]);
3004	if (pkt[3] & 0x10 == 0 && length != 183) || (pkt[3] & 0x10 != 0 && length > 182) {
3005		return false;
3006	}
3007	let Some(field) = pkt.get(5..5 + usize::from(pkt[4])) else {
3008		return false;
3009	};
3010	let Some(&flags) = field.first() else {
3011		return true;
3012	};
3013	if flags & 0x10 != 0 && field.len() >= 7 && pcr(pkt).is_none() {
3014		return false;
3015	}
3016	let mut off =
3017		1 + usize::from(flags & 0x10 != 0) * 6 + usize::from(flags & 0x08 != 0) * 6 + usize::from(flags & 0x04 != 0);
3018	for flag in [0x02, 0x01] {
3019		if flags & flag != 0 {
3020			let Some(&len) = field.get(off) else {
3021				return false;
3022			};
3023			off += 1 + usize::from(len);
3024		}
3025	}
3026	off <= field.len()
3027}
3028
3029/// Where a packet's payload is.
3030pub(super) enum Payload<'a> {
3031	/// Adaptation field only, or reserved `adaptation_field_control`.
3032	None,
3033	Bytes(&'a [u8]),
3034	/// The adaptation field claims to run past the packet.
3035	Malformed,
3036}
3037
3038pub(super) fn payload(pkt: &[u8; TsPacket::SIZE]) -> Payload<'_> {
3039	let afc = (pkt[3] >> 4) & 0x3;
3040	if afc & 0x1 == 0 {
3041		return Payload::None;
3042	}
3043	let off = if afc & 0x2 != 0 { 5 + pkt[4] as usize } else { 4 };
3044	match pkt.get(off..) {
3045		Some([]) => Payload::None,
3046		Some(payload) => Payload::Bytes(payload),
3047		None => Payload::Malformed,
3048	}
3049}
3050
3051/// Byte-level reassembler for MPEG-TS private sections on one PID.
3052///
3053/// Private sections (SCTE-35 table_id 0xFC and others) are not PES. This handles
3054/// pointer_field alignment, sections split across packets (including a 3-byte
3055/// header split, where section_length is not yet known), continuity-counter
3056/// gaps, and adaptation-field discontinuities. Deliberately minimal: just enough to
3057/// recover whole sections verbatim.
3058#[derive(Clone, Default)]
3059pub(super) struct SectionReassembler {
3060	/// Bytes of the section currently being reassembled. Its 3-byte header (and
3061	/// thus section_length) may not all be present yet, so completeness is
3062	/// re-checked as bytes arrive; empty means no section in progress.
3063	acc: Vec<u8>,
3064	/// Placement of the partial section's first byte, bracketed even while it assembles.
3065	span: Option<Span>,
3066	/// Shared with the PES path: a broken chain drops the partial either way.
3067	continuity: Continuity,
3068}
3069
3070impl SectionReassembler {
3071	/// Consume one 188-byte TS packet, appending every completed section to `out`.
3072	pub(super) fn push(&mut self, pkt: &[u8], out: &mut Vec<Vec<u8>>) {
3073		let mut completed = Vec::new();
3074		self.push_at(pkt, None, &mut completed);
3075		out.extend(completed.into_iter().map(|(_, section)| section));
3076	}
3077
3078	fn push_at(&mut self, pkt: &[u8], source: Option<(u64, &Placement)>, out: &mut Vec<(Option<Span>, Vec<u8>)>) {
3079		let pkt: &[u8; 188] = pkt.try_into().expect("section packet must be 188 bytes");
3080		match self.continuity.observe(pkt) {
3081			Continuation::Duplicate => return,
3082			// A packet flagged corrupt takes its own payload down with the partial: this is
3083			// the one case where the packet itself must not be processed.
3084			Continuation::Corrupt => {
3085				self.acc.clear();
3086				return;
3087			}
3088			Continuation::Broken => self.acc.clear(),
3089			Continuation::Contiguous => {}
3090		}
3091
3092		let pusi = pkt[1] & 0x40 != 0;
3093		let payload = match payload(pkt) {
3094			Payload::None => return,
3095			Payload::Bytes(payload) => payload,
3096			// A section can't be found in it, so like a counter gap it costs the partial.
3097			Payload::Malformed => {
3098				self.acc.clear();
3099				return;
3100			}
3101		};
3102
3103		let end = source.map_or(TsPacket::SIZE as u64, |(at, _)| at + TsPacket::SIZE as u64);
3104		if pusi {
3105			// pointer_field: payload[1..1+ptr] is the tail of the section already in
3106			// progress; a fresh section starts at 1+ptr.
3107			let ptr = payload[0] as usize;
3108			if 1 + ptr > payload.len() {
3109				// pointer_field points past the payload: malformed packet. Drop the
3110				// partial and resync at the next PUSI rather than slicing out of bounds
3111				// or treating the bytes as a valid continuation.
3112				self.acc.clear();
3113				return;
3114			}
3115			if !self.acc.is_empty() {
3116				// Complete the section in progress with its tail. With nothing in
3117				// progress (stream just joined, or a reset dropped the partial) these
3118				// bytes are an orphaned fragment, so skip straight to the pointer_field.
3119				self.acc.extend_from_slice(&payload[1..1 + ptr]);
3120				self.drain(out, source, end - (payload.len() - 1 - ptr) as u64);
3121			}
3122			// The pointer_field is a hard section boundary: drop any leftover partial
3123			// and start the section it points to.
3124			self.acc.clear();
3125			self.acc.extend_from_slice(&payload[1 + ptr..]);
3126			self.span = source.and_then(|(_, placement)| placement.span(end - self.acc.len() as u64));
3127			self.drain(out, source, end);
3128		} else if !self.acc.is_empty() {
3129			// Continuation of the section in progress. A non-PUSI packet with nothing
3130			// in progress is unaligned (no pointer_field to resync on), so it is
3131			// ignored until the next PUSI. This keeps us desynced after a gap,
3132			// discontinuity, or corrupt pointer dropped the partial, rather than
3133			// resuming on stray bytes that merely look like a section.
3134			self.acc.extend_from_slice(payload);
3135			self.drain(out, source, end);
3136		}
3137	}
3138
3139	/// Move every complete section out of `acc` into `out`, stopping at the first
3140	/// partial. The 3-byte header (which holds section_length) can itself be split
3141	/// across TS packets, so a short buffer waits for more bytes rather than being
3142	/// dropped. Every complete section is carried verbatim (SCTE-35 and any other
3143	/// private-section table on the PID); only 0xff stuffing is dropped.
3144	fn drain(&mut self, out: &mut Vec<(Option<Span>, Vec<u8>)>, source: Option<(u64, &Placement)>, end: u64) {
3145		loop {
3146			match self.acc.first() {
3147				None => return,
3148				// table_id 0xff is stuffing: the rest of the section area is padding.
3149				Some(&0xff) => {
3150					self.acc.clear();
3151					return;
3152				}
3153				_ => {}
3154			}
3155			if self.acc.len() < 3 {
3156				return;
3157			}
3158			let section_length = (((self.acc[1] & 0x0f) as usize) << 8) | self.acc[2] as usize;
3159			// section_length tops out at 4093 per spec (12-bit field, top 2 bits zero). A
3160			// larger value means we are misparsing garbage, so drop and resync at the next
3161			// pointer_field rather than buffering up to ~4 KB of junk.
3162			if section_length > 4093 {
3163				self.acc.clear();
3164				return;
3165			}
3166			let full = 3 + section_length;
3167			if self.acc.len() < full {
3168				return;
3169			}
3170			out.push((self.span.take(), self.acc.drain(..full).collect()));
3171			self.span = source.and_then(|(_, placement)| placement.span(end - self.acc.len() as u64));
3172		}
3173	}
3174}
3175
3176/// Whether `stream_type` is MPEG-1 or MPEG-2 video, which is carried whole but still paces the
3177/// program like decoded video.
3178fn mpeg_video(stream_type: u8) -> bool {
3179	matches!(stream_type, 0x01 | 0x02)
3180}
3181
3182/// An MPEG-1/2 `sequence_header_code` (ISO 13818-2 6.2.2.1), where a decoder can start. Start
3183/// codes never occur inside coded data, so any match is one.
3184const SEQUENCE_HEADER: [u8; 4] = [0x00, 0x00, 0x01, 0xb3];
3185
3186/// The elementary stream bytes of the whole PES `pes`, after its header.
3187fn es_payload(pes: &[u8]) -> &[u8] {
3188	let header = match pes.get(3) {
3189		Some(&stream_id) if psi::has_optional_header(stream_id) => 9 + usize::from(pes.get(8).copied().unwrap_or(0)),
3190		_ => 6,
3191	};
3192	pes.get(header..).unwrap_or_default()
3193}
3194
3195/// Whether `payload` ends in the first one to three bytes of a start code (`00`, `00 00`, or
3196/// `00 00 01`), which the next PES may complete.
3197fn partial_start_code(payload: &[u8]) -> bool {
3198	matches!(payload, [.., 0x00] | [.., 0x00, 0x00, 0x01])
3199}
3200
3201/// Whether a sequence header begins in `before`'s payload and ends in `after`'s, the next PES
3202/// on the stream.
3203fn straddled_header(before: &[u8], after: &[u8]) -> bool {
3204	let before = &before[before.len().saturating_sub(SEQUENCE_HEADER.len() - 1)..];
3205	let after = &after[..after.len().min(SEQUENCE_HEADER.len() - 1)];
3206	memchr::memmem::find(&[before, after].concat(), &SEQUENCE_HEADER).is_some()
3207}
3208
3209/// One elementary stream's codec importer.
3210enum Stream<E: catalog::Catalog = ()> {
3211	H264 {
3212		split: h264::Split,
3213		assembly: video::Assembly,
3214		import: Box<h264::Import>,
3215	},
3216	H265 {
3217		split: h265::Split,
3218		assembly: video::Assembly,
3219		import: Box<h265::Import>,
3220	},
3221	Aac(Box<AacStream<E>>),
3222	Opus(Box<OpusStream>),
3223	Legacy(Box<LegacyStream<E>>),
3224	/// A codec we don't decode, carried as whole PES (MPEG-1/2 video, LATM AAC, private PES, ...).
3225	PesPacket(Box<PesPacketStream<E>>),
3226	/// MPEG-1/2 video this import refused to carry, kept only to advance the media clock.
3227	/// [`Self::video`] counts it, so never reuse this variant for audio or data.
3228	Clock,
3229	Ignored,
3230}
3231
3232impl<E: catalog::Catalog> Stream<E> {
3233	/// Route one reassembled PES, returning how many access units it published.
3234	fn write(&mut self, pending: Pending, batched: bool) -> Result<u64> {
3235		match self {
3236			Stream::H264 {
3237				split,
3238				assembly,
3239				import,
3240			} => {
3241				assembly.push(pending)?;
3242				video::avc(split, import, assembly, false)
3243			}
3244			Stream::H265 {
3245				split,
3246				assembly,
3247				import,
3248			} => {
3249				assembly.push(pending)?;
3250				video::hevc(split, import, assembly, false)
3251			}
3252			Stream::Aac(stream) => stream.write(pending, batched),
3253			Stream::Opus(stream) => stream.write(pending),
3254			Stream::Legacy(stream) => stream.write(pending),
3255			// Published once placed: [`Import::release_placed`].
3256			Stream::PesPacket(stream) => {
3257				stream.hold(pending);
3258				Ok(0)
3259			}
3260			Stream::Clock | Stream::Ignored => Ok(0),
3261		}
3262	}
3263
3264	/// Whether this is the program's video, decoded or not, whose pictures pace the program.
3265	fn video(&self) -> bool {
3266		match self {
3267			Stream::H264 { .. } | Stream::H265 { .. } | Stream::Clock => true,
3268			Stream::PesPacket(stream) => mpeg_video(stream.stream_type),
3269			_ => false,
3270		}
3271	}
3272
3273	/// Whether nothing waits to be placed on the program clock.
3274	fn placed(&self) -> bool {
3275		match self {
3276			Stream::PesPacket(stream) => stream.held.is_empty(),
3277			_ => true,
3278		}
3279	}
3280
3281	/// Whether a PES cut short by a break is still worth publishing.
3282	///
3283	/// True where codec framing proves complete units ahead of the cut. A video
3284	/// assembler publishes only pictures closed by a following codec boundary;
3285	/// its unconfirmed tail is discarded by `lost`. Verbatim PES are all-or-nothing.
3286	fn salvages_partial_pes(&self) -> bool {
3287		match self {
3288			Stream::Aac(_) | Stream::Legacy(_) | Stream::H264 { .. } | Stream::H265 { .. } => true,
3289			// Opus carries many packets per PES like the audio above, but its framing is
3290			// declared rather than self-describing: a trailing packet cut short of the length
3291			// its control header promises is a parse error, and that error would travel up out
3292			// of `decode` and end the session. Losing the PES beats losing the broadcast.
3293			Stream::Opus(_) => false,
3294			Stream::PesPacket(_) => false,
3295			Stream::Clock | Stream::Ignored => false,
3296		}
3297	}
3298
3299	/// Sync was lost: drop whatever partial unit is held and stop vouching for the next
3300	/// boundary, for a break the stream recovers from in place.
3301	fn desync(&mut self) {
3302		match self {
3303			Stream::H264 { split, assembly, .. } => {
3304				split.reset();
3305				assembly.reset();
3306			}
3307			Stream::H265 { split, assembly, .. } => {
3308				split.reset();
3309				assembly.reset();
3310			}
3311			Stream::Aac(stream) => stream.desync(),
3312			Stream::Legacy(stream) => stream.desync(),
3313			Stream::Opus(_) | Stream::PesPacket(_) | Stream::Clock | Stream::Ignored => {}
3314		}
3315	}
3316
3317	/// Bytes were lost mid-stream: [`desync`](Self::desync), and close the open video group
3318	/// where its content stops. Every picture until the next keyframe may reference what was
3319	/// lost, so the producer refuses them until a keyframe opens the next group. Left open,
3320	/// the group would close a GOP later at that keyframe, with an end past its content.
3321	fn lost(&mut self) -> Result<()> {
3322		// An audio group closes at its last intact frame, so recovered frames open a fresh group
3323		// rather than join the audio from before the loss.
3324		match self {
3325			Stream::Aac(stream) => stream.close_group()?,
3326			Stream::Legacy(stream) => stream.close_group()?,
3327			Stream::Opus(stream) => stream.close_group()?,
3328			_ => {}
3329		}
3330		self.desync();
3331		match self {
3332			Stream::H264 { import, .. } => import.cut(None)?,
3333			Stream::H265 { import, .. } => import.cut(None)?,
3334			Stream::PesPacket(stream) => stream.lost(),
3335			_ => {}
3336		}
3337		Ok(())
3338	}
3339
3340	/// No PES follows the last on this clock or input: see [`PesPacketStream::end`].
3341	fn end(&mut self) {
3342		if let Stream::PesPacket(stream) = self {
3343			stream.end();
3344		}
3345	}
3346
3347	/// The program clock restarted: mark the break on this track.
3348	fn discontinuity(&mut self, published: bool) -> Result<()> {
3349		match self {
3350			Stream::H264 { import, .. } => {
3351				if published {
3352					import.discontinuity()?;
3353				}
3354				Ok(())
3355			}
3356			Stream::H265 { import, .. } => {
3357				if published {
3358					import.discontinuity()?;
3359				}
3360				Ok(())
3361			}
3362			Stream::Aac(stream) => stream.discontinuity(published),
3363			Stream::Opus(stream) => stream.discontinuity(published),
3364			Stream::Legacy(stream) => stream.discontinuity(published),
3365			Stream::PesPacket(stream) => stream.discontinuity(published),
3366			Stream::Clock | Stream::Ignored => Ok(()),
3367		}
3368	}
3369
3370	/// Finish the track, returning the access units a drained tail published.
3371	fn finish(&mut self) -> Result<u64> {
3372		match self {
3373			// Only the self-describing audio holds a frame back for a successor to confirm.
3374			Stream::Aac(stream) => return stream.finish(),
3375			Stream::Legacy(stream) => return stream.finish(),
3376			// No input follows: drain the clean tail, then release the splitter and
3377			// assembler outright, including the parameter caches a loss reset keeps.
3378			Stream::H264 {
3379				split,
3380				assembly,
3381				import,
3382			} => {
3383				let published = video::avc(split, import, assembly, true)?;
3384				*split = Default::default();
3385				assembly.finish();
3386				import.finish_in_place()?;
3387				return Ok(published);
3388			}
3389			Stream::H265 {
3390				split,
3391				assembly,
3392				import,
3393			} => {
3394				let published = video::hevc(split, import, assembly, true)?;
3395				*split = Default::default();
3396				assembly.finish();
3397				import.finish_in_place()?;
3398				return Ok(published);
3399			}
3400			Stream::Opus(stream) => stream.finish()?,
3401			Stream::PesPacket(stream) => stream.finish()?,
3402			Stream::Clock | Stream::Ignored => {}
3403		}
3404		Ok(0)
3405	}
3406
3407	fn abort(self, err: moq_net::Error) {
3408		match self {
3409			Stream::H264 { import, .. } => import.abort(err),
3410			Stream::H265 { import, .. } => import.abort(err),
3411			Stream::Aac(stream) => stream.abort(err),
3412			Stream::Opus(stream) => stream.abort(err),
3413			Stream::Legacy(stream) => stream.abort(err),
3414			Stream::PesPacket(stream) => stream.abort(err),
3415			Stream::Clock | Stream::Ignored => {}
3416		}
3417	}
3418
3419	/// Whether the stream's PTS keeps a cadence `PTS_error` grades. Verbatim streams with none
3420	/// (SCTE-35, DVB subtitles) are left ungraded rather than watched against an invented one.
3421	fn cadenced(&self) -> bool {
3422		self.video() || !matches!(self, Stream::PesPacket(_) | Stream::Ignored)
3423	}
3424
3425	/// This route's track and the frame sync it has lost (only the self-describing audio
3426	/// codecs scan for it), or `None` for a PID that is dropped rather than carried.
3427	fn stats(&self) -> Option<stats::Stream> {
3428		Some(match self {
3429			Stream::Aac(stream) => stream.resync.stats(),
3430			Stream::Legacy(stream) => stream.resync.stats(),
3431			Stream::H264 { .. } => stats::Stream::new(".avc3", stats::Class::Video),
3432			Stream::H265 { .. } => stats::Stream::new(".hev1", stats::Class::Video),
3433			Stream::Opus(_) => stats::Stream::new(".opus", stats::Class::Audio),
3434			Stream::PesPacket(stream) => match mpeg_video(stream.stream_type) {
3435				true => stats::Stream::new(".ts", stats::Class::Video),
3436				false => stats::Stream::new(".ts", stats::Class::Data),
3437			},
3438			Stream::Clock => stats::Stream::new("", stats::Class::Video),
3439			Stream::Ignored => return None,
3440		})
3441	}
3442
3443	/// The MoQ track name of a decoded media stream, once its (lazily created) track
3444	/// exists. `None` for verbatim/clock/ignored streams (verbatim self-registers).
3445	fn media_track_name(&self) -> Option<String> {
3446		match self {
3447			Stream::H264 { import, .. } => Some(import.name().to_string()),
3448			Stream::H265 { import, .. } => Some(import.name().to_string()),
3449			Stream::Aac(stream) => stream.import.as_ref().map(|i| i.name().to_string()),
3450			Stream::Opus(stream) => Some(stream.import.name().to_string()),
3451			Stream::Legacy(stream) => stream.import.as_ref().map(|i| i.name().to_string()),
3452			Stream::PesPacket(_) | Stream::Clock | Stream::Ignored => None,
3453		}
3454	}
3455}
3456
3457/// Tracks how far a self-describing audio stream has scanned without finding a frame.
3458///
3459/// A frame header that doesn't parse means sync was lost: a damaged byte, a dropped PES,
3460/// or a splice (a looping file wraps mid-frame). The stream scans to the next sync-word
3461/// candidate and resumes, so a few lost milliseconds of audio stay a gap in one track
3462/// rather than an error that takes the whole session down.
3463///
3464/// A scanned candidate is not trusted on its own. Sync words are short enough to occur by
3465/// chance in compressed payload (a valid-looking MP2 header turns up about every 25 KiB of
3466/// random bytes, an ADTS one every 5 KiB), so a candidate is only accepted once a second
3467/// header parses exactly where the frame it declares ends. Without that the scan would
3468/// publish payload bytes as audio, and worse, each false positive would reset the budget
3469/// below and keep a stream that never really parses scanning forever.
3470///
3471/// A frame joined out of a carried tail is confirmed the same way, even though the previous
3472/// frame vouched for where that tail begins. What it vouched for is the boundary, not the
3473/// bytes the next PES supplies, and a splice joins two unrelated halves whose seam a header
3474/// alone can't see. See [`needs_confirmation`](Self::needs_confirmation).
3475///
3476/// The budget is what keeps that from failing silently. A PID whose frames never parse
3477/// (a PMT declaring a stream type the payload doesn't match) would otherwise scan
3478/// forever, publishing nothing and holding its catalog reservation open, which withholds
3479/// the catalog for every other track. Past the budget the parse error propagates, so a
3480/// stream that is simply the wrong codec still fails the way it always has.
3481struct Resync {
3482	/// Elementary stream PID, for the log line and the [`stats::Snapshot`] key.
3483	pid: u16,
3484	/// Bytes discarded since the last frame was emitted.
3485	discarded: usize,
3486	/// Whether the next frame comes from a scan rather than the previous frame's end, and
3487	/// so has to be confirmed before it can be published.
3488	unconfirmed: bool,
3489	/// End of stream: nothing more can arrive to confirm anything, so publish what parses
3490	/// rather than drop a frame that is whole.
3491	draining: bool,
3492	/// Cumulative counters, published through [`Import::stats`]. Kept beside the scanner
3493	/// because it is the only thing that knows a scan happened; `discarded` above is the
3494	/// in-progress scan and is folded in here once it is spent.
3495	stats: stats::Stream,
3496}
3497
3498impl Resync {
3499	fn new(pid: u16, track: &'static str) -> Self {
3500		Self {
3501			pid,
3502			discarded: 0,
3503			// A stream starts unconfirmed for the same reason a scan does: nothing has
3504			// vouched for the boundary yet. A capture joins mid-stream, so the first PES
3505			// routed to a PID can open in the middle of a frame, and a chance header there
3506			// would publish payload as audio and take the track's sample rate and channel
3507			// count from it for the life of the broadcast.
3508			unconfirmed: true,
3509			draining: false,
3510			stats: stats::Stream::new(track, stats::Class::Audio),
3511		}
3512	}
3513
3514	/// Roughly a second of audio at the highest legacy bitrate: orders of magnitude more
3515	/// than the one or two frames a damaged header costs, and short enough that a stream
3516	/// that never parses fails while its capture is still on screen.
3517	const BUDGET: usize = 64 * 1024;
3518
3519	/// Where to resume after the header at `offset` failed to parse, discarding what is
3520	/// skipped.
3521	///
3522	/// The offset it picks is only a candidate: the caller confirms it by parsing a header
3523	/// there and comes back here if that fails too. That mirrors how the TS layer
3524	/// reacquires packet alignment, where a lone sync byte is a guess until the next
3525	/// packet confirms it.
3526	///
3527	/// `offset` must leave room for a header, which is the loop condition at both call
3528	/// sites; the scan starts one byte past it, since a header just failed to parse there.
3529	fn recover(&mut self, data: &[u8], offset: usize, codec: &SyncWord) -> Recover {
3530		self.unconfirmed = true;
3531		if let Some(rel) = memchr::memchr(codec.sync_byte, &data[offset + 1..]) {
3532			let found = offset + 1 + rel;
3533			self.discarded += found - offset;
3534			return Recover::At(found);
3535		}
3536		// No candidate left, so only a partial sync word can remain: keep that much for
3537		// the next PES (the word can straddle the boundary) and discard the rest.
3538		let keep = data.len().saturating_sub(codec.min_header_len - 1).max(offset);
3539		self.discarded += keep - offset;
3540		Recover::Carry(keep)
3541	}
3542
3543	/// Give up once a stream has scanned further than [`BUDGET`](Self::BUDGET) without
3544	/// emitting a frame.
3545	fn exhausted(&self) -> bool {
3546		self.discarded > Self::BUDGET
3547	}
3548
3549	/// Whether the offset itself is one nothing has vouched for, which is true from a scan
3550	/// (or the start of a stream, or a discontinuity) until the frame it found is published.
3551	fn unconfirmed(&self) -> bool {
3552		self.unconfirmed
3553	}
3554
3555	/// Whether the frame at the current offset has to be confirmed by a header where it ends
3556	/// before it can be published. Beyond an unconfirmed offset, that covers a frame
3557	/// beginning in a carried tail: the previous frame vouched for where the tail starts, but
3558	/// nothing vouches for the bytes joined onto it, and at a splice the two halves are
3559	/// unrelated. Confirming only these keeps the cost off the common path, since a frame
3560	/// that begins inside a PES is whole by the time it is parsed.
3561	fn needs_confirmation(&self, in_tail: bool) -> bool {
3562		!self.draining && (self.unconfirmed || in_tail)
3563	}
3564
3565	/// A frame was published, so the stream is back in sync: the next frame starts where
3566	/// this one ended and needs no confirmation of its own.
3567	///
3568	/// `unvouched` says nothing confirmed this frame's boundary, which only happens while
3569	/// draining at end of stream. It is the one case where recovery substitutes audio
3570	/// instead of leaving a gap, so it is counted apart from a resync.
3571	fn published(&mut self, unvouched: bool) {
3572		if self.discarded > 0 {
3573			self.stats.discarded += self.discarded as u64;
3574			// Only a confirmed frame proves that the stream regained sync. The EOF drain
3575			// can publish an unvouched candidate, but that is a substitution rather than a
3576			// completed resync.
3577			if !unvouched {
3578				self.stats.resyncs += 1;
3579				tracing::warn!(
3580					pid = self.pid,
3581					track = self.stats.track,
3582					discarded = self.discarded,
3583					resyncs = self.stats.resyncs,
3584					"audio stream lost frame sync and resynced"
3585				);
3586			}
3587		}
3588		self.stats.unconfirmed += u64::from(unvouched);
3589		self.discarded = 0;
3590		self.unconfirmed = false;
3591	}
3592
3593	/// The counters an operator alarms on. See [`stats::Snapshot`].
3594	fn stats(&self) -> stats::Stream {
3595		let mut stats = self.stats.clone();
3596		stats.discarded += self.discarded as u64;
3597		stats
3598	}
3599
3600	/// Undo the scanning charged since `discarded`. Those bytes turned out to be retained
3601	/// rather than discarded, and charging for bytes we keep would fail a large frame that
3602	/// legitimately arrives over many small PES.
3603	fn refund(&mut self, discarded: usize) {
3604		self.discarded = discarded;
3605	}
3606
3607	/// A discontinuity: whatever vouched for the next boundary no longer applies, so the
3608	/// frame after it has to be confirmed again.
3609	///
3610	/// The budget resets too. It measures how long *this* run of the stream has gone without
3611	/// a frame, and a discontinuity ends that run: carrying the count over would fail a
3612	/// perfectly good stream on its first parse failure after it moved past the damage.
3613	fn desynced(&mut self) {
3614		// A scan in flight is abandoned rather than completed, so the bytes it discarded
3615		// still count while the resync it belongs to does not.
3616		self.stats.discarded += self.discarded as u64;
3617		self.unconfirmed = true;
3618		self.discarded = 0;
3619	}
3620
3621	/// End of stream. Nothing more can arrive to confirm the carried tail, so take it as-is
3622	/// rather than drop a frame that is whole and parses.
3623	fn drain(&mut self) {
3624		self.unconfirmed = false;
3625		self.draining = true;
3626	}
3627}
3628
3629/// Where a stream picks up after losing frame sync. See [`Resync::recover`].
3630enum Recover {
3631	/// Try to parse a frame header at this offset.
3632	At(usize),
3633	/// Nothing else in this buffer can start a frame; carry from this offset into the
3634	/// next PES.
3635	Carry(usize),
3636}
3637
3638/// A candidate passed over for declaring a frame longer than the buffer holds, kept in case
3639/// nothing later in the buffer confirms.
3640///
3641/// Restoring it has to undo the scan that followed: its bytes end up retained rather than
3642/// discarded, and it still belongs to the tail its timestamp was derived from.
3643struct Fallback {
3644	offset: usize,
3645	discarded: usize,
3646	pts: Option<Timestamp>,
3647	pes: PesStarts,
3648}
3649
3650/// Where each PES begins in an audio buffer, oldest first, while no frame has taken its PTS:
3651/// the first frame beginning at or past a start takes it (ISO 13818-1).
3652///
3653/// A start at the same offset as the last replaces it, since a PES holding no bytes has no
3654/// frame to time, so the count stays within the buffer's bytes.
3655#[derive(Clone, Default)]
3656struct PesStarts(VecDeque<(usize, Option<Timestamp>)>);
3657
3658impl PesStarts {
3659	/// A PES with PTS `pts` begins at `at`.
3660	fn begin(&mut self, at: usize, pts: Option<Timestamp>) {
3661		if self.0.back().is_some_and(|&(last, _)| last == at) {
3662			self.0.pop_back();
3663		}
3664		self.0.push_back((at, pts));
3665	}
3666
3667	/// The PTS for a frame beginning at `offset`, when it is the first to begin in its PES.
3668	fn reach(&mut self, offset: usize) -> Option<Option<Timestamp>> {
3669		let mut pts = None;
3670		while let Some(&(at, base)) = self.0.front()
3671			&& at <= offset
3672		{
3673			pts = Some(base);
3674			self.0.pop_front();
3675		}
3676		pts
3677	}
3678
3679	/// A resync abandoned the carried tail for `next`, whose bytes may still be the tail's: the
3680	/// candidate there takes the earliest PTS left, or that of its PES if later.
3681	fn abandon(&mut self, next: usize) -> Option<Option<Timestamp>> {
3682		self.reach(next).or_else(|| self.0.pop_front().map(|(_, base)| base))
3683	}
3684
3685	/// The buffer now starts at `offset`, which every remaining start lies past.
3686	fn cut(&mut self, offset: usize) {
3687		for (at, _) in &mut self.0 {
3688			*at -= offset;
3689		}
3690	}
3691}
3692
3693/// What a resync needs to know about the codec it is scanning for.
3694struct SyncWord {
3695	/// Bytes needed to attempt a header parse.
3696	min_header_len: usize,
3697	/// First byte of the frame sync word.
3698	sync_byte: u8,
3699}
3700
3701impl SyncWord {
3702	/// ADTS: an 11-bit sync of all ones, then at least 7 bytes of header.
3703	const ADTS: Self = Self {
3704		min_header_len: adts::MIN_HEADER_LEN,
3705		sync_byte: 0xFF,
3706	};
3707}
3708
3709impl From<&legacy::Descriptor> for SyncWord {
3710	fn from(descriptor: &legacy::Descriptor) -> Self {
3711		Self {
3712			min_header_len: descriptor.min_header_len,
3713			sync_byte: descriptor.sync_byte,
3714		}
3715	}
3716}
3717
3718/// AAC needs the first ADTS header before it can build a [`aac::Import`]
3719/// (the sample rate and channel layout aren't in the PMT), so creation is
3720/// deferred until the first frame arrives.
3721/// An audio stream's open group. It spans PES until one brings it to a join, closing at that PES's
3722/// end: the transport sends a track's newest group first, so splitting a PES across groups would
3723/// deliver its oldest frames last.
3724#[derive(Default)]
3725struct AudioGroup {
3726	join: crate::container::Join,
3727	/// Where the open group starts and where its last frame stops, while one is open.
3728	open: Option<(Timestamp, Timestamp)>,
3729}
3730
3731impl AudioGroup {
3732	/// A frame from `start` to `end` joined the open group, or opened one.
3733	fn extend(&mut self, start: Timestamp, end: Timestamp) {
3734		let start = self.open.map_or(start, |(start, _)| start);
3735		self.open = Some((start, end));
3736	}
3737
3738	/// Close the open group whatever it holds, returning where its content stops.
3739	fn take(&mut self) -> Option<Timestamp> {
3740		self.open.take().map(|(_, end)| end)
3741	}
3742
3743	/// Close the open group at a PES end once it carries a join, returning where its content stops.
3744	fn fill(&mut self) -> Option<Timestamp> {
3745		let (start, end) = self.open?;
3746		if self.join.full(start, end) { self.take() } else { None }
3747	}
3748
3749	/// At a PES end, close the open group once it carries a join, or whatever it holds after an
3750	/// error, returning where its content stops.
3751	fn close<T>(&mut self, result: &Result<T>) -> Option<Timestamp> {
3752		match result {
3753			Ok(_) => self.fill(),
3754			Err(_) => self.take(),
3755		}
3756	}
3757}
3758
3759struct AacStream<E: CatalogExt = ()> {
3760	import: Option<aac::Import>,
3761	/// The AudioSpecificConfig `import` was built with. A program config element in a later frame
3762	/// must rebuild it exactly.
3763	asc: bytes::Bytes,
3764	/// The ADTS object type, sample rate, and channel configuration `import` was built with. A
3765	/// frame header that changes them starts a new track.
3766	format: (u8, u32, u8),
3767	broadcast: moq_net::broadcast::Producer,
3768	/// Reservation held from the PMT until the first frame builds the importer, so the catalog stays
3769	/// withheld until this deferred rendition resolves (config comes from the first ADTS header).
3770	/// Consumed when `import` is built, or released by a frame that cannot build it.
3771	reserved: Option<crate::catalog::Reserved<E>>,
3772	/// Reserves the rendition anew when `import` is built after `reserved` was released, or for the
3773	/// next track after a config change.
3774	catalog: crate::catalog::Producer<E>,
3775	/// The container this importer publishes decoded renditions with.
3776	container: hang::catalog::Container,
3777	/// Partial frame left at the end of the previous PES. ISO 13818-1 doesn't require
3778	/// audio frames to align with PES boundaries, so a legitimate mux can split one.
3779	tail: Vec<u8>,
3780	/// PTS for the frame the tail begins, computed when it was cut. The PES PTS only
3781	/// covers frames that begin in that PES.
3782	tail_pts: Option<Timestamp>,
3783	/// Where in `tail` each PES begins whose PTS no frame has taken yet.
3784	tail_pes: PesStarts,
3785	resync: Resync,
3786	// Completed audio duration since the last video PES, measured independently for each PID.
3787	burst: std::time::Duration,
3788	/// The PTS of the last frame `import` published: see [`forward`].
3789	last: Option<Timestamp>,
3790	group: AudioGroup,
3791}
3792
3793impl<E: CatalogExt> AacStream<E> {
3794	fn write(&mut self, pending: Pending, batched: bool) -> Result<u64> {
3795		// The frames a PES completes share a group (see `AudioGroup`), closed once the PES is spent
3796		// if the group carries a join, and by an error whatever it holds.
3797		let mut group = std::mem::take(&mut self.group);
3798		let result = self.split(pending, batched, &mut group);
3799		let end = group.close(&result);
3800		self.group = group;
3801		// A failed cut is a publishing failure, which outranks the split's own error.
3802		if let (Some(end), Some(import)) = (end, &mut self.import) {
3803			import.cut(Some(end))?;
3804		}
3805		result
3806	}
3807
3808	/// Publish the frames `pending` completes into the open group, extending `group` to where its
3809	/// last frame stops. A frame without a PTS is stamped by the producer, which checks only where
3810	/// groups start, so it keeps a group of its own, as every frame once did.
3811	fn split(&mut self, pending: Pending, batched: bool, group: &mut AudioGroup) -> Result<u64> {
3812		let pes_base = on_clock(pending.pts, pending.offset)?;
3813
3814		// Prepend the partial frame left by the previous PES, if any.
3815		let carried = self.tail.len();
3816		let joined;
3817		let data: &[u8] = if carried == 0 {
3818			&pending.data
3819		} else {
3820			let mut j = std::mem::take(&mut self.tail);
3821			j.extend_from_slice(&pending.data);
3822			joined = j;
3823			&joined
3824		};
3825
3826		// PTS for the next frame to emit. The tail frame keeps the PTS computed at its cut;
3827		// the first frame that BEGINS in this PES takes the PES PTS (per ISO 13818-1).
3828		let mut pts = if carried > 0 || pending.continuation {
3829			self.tail_pts.take()
3830		} else {
3831			pes_base
3832		};
3833		let mut in_tail = carried > 0;
3834		// Where each PES PTS takes over: past the tail this PES continues, and wherever an
3835		// earlier PES or piece left one unapplied in the tail.
3836		let mut pes = std::mem::take(&mut self.tail_pes);
3837		if !pending.continuation {
3838			pes.begin(carried, pes_base);
3839		}
3840
3841		// A single PES can carry several ADTS frames; split and feed each raw frame.
3842		let mut burst = std::time::Duration::ZERO;
3843		let mut published = 0;
3844		let mut offset = 0;
3845		// Earliest candidate passed over for declaring a frame longer than the buffer holds,
3846		// carried only if nothing later in the buffer confirms.
3847		let mut fallback = None;
3848		while offset + adts::MIN_HEADER_LEN <= data.len() {
3849			if let Some(base) = pes.reach(offset) {
3850				pts = base;
3851			}
3852			in_tail &= offset < carried;
3853
3854			// Parse the frame here, and unless the previous frame vouched for this offset and
3855			// for the bytes past it, require a header where the frame it declares ends before
3856			// believing it. See `Resync`. `Err(None)` means nothing parsed badly, the
3857			// candidate just isn't usable.
3858			let confirm = self.resync.needs_confirmation(in_tail);
3859			// Nothing vouches for a frame found by a scan or joined onto a carried tail, so
3860			// publishing one without confirming it (which only end of stream does) substitutes
3861			// audio rather than leaving a gap. Sampled here, before the publish clears it.
3862			let unvouched = !confirm && (self.resync.unconfirmed() || in_tail);
3863			let parsed: Result<_, Option<crate::Error>> = match adts::Header::parse(&data[offset..]) {
3864				Ok(header) => {
3865					let end = offset + header.frame_len;
3866					if end > data.len() {
3867						if !self.resync.unconfirmed() {
3868							// A boundary the previous frame vouched for: the frame continues in
3869							// the next PES, so finish it there. A joined tail waits here too, since
3870							// nothing can confirm a frame the buffer doesn't hold yet.
3871							break;
3872						}
3873						// Unconfirmed, and the length it declares outruns the buffer, so a split
3874						// frame and a false sync claiming a length the stream never delivers look
3875						// identical. Remember it, but prefer any later candidate that does fit
3876						// and confirm: waiting here would swallow the real frames inside the
3877						// range this one claims. A byte of a real ADTS header is 0xFF often
3878						// enough for this to matter.
3879						fallback.get_or_insert_with(|| Fallback {
3880							offset,
3881							discarded: self.resync.discarded,
3882							pts,
3883							pes: pes.clone(),
3884						});
3885						Err(None)
3886					} else if !confirm {
3887						Ok((header, end))
3888					} else if end + adts::MIN_HEADER_LEN > data.len() {
3889						// Whole, but too few bytes left to confirm it. Carry it and retry once
3890						// the next PES extends the buffer, rather than trusting it now.
3891						break;
3892					} else {
3893						adts::Header::parse(&data[end..])
3894							.map(|_| (header, end))
3895							.map_err(|err| Some(err.into()))
3896					}
3897				}
3898				Err(err) => Err(Some(err.into())),
3899			};
3900
3901			let (header, end) = match parsed {
3902				Ok(found) => found,
3903				Err(err) => {
3904					// Sync is lost; scan to the next candidate. See `Resync`.
3905					if self.resync.exhausted() {
3906						let context = format!("AAC stream never regained sync after {} bytes", self.resync.discarded);
3907						return Err(match err {
3908							Some(err) => malformed!("{context}: {err}"),
3909							None => Error::Malformed(context),
3910						});
3911					}
3912					// Take the PES PTS only where the tail is actually abandoned: restoring a fallback
3913					// keeps the candidate, so it keeps the timestamp it was found with.
3914					match self.resync.recover(data, offset, &SyncWord::ADTS) {
3915						Recover::At(next) => {
3916							if in_tail && let Some(base) = pes.abandon(next) {
3917								pts = base;
3918							}
3919							in_tail = false;
3920							offset = next;
3921							continue;
3922						}
3923						// Nothing in the buffer confirmed, so fall back to the earliest
3924						// candidate that was merely too long; it may complete next PES.
3925						Recover::Carry(next) => {
3926							match fallback {
3927								Some(found) => {
3928									self.resync.refund(found.discarded);
3929									offset = found.offset;
3930									pts = found.pts;
3931									pes = found.pes;
3932								}
3933								None => {
3934									if in_tail && let Some(base) = pes.abandon(next) {
3935										pts = base;
3936									}
3937									offset = next;
3938								}
3939							}
3940							break;
3941						}
3942					}
3943				}
3944			};
3945
3946			let mut block = &data[offset + header.header_len..end];
3947			let format = (header.object_type, header.sample_rate, header.channel_config);
3948			// A new object type, sample rate, or channel configuration is a new decoder identity:
3949			// end this track, and publish the rest under a new name.
3950			if let Some(import) = &mut self.import
3951				&& format != self.format
3952			{
3953				tracing::info!(
3954					name = import.name(),
3955					"AAC format changed mid-stream, starting a new track"
3956				);
3957				if let Some(end) = group.take() {
3958					import.cut(Some(end))?;
3959				}
3960				// The ended track retires with its handle, since the rest publishes under a new name.
3961				drop(self.import.take().map(aac::Import::finish).transpose()?);
3962				self.last = None;
3963			}
3964			let import = match &mut self.import {
3965				Some(import) => {
3966					// The description already carries the layout, so a repeated program config
3967					// element (the TS export writes one after each PAT/PMT) leaves the frame too.
3968					if header.channel_config == 0 && aac::leads_with_program_config(block) {
3969						let mut rest = block;
3970						let asc = aac::in_band_config(header.object_type, header.sample_rate, 0, &mut rest)?;
3971						ensure!(asc == self.asc, "AAC program config element changed mid-stream");
3972						block = rest;
3973					}
3974					import
3975				}
3976				// ffmpeg writes the element in its first frame only, so a receiver that joined
3977				// later may never see one. Skip the frame, and stop withholding the catalog for
3978				// this track; it joins the catalog if an element arrives.
3979				None if header.channel_config == 0 && !aac::leads_with_program_config(block) => {
3980					self.reserved.take();
3981					pts = advance_pts(pts, 1024, header.sample_rate)?;
3982					// The frame was confirmed, so the stream is in sync even though nothing published.
3983					self.resync.published(unvouched);
3984					fallback = None;
3985					offset = end;
3986					continue;
3987				}
3988				None => {
3989					// Synthesize the AudioSpecificConfig `description` so out-of-band consumers
3990					// (fMP4/MKV export, WebCodecs) can configure the decoder. A channel_config of 0
3991					// moves the program config element out of this first frame into it, as
3992					// ffmpeg's aac_adtstoasc does; the TS export puts it back.
3993					let asc = aac::in_band_config(
3994						header.object_type,
3995						header.sample_rate,
3996						header.channel_config,
3997						&mut block,
3998					)?;
3999					let mut config = aac::config(&asc)?;
4000					config.container = self.container.clone();
4001					// Consume the reservation held since the PMT: this resolves the gated rendition,
4002					// and carries the catalog's declared media max age onto the track.
4003					let reserved = self.reserved.take().unwrap_or_else(|| self.catalog.reserve());
4004					let track = self
4005						.broadcast
4006						.unique_track(".aac", reserved.track_info(hang::catalog::PRIORITY.audio));
4007					let aac = aac::Import::new(track, reserved, config)?;
4008					self.asc = asc;
4009					self.format = format;
4010					self.import.insert(aac)
4011				}
4012			};
4013
4014			forward(&mut self.last, pts)?;
4015			if pts.is_none()
4016				&& let Some(end) = group.take()
4017			{
4018				import.cut(Some(end))?;
4019			}
4020			import.decode(block, pts)?;
4021			// Count only completed frames; input gaps and unfinished tails are not a media burst.
4022			burst += std::time::Duration::from_nanos((1024_u64 * 1_000_000_000).div_ceil(header.sample_rate as u64));
4023			let start = pts;
4024			pts = advance_pts(pts, 1024, header.sample_rate)?;
4025			match start.zip(pts) {
4026				Some((start, end)) => group.extend(start, end),
4027				None => import.cut(None)?,
4028			}
4029			self.resync.published(unvouched);
4030			published += 1;
4031			// Offsets behind the published frame are spent; carrying one would republish it.
4032			fallback = None;
4033			offset = end;
4034		}
4035
4036		if let Some(import) = &mut self.import {
4037			self.burst = if batched || pending.continuation {
4038				self.burst + burst
4039			} else {
4040				burst
4041			};
4042			import.burst(self.burst)?;
4043		}
4044
4045		// Keep any partial frame (cut mid-frame, or even mid-header) for the next PES,
4046		// with the PTS it should carry.
4047		if let Some(base) = pes.reach(offset) {
4048			pts = base;
4049		}
4050		if offset < data.len() {
4051			self.tail = data[offset..].to_vec();
4052		}
4053		self.tail_pts = pts;
4054		pes.cut(offset);
4055		self.tail_pes = pes;
4056
4057		Ok(published)
4058	}
4059
4060	fn discontinuity(&mut self, published: bool) -> Result<()> {
4061		// The open group ends where its last frame does, not where the next clock picks up.
4062		self.close_group()?;
4063		self.desync();
4064		if published && let Some(import) = &mut self.import {
4065			import.discontinuity()?;
4066		}
4067		Ok(())
4068	}
4069
4070	/// Close the open group where its last frame stops.
4071	fn close_group(&mut self) -> Result<()> {
4072		if let (Some(end), Some(import)) = (self.group.take(), &mut self.import) {
4073			import.cut(Some(end))?;
4074		}
4075		Ok(())
4076	}
4077
4078	/// The partial frame will never see its end, and whatever vouched for the next frame
4079	/// boundary no longer applies. The open group keeps its end for the caller to close it at.
4080	fn desync(&mut self) {
4081		self.burst = std::time::Duration::ZERO;
4082		self.tail.clear();
4083		self.tail_pts = None;
4084		self.tail_pes = PesStarts::default();
4085		self.resync.desynced();
4086	}
4087
4088	fn finish(&mut self) -> Result<u64> {
4089		// Drain a frame held only for want of a successor to confirm it: at end of stream
4090		// that successor is never coming. Only once this stream has published a frame,
4091		// though. Before that nothing has vouched for any boundary, so accepting one here
4092		// would hand a capture that joined mid-frame and ended immediately the same false
4093		// frame that starting unconfirmed exists to reject, and build the track's config out
4094		// of it.
4095		let mut drained = 0;
4096		if !self.tail.is_empty() && self.import.is_some() {
4097			self.resync.drain();
4098			// No PTS to translate, so no mapping needed.
4099			drained = self.write(Pending::empty(), true)?;
4100		}
4101		// A partial frame at end of stream isn't emissible; drop it, but leave a trace for
4102		// diagnosing truncated captures.
4103		if !self.tail.is_empty() {
4104			tracing::debug!(bytes = self.tail.len(), "dropping partial ADTS frame at end of stream");
4105		}
4106		// Nothing was ever published here, so this rendition will never resolve. Release its
4107		// reservation or it gates the initial catalog publish for every other track: `finish`
4108		// takes streams by reference, and callers keep the importer alive past it.
4109		if self.import.is_none() {
4110			self.reserved.take();
4111		}
4112		// The last group ends where its last frame does, rather than at an end estimated from cadence.
4113		self.close_group()?;
4114		if let Some(import) = &mut self.import {
4115			import.finish_in_place()?;
4116		}
4117		Ok(drained)
4118	}
4119
4120	fn abort(mut self, err: moq_net::Error) {
4121		if let Some(import) = self.import.take() {
4122			import.abort(err);
4123		}
4124	}
4125}
4126
4127/// One Opus elementary stream. The channels come from the PMT descriptors and the rate
4128/// is always 48 kHz, so (unlike AAC) the importer is built up front. A PES carries one or
4129/// more Opus packets, each prefixed by the Opus-in-TS control header.
4130struct OpusStream {
4131	import: opus::Import,
4132	/// The PTS of the last packet `import` published: see [`forward`].
4133	last: Option<Timestamp>,
4134	group: AudioGroup,
4135}
4136
4137impl OpusStream {
4138	fn write(&mut self, pending: Pending) -> Result<u64> {
4139		let base = on_clock(pending.pts, pending.offset)?;
4140
4141		let packets = opus_packets(&pending.data)?;
4142		let mut published = 0;
4143		// 48 kHz samples elapsed since this PES's PTS, advancing each packet after the first.
4144		let mut elapsed: u64 = 0;
4145		for packet in packets {
4146			let pts = advance_pts(base, elapsed, 48_000)?;
4147			// Default to 20 ms (960 samples) if the TOC can't be read, so a malformed packet
4148			// doesn't stall the timeline for the rest of the PES.
4149			elapsed += opus::packet_samples(packet).unwrap_or(960) as u64;
4150			forward(&mut self.last, pts)?;
4151			// The producer stamps a packet without a PTS and checks only where groups start, so it
4152			// keeps a group of its own.
4153			if pts.is_none()
4154				&& let Some(end) = self.group.take()
4155			{
4156				self.import.cut(Some(end))?;
4157			}
4158			self.import.decode(packet, pts)?;
4159			published += 1;
4160			match pts.zip(advance_pts(base, elapsed, 48_000)?) {
4161				Some((start, end)) => self.group.extend(start, end),
4162				None => self.import.cut(None)?,
4163			}
4164		}
4165		// Grouped as `AacStream::write` does. A failed decode ends the import, so there is no open
4166		// group to close on that path.
4167		if let Some(end) = self.group.fill() {
4168			self.import.cut(Some(end))?;
4169		}
4170		Ok(published)
4171	}
4172
4173	/// Close the open group where its last packet stops.
4174	fn close_group(&mut self) -> Result<()> {
4175		if let Some(end) = self.group.take() {
4176			self.import.cut(Some(end))?;
4177		}
4178		Ok(())
4179	}
4180
4181	fn discontinuity(&mut self, published: bool) -> Result<()> {
4182		// The open group ends where its last packet does, not where the next clock picks up.
4183		self.close_group()?;
4184		if published {
4185			self.import.discontinuity()?;
4186		}
4187		Ok(())
4188	}
4189
4190	fn finish(&mut self) -> Result<()> {
4191		// The last group ends where its last packet does, rather than at an end estimated from cadence.
4192		self.close_group()?;
4193		Ok(self.import.finish_in_place()?)
4194	}
4195
4196	fn abort(self, err: moq_net::Error) {
4197		self.import.abort(err);
4198	}
4199}
4200
4201/// The 4-byte registration `format_identifier` from a PMT registration descriptor
4202/// (tag 0x05), if present. Identifies the codec of a private-data (0x06) stream.
4203fn registration_format(descriptors: &[catalog::Descriptor]) -> Option<[u8; 4]> {
4204	descriptors
4205		.iter()
4206		.find(|d| d.tag == 0x05)
4207		.and_then(|d| d.data.get(..4))
4208		.and_then(|s| s.try_into().ok())
4209}
4210
4211/// The OpusHead implied by the DVB extension descriptor (tag 0x7f, ext tag 0x80).
4212///
4213/// Codes 0x00..=0x08 follow the plain Opus-in-TS table (and ffmpeg's demuxer): 0 is dual
4214/// mono read as one stereo stream, and 1..=8 is that many channels, family 0 up to stereo
4215/// and the Vorbis family 1 mapping above it. The packet shape of code 0 is one coupled
4216/// stream either way, so this keeps the family 0 head those streams already imported with.
4217///
4218/// 0x80 and 0x82..=0x88 are the other named layouts in Table 4-3 of the Opus-in-TS draft
4219/// (Xiph's "ETSI TS opus" v0.1.3, never published by ETSI): two
4220/// independent mono streams, and the uncoupled family 1 tables ffmpeg writes as
4221/// `0x80 | channels` and then does not read back. 0x81 carries the layout in the
4222/// descriptor (channel count, mapping family, then the stream counts and table,
4223/// bit-packed). A reserved code, or an explicit layout that does not parse, refuses this
4224/// stream. A stream with no extension descriptor stays stereo.
4225fn opus_config(descriptors: &[catalog::Descriptor]) -> Result<opus::Config> {
4226	let Some(data) = descriptors
4227		.iter()
4228		.find(|d| d.tag == 0x7f && d.data.first() == Some(&0x80))
4229		.map(|d| d.data.as_ref())
4230	else {
4231		return Ok(opus::Config::new(48_000, 2));
4232	};
4233	let Some(&code) = data.get(1) else {
4234		bail!("Opus extension descriptor has no channel_config_code");
4235	};
4236
4237	match code {
4238		0 => Ok(opus::Config::new(48_000, 2)),
4239		1..=2 => Ok(opus::Config::new(48_000, u32::from(code))),
4240		3..=8 => vorbis(code),
4241		0x80 => {
4242			ensure!(data.len() == 2, "trailing bytes after Opus channel_config_code 0x80");
4243			mapped(2, 255, 2, 0, &[0, 1])
4244		}
4245		0x81 => explicit_layout(&data[2..]),
4246		0x82..=0x88 => {
4247			ensure!(
4248				data.len() == 2,
4249				"trailing bytes after Opus channel_config_code 0x{code:02x}"
4250			);
4251			let channels = code - 0x80;
4252			const IDENTITY: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
4253			mapped(u32::from(channels), 1, channels, 0, &IDENTITY[..channels as usize])
4254		}
4255		_ => bail!("reserved Opus channel_config_code 0x{code:02x}"),
4256	}
4257}
4258
4259/// Family 1 Vorbis mapping for a plain channel count of 3..=8.
4260fn vorbis(channels: u8) -> Result<opus::Config> {
4261	let mut config = opus::Config::new(48_000, u32::from(channels));
4262	config.mapping = Some(opus::Mapping::vorbis(channels)?);
4263	Ok(config)
4264}
4265
4266/// A mapping table checked by [`opus::Mapping::new`].
4267fn mapped(channels: u32, family: u8, streams: u8, coupled: u8, table: &[u8]) -> Result<opus::Config> {
4268	let mut config = opus::Config::new(48_000, channels);
4269	config.mapping = Some(opus::Mapping::new(opus::mapping::Config {
4270		family,
4271		streams,
4272		coupled,
4273		table,
4274	})?);
4275	Ok(config)
4276}
4277
4278/// The bit-packed layout after `channel_config_code` 0x81 (Opus-in-TS draft Table 4-2).
4279///
4280/// `channel_count` and `mapping_family` are bytes. Family 0 stops there. Otherwise
4281/// `stream_count - 1`, `coupled_stream_count`, and each `channel_mapping` entry follow
4282/// at `ceil(log2(...))` bits, MSB first, then zero pad to a byte. The all-ones mapping
4283/// value is silence, which an OpusHead stores as 255.
4284///
4285/// gstreamer sizes each field with `g_bit_storage(n)`, one bit wider than the draft
4286/// whenever `n` is a power of two. Those descriptors fail the trailing or pad check and
4287/// are refused. Retrying with gstreamer's widths could misread a descriptor written to
4288/// the draft, so there is no fallback.
4289fn explicit_layout(data: &[u8]) -> Result<opus::Config> {
4290	use bitstream_io::BitRead;
4291
4292	let (&channel_count, rest) = data.split_first().context("truncated Opus channel configuration")?;
4293	let (&family, rest) = rest.split_first().context("truncated Opus channel configuration")?;
4294	ensure!(channel_count > 0, "Opus channel_count is zero");
4295	if family == 0 {
4296		ensure!(
4297			rest.is_empty(),
4298			"trailing bytes after a family 0 Opus channel configuration"
4299		);
4300		ensure!(
4301			(1..=2).contains(&channel_count),
4302			"channel mapping family 0 does not allow {channel_count} channels"
4303		);
4304		return Ok(opus::Config::new(48_000, u32::from(channel_count)));
4305	}
4306
4307	let mut bits = bitstream_io::BitReader::endian(rest, bitstream_io::BigEndian);
4308	let stream_count = read_bits(&mut bits, ceil_log2(u32::from(channel_count)))? + 1;
4309	ensure!(
4310		stream_count <= u32::from(channel_count),
4311		"Opus stream_count {stream_count} exceeds channel_count {channel_count}"
4312	);
4313	let coupled = read_bits(&mut bits, ceil_log2(stream_count + 1))?;
4314	ensure!(
4315		coupled <= stream_count,
4316		"Opus coupled_stream_count {coupled} exceeds stream_count {stream_count}"
4317	);
4318	let decoded = stream_count + coupled;
4319	ensure!(
4320		decoded <= 255,
4321		"Opus channel configuration has {decoded} coded channels"
4322	);
4323	let width = ceil_log2(decoded + 1);
4324	let silence = (1u32 << width) - 1;
4325	let mut table = Vec::with_capacity(channel_count as usize);
4326	for _ in 0..channel_count {
4327		let entry = read_bits(&mut bits, width)?;
4328		table.push(if entry == silence { 255 } else { entry as u8 });
4329	}
4330	while !bits.byte_aligned() {
4331		let reserved = read_bits(&mut bits, 1)?;
4332		ensure!(reserved == 0, "nonzero reserved bits in Opus channel configuration");
4333	}
4334	ensure!(
4335		bits.into_reader().is_empty(),
4336		"trailing bytes in Opus channel configuration"
4337	);
4338
4339	mapped(
4340		u32::from(channel_count),
4341		family,
4342		stream_count as u8,
4343		coupled as u8,
4344		&table,
4345	)
4346}
4347
4348/// `ceil(log2(n))` for `n >= 1`. `ceil(log2(1))` is 0, a zero-width field.
4349fn ceil_log2(n: u32) -> u8 {
4350	debug_assert!(n >= 1);
4351	(u32::BITS - (n - 1).leading_zeros()) as u8
4352}
4353
4354/// Read an `n`-bit field, MSB-first, from the bit-packed tail of an explicit Opus channel
4355/// configuration. A zero-width field reads 0.
4356fn read_bits(bits: &mut impl bitstream_io::BitRead, n: u8) -> Result<u32> {
4357	bits.read_var(n.into())
4358		.map_err(|_| malformed!("truncated Opus channel configuration"))
4359}
4360
4361/// Validate the complete PES before exposing any of its declared Opus units.
4362fn opus_packets(mut data: &[u8]) -> Result<Vec<&[u8]>> {
4363	let mut packets = Vec::new();
4364	while !data.is_empty() {
4365		let (header_len, size) = parse_opus_control_header(data)?;
4366		let end = header_len + size;
4367		let packet = data
4368			.get(header_len..end)
4369			.context("Opus access unit exceeds PES payload")?;
4370		packets.push(packet);
4371		data = &data[end..];
4372	}
4373	Ok(packets)
4374}
4375
4376/// Parse one Opus-in-TS access-unit control header, returning `(header_len, payload_size)`.
4377fn parse_opus_control_header(data: &[u8]) -> Result<(usize, usize)> {
4378	ensure!(data.len() >= 2, "Opus control header truncated");
4379	// 11-bit 0x3FF sync: byte 0 == 0x7F and the top 3 bits of byte 1 == 0b111.
4380	ensure!(
4381		data[0] == 0x7f && (data[1] & 0xe0) == 0xe0,
4382		"invalid Opus control header sync (0x{:02x}{:02x})",
4383		data[0],
4384		data[1]
4385	);
4386	let start_trim = (data[1] & 0x10) != 0;
4387	let end_trim = (data[1] & 0x08) != 0;
4388	let control_ext = (data[1] & 0x04) != 0;
4389
4390	let mut pos = 2;
4391	// au_size: sum a run of 0xFF bytes plus the final byte < 0xFF.
4392	let mut size = 0usize;
4393	loop {
4394		let b = *data.get(pos).context("Opus au_size truncated")?;
4395		pos += 1;
4396		size += b as usize;
4397		if b != 0xff {
4398			break;
4399		}
4400	}
4401	// Each trim field is 16 bits; the control extension is a length byte plus that many bytes.
4402	if start_trim {
4403		pos += 2;
4404	}
4405	if end_trim {
4406		pos += 2;
4407	}
4408	if control_ext {
4409		let len = *data.get(pos).context("Opus control extension truncated")? as usize;
4410		pos += 1 + len;
4411	}
4412	ensure!(pos <= data.len(), "Opus control header exceeds payload");
4413	Ok((pos, size))
4414}
4415
4416/// One stream of legacy broadcast audio (MP2, AC-3, E-AC-3), carried verbatim:
4417/// whole self-describing frames, split out of the PES by the codec's header
4418/// parser. Like AAC, import creation is deferred until the first frame header
4419/// (the config isn't in the PMT).
4420struct LegacyStream<E: CatalogExt = ()> {
4421	descriptor: &'static legacy::Descriptor,
4422	import: Option<legacy::Import>,
4423	broadcast: moq_net::broadcast::Producer,
4424	/// Reservation held from the PMT until the first frame builds the importer, so the catalog stays
4425	/// withheld until this deferred rendition resolves (config comes from the first frame header).
4426	/// Consumed when `import` is built.
4427	reserved: Option<crate::catalog::Reserved<E>>,
4428	/// Reserves the next track after a config change.
4429	catalog: crate::catalog::Producer<E>,
4430	/// The sample rate and channel count `import` was built with, from the first frame header.
4431	format: (u32, u32),
4432	/// The container this importer publishes decoded renditions with.
4433	container: hang::catalog::Container,
4434	/// Partial frame left at the end of the previous PES. ISO 13818-1 doesn't
4435	/// require audio frames to align with PES boundaries, so a legitimate mux can
4436	/// split one; it's reassembled here. A lost or spliced PES makes the join
4437	/// garbage, which [`Resync`] then scans past.
4438	tail: Vec<u8>,
4439	/// PTS for the frame the tail begins, computed when it was cut. The PES PTS
4440	/// only covers frames that begin in that PES.
4441	tail_pts: Option<Timestamp>,
4442	/// Where in `tail` each PES begins whose PTS no frame has taken yet.
4443	tail_pes: PesStarts,
4444	resync: Resync,
4445	/// The PTS of the last frame `import` published: see [`forward`].
4446	last: Option<Timestamp>,
4447	group: AudioGroup,
4448}
4449
4450impl<E: CatalogExt> LegacyStream<E> {
4451	fn write(&mut self, pending: Pending) -> Result<u64> {
4452		// Grouped as `AacStream::write` does.
4453		let mut group = std::mem::take(&mut self.group);
4454		let result = self.split(pending, &mut group);
4455		let end = group.close(&result);
4456		self.group = group;
4457		// A failed cut is a publishing failure, which outranks the split's own error.
4458		if let (Some(end), Some(import)) = (end, &mut self.import) {
4459			import.cut(Some(end))?;
4460		}
4461		result
4462	}
4463
4464	/// Publish the frames `pending` completes into the open group, extending `group` to where its
4465	/// last frame stops. A frame without a PTS is stamped by the producer, which checks only where
4466	/// groups start, so it keeps a group of its own, as every frame once did.
4467	fn split(&mut self, pending: Pending, group: &mut AudioGroup) -> Result<u64> {
4468		let mut published = 0;
4469		let pes_base = on_clock(pending.pts, pending.offset)?;
4470
4471		// Prepend the partial frame left by the previous PES, if any.
4472		let carried = self.tail.len();
4473		let joined;
4474		let data: &[u8] = if carried == 0 {
4475			&pending.data
4476		} else {
4477			let mut j = std::mem::take(&mut self.tail);
4478			j.extend_from_slice(&pending.data);
4479			joined = j;
4480			&joined
4481		};
4482
4483		// PTS for the next frame to emit. The tail frame keeps the PTS computed at
4484		// its cut; the first frame that BEGINS in this PES takes the PES PTS (per
4485		// ISO 13818-1, a PES PTS refers to the first access unit starting in it).
4486		// After each frame it advances by that frame's duration (per frame, not
4487		// `index * constant`: E-AC-3 varies the samples per frame).
4488		let mut pts = if carried > 0 || pending.continuation {
4489			self.tail_pts.take()
4490		} else {
4491			pes_base
4492		};
4493		let mut in_tail = carried > 0;
4494		// Where each PES PTS takes over: past the tail this PES continues, and wherever an
4495		// earlier PES or piece left one unapplied in the tail.
4496		let mut pes = std::mem::take(&mut self.tail_pes);
4497		if !pending.continuation {
4498			pes.begin(carried, pes_base);
4499		}
4500
4501		let mut offset = 0;
4502		// Earliest candidate passed over for declaring a frame longer than the buffer holds,
4503		// carried only if nothing later in the buffer confirms.
4504		let mut fallback = None;
4505		while offset + self.descriptor.min_header_len <= data.len() {
4506			if let Some(base) = pes.reach(offset) {
4507				pts = base;
4508			}
4509			in_tail &= offset < carried;
4510
4511			// Parse the frame here, and unless the previous frame vouched for this offset and
4512			// for the bytes past it, require a header where the frame it declares ends before
4513			// believing it. See `Resync`. `Err(None)` means nothing parsed badly, the
4514			// candidate just isn't usable.
4515			let confirm = self.resync.needs_confirmation(in_tail);
4516			// Nothing vouches for a frame found by a scan or joined onto a carried tail, so
4517			// publishing one without confirming it (which only end of stream does) substitutes
4518			// audio rather than leaving a gap. Sampled here, before the publish clears it.
4519			let unvouched = !confirm && (self.resync.unconfirmed() || in_tail);
4520			let parsed: Result<_, Option<legacy::Error>> = match (self.descriptor.parse)(&data[offset..]) {
4521				Ok(header) => {
4522					let end = offset + header.len;
4523					if end > data.len() {
4524						if !self.resync.unconfirmed() {
4525							// A boundary the previous frame vouched for: the frame continues in
4526							// the next PES, so finish it there. A joined tail waits here too, since
4527							// nothing can confirm a frame the buffer doesn't hold yet.
4528							break;
4529						}
4530						// Unconfirmed, and the length it declares outruns the buffer, so a split
4531						// frame and a false sync claiming a length the stream never delivers look
4532						// identical. Remember it, but prefer any later candidate that does fit
4533						// and confirm: waiting here would swallow the real frames inside the
4534						// range this one claims.
4535						fallback.get_or_insert_with(|| Fallback {
4536							offset,
4537							discarded: self.resync.discarded,
4538							pts,
4539							pes: pes.clone(),
4540						});
4541						Err(None)
4542					} else if !confirm {
4543						Ok((header, end))
4544					} else if end + self.descriptor.min_header_len > data.len() {
4545						// Whole, but too few bytes left to confirm it. Carry it and retry once
4546						// the next PES extends the buffer, rather than trusting it now.
4547						break;
4548					} else {
4549						(self.descriptor.parse)(&data[end..])
4550							.map(|_| (header, end))
4551							.map_err(Some)
4552					}
4553				}
4554				Err(err) => Err(Some(err)),
4555			};
4556
4557			let (header, end) = match parsed {
4558				Ok(found) => found,
4559				Err(err) => {
4560					// Sync is lost. Scan past this byte to the next candidate and let the
4561					// next iteration confirm it by parsing there.
4562					if self.resync.exhausted() {
4563						// Nothing in this PID parses, so it isn't the codec its PMT declares.
4564						// That's a mux or config error rather than damage: fail loudly instead
4565						// of scanning forever behind an unresolved catalog reservation.
4566						let context = format!(
4567							"{} stream never regained sync after {} bytes",
4568							self.descriptor.track_suffix, self.resync.discarded
4569						);
4570						return Err(match err {
4571							Some(err) => malformed!("{context}: {err}"),
4572							None => Error::Malformed(context),
4573						});
4574					}
4575					// The tail's frame boundary is what we just lost, so its PTS no longer
4576					// describes anything. Re-anchor on the PES, whose PTS covers the first
4577					// frame starting in it: wrong by less than one PES, where a stale tail
4578					// (a loop wrap carries the PTS from before it) can be wrong by hours.
4579					// Only where the tail is actually abandoned, though: restoring a fallback
4580					// keeps the candidate, so it keeps the timestamp it was found with.
4581					match self.resync.recover(data, offset, &self.descriptor.into()) {
4582						Recover::At(next) => {
4583							if in_tail && let Some(base) = pes.abandon(next) {
4584								pts = base;
4585							}
4586							in_tail = false;
4587							offset = next;
4588							continue;
4589						}
4590						// Nothing in the buffer confirmed, so fall back to the earliest
4591						// candidate that was merely too long; it may complete next PES.
4592						Recover::Carry(next) => {
4593							match fallback {
4594								Some(found) => {
4595									self.resync.refund(found.discarded);
4596									offset = found.offset;
4597									pts = found.pts;
4598									pes = found.pes;
4599								}
4600								None => {
4601									if in_tail && let Some(base) = pes.abandon(next) {
4602										pts = base;
4603									}
4604									offset = next;
4605								}
4606							}
4607							break;
4608						}
4609					}
4610				}
4611			};
4612
4613			let format = (header.sample_rate, header.channel_count);
4614			// A new sample rate or channel count is a new decoder identity: end this track, and
4615			// publish the rest under a new name.
4616			if let Some(import) = &mut self.import
4617				&& format != self.format
4618			{
4619				tracing::info!(
4620					name = import.name(),
4621					"audio format changed mid-stream, starting a new track"
4622				);
4623				if let Some(end) = group.take() {
4624					import.cut(Some(end))?;
4625				}
4626				// The ended track retires with its handle, since the rest publishes under a new name.
4627				drop(self.import.take().map(legacy::Import::finish).transpose()?);
4628				self.last = None;
4629			}
4630			let import = match &mut self.import {
4631				Some(import) => import,
4632				None => {
4633					let config = legacy::Config {
4634						sample_rate: header.sample_rate,
4635						channel_count: header.channel_count,
4636						container: self.container.clone(),
4637					};
4638					// Consume the reservation held since the PMT: this resolves the gated rendition,
4639					// and carries the catalog's declared media max age onto the track. A track
4640					// after a format change reserves anew on the same timebase.
4641					let reserved = self.reserved.take().unwrap_or_else(|| self.catalog.reserve());
4642					let track = self.broadcast.unique_track(
4643						self.descriptor.track_suffix,
4644						reserved.track_info(hang::catalog::PRIORITY.audio),
4645					);
4646					let legacy = legacy::Import::new(self.descriptor, track, reserved, config)?;
4647					self.format = format;
4648					self.import.insert(legacy)
4649				}
4650			};
4651
4652			forward(&mut self.last, pts)?;
4653			if pts.is_none()
4654				&& let Some(end) = group.take()
4655			{
4656				import.cut(Some(end))?;
4657			}
4658			import.decode(&data[offset..end], pts)?;
4659			let start = pts;
4660			pts = advance_pts(pts, header.samples, header.sample_rate)?;
4661			match start.zip(pts) {
4662				Some((start, end)) => group.extend(start, end),
4663				None => import.cut(None)?,
4664			}
4665			self.resync.published(unvouched);
4666			published += 1;
4667			// Offsets behind the published frame are spent; carrying one would republish it.
4668			fallback = None;
4669			offset = end;
4670		}
4671
4672		// Keep any partial frame (cut mid-frame, or even mid-header) for the next
4673		// PES, with the PTS it should carry.
4674		if let Some(base) = pes.reach(offset) {
4675			pts = base;
4676		}
4677		if offset < data.len() {
4678			self.tail = data[offset..].to_vec();
4679		}
4680		self.tail_pts = pts;
4681		pes.cut(offset);
4682		self.tail_pes = pes;
4683
4684		Ok(published)
4685	}
4686
4687	fn discontinuity(&mut self, published: bool) -> Result<()> {
4688		// The open group ends where its last frame does, not where the next clock picks up.
4689		self.close_group()?;
4690		self.desync();
4691		if published && let Some(import) = &mut self.import {
4692			import.discontinuity()?;
4693		}
4694		Ok(())
4695	}
4696
4697	/// Close the open group where its last frame stops.
4698	fn close_group(&mut self) -> Result<()> {
4699		if let (Some(end), Some(import)) = (self.group.take(), &mut self.import) {
4700			import.cut(Some(end))?;
4701		}
4702		Ok(())
4703	}
4704
4705	/// The partial frame will never see its end, and whatever vouched for the next frame
4706	/// boundary no longer applies. The open group keeps its end for the caller to close it at.
4707	fn desync(&mut self) {
4708		self.tail.clear();
4709		self.tail_pts = None;
4710		self.tail_pes = PesStarts::default();
4711		self.resync.desynced();
4712	}
4713
4714	fn finish(&mut self) -> Result<u64> {
4715		// Drain a frame held only for want of a successor to confirm it: at end of stream
4716		// that successor is never coming. Only once this stream has published a frame,
4717		// though. Before that nothing has vouched for any boundary, so accepting one here
4718		// would hand a capture that joined mid-frame and ended immediately the same false
4719		// frame that starting unconfirmed exists to reject, and build the track's config out
4720		// of it.
4721		let mut drained = 0;
4722		if !self.tail.is_empty() && self.import.is_some() {
4723			self.resync.drain();
4724			// No PTS to translate, so no mapping needed.
4725			drained = self.write(Pending::empty())?;
4726		}
4727		// A partial frame at end of stream isn't emissible verbatim; drop it, but
4728		// leave a trace for diagnosing truncated captures.
4729		if !self.tail.is_empty() {
4730			tracing::debug!(
4731				suffix = self.descriptor.track_suffix,
4732				bytes = self.tail.len(),
4733				"dropping partial frame at end of stream"
4734			);
4735		}
4736		// Nothing was ever published here, so this rendition will never resolve. Release its
4737		// reservation or it gates the initial catalog publish for every other track: `finish`
4738		// takes streams by reference, and callers keep the importer alive past it.
4739		if self.import.is_none() {
4740			self.reserved.take();
4741		}
4742		// The last group ends where its last frame does, rather than at an end estimated from cadence.
4743		self.close_group()?;
4744		if let Some(import) = &mut self.import {
4745			import.finish_in_place()?;
4746		}
4747		Ok(drained)
4748	}
4749
4750	fn abort(mut self, err: moq_net::Error) {
4751		if let Some(import) = self.import.take() {
4752			import.abort(err);
4753		}
4754	}
4755}
4756
4757/// Swallow a [`MissingKeyframe`](crate::container::MissingKeyframe) from a video
4758/// decode: a TS capture can join mid-GOP, so the deltas before the first keyframe
4759/// have no group to anchor and are simply dropped rather than aborting the demux.
4760fn skip_missing_keyframe(result: crate::Result<()>) -> Result<bool> {
4761	match result {
4762		Ok(()) => Ok(true),
4763		Err(crate::Error::MissingKeyframe(_)) => Ok(false),
4764		Err(e) => Err(e.into()),
4765	}
4766}
4767
4768/// Refuse an audio frame that starts below the last one its track published: a restart, which is
4769/// a new broadcast. Audio never reorders, and the producer only checks where groups start, which
4770/// is once a PES. A frame without a PTS is left to the producer, in a group of its own.
4771fn forward(last: &mut Option<Timestamp>, pts: Option<Timestamp>) -> crate::Result<()> {
4772	let Some(pts) = pts else {
4773		return Ok(());
4774	};
4775	if let Some(floor) = *last
4776		&& pts < floor
4777	{
4778		return Err(crate::container::TimestampRewind { timestamp: pts, floor }.into());
4779	}
4780	*last = Some(pts);
4781	Ok(())
4782}
4783
4784/// Advance a PES-derived PTS past one frame of `samples` at `sample_rate`.
4785///
4786/// Per frame rather than `index * constant`: E-AC-3 varies the samples per frame, and a
4787/// resync means the frames in a PES are no longer a contiguous run to index into.
4788fn advance_pts(pts: Option<Timestamp>, samples: u64, sample_rate: u32) -> Result<Option<Timestamp>> {
4789	let Some(pts) = pts else {
4790		return Ok(None);
4791	};
4792	// `pts` is a 90 kHz PES PTS; rescale the sample-rate advance to match before adding
4793	// (the scale-aware Timestamp rejects mixed scales).
4794	let advance = Timestamp::from_scale(samples, sample_rate as u64)?;
4795	let scale = pts.scale().ok_or(moq_net::TimeOverflow)?;
4796	Ok(Some(pts.checked_add(advance.convert(scale)?)?))
4797}
4798
4799/// Tracks the wrap-around of the 33-bit, 90 kHz PTS field so timestamps stay
4800/// monotonic across the ~26.5 hour wrap period.
4801///
4802/// A flagged clock break keeps the history: a forward jump across the wrap lands in the next
4803/// one, as the passthrough's PCR count does, while a step back of under half a wrap still reads
4804/// as the rewind it is. That holds before the first wrap too: a stream still behind a wrap the
4805/// first PTS already crossed (an import started while audio and video straddle it) reads as
4806/// negative, before the broadcast clock's zero, rather than a whole wrap ahead.
4807#[derive(Default)]
4808struct PtsUnwrap {
4809	last: Option<u64>,
4810	offset: i64,
4811}
4812
4813impl PtsUnwrap {
4814	fn unwrap(&mut self, raw: u64) -> i64 {
4815		const WRAP: i64 = 1 << 33;
4816		if let Some(last) = self.last {
4817			let diff = raw as i64 - last as i64;
4818			if diff < -WRAP / 2 {
4819				self.offset += WRAP;
4820			} else if diff > WRAP / 2 {
4821				self.offset -= WRAP;
4822			}
4823		}
4824		self.last = Some(raw);
4825		self.offset + raw as i64
4826	}
4827
4828	/// `raw`, a 27 MHz PCR, in the wrap nearest the last PTS, or in the current one before any:
4829	/// signed, since a PCR just behind a wrap the PTS already crossed lands in the one before.
4830	fn pcr(&self, raw: u64) -> i128 {
4831		let period = i128::from(PCR_WRAP);
4832		let reference = (i128::from(self.offset) + i128::from(self.last.unwrap_or(raw / 300))) * 300;
4833		let raw = i128::from(raw);
4834		raw + (reference - raw + period / 2).div_euclid(period) * period
4835	}
4836}
4837
4838/// A 90 kHz PTS already in its era, as a [`Timestamp`] on the catalog clock: shifted by the
4839/// timebase's `offset`. Returns `None` when the PES carried no PTS.
4840fn on_clock(pts: Option<u64>, offset: Offset) -> Result<Option<Timestamp>> {
4841	let Some(pts) = pts else {
4842		return Ok(None);
4843	};
4844	Ok(Some(offset.apply(Timestamp::from_scale(pts, 90_000)?)?))
4845}
4846
4847/// The reorder delay `PTS - DTS` for one PES, as a microsecond [`Timestamp`]. `None` unless
4848/// both stamps are present and the gap is a plausible reorder (a few seconds); a larger or
4849/// negative gap is a discontinuity or bad DTS, ignored so it can't inflate the jitter. Both
4850/// are raw 90 kHz, so the subtraction is done modulo the 33-bit field to stay correct across
4851/// the wrap.
4852fn reorder_delay(pts: Option<u64>, dts: Option<u64>) -> Option<Timestamp> {
4853	const FIELD: u64 = 1 << 33;
4854	const MAX_REORDER_TICKS: u64 = 90_000 * 2; // 2 s; broadcast reorder is well under this.
4855	let (pts, dts) = (pts?, dts?);
4856	let delay = pts.wrapping_sub(dts) & (FIELD - 1);
4857	if delay == 0 || delay > MAX_REORDER_TICKS {
4858		return None;
4859	}
4860	Timestamp::from_scale(delay, 90_000).ok()
4861}
4862
4863#[cfg(test)]
4864pub(super) mod test {
4865	use std::collections::BTreeMap;
4866	use std::time::Duration;
4867
4868	use moq_net::Timestamp;
4869
4870	use mpeg2ts::es::StreamType;
4871
4872	use super::{Continuation, Continuity, SectionReassembler, Stream};
4873	use mpeg2ts::ts::{Pid, TsPacket};
4874
4875	/// A drift budget no test timeline comes close to, so the reader sees every group.
4876	///
4877	/// The media track's full max age, so a reader started after importing can
4878	/// still read every fresh group. These tests import a whole file first, which the default
4879	/// [`Duration::ZERO`] budget collapses to the live
4880	/// edge: completeness has to be asked for.
4881	const RECORDING_MAX_AGE: std::time::Duration = Duration::from_secs(30);
4882
4883	// libklvanc public-sample cue: table_id 0xFC, section_length 0x1b (27), 30 bytes total.
4884	pub(in crate::container::ts) const CUE: [u8; 30] = [
4885		0xfc, 0x30, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xf0, 0x0a, 0x05, 0x00, 0x00, 0x2b, 0xb4,
4886		0x7f, 0xdf, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xad, 0x25, 0xe8, 0x39,
4887	];
4888
4889	#[test]
4890	fn resync_stats_include_an_in_progress_scan() {
4891		let mut resync = super::Resync::new(0x61, ".mp2");
4892		let codec = super::SyncWord {
4893			min_header_len: 4,
4894			sync_byte: 0xff,
4895		};
4896
4897		assert!(matches!(resync.recover(&[0; 10], 0, &codec), super::Recover::Carry(7)));
4898		let stats = resync.stats();
4899		assert_eq!(stats.discarded, 7, "the active scan must be visible before recovery");
4900		assert_eq!(stats.resyncs, 0, "the stream has not regained sync yet");
4901	}
4902
4903	#[test]
4904	fn liveness_steps_over_a_corrupt_pcr_and_the_wrap() {
4905		const MS: u64 = 27_000;
4906		let mut liveness = super::Liveness::default();
4907		liveness.register(0x100);
4908		let mut pcr = super::super::mux_rate::PCR_WRAP - 100 * MS;
4909		for _ in 0..10 {
4910			liveness.pcr(pcr);
4911			pcr = (pcr + 40 * MS) % super::super::mux_rate::PCR_WRAP;
4912		}
4913		assert_eq!(liveness.stream(0x100), (0, Some(Duration::from_millis(360))));
4914
4915		// A PCR hours ahead, then the clock carrying on where it was: neither step counts.
4916		liveness.pcr(pcr + 23_861_000 * MS);
4917		liveness.pcr(pcr);
4918		assert_eq!(liveness.stream(0x100).1, Some(Duration::from_millis(360)));
4919
4920		liveness.pcr(pcr + 40 * MS);
4921		liveness.delivered(0x100, 3);
4922		liveness.pcr(pcr + 80 * MS);
4923		assert_eq!(liveness.stream(0x100), (3, Some(Duration::from_millis(40))));
4924	}
4925
4926	#[test]
4927	fn resync_does_not_count_an_unvouched_eof_publication() {
4928		let mut resync = super::Resync::new(0x61, ".mp2");
4929		let codec = super::SyncWord {
4930			min_header_len: 4,
4931			sync_byte: 0xff,
4932		};
4933
4934		resync.recover(&[0; 10], 0, &codec);
4935		resync.drain();
4936		resync.published(true);
4937		let stats = resync.stats();
4938		assert_eq!(stats.discarded, 7, "the bytes skipped before EOF were discarded");
4939		assert_eq!(
4940			stats.resyncs, 0,
4941			"an unconfirmed frame does not prove sync was regained"
4942		);
4943		assert_eq!(stats.unconfirmed, 1, "the unvouched publication is counted separately");
4944	}
4945
4946	#[tokio::test(start_paused = true)]
4947	#[tracing_test::traced_test]
4948	async fn damaged_unit_warnings_are_aggregated_per_pid() {
4949		let mut broadcast = moq_net::broadcast::Info::new().produce();
4950		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
4951		let mut import = super::Import::new(broadcast, catalog.reserve());
4952		let pid = Pid::new(0x61).unwrap();
4953		let peer = Pid::new(0x62).unwrap();
4954		let error = super::Error::Malformed("broken PES".into());
4955		for _ in 0..3 {
4956			import.damage(pid, &error).unwrap();
4957		}
4958		import.damage(peer, &error).unwrap();
4959		logs_assert(|lines| {
4960			let first = lines
4961				.iter()
4962				.filter(|line| line.contains("dropped a damaged TS unit"))
4963				.count();
4964			if first == 2 {
4965				Ok(())
4966			} else {
4967				Err(format!("expected one warning per PID, got {first}"))
4968			}
4969		});
4970
4971		tokio::time::advance(super::stats::Log::INTERVAL).await;
4972		import.decode(&[]).unwrap();
4973		logs_assert(|lines| {
4974			let summary: Vec<_> = lines
4975				.iter()
4976				.filter(|line| line.contains("TS damaged-unit summary"))
4977				.collect();
4978			if summary.len() == 1 && summary[0].contains("pid=97 ") && summary[0].contains("count=2") {
4979				Ok(())
4980			} else {
4981				Err(format!("expected two additional drops on PID 97, got {summary:?}"))
4982			}
4983		});
4984		import.damage(pid, &error).unwrap();
4985		import.damage(pid, &error).unwrap();
4986		import.finish_in_place().unwrap();
4987		assert_eq!(import.stats().streams[&0x61].damaged, 5);
4988		drop(import);
4989		logs_assert(|lines| {
4990			let first = lines
4991				.iter()
4992				.filter(|line| line.contains("dropped a damaged TS unit"))
4993				.count();
4994			let summary = lines
4995				.iter()
4996				.filter(|line| line.contains("TS damaged-unit summary"))
4997				.count();
4998			if (first, summary) == (3, 2) {
4999				Ok(())
5000			} else {
5001				Err(format!("expected new burst and final summary, got {first}/{summary}"))
5002			}
5003		});
5004	}
5005
5006	#[tokio::test(start_paused = true)]
5007	#[tracing_test::traced_test]
5008	async fn abort_summarizes_the_final_damage_burst() {
5009		let mut broadcast = moq_net::broadcast::Info::new().produce();
5010		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5011		let mut import = super::Import::new(broadcast, catalog.reserve());
5012		let pid = Pid::new(0x61).unwrap();
5013		let error = super::Error::Malformed("broken PES".into());
5014		for _ in 0..3 {
5015			import.damage(pid, &error).unwrap();
5016		}
5017		import.abort(moq_net::Error::Cancel);
5018		logs_assert(|lines| {
5019			let summary: Vec<_> = lines
5020				.iter()
5021				.filter(|line| line.contains("TS damaged-unit summary"))
5022				.collect();
5023			if summary.len() == 1 && summary[0].contains("count=2") {
5024				Ok(())
5025			} else {
5026				Err(format!("expected the aborted burst's two drops, got {summary:?}"))
5027			}
5028		});
5029	}
5030
5031	#[test]
5032	fn remapping_a_pid_keeps_its_retired_resync_stats() {
5033		let mut broadcast = moq_net::broadcast::Info::new().produce();
5034		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5035		let mut import = super::Import::new(broadcast, catalog.reserve());
5036		let pid = mpeg2ts::ts::Pid::new(0x61).unwrap();
5037		let mut stream = import.legacy_stream(pid, &super::mp2::DESCRIPTOR);
5038		let super::Stream::Legacy(legacy) = &mut stream else {
5039			unreachable!();
5040		};
5041		let codec = super::SyncWord::from(&super::mp2::DESCRIPTOR);
5042		legacy.resync.recover(&[0; 10], 0, &codec);
5043		legacy.resync.published(false);
5044		import.streams.insert(pid, stream);
5045		import
5046			.damage(pid, &super::Error::Malformed("malformed PES".into()))
5047			.unwrap();
5048		let before = import.stats();
5049		assert_eq!(before.streams[&pid.as_u16()].damaged, 1);
5050
5051		import
5052			.ensure_section(pid, StreamType::Dts8ChannelLosslessAudio as u8, &[])
5053			.unwrap();
5054
5055		assert!(matches!(import.streams.get(&pid), Some(super::Stream::Ignored)));
5056		// A base catalog cannot carry the section route, which counts as refused.
5057		let mut expected = before;
5058		expected.streams.get_mut(&pid.as_u16()).unwrap().refused = 1;
5059		assert_eq!(import.stats(), expected, "a PMT remap must not reset lifetime counters");
5060	}
5061
5062	/// Build a payload-only TS packet (PID 0x0021, afc 0b01). `body` is the bytes
5063	/// after the pointer_field (when `pusi`) or after the 4-byte header, padded to
5064	/// 188 with 0xff stuffing. A packet carrying a section that continues into the
5065	/// next packet must fill `body` exactly (so no stuffing lands mid-section).
5066	fn packet(pusi: bool, cc: u8, pointer: u8, body: &[u8]) -> Vec<u8> {
5067		let mut p = vec![0x47, 0x00, 0x21, 0x10 | (cc & 0x0f)];
5068		if pusi {
5069			p[1] |= 0x40;
5070			p.push(pointer);
5071		}
5072		p.extend_from_slice(body);
5073		assert!(p.len() <= 188, "test packet body overflows 188 bytes");
5074		p.resize(188, 0xff);
5075		p
5076	}
5077
5078	/// A continuation packet (no PUSI) whose adaptation field sets
5079	/// discontinuity_indicator, followed by `body`.
5080	fn discontinuity_packet(cc: u8, body: &[u8]) -> Vec<u8> {
5081		// afc 0b11 (adaptation + payload); adaptation_field_length 1, flags 0x80.
5082		let mut p = vec![0x47, 0x00, 0x21, 0x30 | (cc & 0x0f), 0x01, 0x80];
5083		p.extend_from_slice(body);
5084		assert!(p.len() <= 188, "test packet body overflows 188 bytes");
5085		p.resize(188, 0xff);
5086		p
5087	}
5088
5089	/// A continuation packet carrying PCR and/or OPCR in its adaptation field.
5090	fn clock_packet(cc: u8, pcr: Option<[u8; 6]>, opcr: Option<[u8; 6]>, body: &[u8]) -> Vec<u8> {
5091		let flags = if pcr.is_some() { 0x10 } else { 0 } | if opcr.is_some() { 0x08 } else { 0 };
5092		let length = 1 + usize::from(pcr.is_some()) * 6 + usize::from(opcr.is_some()) * 6;
5093		let mut p = vec![0x47, 0x00, 0x21, 0x30 | (cc & 0x0f), length as u8, flags];
5094		if let Some(pcr) = pcr {
5095			p.extend_from_slice(&pcr);
5096		}
5097		if let Some(opcr) = opcr {
5098			p.extend_from_slice(&opcr);
5099		}
5100		p.extend_from_slice(body);
5101		assert!(p.len() <= 188, "test packet body overflows 188 bytes");
5102		p.resize(188, 0xff);
5103		p
5104	}
5105
5106	/// A synthetic section: `table_id`, a 12-bit length, then `body_len` zero bytes.
5107	fn fake_section(table_id: u8, body_len: usize) -> Vec<u8> {
5108		let mut s = vec![table_id, ((body_len >> 8) & 0x0f) as u8, (body_len & 0xff) as u8];
5109		s.resize(3 + body_len, 0x00);
5110		s
5111	}
5112
5113	fn run(pkts: &[Vec<u8>]) -> Vec<Vec<u8>> {
5114		let mut r = SectionReassembler::default();
5115		let mut out = Vec::new();
5116		for p in pkts {
5117			r.push(p, &mut out);
5118		}
5119		out
5120	}
5121
5122	#[test]
5123	fn single_section() {
5124		assert_eq!(run(&[packet(true, 0, 0, &CUE)]), vec![CUE.to_vec()]);
5125	}
5126
5127	#[test]
5128	fn carries_all_sections_verbatim() {
5129		// A non-SCTE table_id 0x00 section ahead of the cue: both are carried verbatim
5130		// (we no longer filter by table_id), and back-to-back sections parse cleanly.
5131		let other = fake_section(0x00, 5);
5132		let mut body = other.clone();
5133		body.extend_from_slice(&CUE);
5134		assert_eq!(run(&[packet(true, 0, 0, &body)]), vec![other, CUE.to_vec()]);
5135	}
5136
5137	#[test]
5138	fn stuffing_only() {
5139		// A PUSI payload that is all 0xff stuffing emits nothing.
5140		assert!(run(&[packet(true, 0, 0, &[])]).is_empty());
5141	}
5142
5143	#[test]
5144	fn payload_split_across_packets() {
5145		// A 250-byte section spans two packets with intact continuity; it reassembles.
5146		let section = fake_section(0xfc, 247);
5147		let p1 = packet(true, 0, 0, &section[..183]);
5148		let p2 = packet(false, 1, 0, &section[183..]);
5149		assert_eq!(run(&[p1, p2]), vec![section]);
5150	}
5151
5152	#[test]
5153	fn header_split_across_packets() {
5154		// Section A fills packet 1 except for the cue's first two header bytes (`fc 30`);
5155		// the third (`1b`, which carries section_length) arrives in packet 2. The
5156		// reassembler must wait for it instead of dropping the start.
5157		let a = fake_section(0xfc, 178);
5158		let mut body = a.clone();
5159		body.extend_from_slice(&CUE[..2]);
5160		let p1 = packet(true, 0, 0, &body);
5161		let p2 = packet(false, 1, 0, &CUE[2..]);
5162		assert_eq!(run(&[p1, p2]), vec![a, CUE.to_vec()]);
5163	}
5164
5165	#[test]
5166	fn continuity_gap_drops_partial() {
5167		// Same split, but packet 2's continuity_counter jumps (1 -> 3): the partial
5168		// section is dropped rather than completed from the wrong bytes.
5169		let section = fake_section(0xfc, 247);
5170		let p1 = packet(true, 0, 0, &section[..183]);
5171		let p2 = packet(false, 3, 0, &section[183..]);
5172		assert!(run(&[p1, p2]).is_empty());
5173	}
5174
5175	#[test]
5176	fn discontinuity_drops_partial() {
5177		// Same split, but packet 2 carries an adaptation-field discontinuity, which
5178		// drops the partial even though the continuity_counter would line up.
5179		let section = fake_section(0xfc, 247);
5180		let p1 = packet(true, 0, 0, &section[..183]);
5181		let p2 = discontinuity_packet(1, &section[183..]);
5182		assert!(run(&[p1, p2]).is_empty());
5183	}
5184
5185	#[test]
5186	fn gap_then_unaligned_payload_is_not_emitted() {
5187		// After a gap on a non-PUSI packet, the payload is unaligned continuation of
5188		// the dropped section. Even if it happens to start with 0xFC, it must not be
5189		// mistaken for a new section (there is no pointer_field to realign on).
5190		let section = fake_section(0xfc, 247);
5191		let p1 = packet(true, 0, 0, &section[..183]);
5192		let p2 = packet(false, 2, 0, &CUE); // cc gap (expected 1), payload looks like a cue
5193		assert!(run(&[p1, p2]).is_empty());
5194	}
5195
5196	#[test]
5197	fn corrupt_pointer_field_is_dropped() {
5198		// A pointer_field that points past the payload marks a malformed packet; the
5199		// reassembler drops it instead of slicing out of bounds or fabricating a
5200		// section from the bytes that follow.
5201		assert!(run(&[packet(true, 0, 200, &CUE)]).is_empty());
5202	}
5203
5204	#[test]
5205	fn stays_desynced_until_next_pusi() {
5206		// After a gap drops the partial, EVERY following non-PUSI packet is unaligned
5207		// continuation and must be ignored, not just the one carrying the gap, until a
5208		// PUSI re-establishes a section boundary. p3 looks like a cue but arrives with
5209		// no PUSI since the drop, so only p4's cue is emitted.
5210		let section = fake_section(0xfc, 247);
5211		let p1 = packet(true, 0, 0, &section[..183]);
5212		let p2 = packet(false, 2, 0, &section[183..]); // cc gap (expected 1) -> drop
5213		let p3 = packet(false, 3, 0, &CUE); // continuous cc, but unaligned bytes
5214		let p4 = packet(true, 4, 0, &CUE); // a real PUSI -> resync and emit
5215		assert_eq!(run(&[p1, p2, p3, p4]), vec![CUE.to_vec()]);
5216	}
5217
5218	#[test]
5219	fn orphan_tail_before_section_is_skipped() {
5220		// A PUSI packet whose pointer_field skips a leading fragment (the tail of a
5221		// section we never saw the start of): the fragment is discarded even though it
5222		// looks like a cue, and only the section the pointer points to is emitted.
5223		let mut body = CUE.to_vec(); // orphan fragment ahead of the pointer
5224		body.extend_from_slice(&CUE); // the section the pointer points to
5225		let pkt = packet(true, 0, CUE.len() as u8, &body);
5226		assert_eq!(run(&[pkt]), vec![CUE.to_vec()]);
5227	}
5228
5229	/// Serialize PAT + PMT for the given `(stream_type, pid)` elementary streams; with
5230	/// `cuei`, add the program-level CUEI descriptor so a `0x86` PID is detected as SCTE-35.
5231	///
5232	/// The clock rides the first elementary stream, as a real mux puts it on the video.
5233	fn synth_pmt(es: &[(StreamType, u16)], cuei: bool) -> Vec<u8> {
5234		synth_programs(&[(1, 0x0100, es)], cuei)
5235	}
5236
5237	/// A program to synthesize: `(program_num, pmt_pid, [(stream_type, pid)])`.
5238	type SynthProgram<'a> = (u16, u16, &'a [(StreamType, u16)]);
5239
5240	/// Serialize one PAT listing every program, then each program's PMT, as [`synth_pmt`]
5241	/// does for one.
5242	fn synth_programs(programs: &[SynthProgram], cuei: bool) -> Vec<u8> {
5243		use mpeg2ts::ts::payload::{Pat, Pmt};
5244		use mpeg2ts::ts::{
5245			ContinuityCounter, Descriptor, EsInfo, Pid, ProgramAssociation, TransportScramblingControl, TsHeader,
5246			TsPacket, TsPacketWriter, TsPayload, VersionNumber, WriteTsPacket,
5247		};
5248
5249		let pat = Pat {
5250			transport_stream_id: 1,
5251			version_number: VersionNumber::default(),
5252			table: programs
5253				.iter()
5254				.map(|&(program_num, pmt_pid, _)| ProgramAssociation {
5255					program_num,
5256					program_map_pid: Pid::new(pmt_pid).unwrap(),
5257				})
5258				.collect(),
5259		};
5260		let pmt = |program_num: u16, es: &[(StreamType, u16)]| Pmt {
5261			program_num,
5262			pcr_pid: es.first().map(|&(_, pid)| Pid::new(pid).unwrap()),
5263			version_number: VersionNumber::default(),
5264			program_info: if cuei {
5265				vec![Descriptor {
5266					tag: 0x05,
5267					data: b"CUEI".to_vec(),
5268				}]
5269			} else {
5270				Vec::new()
5271			},
5272			es_info: es
5273				.iter()
5274				.map(|&(stream_type, pid)| EsInfo {
5275					stream_type,
5276					elementary_pid: Pid::new(pid).unwrap(),
5277					descriptors: Vec::new(),
5278				})
5279				.collect(),
5280		};
5281
5282		let write = |out: &mut Vec<u8>, pid: u16, payload: TsPayload| {
5283			let packet = TsPacket {
5284				header: TsHeader {
5285					transport_error_indicator: false,
5286					transport_priority: false,
5287					pid: Pid::new(pid).unwrap(),
5288					transport_scrambling_control: TransportScramblingControl::NotScrambled,
5289					continuity_counter: ContinuityCounter::default(),
5290				},
5291				adaptation_field: None,
5292				payload: Some(payload),
5293			};
5294			TsPacketWriter::new(out).write_ts_packet(&packet).unwrap();
5295		};
5296
5297		let mut out = Vec::new();
5298		write(&mut out, Pid::PAT, TsPayload::Pat(pat));
5299		for &(program_num, pmt_pid, es) in programs {
5300			write(&mut out, pmt_pid, TsPayload::Pmt(pmt(program_num, es)));
5301		}
5302		out
5303	}
5304
5305	// An extended catalog detects the CUEI PID, advertises a cue track, and the
5306	// section is published (a `Catalog<catalog::Ext>` carries the rendition).
5307	#[test]
5308	fn scte35_extension_catalogs_the_cue_track() {
5309		use crate::catalog::hang::Catalog;
5310		use crate::container::ts::catalog::Ext;
5311
5312		let mut broadcast = moq_net::broadcast::Info::new().produce();
5313		let catalog = crate::catalog::Producer::new(
5314			&mut broadcast,
5315			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
5316		)
5317		.unwrap();
5318		let mut import = super::Import::new(broadcast, catalog.reserve());
5319
5320		let mut bytes = bytes::BytesMut::new();
5321		bytes.extend_from_slice(&synth_pmt(
5322			&[
5323				(StreamType::Mpeg2Video, PCR_PID),
5324				(StreamType::Dts8ChannelLosslessAudio, 0x21),
5325			],
5326			true,
5327		));
5328		bytes.extend_from_slice(&pcr_packet(PCR_PID, 24_300_000));
5329		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
5330		bytes.extend_from_slice(&pes_packet(PCR_PID, 90_000));
5331		bytes.extend_from_slice(&pcr_packet(PCR_PID, 27_000_000));
5332		import.decode(&bytes).unwrap();
5333		let _finished = import.finish().unwrap();
5334
5335		assert_eq!(
5336			cue_tracks(&catalog.snapshot().ext.mpegts),
5337			1,
5338			"expected one scte35 rendition"
5339		);
5340	}
5341
5342	// An application extension composing the `mpegts` section counts its verbatim tracks as
5343	// servable without implementing anything beyond `ts::Catalog`, so an input whose only track
5344	// is a cue announces.
5345	#[tokio::test(start_paused = true)]
5346	async fn a_composed_extension_publishes_a_cue_only_catalog() {
5347		use crate::catalog::hang::{Catalog, CatalogExt};
5348		use crate::container::ts::catalog::{Catalog as TsCatalog, Mpegts};
5349
5350		#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, PartialEq)]
5351		struct Composed {
5352			#[serde(default, skip_serializing_if = "Mpegts::is_empty")]
5353			mpegts: Mpegts,
5354			#[serde(default, skip_serializing_if = "Option::is_none")]
5355			app: Option<u32>,
5356		}
5357		impl CatalogExt for Composed {}
5358		impl TsCatalog for Composed {
5359			fn mpegts_mut(&mut self) -> Option<&mut Mpegts> {
5360				Some(&mut self.mpegts)
5361			}
5362		}
5363
5364		let mut broadcast = moq_net::broadcast::Info::new().produce();
5365		let catalog = crate::catalog::Producer::new(
5366			&mut broadcast,
5367			crate::catalog::Config::default().with_catalog(Catalog::<Composed>::default()),
5368		)
5369		.unwrap();
5370		let mut updates = catalog.consume().unwrap();
5371		let mut import = super::Import::new(broadcast, catalog.reserve());
5372
5373		let mut bytes = bytes::BytesMut::new();
5374		bytes.extend_from_slice(&synth_pmt(
5375			&[
5376				(StreamType::Mpeg2Video, PCR_PID),
5377				(StreamType::Dts8ChannelLosslessAudio, 0x21),
5378			],
5379			true,
5380		));
5381		bytes.extend_from_slice(&pcr_packet(PCR_PID, 24_300_000));
5382		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
5383		bytes.extend_from_slice(&pes_packet(PCR_PID, 90_000));
5384		bytes.extend_from_slice(&pcr_packet(PCR_PID, 27_000_000));
5385		import.decode(&bytes).unwrap();
5386		let _finished = import.finish().unwrap();
5387
5388		let first = kio::clock::timeout(Duration::from_secs(10), updates.next())
5389			.await
5390			.expect("the cue track publishes the initial catalog")
5391			.unwrap()
5392			.unwrap()
5393			.value;
5394		assert!(
5395			first.video.renditions.is_empty() && first.audio.renditions.is_empty(),
5396			"only the extension lists a track"
5397		);
5398		assert_eq!(cue_tracks(&first.ext.mpegts), 1, "the cue track is listed");
5399	}
5400
5401	// The base catalog (`Catalog<()>`) can't carry cues, so a detected CUEI PID routes to
5402	// Stream::Ignored: dropped before the reader (no abort), with no ScteStream created, so
5403	// the publishing lock is never taken and the catalog is never republished empty.
5404	#[tokio::test(start_paused = true)]
5405	async fn base_catalog_routes_cue_pid_to_ignored() {
5406		let mut broadcast = moq_net::broadcast::Info::new().produce();
5407		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5408		let mut updates = catalog.consume().unwrap();
5409		let mut import = super::Import::new(broadcast, catalog.reserve());
5410
5411		let mut bytes = bytes::BytesMut::new();
5412		bytes.extend_from_slice(&synth_pmt(&[(StreamType::Dts8ChannelLosslessAudio, 0x21)], true));
5413		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
5414		import.decode(&bytes).unwrap(); // must not abort on the private section
5415
5416		assert!(
5417			import.sections.is_empty(),
5418			"no cue stream is created for a base catalog"
5419		);
5420		assert!(
5421			matches!(
5422				import.streams.get(&mpeg2ts::ts::Pid::new(0x21).unwrap()),
5423				Some(super::Stream::Ignored)
5424			),
5425			"the CUEI PID routes to Ignored"
5426		);
5427		let _finished = import.finish().unwrap();
5428		// SCTE detection takes no lock here (video/audio would still publish later): the old
5429		// discarding ScteStream took the lock and republished an empty catalog on this path.
5430		assert!(
5431			kio::clock::timeout(Duration::from_millis(10), updates.next())
5432				.await
5433				.is_err(),
5434			"SCTE detection must not publish the base catalog"
5435		);
5436	}
5437
5438	// A PMT without CUEI first routes the 0x86 PID to Ignored; a later PMT with CUEI upgrades
5439	// it to a cue track. ensure_scte drops the stale Ignored route and decode prefers `scte`,
5440	// so the cue publishes.
5441	#[tokio::test(start_paused = true)]
5442	async fn pmt_without_cuei_then_with_cuei_upgrades() {
5443		use crate::catalog::hang::{Catalog, Wire};
5444		use crate::container::Consumer;
5445		use crate::container::ts::catalog::Ext;
5446
5447		const SECTION_PID: u16 = 0x0021;
5448		let pid = mpeg2ts::ts::Pid::new(SECTION_PID).unwrap();
5449
5450		let mut broadcast = moq_net::broadcast::Info::new().produce();
5451		let consumer = broadcast.consume();
5452		let catalog = crate::catalog::Producer::new(
5453			&mut broadcast,
5454			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
5455		)
5456		.unwrap();
5457		let mut import = super::Import::new(broadcast, catalog.reserve());
5458
5459		// First PMT lacks CUEI: the 0x86 PID is ambiguous and routes to Ignored.
5460		let mut bytes = bytes::BytesMut::new();
5461		bytes.extend_from_slice(&synth_pmt(
5462			&[
5463				(StreamType::Mpeg2Video, PCR_PID),
5464				(StreamType::Dts8ChannelLosslessAudio, SECTION_PID),
5465			],
5466			false,
5467		));
5468		import.decode(&bytes).unwrap();
5469		assert!(
5470			matches!(import.streams.get(&pid), Some(super::Stream::Ignored)),
5471			"pre-CUEI PMT routes the PID to Ignored"
5472		);
5473
5474		// Second PMT carries CUEI: upgrade to a cue track, then a section on the same PID.
5475		let mut bytes = bytes::BytesMut::new();
5476		bytes.extend_from_slice(&synth_pmt(
5477			&[
5478				(StreamType::Mpeg2Video, PCR_PID),
5479				(StreamType::Dts8ChannelLosslessAudio, SECTION_PID),
5480			],
5481			true,
5482		));
5483		bytes.extend_from_slice(&pcr_packet(PCR_PID, 24_300_000));
5484		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
5485		bytes.extend_from_slice(&pes_packet(PCR_PID, 90_000));
5486		bytes.extend_from_slice(&pcr_packet(PCR_PID, 27_000_000));
5487		import.decode(&bytes).unwrap();
5488
5489		assert!(
5490			!import.streams.contains_key(&pid),
5491			"upgrade drops the stale Ignored route"
5492		);
5493		assert_eq!(
5494			cue_tracks(&catalog.snapshot().ext.mpegts),
5495			1,
5496			"upgrade advertises the cue track"
5497		);
5498
5499		// The importer clears its verbatim entries from the catalog when it drops, so read the
5500		// track name while it is still registered.
5501		let name = track_on(&catalog.snapshot().ext.mpegts, SECTION_PID);
5502		let _finished = import.finish().unwrap();
5503		let track = consumer
5504			.track(&name)
5505			.unwrap()
5506			.subscribe(
5507				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
5508					moq_net::track::Start::Live {
5509						min: Some(RECORDING_MAX_AGE),
5510						max: Some(RECORDING_MAX_AGE),
5511					},
5512				)]),
5513			)
5514			.await
5515			.unwrap();
5516		let mut reader = Consumer::new(track, Wire::legacy(crate::container::Kind::Data));
5517		let frame = kio::clock::timeout(Duration::from_secs(1), reader.read_frame())
5518			.await
5519			.expect("cue read timed out")
5520			.unwrap()
5521			.expect("a published cue frame");
5522		assert_eq!(
5523			&frame.payload[..],
5524			&CUE[..],
5525			"verbatim splice_info_section after upgrade"
5526		);
5527	}
5528
5529	/// A CUEI-marked 0x86 section is data, not audio, so a quiet second is not logged.
5530	/// The video PID beside it, stalled with the same frozen count, is.
5531	#[test]
5532	#[tracing_test::traced_test]
5533	fn sparse_cuei_pid_beside_a_stalled_video_is_not_logged() {
5534		use crate::catalog::hang::Catalog;
5535		use crate::container::ts::catalog::Ext;
5536
5537		// Not 0x100: `synth_pmt` puts the PMT there, and a later packet on that PID is PSI.
5538		const VIDEO: u16 = 0x110;
5539		const CUE_PID: u16 = 0x21;
5540
5541		let mut broadcast = moq_net::broadcast::Info::new().produce();
5542		let catalog = crate::catalog::Producer::new(
5543			&mut broadcast,
5544			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
5545		)
5546		.unwrap();
5547		let mut import = super::Import::new(broadcast, catalog.reserve());
5548
5549		let mut bytes = bytes::BytesMut::new();
5550		bytes.extend_from_slice(&synth_pmt(
5551			&[
5552				(StreamType::Mpeg2Video, VIDEO),
5553				(StreamType::Dts8ChannelLosslessAudio, CUE_PID),
5554			],
5555			true,
5556		));
5557		bytes.extend_from_slice(&pcr_packet(VIDEO, 24_300_000));
5558		// A sequence header, so the picture opens a group rather than waiting for one.
5559		bytes.extend_from_slice(&video_pes(VIDEO, 0, 90_000, None, &[0, 0, 1, 0xb3, 0, 0, 1, 0]));
5560		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
5561		bytes.extend_from_slice(&pcr_packet(VIDEO, 27_000_000));
5562		import.decode(&bytes).unwrap();
5563
5564		let stats = import.stats();
5565		assert_eq!(stats.streams[&VIDEO].class, super::stats::Class::Video);
5566		assert_eq!(stats.streams[&VIDEO].track, ".ts");
5567		assert!(
5568			stats.streams[&VIDEO].units >= 1,
5569			"the video PID delivered before it stalled"
5570		);
5571		assert_eq!(stats.streams[&CUE_PID].class, super::stats::Class::Data, "{stats:?}");
5572		assert_eq!(stats.streams[&CUE_PID].track, ".ts");
5573		assert!(stats.streams[&CUE_PID].units >= 1, "the cue section was counted");
5574
5575		let mut log = crate::container::ts::stats::Log::default();
5576		log.sample(stats);
5577		log.sample(import.stats());
5578
5579		logs_assert(|lines: &[&str]| {
5580			let stopped: Vec<_> = lines
5581				.iter()
5582				.filter(|line| line.contains("stopped delivering access units"))
5583				.collect();
5584			match stopped.as_slice() {
5585				[line] if line.contains("pid=272 ") && !line.contains("pid=33 ") => Ok(()),
5586				_ => Err(format!("expected only the stalled video PID, got {stopped:?}")),
5587			}
5588		});
5589	}
5590
5591	/// The section tracks the `mpegts` section lists, beside any whole-PES video clocking them.
5592	fn cue_tracks(mpegts: &super::catalog::Mpegts) -> usize {
5593		mpegts.tracks.values().filter(|track| track.verbatim.is_some()).count()
5594	}
5595
5596	/// The track the `mpegts` section carries `pid` on.
5597	fn track_on(mpegts: &super::catalog::Mpegts, pid: u16) -> String {
5598		let found = mpegts.tracks.iter().find(|(_, track)| track.pid == pid);
5599		found.expect("a track on the PID").0.clone()
5600	}
5601
5602	/// A PUSI TS packet on `pid` carrying a minimal PES with `pts` (90 kHz) and a
5603	/// 1-byte dummy payload, for streams we observe only for their PTS.
5604	fn pes_packet(pid: u16, pts: u64) -> Vec<u8> {
5605		let pts_field = [
5606			0x21 | (((pts >> 30) & 0x07) << 1) as u8,
5607			((pts >> 22) & 0xff) as u8,
5608			0x01 | (((pts >> 15) & 0x7f) << 1) as u8,
5609			((pts >> 7) & 0xff) as u8,
5610			0x01 | ((pts & 0x7f) << 1) as u8,
5611		];
5612		let mut pes = vec![0x00, 0x00, 0x01, 0xe0]; // PES start code + a video stream_id
5613		let pes_len = 3 + 5 + 1; // flags(2) + header_data_length(1) + PTS(5) + payload(1)
5614		pes.push((pes_len >> 8) as u8);
5615		pes.push((pes_len & 0xff) as u8);
5616		pes.push(0x80); // '10' marker bits
5617		pes.push(0x80); // PTS_DTS_flags = '10' (PTS only)
5618		pes.push(0x05); // PES_header_data_length
5619		pes.extend_from_slice(&pts_field);
5620		pes.push(0xff); // dummy payload
5621
5622		let mut p = vec![0x47, 0x40 | ((pid >> 8) as u8 & 0x1f), (pid & 0xff) as u8, 0x10];
5623		p.extend_from_slice(&pes);
5624		assert!(p.len() <= 188, "PES packet overflows 188 bytes");
5625		p.resize(188, 0xff);
5626		p
5627	}
5628
5629	// The SCTE-35 media clock follows the video PTS only: a private PES never sets it,
5630	// and a private PES arriving after the video must not overwrite it.
5631	#[test]
5632	fn media_clock_follows_video_not_private_pes() {
5633		const VIDEO_PID: u16 = 0x0050;
5634		const PRIVATE_PID: u16 = 0x0051;
5635
5636		let mut broadcast = moq_net::broadcast::Info::new().produce();
5637		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5638		let mut import = super::Import::new(broadcast, catalog.reserve());
5639
5640		let mut bytes = bytes::BytesMut::new();
5641		bytes.extend_from_slice(&synth_pmt(
5642			&[
5643				(StreamType::Mpeg2Video, VIDEO_PID),
5644				(StreamType::Mpeg2PacketizedData, PRIVATE_PID),
5645			],
5646			true,
5647		));
5648		import.decode(&bytes).unwrap();
5649
5650		// Private before video: no clock yet.
5651		import.decode(pes_packet(PRIVATE_PID, 1_000).as_slice()).unwrap();
5652		assert!(import.last_pts.is_none(), "a private PES must not start the clock");
5653
5654		// Video sets the clock.
5655		import.decode(pes_packet(VIDEO_PID, 90_000).as_slice()).unwrap();
5656		let after_video = import.last_pts;
5657		assert!(after_video.is_some(), "MPEG-2 video PTS must set the clock");
5658
5659		// Private after video: must NOT overwrite it.
5660		import.decode(pes_packet(PRIVATE_PID, 270_000).as_slice()).unwrap();
5661		assert_eq!(
5662			import.last_pts, after_video,
5663			"a later private PES must not overwrite the clock"
5664		);
5665	}
5666
5667	// MPEG-2 video only drives the section clock, so with nothing else to flush it must still
5668	// anchor the catalog, or cues stamped with its PTS map to the construction-time clock.
5669	#[test]
5670	fn a_clock_only_stream_anchors_the_catalog() {
5671		const VIDEO_PID: u16 = 0x0050;
5672		const PTS_SECS: u64 = 3600;
5673
5674		let mut broadcast = moq_net::broadcast::Info::new().produce();
5675		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5676		let mut import = super::Import::new(broadcast, catalog.reserve());
5677
5678		import
5679			.decode(&synth_pmt(&[(StreamType::Mpeg2Video, VIDEO_PID)], true))
5680			.unwrap();
5681		import
5682			.decode(pes_packet(VIDEO_PID, PTS_SECS * 90_000).as_slice())
5683			.unwrap();
5684
5685		let now = catalog.clock().now().as_micros().unwrap() / 1_000_000;
5686		assert!(
5687			(PTS_SECS as u128..PTS_SECS as u128 + 5).contains(&now),
5688			"catalog clock reads {now}s, not the first video PTS"
5689		);
5690	}
5691
5692	/// A `splice_insert` section splicing at `pts_time`, with no `pts_adjustment` and a valid CRC.
5693	fn splice_insert(pts_time: u64) -> Vec<u8> {
5694		// table_id, length (filled below), protocol_version, pts_adjustment, cw_index, tier, and a
5695		// 15-byte splice_insert command.
5696		let mut section = vec![0xfc, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xf0, 15, 0x05];
5697		section.extend_from_slice(&1u32.to_be_bytes()); // splice_event_id
5698		section.push(0x7f); // not cancelled
5699		section.push(0xcf); // out of network, program splice, no duration, not immediate
5700		section.push(0xfe | ((pts_time >> 32) as u8 & 1)); // time_specified, then the PTS
5701		section.extend_from_slice(&(pts_time as u32).to_be_bytes());
5702		section.extend_from_slice(&[0, 1, 0, 0]); // unique_program_id, avail_num, avails_expected
5703		section.extend_from_slice(&[0, 0]); // descriptor_loop_length
5704		section[2] = (section.len() - 3 + 4) as u8;
5705		let crc = super::psi::CRC.checksum(&section);
5706		section.extend_from_slice(&crc.to_be_bytes());
5707		section
5708	}
5709
5710	/// A TS import joining a clock already in use shifts its media onto that clock, so its
5711	/// SCTE-35 sections absorb the same shift in `pts_adjustment`: in the export, a splice time
5712	/// lands on the exported picture it names, and the section still verifies.
5713	#[tokio::test(start_paused = true)]
5714	async fn a_splice_follows_its_media_onto_a_clock_in_use() {
5715		splice_onto_a_clock_in_use(CueAt::AfterVideo).await;
5716	}
5717
5718	/// A cue arriving before any PES waits for the offset the media takes, rather than
5719	/// publishing unshifted.
5720	#[tokio::test(start_paused = true)]
5721	async fn a_startup_splice_follows_its_media_onto_a_clock_in_use() {
5722		splice_onto_a_clock_in_use(CueAt::BeforeVideo).await;
5723	}
5724
5725	/// A non-video PES anchors a cue's placement on the shifted media timeline.
5726	#[tokio::test(start_paused = true)]
5727	async fn a_splice_released_before_video_lands_on_the_media_timeline() {
5728		splice_onto_a_clock_in_use(CueAt::BeforePrivate).await;
5729	}
5730
5731	/// A timebase another importer already anchored still holds a cue until this importer has a
5732	/// timestamp to stamp it with.
5733	#[tokio::test(start_paused = true)]
5734	async fn a_splice_on_an_anchored_input_waits_for_its_media() {
5735		splice_onto_a_clock_in_use(CueAt::BeforeVideoOnAnAnchoredInput).await;
5736	}
5737
5738	/// Where the cue arrives relative to the first PES.
5739	enum CueAt {
5740		AfterVideo,
5741		BeforeVideo,
5742		/// Ahead of a private PES at the first picture's PTS, which anchors the timebase.
5743		BeforePrivate,
5744		/// Ahead of the first picture, on a timebase placed before the import starts.
5745		BeforeVideoOnAnAnchoredInput,
5746	}
5747
5748	async fn splice_onto_a_clock_in_use(at: CueAt) {
5749		use crate::catalog::hang::Catalog;
5750		use crate::container::ts::catalog::Ext;
5751
5752		const VIDEO_PID: u16 = 0x0050;
5753		const CUE_PID: u16 = 0x0021;
5754		const PRIVATE_PID: u16 = 0x0051;
5755		const MASK: u64 = (1 << 33) - 1;
5756		// Ten pictures a second from one second in; the cue splices at the sixth.
5757		let picture = |k: u64| 90_000 + k * 9_000;
5758
5759		let mut broadcast = moq_net::broadcast::Info::new().produce();
5760		let consumer = broadcast.consume();
5761		let catalog = crate::catalog::Producer::new(
5762			&mut broadcast,
5763			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
5764		)
5765		.unwrap();
5766		// A capture took the clock, which reads ten seconds: the feed shifts nine seconds later.
5767		let _capture = catalog.clock();
5768		let anchored = matches!(at, CueAt::BeforeVideoOnAnAnchoredInput);
5769		let timebase = catalog.timebase();
5770		if anchored {
5771			// The shift then depends on the wall clock, so only its consistency is checked.
5772			let first = Timestamp::from_scale(picture(0), 90_000).unwrap();
5773			timebase.place(first, kio::clock::wall()).unwrap();
5774		}
5775		let mut import = super::Import::new(broadcast, catalog.reserve()).with_timebase(timebase);
5776
5777		let mut bytes = synth_pmt(
5778			&[
5779				(StreamType::H264, VIDEO_PID),
5780				(StreamType::Dts8ChannelLosslessAudio, CUE_PID),
5781				(StreamType::Mpeg2PacketizedData, PRIVATE_PID),
5782			],
5783			true,
5784		);
5785		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 24_300_000));
5786		let cue_packet = packet(true, 0, 0, &splice_insert(picture(5)));
5787		match at {
5788			CueAt::AfterVideo => {}
5789			CueAt::BeforeVideo | CueAt::BeforeVideoOnAnAnchoredInput => bytes.extend_from_slice(&cue_packet),
5790			CueAt::BeforePrivate => {
5791				bytes.extend_from_slice(&cue_packet);
5792				bytes.extend_from_slice(&pes_packet(PRIVATE_PID, picture(0)));
5793			}
5794		}
5795		for k in 0..20 {
5796			bytes.extend_from_slice(&pcr_packet(VIDEO_PID, (81_000 + k * 9_000) * 300));
5797			bytes.extend_from_slice(&audio_pes_packet(
5798				VIDEO_PID,
5799				k as u8,
5800				picture(k),
5801				&annexb_au(k % 10 == 0),
5802			));
5803			if k == 0 && matches!(at, CueAt::AfterVideo) {
5804				bytes.extend_from_slice(&cue_packet);
5805			}
5806		}
5807		import.decode(&bytes).unwrap();
5808		let _finished = import.finish().unwrap();
5809
5810		let exporter = crate::container::ts::export_test::open_ts(
5811			crate::source::announced(&consumer).await,
5812			crate::catalog::CatalogFormat::Hang,
5813			RECORDING_MAX_AGE,
5814		)
5815		.await
5816		.unwrap();
5817		let mut exporter = exporter.with_replay();
5818		let mut ts = Vec::new();
5819		while let Ok(Some(frame)) = kio::clock::timeout(RECORDING_MAX_AGE * 3, exporter.next())
5820			.await
5821			.map(|r| r.unwrap())
5822		{
5823			ts.extend_from_slice(&frame.payload);
5824		}
5825
5826		let stamp = |b: &[u8]| {
5827			u64::from((b[0] >> 1) & 7) << 30
5828				| u64::from(b[1]) << 22
5829				| u64::from(b[2] >> 1) << 15
5830				| u64::from(b[3]) << 7
5831				| u64::from(b[4] >> 1)
5832		};
5833		let mut pictures = Vec::new();
5834		let mut cue = None;
5835		for packet in ts.as_chunks::<188>().0 {
5836			let pid = u16::from(packet[1] & 0x1f) << 8 | u16::from(packet[2]);
5837			if packet[1] & 0x40 == 0 || packet[3] & 0x10 == 0 {
5838				continue;
5839			}
5840			let start = 4 + if packet[3] & 0x20 != 0 {
5841				usize::from(packet[4]) + 1
5842			} else {
5843				0
5844			};
5845			let payload = &packet[start..];
5846			if pid == CUE_PID {
5847				let section = &payload[1 + usize::from(payload[0])..];
5848				let len = 3 + (usize::from(section[1] & 0x0f) << 8 | usize::from(section[2]));
5849				cue = Some(section[..len].to_vec());
5850			} else if pid != PRIVATE_PID && payload.starts_with(&[0, 0, 1]) && (0xe0..=0xef).contains(&payload[3]) {
5851				pictures.push(stamp(&payload[9..14]));
5852			}
5853		}
5854
5855		let cue = cue.expect("the cue is exported");
5856		assert_eq!(super::psi::CRC.checksum(&cue), 0, "the section's CRC verifies");
5857		let adjustment = u64::from(cue[4] & 1) << 32 | u64::from(u32::from_be_bytes(cue[5..9].try_into().unwrap()));
5858		let pts_time = u64::from(cue[20] & 1) << 32 | u64::from(u32::from_be_bytes(cue[21..25].try_into().unwrap()));
5859		assert_eq!(pts_time, picture(5), "the splice time itself is untouched");
5860		if !anchored {
5861			assert_eq!(adjustment, 810_000, "the nine seconds the media shifted");
5862		}
5863		assert_eq!(pictures.len(), 20, "{pictures:?}");
5864		// A wall-derived shift isn't a whole number of ticks, so the exported picture may round
5865		// one tick lower than the section's shift.
5866		let slack = u64::from(anchored);
5867		let splice = (pts_time + adjustment) & MASK;
5868		assert!(
5869			(pictures[5]..=pictures[5] + slack).contains(&splice),
5870			"the splice at {splice} lands on the picture it names: {pictures:?}"
5871		);
5872	}
5873
5874	/// A PUSI TS packet on `pid`: a bounded audio PES (stream_id 0xC0) carrying
5875	/// `payload` (whole codec frames or a fragment of one), sized exactly via
5876	/// adaptation-field stuffing so the PES completes (and flushes) on this packet.
5877	fn audio_pes_packet(pid: u16, cc: u8, pts: u64, payload: &[u8]) -> Vec<u8> {
5878		let pts_field = [
5879			0x21 | (((pts >> 30) & 0x07) << 1) as u8,
5880			((pts >> 22) & 0xff) as u8,
5881			0x01 | (((pts >> 15) & 0x7f) << 1) as u8,
5882			((pts >> 7) & 0xff) as u8,
5883			0x01 | ((pts & 0x7f) << 1) as u8,
5884		];
5885		let mut pes = vec![0x00, 0x00, 0x01, 0xc0];
5886		let pes_len = 3 + 5 + payload.len();
5887		pes.push((pes_len >> 8) as u8);
5888		pes.push((pes_len & 0xff) as u8);
5889		pes.extend_from_slice(&[0x80, 0x80, 0x05]); // marker bits, PTS only, header len
5890		pes.extend_from_slice(&pts_field);
5891		pes.extend_from_slice(payload);
5892
5893		let af_len = 184 - 1 - pes.len();
5894		let mut p = vec![
5895			0x47,
5896			0x40 | ((pid >> 8) as u8 & 0x1f),
5897			(pid & 0xff) as u8,
5898			0x30 | (cc & 0x0f),
5899		];
5900		p.push(af_len as u8);
5901		if af_len > 0 {
5902			p.push(0x00); // no AF flags; the rest is stuffing
5903			p.extend(std::iter::repeat_n(0xff, af_len - 1));
5904		}
5905		p.extend_from_slice(&pes);
5906		assert_eq!(p.len(), 188, "audio PES packet must fill exactly one TS packet");
5907		p
5908	}
5909
5910	#[test]
5911	fn aac_jitter_accumulates_adjacent_pes_per_pid() {
5912		const AUDIO: u16 = 0x60;
5913		const VIDEO: u16 = 0x61;
5914		const OTHER: u16 = 0x62;
5915		let mut broadcast = moq_net::broadcast::Info::new().produce();
5916		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5917		let mut import = super::Import::new(broadcast, catalog.reserve());
5918		import
5919			.decode(&synth_pmt(
5920				&[
5921					(StreamType::AdtsAac, AUDIO),
5922					(StreamType::Mpeg2Video, VIDEO),
5923					(StreamType::AdtsAac, OTHER),
5924				],
5925				false,
5926			))
5927			.unwrap();
5928		let mut frame = super::adts::write_header(2, 44_100, 2, 8).unwrap().to_vec();
5929		frame.extend_from_slice(&[0; 8]);
5930		for i in 0..4 {
5931			import
5932				.decode(&audio_pes_packet(
5933					AUDIO,
5934					i,
5935					90_000 + u64::from(i) * 4180,
5936					&frame.repeat(2),
5937				))
5938				.unwrap();
5939		}
5940		let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
5941		let jitter = catalog.snapshot().audio.renditions[&name].jitter.unwrap();
5942		import
5943			.decode(&audio_pes_packet(OTHER, 0, 900_000, &frame.repeat(2)))
5944			.unwrap();
5945		let snapshot = catalog.snapshot();
5946		let other = snapshot
5947			.audio
5948			.renditions
5949			.iter()
5950			.find(|(key, _)| *key != &name)
5951			.unwrap()
5952			.1;
5953		assert_eq!(other.jitter.unwrap().as_nanos().div_ceil(1_000_000), 47);
5954		assert_eq!(jitter.as_nanos().div_ceil(1_000_000), 186);
5955		import.decode(&pes_packet(VIDEO, 110_000)).unwrap();
5956		import
5957			.decode(&audio_pes_packet(AUDIO, 4, 110_000, &frame.repeat(2)))
5958			.unwrap();
5959		assert_eq!(catalog.snapshot().audio.renditions[&name].jitter, Some(jitter));
5960	}
5961
5962	#[test]
5963	fn aac_pes_jitter_survives_bitrate_updates() {
5964		const PID: u16 = 0x60;
5965		let mut broadcast = moq_net::broadcast::Info::new().produce();
5966		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
5967		let mut import = super::Import::new(broadcast, catalog.reserve());
5968		import.decode(&synth_pmt(&[(StreamType::AdtsAac, PID)], false)).unwrap();
5969		let mut frame = super::adts::write_header(2, 44_100, 2, 8).unwrap().to_vec();
5970		frame.extend_from_slice(&[0; 8]);
5971		import
5972			.decode(&audio_pes_packet(PID, 0, 90_000, &frame.repeat(7)))
5973			.unwrap();
5974		let initial = catalog
5975			.snapshot()
5976			.audio
5977			.renditions
5978			.values()
5979			.next()
5980			.unwrap()
5981			.jitter
5982			.unwrap();
5983		assert_eq!(
5984			initial.as_nanos().div_ceil(1_000_000),
5985			163,
5986			"a seven-frame PES is one burst"
5987		);
5988		for i in 0..60 {
5989			let pts = 90_000 + (7 + i) * 1024 * 90_000 / 44_100;
5990			import
5991				.decode(&audio_pes_packet(PID, ((i + 1) % 16) as u8, pts, &frame))
5992				.unwrap();
5993		}
5994		let _finished = import.finish().unwrap();
5995		let snapshot = catalog.snapshot();
5996		let config = snapshot.audio.renditions.values().next().unwrap();
5997		assert!(config.bitrate.is_some(), "exercise a bitrate refinement");
5998		assert_eq!(config.jitter, Some(initial));
5999	}
6000
6001	#[test]
6002	fn aac_pes_jitter_counts_completed_split_frames() {
6003		const PID: u16 = 0x60;
6004		let mut broadcast = moq_net::broadcast::Info::new().produce();
6005		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6006		let mut import = super::Import::new(broadcast, catalog.reserve());
6007		import.decode(&synth_pmt(&[(StreamType::AdtsAac, PID)], false)).unwrap();
6008		let mut frame = super::adts::write_header(2, 44_100, 2, 8).unwrap().to_vec();
6009		frame.extend_from_slice(&[0; 8]);
6010		let mut first = frame.repeat(2);
6011		first.extend_from_slice(&frame[..10]);
6012		import.decode(&audio_pes_packet(PID, 0, 90_000, &first)).unwrap();
6013		let mut second = frame[10..].to_vec();
6014		second.extend_from_slice(&frame.repeat(6));
6015		// A timestamp jump must not turn time spent waiting for input into publisher jitter.
6016		import.decode(&audio_pes_packet(PID, 1, 900_000, &second)).unwrap();
6017		let snapshot = catalog.snapshot();
6018		let jitter = snapshot.audio.renditions.values().next().unwrap().jitter.unwrap();
6019		assert_eq!(jitter.as_nanos().div_ceil(1_000_000), 163);
6020	}
6021
6022	/// Open a bounded audio PES whose declared payload is longer than this packet carries.
6023	fn audio_pes_open(pid: u16, cc: u8, pts: u64, declared: usize, payload: &[u8]) -> Vec<u8> {
6024		assert!(payload.len() < declared, "the test PES must remain open");
6025		let pts_field = [
6026			0x21 | (((pts >> 30) & 0x07) << 1) as u8,
6027			((pts >> 22) & 0xff) as u8,
6028			0x01 | (((pts >> 15) & 0x7f) << 1) as u8,
6029			((pts >> 7) & 0xff) as u8,
6030			0x01 | ((pts & 0x7f) << 1) as u8,
6031		];
6032		let mut pes = vec![0x00, 0x00, 0x01, 0xc0];
6033		let pes_len = 3 + 5 + declared;
6034		pes.push((pes_len >> 8) as u8);
6035		pes.push((pes_len & 0xff) as u8);
6036		pes.extend_from_slice(&[0x80, 0x80, 0x05]);
6037		pes.extend_from_slice(&pts_field);
6038		pes.extend_from_slice(payload);
6039
6040		let af_len = 184 - 1 - pes.len();
6041		let mut p = vec![
6042			0x47,
6043			0x40 | ((pid >> 8) as u8 & 0x1f),
6044			(pid & 0xff) as u8,
6045			0x30 | (cc & 0x0f),
6046		];
6047		p.push(af_len as u8);
6048		if af_len > 0 {
6049			p.push(0x00);
6050			p.extend(std::iter::repeat_n(0xff, af_len - 1));
6051		}
6052		p.extend_from_slice(&pes);
6053		assert_eq!(p.len(), 188, "open audio PES packet must fill exactly one TS packet");
6054		p
6055	}
6056
6057	/// Build a non-PUSI TS payload packet with adaptation-field stuffing.
6058	fn ts_continuation(pid: u16, cc: u8, payload: &[u8]) -> Vec<u8> {
6059		let af_len = 184 - 1 - payload.len();
6060		let mut p = vec![0x47, ((pid >> 8) as u8 & 0x1f), (pid & 0xff) as u8, 0x30 | (cc & 0x0f)];
6061		p.push(af_len as u8);
6062		if af_len > 0 {
6063			p.push(0x00);
6064			p.extend(std::iter::repeat_n(0xff, af_len - 1));
6065		}
6066		p.extend_from_slice(payload);
6067		assert_eq!(p.len(), 188, "continuation packet must fill exactly one TS packet");
6068		p
6069	}
6070
6071	/// ffmpeg packs several ADTS frames into one PES, and the importer publishes them as one group
6072	/// in a single synchronous pass. The catalog has to describe that burst, not the
6073	/// 21 ms frame the estimator sees between writes, and a later bitrate refinement must not walk
6074	/// it back to one frame.
6075	#[test]
6076	fn aac_jitter_is_the_pes_burst_not_one_frame() {
6077		const AAC_PID: u16 = 0x0060;
6078		// 1024 samples at 48 kHz, in 90 kHz ticks.
6079		const FRAME: u64 = 1024 * 90_000 / 48_000;
6080		const PER_PES: u64 = 7;
6081
6082		let mut broadcast = moq_net::broadcast::Info::new().produce();
6083		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6084		let mut import = super::Import::new(broadcast, catalog.reserve());
6085
6086		let mut bytes = bytes::BytesMut::new();
6087		bytes.extend_from_slice(&synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false));
6088
6089		// Ten PES of seven frames: well over a second of media, so the bitrate window closes and
6090		// republishes the rendition at least once.
6091		for pes in 0..10u64 {
6092			let mut payload = Vec::new();
6093			for frame in 0..PER_PES {
6094				payload.extend_from_slice(&adts_frame(17, 0xA0 | frame as u8));
6095			}
6096			bytes.extend_from_slice(&audio_pes_packet(
6097				AAC_PID,
6098				pes as u8 & 0x0f,
6099				pes * PER_PES * FRAME,
6100				&payload,
6101			));
6102		}
6103
6104		import.decode(&bytes).unwrap();
6105		let _finished = import.finish().unwrap();
6106
6107		let snap = catalog.snapshot();
6108		let aac = snap.audio.renditions.values().next().expect("an AAC rendition");
6109		assert!(aac.bitrate.is_some(), "the bitrate window closed at least once");
6110
6111		let jitter = aac.jitter.expect("AAC publishes a jitter");
6112		// One frame is ~21 ms; the burst is six or seven of them (the last frame of a PES waits
6113		// for the next one to confirm it).
6114		assert!(
6115			jitter >= std::time::Duration::from_millis(120),
6116			"jitter describes one frame, not the burst: {jitter:?}"
6117		);
6118		assert!(
6119			jitter <= std::time::Duration::from_millis(160),
6120			"jitter grew past one burst: {jitter:?}"
6121		);
6122	}
6123
6124	// MP2/AC-3 flush like any audio PES but don't consume the jitter hint; if one
6125	// anchored the audio run, an AAC PID in the same TS would publish a jitter
6126	// inflated by the inter-PID PTS offset.
6127	#[test]
6128	fn verbatim_audio_does_not_anchor_aac_jitter() {
6129		const AAC_PID: u16 = 0x0060;
6130		const MP2_PID: u16 = 0x0061;
6131
6132		let mut broadcast = moq_net::broadcast::Info::new().produce();
6133		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6134		let mut import = super::Import::new(broadcast, catalog.reserve());
6135
6136		let mut bytes = bytes::BytesMut::new();
6137		bytes.extend_from_slice(&synth_pmt(
6138			&[(StreamType::AdtsAac, AAC_PID), (StreamType::Mpeg1Audio, MP2_PID)],
6139			false,
6140		));
6141		// A whole MP2 frame (MPEG-1 Layer II, 32 kbps, 48 kHz, stereo = 96 bytes),
6142		// 2 s ahead of the AAC PES that follows in the same audio run.
6143		// Two frames, in their own PES: a frame is confirmed by the one after it, so a lone
6144		// frame on a PID that never establishes sync is not published at all.
6145		let mut mp2 = vec![0xFF, 0xFD, 0x14, 0x00];
6146		mp2.resize(96, 0xAA);
6147		bytes.extend_from_slice(&audio_pes_packet(MP2_PID, 0, 90_000, &mp2));
6148		bytes.extend_from_slice(&audio_pes_packet(MP2_PID, 1, 92_160, &mp2));
6149
6150		// Two ADTS frames: a frame is confirmed by the one after it, so a lone frame is only
6151		// published at end of stream, after the jitter accounting for its PES has run.
6152		let mut aac = Vec::new();
6153		for _ in 0..2 {
6154			aac.extend_from_slice(&super::adts::write_header(2, 48_000, 2, 8).unwrap());
6155			aac.extend_from_slice(&[0u8; 8]);
6156		}
6157		bytes.extend_from_slice(&audio_pes_packet(AAC_PID, 0, 270_000, &aac));
6158
6159		import.decode(&bytes).unwrap();
6160		let _finished = import.finish().unwrap();
6161
6162		let snap = catalog.snapshot();
6163		assert_eq!(snap.audio.renditions.len(), 2, "AAC and MP2 renditions");
6164		let aac_rendition = snap
6165			.audio
6166			.renditions
6167			.values()
6168			.find(|a| a.codec.to_string().starts_with("mp4a"))
6169			.expect("AAC rendition");
6170		let jitter = aac_rendition.jitter.expect("AAC publishes a jitter");
6171		// Anchored on its own PES: one 1024-sample frame at 48 kHz (~21 ms).
6172		// Anchored on the MP2 PES it would be ~2 s.
6173		assert!(
6174			jitter <= Duration::from_millis(100),
6175			"AAC jitter anchored on a foreign PID: {jitter:?}"
6176		);
6177	}
6178
6179	/// Read every retained frame of the single audio rendition in `catalog`.
6180	async fn read_audio_frames<E: crate::catalog::hang::CatalogExt>(
6181		consumer: &moq_net::broadcast::Consumer,
6182		catalog: &crate::catalog::Producer<E>,
6183	) -> Vec<crate::container::Frame> {
6184		let name = catalog
6185			.snapshot()
6186			.audio
6187			.renditions
6188			.keys()
6189			.next()
6190			.expect("an audio track")
6191			.clone();
6192		let track = consumer
6193			.track(&name)
6194			.unwrap()
6195			.subscribe(
6196				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
6197					moq_net::track::Start::Live {
6198						min: Some(RECORDING_MAX_AGE),
6199						max: Some(RECORDING_MAX_AGE),
6200					},
6201				)]),
6202			)
6203			.await
6204			.unwrap();
6205		let mut reader =
6206			crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Audio));
6207		let mut frames = Vec::new();
6208		while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await {
6209			frames.push(frame);
6210		}
6211		frames
6212	}
6213
6214	// A looping publisher plays part of a file and wraps to the top (#2729). The wrap rewinds
6215	// the PCR and the audio PTS together, which is an encoder restart, so the identity ends at
6216	// the wrap and the caller publishes the rest as a new broadcast. Every frame published
6217	// before it is still a whole AC-3 frame.
6218	#[tokio::test(start_paused = true)]
6219	async fn legacy_restarts_at_a_looping_file_wrap() {
6220		let data = include_bytes!("test_data/ac3.ts");
6221
6222		// Wrap mid-file on a packet boundary, so the TS layer stays aligned.
6223		let cut = (data.len() / 2) / 188 * 188;
6224		let mut looped = data[..cut].to_vec();
6225		looped.extend_from_slice(data);
6226
6227		let mut broadcast = moq_net::broadcast::Info::new().produce();
6228		let consumer = broadcast.consume();
6229		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6230		let mut import = super::Import::new(broadcast, catalog.reserve());
6231		let restart = import
6232			.decode_or_restart(&bytes::BytesMut::from(&looped[..]))
6233			.unwrap()
6234			.expect("a loop wrap is a restart");
6235		assert!(
6236			matches!(restart.step, crate::container::ts::Step::Rewind { flagged: false, .. }),
6237			"{restart:?}"
6238		);
6239		assert!(
6240			looped.ends_with(&restart.remainder) && restart.remainder.len() <= data.len(),
6241			"the new identity starts at the wrap"
6242		);
6243		let _finished = import.finish().unwrap();
6244
6245		let frames = read_audio_frames(&consumer, &catalog).await;
6246		assert!(!frames.is_empty(), "the pass before the wrap published");
6247		assert!(
6248			frames.iter().all(|f| f.payload[0] == 0x0B && f.payload[1] == 0x77),
6249			"published a frame that doesn't start at an AC-3 sync word"
6250		);
6251	}
6252
6253	/// Read every retained frame of the single video rendition in `catalog`.
6254	async fn read_video_frames(
6255		consumer: &moq_net::broadcast::Consumer,
6256		catalog: &crate::catalog::Producer,
6257	) -> Vec<crate::container::Frame> {
6258		let name = catalog
6259			.snapshot()
6260			.video
6261			.renditions
6262			.keys()
6263			.next()
6264			.expect("a video track")
6265			.clone();
6266		let track = consumer.track(&name).unwrap().subscribe(None).await.unwrap();
6267		let mut reader =
6268			crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data));
6269		let mut frames = Vec::new();
6270		while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await {
6271			frames.push(frame);
6272		}
6273		frames
6274	}
6275
6276	/// Annex-B bytes for one access unit: SPS + PPS + IDR for a keyframe, else a delta slice.
6277	pub(in crate::container::ts) fn annexb_au(keyframe: bool) -> Vec<u8> {
6278		use crate::container::test_util::{IDR, PPS, SPS};
6279		let nals: &[&[u8]] = if keyframe {
6280			&[SPS, PPS, IDR]
6281		} else {
6282			&[&[0x41, 0x9a, 0x00, 0x01]]
6283		};
6284		let mut out = Vec::new();
6285		for nal in nals {
6286			out.extend_from_slice(&[0, 0, 0, 1]);
6287			out.extend_from_slice(nal);
6288		}
6289		out
6290	}
6291
6292	// A PES ending mid-picture cannot prove that picture complete. Keep only AUs
6293	// closed by a codec boundary ahead of a cut, and recover at the next keyframe.
6294	#[tokio::test(start_paused = true)]
6295	async fn video_drops_a_partial_access_unit_across_a_continuity_break() {
6296		const VIDEO_PID: u16 = 0x0050;
6297
6298		let mut broadcast = moq_net::broadcast::Info::new().produce();
6299		let consumer = broadcast.consume();
6300		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6301		let mut import = super::Import::new(broadcast, catalog.reserve());
6302
6303		let pmt = synth_pmt(&[(StreamType::H264, VIDEO_PID)], false);
6304		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6305
6306		// A keyframe cut in half by the wrap: the PES declares more than this packet carries.
6307		let whole = annexb_au(true);
6308		import
6309			.decode(audio_pes_open(VIDEO_PID, 0, 90_000, whole.len() + 32, &whole[..28]).as_slice())
6310			.unwrap();
6311		// The wrap completes the open PES with unrelated bytes, and continuity gives it away.
6312		import
6313			.decode(ts_continuation(VIDEO_PID, 12, &whole[28..]).as_slice())
6314			.unwrap();
6315		// A clean keyframe after it, which is what the track should carry.
6316		import
6317			.decode(audio_pes_packet(VIDEO_PID, 13, 270_000, &whole).as_slice())
6318			.unwrap();
6319		import
6320			.decode(audio_pes_packet(VIDEO_PID, 14, 450_000, &annexb_au(false)).as_slice())
6321			.unwrap();
6322		let _finished = import.finish().unwrap();
6323
6324		let frames = read_video_frames(&consumer, &catalog).await;
6325		assert!(
6326			frames.iter().all(|f| f.payload.len() >= whole.len() || !f.keyframe),
6327			"a keyframe with missing slices reached the track: {:?}",
6328			frames.iter().map(|f| (f.keyframe, f.payload.len())).collect::<Vec<_>>()
6329		);
6330		assert_eq!(
6331			frames.first().map(|f| f.payload.to_vec()),
6332			Some(whole.clone()),
6333			"the first published picture is not the whole keyframe"
6334		);
6335	}
6336
6337	/// One whole ADTS frame carrying `raw_len` bytes of `fill`. `fill` must not be 0xFF,
6338	/// which a resync would mistake for a frame sync.
6339	fn adts_frame(raw_len: usize, fill: u8) -> Vec<u8> {
6340		let mut f = super::adts::write_header(2, 48_000, 2, raw_len).unwrap().to_vec();
6341		f.resize(raw_len + 7, fill);
6342		f
6343	}
6344
6345	// The AAC mirror of `legacy_drops_a_pes_completed_across_a_continuity_break`.
6346	#[tokio::test(start_paused = true)]
6347	async fn aac_drops_a_pes_completed_across_a_continuity_break() {
6348		const AAC_PID: u16 = 0x0060;
6349
6350		let mut broadcast = moq_net::broadcast::Info::new().produce();
6351		let consumer = broadcast.consume();
6352		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6353		let mut import = super::Import::new(broadcast, catalog.reserve());
6354
6355		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
6356		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6357
6358		let mut opening = adts_frame(40, 0xAA);
6359		opening.extend_from_slice(&adts_frame(40, 0xBB)[..25]);
6360		import
6361			.decode(audio_pes_open(AAC_PID, 0, 90_000, 94, &opening).as_slice())
6362			.unwrap();
6363		import
6364			.decode(ts_continuation(AAC_PID, 12, &adts_frame(40, 0xCC)[..32]).as_slice())
6365			.unwrap();
6366		let mut normal = adts_frame(40, 0xDD);
6367		normal.extend_from_slice(&adts_frame(40, 0xEE));
6368		import
6369			.decode(audio_pes_packet(AAC_PID, 13, 270_000, &normal).as_slice())
6370			.unwrap();
6371		let _finished = import.finish().unwrap();
6372
6373		let frames = read_audio_frames(&consumer, &catalog).await;
6374		assert_eq!(
6375			frames.iter().map(|f| f.payload.to_vec()).collect::<Vec<_>>(),
6376			[0xAA, 0xDD, 0xEE]
6377				.map(|fill| adts_frame(40, fill)[7..].to_vec())
6378				.to_vec(),
6379			"the wrap was spliced onto the frame the cut left open"
6380		);
6381	}
6382
6383	// ISO 13818-1 doesn't require AAC frames to align with PES boundaries any more than it
6384	// does the legacy codecs, but only the legacy path reassembled a split frame: AAC
6385	// rejected the PES outright, so a mux that split one killed the broadcast on well-formed
6386	// input, with no corruption or discontinuity involved.
6387	#[tokio::test(start_paused = true)]
6388	async fn aac_frame_split_across_pes_reassembles() {
6389		const AAC_PID: u16 = 0x0060;
6390
6391		let mut broadcast = moq_net::broadcast::Info::new().produce();
6392		let consumer = broadcast.consume();
6393		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6394		let mut import = super::Import::new(broadcast, catalog.reserve());
6395
6396		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
6397		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6398
6399		let frame = adts_frame(40, 0x5A);
6400		import
6401			.decode(audio_pes_packet(AAC_PID, 0, 90_000, &frame[..25]).as_slice())
6402			.expect("a split ADTS frame is not fatal");
6403		// The rest of the split frame, plus the frame that confirms its boundary.
6404		let mut rest = frame[25..].to_vec();
6405		rest.extend_from_slice(&adts_frame(40, 0x77));
6406		import
6407			.decode(audio_pes_packet(AAC_PID, 1, 270_000, &rest).as_slice())
6408			.unwrap();
6409		let _finished = import.finish().unwrap();
6410
6411		let frames = read_audio_frames(&consumer, &catalog).await;
6412		assert_eq!(frames.len(), 2, "the split frame is reassembled, not dropped");
6413		// The ADTS header is stripped: the track carries raw AAC.
6414		assert_eq!(frames[0].payload.as_ref(), &frame[7..], "reassembled byte-exact");
6415		// It began in PES 1 (90000 ticks = 1 s), so PES 2's PTS must not apply to it.
6416		assert_eq!(frames[0].timestamp, Timestamp::from_micros(1_000_000).unwrap());
6417	}
6418
6419	// AAC resyncs past a damaged header for the same reason the legacy codecs do.
6420	#[tokio::test(start_paused = true)]
6421	async fn aac_resyncs_past_damaged_header() {
6422		const AAC_PID: u16 = 0x0060;
6423
6424		let mut broadcast = moq_net::broadcast::Info::new().produce();
6425		let consumer = broadcast.consume();
6426		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6427		let mut import = super::Import::new(broadcast, catalog.reserve());
6428
6429		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
6430		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6431
6432		// Two good frames to lock onto (a frame is confirmed by the one after it), then a
6433		// frame whose syncword lost a bit, then two more good ones.
6434		let mut payload = adts_frame(40, 0xAA);
6435		payload.extend_from_slice(&adts_frame(40, 0xBB));
6436		import
6437			.decode(audio_pes_packet(AAC_PID, 0, 90_000, &payload).as_slice())
6438			.unwrap();
6439
6440		let mut damaged = adts_frame(40, 0x11);
6441		damaged[0] = 0xFE;
6442		let mut hit = damaged.clone();
6443		hit.extend_from_slice(&adts_frame(40, 0xCC));
6444		import
6445			.decode(audio_pes_packet(AAC_PID, 1, 270_000, &hit).as_slice())
6446			.expect("a damaged ADTS header is not fatal");
6447		import
6448			.decode(audio_pes_packet(AAC_PID, 2, 450_000, &adts_frame(40, 0xDD)).as_slice())
6449			.unwrap();
6450		import.finish_in_place().unwrap();
6451
6452		// The track carries raw AAC, so each published frame is its ADTS body.
6453		let frames = read_audio_frames(&consumer, &catalog).await;
6454		assert_eq!(
6455			frames.iter().map(|f| f.payload.to_vec()).collect::<Vec<_>>(),
6456			[0xAA, 0xBB, 0xCC, 0xDD]
6457				.map(|fill| adts_frame(40, fill)[7..].to_vec())
6458				.to_vec(),
6459			"the undamaged frames either side survive, and only the damaged one is dropped"
6460		);
6461		// One resync, charged the damaged frame's 47 bytes (7 header + 40 body).
6462		assert_eq!(
6463			import.stats().streams,
6464			BTreeMap::from([(
6465				AAC_PID,
6466				super::stats::Stream {
6467					track: ".aac".to_string(),
6468					class: super::stats::Class::Audio,
6469					units: 4,
6470					quiet: None,
6471					resyncs: 1,
6472					discarded: 47,
6473					unconfirmed: 0,
6474					..Default::default()
6475				}
6476			)]),
6477			"the resync left no trace an operator could alarm on"
6478		);
6479	}
6480
6481	// AAC reassembles a split frame the same way the legacy codecs do, so it splices the same
6482	// way at a wrap and confirms the join for the same reason. See
6483	// `legacy_confirms_a_frame_joined_out_of_a_carried_tail`.
6484	#[tokio::test(start_paused = true)]
6485	async fn aac_confirms_a_frame_joined_out_of_a_carried_tail() {
6486		const AAC_PID: u16 = 0x0060;
6487
6488		let mut broadcast = moq_net::broadcast::Info::new().produce();
6489		let consumer = broadcast.consume();
6490		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6491		let mut import = super::Import::new(broadcast, catalog.reserve());
6492
6493		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
6494		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6495
6496		// A whole frame, then one cut mid-frame by the wrap.
6497		let mut payload = adts_frame(40, 0xAA);
6498		payload.extend_from_slice(&adts_frame(40, 0xBB)[..25]);
6499		import
6500			.decode(audio_pes_packet(AAC_PID, 0, 90_000, &payload).as_slice())
6501			.unwrap();
6502		// The top of the file again: the tail splices onto its first frame.
6503		let mut wrapped = adts_frame(40, 0xCC);
6504		wrapped.extend_from_slice(&adts_frame(40, 0xDD));
6505		import
6506			.decode(audio_pes_packet(AAC_PID, 1, 270_000, &wrapped).as_slice())
6507			.expect("a splice is not fatal");
6508		import
6509			.decode(audio_pes_packet(AAC_PID, 2, 450_000, &adts_frame(40, 0xEE)).as_slice())
6510			.unwrap();
6511		let _finished = import.finish().unwrap();
6512
6513		// The track carries raw AAC, so each published frame is its ADTS body.
6514		let frames = read_audio_frames(&consumer, &catalog).await;
6515		assert_eq!(
6516			frames.iter().map(|f| f.payload.to_vec()).collect::<Vec<_>>(),
6517			[0xAA, 0xCC, 0xDD, 0xEE]
6518				.map(|fill| adts_frame(40, fill)[7..].to_vec())
6519				.to_vec(),
6520			"the splice cost more than the frame it interrupted"
6521		);
6522		assert_eq!(
6523			frames[1].timestamp,
6524			Timestamp::from_micros(3_000_000).unwrap(),
6525			"not re-anchored on the new PES"
6526		);
6527	}
6528
6529	// The end-of-stream drain, for AAC. See `legacy_drains_a_joined_frame_at_end_of_stream`.
6530	#[tokio::test(start_paused = true)]
6531	async fn aac_drains_a_joined_frame_at_end_of_stream() {
6532		const AAC_PID: u16 = 0x0060;
6533
6534		let mut broadcast = moq_net::broadcast::Info::new().produce();
6535		let consumer = broadcast.consume();
6536		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6537		let mut import = super::Import::new(broadcast, catalog.reserve());
6538
6539		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
6540		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6541
6542		let split = adts_frame(40, 0xBB);
6543		let mut payload = adts_frame(40, 0xAA);
6544		payload.extend_from_slice(&split[..25]);
6545		import
6546			.decode(audio_pes_packet(AAC_PID, 0, 90_000, &payload).as_slice())
6547			.unwrap();
6548		// The rest of the split frame and nothing else, so the stream ends with it joined,
6549		// whole, and unconfirmed.
6550		import
6551			.decode(audio_pes_packet(AAC_PID, 1, 270_000, &split[25..]).as_slice())
6552			.unwrap();
6553		let _finished = import.finish().unwrap();
6554
6555		let frames = read_audio_frames(&consumer, &catalog).await;
6556		assert_eq!(
6557			frames.iter().map(|f| f.payload.to_vec()).collect::<Vec<_>>(),
6558			[0xAA, 0xBB].map(|fill| adts_frame(40, fill)[7..].to_vec()).to_vec(),
6559			"the last frame was held for a confirmation that could never arrive"
6560		);
6561	}
6562
6563	/// One whole MPEG-2 Layer II frame (8 kbps, 16 kHz, mono = 72 bytes), filled with
6564	/// `fill` so frames are told apart on the wire. Small enough that two fit in the
6565	/// single TS packet [`audio_pes_packet`] builds. `fill` must not be 0xFF, which a
6566	/// resync would mistake for a frame sync.
6567	fn mp2_frame(fill: u8) -> Vec<u8> {
6568		let mut f = vec![0xFF, 0xF5, 0x18, 0xC0];
6569		f.resize(72, fill);
6570		f
6571	}
6572
6573	/// The first confirmed frame resolves the catalog while the rest of its bounded PES is
6574	/// still arriving. Later pieces keep every frame's timestamp, including an empty tail.
6575	#[tokio::test(start_paused = true)]
6576	async fn a_complete_audio_frame_does_not_wait_for_its_pes_tail() {
6577		const PID: u16 = 0x61;
6578		let expected: Vec<_> = (1..=10).map(mp2_frame).collect();
6579		let payload = expected.concat();
6580		let len = 8 + payload.len();
6581		let mut pes = vec![0, 0, 1, 0xc0, (len >> 8) as u8, len as u8, 0x80, 0x80, 5];
6582		pes.extend_from_slice(&pes_timestamp(2, 90_000));
6583		pes.extend_from_slice(&payload);
6584		let (_, packets) = super::super::fixture::Mux::default().split(PID, &pes);
6585		let mut broadcast = moq_net::broadcast::Info::new().produce();
6586		let consumer = broadcast.consume();
6587		let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
6588		let mut import = super::Import::new(broadcast, catalog.reserve());
6589		import
6590			.decode(&synth_pmt(&[(StreamType::Mpeg1Audio, PID)], false))
6591			.unwrap();
6592		// The last stream's config arrives 760 ms after a cut; its PES ends at 1.2 s.
6593		tokio::time::advance(Duration::from_millis(760)).await;
6594		import.decode(&packets[0]).unwrap();
6595		assert!(
6596			matches!(
6597				consumer
6598					.track(hang::Catalog::DEFAULT_NAME)
6599					.unwrap()
6600					.poll_largest(&kio::Waiter::noop()),
6601				std::task::Poll::Ready(Some(_))
6602			),
6603			"the first confirmed stream config releases the catalog before its PES ends"
6604		);
6605		for packet in &packets[1..] {
6606			tokio::time::advance(Duration::from_millis(440) / (packets.len() - 1) as u32).await;
6607			import.decode(packet).unwrap();
6608		}
6609		let _finished = import.finish().unwrap();
6610		let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
6611		let frames = read_track(&consumer, &name, crate::container::Kind::Audio).await;
6612		assert_eq!(
6613			frames.iter().map(|frame| frame.payload.to_vec()).collect::<Vec<_>>(),
6614			expected
6615		);
6616		assert_eq!(
6617			frames
6618				.iter()
6619				.map(|frame| frame.timestamp.as_micros().unwrap())
6620				.collect::<Vec<_>>(),
6621			(0..10).map(|i| 1_000_000 + i * 72_000).collect::<Vec<_>>()
6622		);
6623	}
6624
6625	/// A PES whose first piece only extends the frame carried from the last PES keeps its PTS
6626	/// for the first frame beginning in it, so a timestamp gap survives any read boundary.
6627	#[tokio::test(start_paused = true)]
6628	async fn a_pes_timestamp_waits_for_its_first_frame_across_pieces() {
6629		const PID: u16 = 0x61;
6630		for stream_type in [StreamType::AdtsAac, StreamType::Mpeg1Audio] {
6631			let (frame, step): (fn(u8) -> Vec<u8>, u128) = match stream_type {
6632				StreamType::AdtsAac => (|fill| adts_frame(65, fill), 21_333),
6633				_ => (mp2_frame, 72_000),
6634			};
6635			let mut broadcast = moq_net::broadcast::Info::new().produce();
6636			let consumer = broadcast.consume();
6637			let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
6638			let mut import = super::Import::new(broadcast, catalog.reserve());
6639			import.decode(&synth_pmt(&[(stream_type, PID)], false)).unwrap();
6640			let (split, next) = (frame(0xbb), frame(0xcc));
6641			import
6642				.decode(&audio_pes_packet(
6643					PID,
6644					0,
6645					90_000,
6646					&[frame(0xaa), split[..20].to_vec()].concat(),
6647				))
6648				.unwrap();
6649			// Two seconds on, the next PES finishes the split frame only in its second piece.
6650			let rest = [&split[20..], &next[..]].concat();
6651			import
6652				.decode(&audio_pes_open(PID, 1, 180_000, rest.len(), &rest[..20]))
6653				.unwrap();
6654			import.decode(&ts_continuation(PID, 2, &rest[20..])).unwrap();
6655			let _finished = import.finish().unwrap();
6656			let frames = read_audio_frames(&consumer, &catalog).await;
6657			assert_eq!(
6658				frames
6659					.iter()
6660					.map(|frame| frame.timestamp.as_micros().unwrap())
6661					.collect::<Vec<_>>(),
6662				[1_000_000, 1_000_000 + step, 2_000_000],
6663				"{stream_type:?}"
6664			);
6665		}
6666	}
6667
6668	/// A frame waiting for the next header to confirm it keeps the PES that began after it
6669	/// pending, so a later PES does not take that PES's PTS from the frame beginning in it.
6670	#[tokio::test(start_paused = true)]
6671	async fn each_pes_timestamp_waits_for_its_first_frame_behind_an_unconfirmed_one() {
6672		const PID: u16 = 0x61;
6673		for stream_type in [StreamType::AdtsAac, StreamType::Mpeg1Audio] {
6674			let (frame, step): (fn(u8) -> Vec<u8>, u128) = match stream_type {
6675				StreamType::AdtsAac => (|fill| adts_frame(65, fill), 21_333),
6676				_ => (mp2_frame, 72_000),
6677			};
6678			let mut broadcast = moq_net::broadcast::Info::new().produce();
6679			let consumer = broadcast.consume();
6680			let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
6681			let mut import = super::Import::new(broadcast, catalog.reserve());
6682			import.decode(&synth_pmt(&[(stream_type, PID)], false)).unwrap();
6683			let (b, c) = (frame(0xbb), frame(0xcc));
6684			// The second PES finishes `b` but holds too little of `c` to confirm it.
6685			for (cc, pts, payload) in [
6686				(0, 90_000, [&frame(0xaa)[..], &b[..20]].concat()),
6687				(1, 180_000, [&b[20..], &c[..3]].concat()),
6688				(2, 270_000, [&c[3..], &frame(0xdd)[..]].concat()),
6689			] {
6690				import.decode(&audio_pes_packet(PID, cc, pts, &payload)).unwrap();
6691			}
6692			let _finished = import.finish().unwrap();
6693			let frames = read_audio_frames(&consumer, &catalog).await;
6694			assert_eq!(
6695				frames
6696					.iter()
6697					.map(|frame| frame.timestamp.as_micros().unwrap())
6698					.collect::<Vec<_>>(),
6699				[1_000_000, 1_000_000 + step, 2_000_000, 3_000_000],
6700				"{stream_type:?}"
6701			);
6702		}
6703	}
6704
6705	/// A frame split across PES whose next PES arrives in pieces too short to finish it: the
6706	/// first frame beginning in that PES still takes its PTS, not the previous PES's cadence.
6707	#[tokio::test(start_paused = true)]
6708	async fn a_pes_timestamp_waits_for_a_carried_frame_across_pieces() {
6709		const PID: u16 = 0x61;
6710		for stream_type in [StreamType::AdtsAac, StreamType::Mpeg1Audio] {
6711			let frame = |fill| match stream_type {
6712				StreamType::AdtsAac => adts_frame(65, fill),
6713				_ => mp2_frame(fill),
6714			};
6715			let mut broadcast = moq_net::broadcast::Info::new().produce();
6716			let consumer = broadcast.consume();
6717			let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
6718			let mut import = super::Import::new(broadcast, catalog.reserve());
6719			import.decode(&synth_pmt(&[(stream_type, PID)], false)).unwrap();
6720			let (a, b, c, d) = (frame(0xaa), frame(0xbb), frame(0xcc), frame(0xdd));
6721			// The first PES ends 40 bytes into `b`.
6722			import
6723				.decode(&audio_pes_open(
6724					PID,
6725					0,
6726					90_000,
6727					a.len() + 40,
6728					&[&a[..], &b[..20]].concat(),
6729				))
6730				.unwrap();
6731			import.decode(&ts_continuation(PID, 1, &b[20..40])).unwrap();
6732			// The next PES, half a second on, opens with 20 more bytes of `b`.
6733			let rest = [&b[60..], &c[..], &d[..]].concat();
6734			import
6735				.decode(&audio_pes_open(PID, 2, 135_000, 20 + rest.len(), &b[40..60]))
6736				.unwrap();
6737			import.decode(&ts_continuation(PID, 3, &rest)).unwrap();
6738			let _finished = import.finish().unwrap();
6739			let frames = read_audio_frames(&consumer, &catalog).await;
6740			let step = if stream_type == StreamType::AdtsAac {
6741				21_333
6742			} else {
6743				72_000
6744			};
6745			assert_eq!(
6746				frames
6747					.iter()
6748					.map(|frame| frame.timestamp.as_micros().unwrap())
6749					.collect::<Vec<_>>(),
6750				[1_000_000, 1_000_000 + step, 1_500_000, 1_500_000 + step],
6751				"{stream_type:?}"
6752			);
6753		}
6754	}
6755
6756	/// Resync within one PES keeps its clock, whether it finds a frame immediately or
6757	/// discards a whole piece before the next candidate arrives.
6758	#[tokio::test(start_paused = true)]
6759	async fn audio_resync_in_a_pes_continuation_keeps_its_timestamp() {
6760		const PID: u16 = 0x61;
6761		for stream_type in [StreamType::AdtsAac, StreamType::Mpeg1Audio] {
6762			for carry in [false, true] {
6763				let frame = |fill| match stream_type {
6764					StreamType::AdtsAac => adts_frame(65, fill),
6765					_ => mp2_frame(fill),
6766				};
6767				let mut broadcast = moq_net::broadcast::Info::new().produce();
6768				let consumer = broadcast.consume();
6769				let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap();
6770				let mut import = super::Import::new(broadcast, catalog.reserve());
6771				import.decode(&synth_pmt(&[(stream_type, PID)], false)).unwrap();
6772				let recovered = [frame(0xcc), frame(0xdd)].concat();
6773				let junk = vec![0; if carry { 40 } else { 8 }];
6774				let declared = 40 + junk.len() + recovered.len();
6775				import
6776					.decode(&audio_pes_open(PID, 0, 90_000, declared, &frame(0xaa)[..40]))
6777					.unwrap();
6778				if carry {
6779					import.decode(&ts_continuation(PID, 1, &junk)).unwrap();
6780					import.decode(&ts_continuation(PID, 2, &recovered)).unwrap();
6781				} else {
6782					import
6783						.decode(&ts_continuation(PID, 1, &[junk, recovered].concat()))
6784						.unwrap();
6785				}
6786				let _finished = import.finish().unwrap();
6787				let frames = read_audio_frames(&consumer, &catalog).await;
6788				assert_eq!(frames.len(), 2, "{stream_type:?} carry={carry}");
6789				let step = if stream_type == StreamType::AdtsAac {
6790					21_333
6791				} else {
6792					72_000
6793				};
6794				assert_eq!(
6795					frames
6796						.iter()
6797						.map(|frame| frame.timestamp.as_micros().unwrap())
6798						.collect::<Vec<_>>(),
6799					[1_000_000, 1_000_000 + step],
6800					"{stream_type:?} carry={carry}"
6801				);
6802			}
6803		}
6804	}
6805
6806	// A frame header that changes the channel count is a new decoder identity: the frames after
6807	// it publish on a new track, and the first track is retired rather than rewritten.
6808	#[tokio::test(start_paused = true)]
6809	async fn legacy_channel_change_starts_a_new_track() {
6810		const MP2_PID: u16 = 0x0061;
6811
6812		let mut broadcast = moq_net::broadcast::Info::new().produce();
6813		let consumer = broadcast.consume();
6814		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6815		let mut import = super::Import::new(broadcast, catalog.reserve());
6816		import
6817			.decode(&synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false))
6818			.unwrap();
6819
6820		// The same frame in stereo: the mode bits clear.
6821		let stereo = |fill| {
6822			let mut frame = mp2_frame(fill);
6823			frame[3] = 0x00;
6824			frame
6825		};
6826		let mono = [mp2_frame(0xAA), mp2_frame(0xBB)].concat();
6827		import.decode(&audio_pes_packet(MP2_PID, 0, 90_000, &mono)).unwrap();
6828		let first = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
6829		let both = [stereo(0xCC), stereo(0xDD)].concat();
6830		import.decode(&audio_pes_packet(MP2_PID, 1, 180_000, &both)).unwrap();
6831		import.decode(&audio_pes_packet(MP2_PID, 2, 270_000, &both)).unwrap();
6832
6833		let snapshot = catalog.snapshot();
6834		assert_eq!(snapshot.audio.renditions.len(), 1, "the mono track is retired");
6835		let (name, config) = snapshot.audio.renditions.iter().next().unwrap();
6836		assert_ne!(name, &first, "the stereo frames publish under a new name");
6837		assert_eq!(config.channel_count, 2);
6838		let _finished = import.finish().unwrap();
6839		let frames = read_audio_frames(&consumer, &catalog).await;
6840		assert_eq!(frames[0].payload, stereo(0xCC), "the new track starts at the change");
6841	}
6842
6843	// An ADTS header that changes the sample rate is a new decoder identity, so the frames after
6844	// it publish on a new track, on the same program timebase.
6845	#[tokio::test(start_paused = true)]
6846	async fn aac_sample_rate_change_starts_a_new_track() {
6847		const AAC_PID: u16 = 0x0060;
6848		let frame = |rate| {
6849			let mut f = super::adts::write_header(2, rate, 2, 10).unwrap().to_vec();
6850			f.resize(f.len() + 10, 0x20);
6851			f
6852		};
6853
6854		let mut broadcast = moq_net::broadcast::Info::new().produce();
6855		let consumer = broadcast.consume();
6856		let catalog = crate::catalog::Producer::new(
6857			&mut broadcast,
6858			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
6859		)
6860		.unwrap();
6861		let mut import = super::Import::new(broadcast, catalog.reserve());
6862		let mut mux = Mux {
6863			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
6864			..Default::default()
6865		};
6866		let cc = mux.cc(AAC_PID);
6867		mux.out.extend(audio_pes_packet(
6868			AAC_PID,
6869			cc,
6870			90_000,
6871			&[frame(48_000), frame(48_000)].concat(),
6872		));
6873		import.decode(&mux.out).unwrap();
6874		let first = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
6875
6876		mux.out.clear();
6877		for pts in [180_000, 270_000] {
6878			let cc = mux.cc(AAC_PID);
6879			mux.out.extend(audio_pes_packet(
6880				AAC_PID,
6881				cc,
6882				pts,
6883				&[frame(44_100), frame(44_100)].concat(),
6884			));
6885		}
6886		import.decode(&mux.out).unwrap();
6887		let snapshot = catalog.snapshot();
6888		assert_eq!(snapshot.audio.renditions.len(), 1, "the 48 kHz track is retired");
6889		let (name, config) = snapshot.audio.renditions.iter().next().unwrap();
6890		assert_ne!(name, &first, "the 44.1 kHz frames publish under a new name");
6891		assert_eq!(config.sample_rate, 44_100);
6892		let recorded: Vec<_> = snapshot.ext.mpegts.tracks.keys().cloned().collect();
6893		assert_eq!(
6894			recorded,
6895			vec![name.clone()],
6896			"the PID's mpegts entry moves to the new track"
6897		);
6898		let _finished = import.finish().unwrap();
6899		let frames = read_audio_frames(&consumer, &catalog).await;
6900		assert_eq!(
6901			frames[0].timestamp,
6902			moq_net::Timestamp::from_micros(2_000_000).unwrap(),
6903			"the new track keeps the program's timebase"
6904		);
6905	}
6906
6907	// The shape a looping mux actually produces, which is not a carried tail: the last PES
6908	// before the cut is truncated, so it stays open, and the next loop's leading continuation
6909	// packets complete it. The foreign bytes land in the SAME PES, so the codec sees one
6910	// buffer with nothing carried, and the confirmation rule above never gets a say. The
6911	// continuity counter is what gives the wrap away, so the truncated PES is flushed for the
6912	// whole frames it did deliver and the stream resumes at the next PES start.
6913	#[tokio::test(start_paused = true)]
6914	async fn legacy_drops_a_pes_completed_across_a_continuity_break() {
6915		const MP2_PID: u16 = 0x0061;
6916
6917		let mut broadcast = moq_net::broadcast::Info::new().produce();
6918		let consumer = broadcast.consume();
6919		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6920		let mut import = super::Import::new(broadcast, catalog.reserve());
6921
6922		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
6923		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6924
6925		let mut opening = mp2_frame(0xAA);
6926		opening.extend_from_slice(&mp2_frame(0xBB)[..40]);
6927		import
6928			.decode(audio_pes_open(MP2_PID, 0, 90_000, 144, &opening).as_slice())
6929			.unwrap();
6930		import
6931			.decode(ts_continuation(MP2_PID, 12, &mp2_frame(0xCC)[..32]).as_slice())
6932			.unwrap();
6933		let mut normal = mp2_frame(0xDD);
6934		normal.extend_from_slice(&mp2_frame(0xEE));
6935		import
6936			.decode(audio_pes_packet(MP2_PID, 13, 270_000, &normal).as_slice())
6937			.unwrap();
6938		let _finished = import.finish().unwrap();
6939
6940		let frames = read_audio_frames(&consumer, &catalog).await;
6941		assert_eq!(
6942			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
6943			vec![mp2_frame(0xAA), mp2_frame(0xDD), mp2_frame(0xEE)],
6944			"the wrap was spliced onto the frame the cut left open"
6945		);
6946	}
6947
6948	// A damaged frame header must not take the session down with it: the demuxer scans to
6949	// the next sync word and keeps publishing, the way the TS and video layers already do.
6950	// One bit flipped in a sync word used to abort the whole broadcast (#2729).
6951	#[tokio::test(start_paused = true)]
6952	async fn legacy_resyncs_past_damaged_header() {
6953		const MP2_PID: u16 = 0x0061;
6954
6955		let mut broadcast = moq_net::broadcast::Info::new().produce();
6956		let consumer = broadcast.consume();
6957		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
6958		let mut import = super::Import::new(broadcast, catalog.reserve());
6959
6960		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
6961		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
6962
6963		// Two good frames to lock onto (a frame is confirmed by the one after it, and two
6964		// 72-byte frames is all one TS packet holds), then a frame whose sync word lost a
6965		// bit, then two more good ones.
6966		let mut payload = mp2_frame(0xAA);
6967		payload.extend_from_slice(&mp2_frame(0xBB));
6968		import
6969			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &payload).as_slice())
6970			.unwrap();
6971
6972		let mut damaged = mp2_frame(0x11);
6973		damaged[0] = 0xFE;
6974		let mut hit = damaged.clone();
6975		hit.extend_from_slice(&mp2_frame(0xCC));
6976		import
6977			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &hit).as_slice())
6978			.expect("a damaged frame header is not fatal");
6979		import
6980			.decode(audio_pes_packet(MP2_PID, 2, 450_000, &mp2_frame(0xDD)).as_slice())
6981			.unwrap();
6982		import.finish_in_place().unwrap();
6983
6984		let frames = read_audio_frames(&consumer, &catalog).await;
6985		assert_eq!(
6986			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
6987			vec![mp2_frame(0xAA), mp2_frame(0xBB), mp2_frame(0xCC), mp2_frame(0xDD)],
6988			"the undamaged frames either side survive, and only the damaged one is dropped"
6989		);
6990		// The recovery leaves evidence: one resync, and the damaged frame's 72 bytes.
6991		assert_eq!(
6992			import.stats().streams,
6993			BTreeMap::from([(
6994				MP2_PID,
6995				super::stats::Stream {
6996					track: ".mp2".to_string(),
6997					class: super::stats::Class::Audio,
6998					units: 4,
6999					quiet: None,
7000					resyncs: 1,
7001					discarded: 72,
7002					unconfirmed: 0,
7003					..Default::default()
7004				}
7005			)]),
7006			"the resync left no trace an operator could alarm on"
7007		);
7008	}
7009
7010	// The reported production shape: a looping publisher wraps mid-frame, so the carried
7011	// tail is spliced onto unrelated bytes and the join can't parse. The stale tail must be
7012	// scanned past rather than ending the session, and the recovered frame takes the new
7013	// PES's PTS instead of the pre-wrap one it would have inherited.
7014	#[tokio::test(start_paused = true)]
7015	async fn legacy_resyncs_past_stale_tail_at_a_splice() {
7016		const MP2_PID: u16 = 0x0061;
7017
7018		let mut broadcast = moq_net::broadcast::Info::new().produce();
7019		let consumer = broadcast.consume();
7020		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7021		let mut import = super::Import::new(broadcast, catalog.reserve());
7022
7023		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7024		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7025
7026		// PES 1 ends mid-frame, leaving a tail the wrap will never complete.
7027		let mut cut = mp2_frame(0xAA);
7028		cut.truncate(40);
7029		import
7030			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &cut).as_slice())
7031			.unwrap();
7032		// PES 2 is the top of the file again: the tail splices onto its first frame.
7033		let mut wrapped = mp2_frame(0xCC);
7034		wrapped.extend_from_slice(&mp2_frame(0xDD));
7035		import
7036			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &wrapped).as_slice())
7037			.expect("a splice is not fatal");
7038		// One more PES to show the wrap costs nothing after it.
7039		import
7040			.decode(audio_pes_packet(MP2_PID, 2, 450_000, &mp2_frame(0xEE)).as_slice())
7041			.unwrap();
7042		let _finished = import.finish().unwrap();
7043
7044		let frames = read_audio_frames(&consumer, &catalog).await;
7045		// The stale tail still carries an intact header claiming 72 bytes, so what gives the
7046		// splice away is the confirmation: the frame it declares ends inside the wrapped
7047		// frame rather than at a header. The tail is scanned past, not published.
7048		assert_eq!(
7049			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7050			vec![mp2_frame(0xCC), mp2_frame(0xDD), mp2_frame(0xEE)],
7051			"the splice was published as audio instead of scanned past"
7052		);
7053		// Re-anchored on PES 2 (270000 ticks = 3 s) rather than inheriting the stale tail's
7054		// 1 s. At a real loop wrap that inherited error is the whole file's duration, not a
7055		// frame.
7056		assert_eq!(
7057			frames[0].timestamp,
7058			Timestamp::from_micros(3_000_000).unwrap(),
7059			"not re-anchored on the new PES"
7060		);
7061	}
7062
7063	// The same splice one frame later, which is the shape a real wrap takes: the stream has
7064	// already published a frame, so the tail sits at a boundary the previous frame vouched
7065	// for. What it vouched for is where the tail begins, not the unrelated bytes the next PES
7066	// joins onto it, so the join still has to be confirmed. Without that this published one
7067	// frame of pre-wrap and post-wrap bytes spliced together, and swallowed the real frame
7068	// underneath it (#2802).
7069	#[tokio::test(start_paused = true)]
7070	async fn legacy_confirms_a_frame_joined_out_of_a_carried_tail() {
7071		const MP2_PID: u16 = 0x0061;
7072
7073		let mut broadcast = moq_net::broadcast::Info::new().produce();
7074		let consumer = broadcast.consume();
7075		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7076		let mut import = super::Import::new(broadcast, catalog.reserve());
7077
7078		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7079		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7080
7081		// A whole frame, then one cut mid-frame by the wrap. The first vouches for where the
7082		// tail begins, which is what made the join look trustworthy.
7083		let mut payload = mp2_frame(0xAA);
7084		payload.extend_from_slice(&mp2_frame(0xBB)[..40]);
7085		import
7086			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &payload).as_slice())
7087			.unwrap();
7088		// The top of the file again: the tail splices onto its first frame.
7089		let mut wrapped = mp2_frame(0xCC);
7090		wrapped.extend_from_slice(&mp2_frame(0xDD));
7091		import
7092			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &wrapped).as_slice())
7093			.expect("a splice is not fatal");
7094		import
7095			.decode(audio_pes_packet(MP2_PID, 2, 450_000, &mp2_frame(0xEE)).as_slice())
7096			.unwrap();
7097		let _finished = import.finish().unwrap();
7098
7099		let frames = read_audio_frames(&consumer, &catalog).await;
7100		assert_eq!(
7101			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7102			vec![mp2_frame(0xAA), mp2_frame(0xCC), mp2_frame(0xDD), mp2_frame(0xEE)],
7103			"the splice cost more than the frame it interrupted"
7104		);
7105		// The wrapped frame keeps the new PES's PTS, not the pre-wrap tail's.
7106		assert_eq!(
7107			frames[1].timestamp,
7108			Timestamp::from_micros(3_000_000).unwrap(),
7109			"not re-anchored on the new PES"
7110		);
7111	}
7112
7113	// #3533: a content join landed a PES PTS a millisecond below the last frame published. Audio
7114	// never reorders, so that is a restart, which ends the import rather than shifting it forward.
7115	#[tokio::test(start_paused = true)]
7116	async fn legacy_pes_below_the_live_edge_is_refused() {
7117		const MP2_PID: u16 = 0x0061;
7118
7119		let mut broadcast = moq_net::broadcast::Info::new().produce();
7120		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7121		let mut import = super::Import::new(broadcast, catalog.reserve());
7122
7123		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7124		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7125
7126		// Two frames so the first is confirmed and published: live edge is 90_000 ticks.
7127		let mut first = mp2_frame(0xAA);
7128		first.extend_from_slice(&mp2_frame(0xBB));
7129		import
7130			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &first).as_slice())
7131			.unwrap();
7132
7133		// A join a millisecond behind the live edge.
7134		let mut join = mp2_frame(0xDD);
7135		join.extend_from_slice(&mp2_frame(0xEE));
7136		let err = import
7137			.decode(audio_pes_packet(MP2_PID, 1, 89_910, &join).as_slice())
7138			.and_then(|_| import.finish_in_place())
7139			.expect_err("a PES PTS below the live edge is a restart");
7140		assert!(is_rewind(&err), "{err:?}");
7141	}
7142
7143	// Confirming a joined frame means holding it when the buffer ends too soon after it to
7144	// hold a header. At end of stream that header is never coming, so the drain publishes it
7145	// anyway rather than dropping a frame that is whole and parses.
7146	#[tokio::test(start_paused = true)]
7147	async fn legacy_drains_a_joined_frame_at_end_of_stream() {
7148		const MP2_PID: u16 = 0x0061;
7149
7150		let mut broadcast = moq_net::broadcast::Info::new().produce();
7151		let consumer = broadcast.consume();
7152		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7153		let mut import = super::Import::new(broadcast, catalog.reserve());
7154
7155		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7156		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7157
7158		let mut payload = mp2_frame(0xAA);
7159		payload.extend_from_slice(&mp2_frame(0xBB)[..40]);
7160		import
7161			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &payload).as_slice())
7162			.unwrap();
7163		// The rest of the split frame and nothing else, so the stream ends with it joined,
7164		// whole, and unconfirmed.
7165		import
7166			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &mp2_frame(0xBB)[40..]).as_slice())
7167			.unwrap();
7168		import.finish_in_place().unwrap();
7169
7170		let frames = read_audio_frames(&consumer, &catalog).await;
7171		assert_eq!(
7172			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7173			vec![mp2_frame(0xAA), mp2_frame(0xBB)],
7174			"the last frame was held for a confirmation that could never arrive"
7175		);
7176		// Publishing it is the right trade, but it is a frame nothing vouched for: at a
7177		// splice those joined bytes are a substitution rather than a gap, so the drain is
7178		// counted instead of being silent.
7179		assert_eq!(
7180			import.stats().streams,
7181			BTreeMap::from([(
7182				MP2_PID,
7183				super::stats::Stream {
7184					track: ".mp2".to_string(),
7185					class: super::stats::Class::Audio,
7186					units: 2,
7187					quiet: None,
7188					resyncs: 0,
7189					discarded: 0,
7190					unconfirmed: 1,
7191					..Default::default()
7192				}
7193			)]),
7194			"the drained frame was published without a trace"
7195		);
7196	}
7197
7198	// A sync word is short enough to turn up by chance in compressed payload (a valid-looking
7199	// MP2 header lands about every 25 KiB of random bytes). Scanning onto one and trusting it
7200	// would publish payload as audio, so a scanned candidate is only accepted once a header
7201	// parses where the frame it declares ends. Here the planted header's frame would end in
7202	// the middle of the next real frame, which is what gives it away.
7203	#[tokio::test(start_paused = true)]
7204	async fn legacy_rejects_an_unconfirmed_sync_candidate() {
7205		const MP2_PID: u16 = 0x0061;
7206
7207		let mut broadcast = moq_net::broadcast::Info::new().produce();
7208		let consumer = broadcast.consume();
7209		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7210		let mut import = super::Import::new(broadcast, catalog.reserve());
7211
7212		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7213		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7214
7215		// Two good frames to lock onto, then a damaged one with an intact header planted 8
7216		// bytes into its payload for the scan to find, then two more good ones.
7217		let mut payload = mp2_frame(0xAA);
7218		payload.extend_from_slice(&mp2_frame(0xBB));
7219		import
7220			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &payload).as_slice())
7221			.unwrap();
7222
7223		let mut damaged = mp2_frame(0x11);
7224		damaged[0] = 0xFE;
7225		damaged[8..12].copy_from_slice(&mp2_frame(0)[..4]);
7226		let mut hit = damaged.clone();
7227		hit.extend_from_slice(&mp2_frame(0xCC));
7228		import
7229			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &hit).as_slice())
7230			.unwrap();
7231		import
7232			.decode(audio_pes_packet(MP2_PID, 2, 450_000, &mp2_frame(0xDD)).as_slice())
7233			.unwrap();
7234		let _finished = import.finish().unwrap();
7235
7236		let frames = read_audio_frames(&consumer, &catalog).await;
7237		// Without confirmation the planted header is published as a frame of payload bytes,
7238		// and it eats the front of the next real frame on the way past.
7239		assert_eq!(
7240			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7241			vec![mp2_frame(0xAA), mp2_frame(0xBB), mp2_frame(0xCC), mp2_frame(0xDD)],
7242			"a false sync inside the payload was published as audio"
7243		);
7244	}
7245
7246	// A capture joins mid-stream, so the first PES routed to a PID can open in the middle of
7247	// a frame whose start was never seen. Nothing vouches for that boundary, so the first
7248	// frame is confirmed like a scanned one: otherwise a chance header there is published as
7249	// audio and, worse, the track takes its sample rate and channel count from it for the
7250	// life of the broadcast.
7251	#[tokio::test(start_paused = true)]
7252	async fn legacy_confirms_the_first_frame_of_a_stream() {
7253		const MP2_PID: u16 = 0x0061;
7254
7255		let mut broadcast = moq_net::broadcast::Info::new().produce();
7256		let consumer = broadcast.consume();
7257		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7258		let mut import = super::Import::new(broadcast, catalog.reserve());
7259
7260		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7261		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7262
7263		// Join mid-frame: a fragment that happens to open with a valid MP2 header. It declares
7264		// 72 bytes but only 40 arrive before the real stream, so the frame it claims ends
7265		// inside a real one. (Confirmation catches a false sync whose declared length misses
7266		// a real boundary; one that happens to land on it is indistinguishable.)
7267		let mut joined = mp2_frame(0)[..4].to_vec();
7268		joined.resize(40, 0x11);
7269		import
7270			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &joined).as_slice())
7271			.unwrap();
7272		// The real stream, which does chain.
7273		let mut real = mp2_frame(0xCC);
7274		real.extend_from_slice(&mp2_frame(0xDD));
7275		import
7276			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &real).as_slice())
7277			.unwrap();
7278		let _finished = import.finish().unwrap();
7279
7280		let frames = read_audio_frames(&consumer, &catalog).await;
7281		assert!(
7282			!frames.iter().any(|f| f.payload.ends_with(&[0x11; 8])),
7283			"published the unvouched-for bytes the capture joined in the middle of"
7284		);
7285		assert_eq!(
7286			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7287			vec![mp2_frame(0xCC), mp2_frame(0xDD)],
7288			"the real stream is picked up once two frames chain"
7289		);
7290	}
7291
7292	// A frame that legitimately arrives over many small PES must not trip the resync budget.
7293	// The candidate is rescanned each time the buffer grows, and charging those bytes on
7294	// every pass would bill a single 8 KiB frame for over a hundred KiB of "discarded" data
7295	// and fail the stream before it ever completes. Bytes that end up retained are refunded.
7296	#[tokio::test(start_paused = true)]
7297	async fn legacy_does_not_bill_a_frame_that_arrives_slowly() {
7298		const MP2_PID: u16 = 0x0061;
7299
7300		let mut broadcast = moq_net::broadcast::Info::new().produce();
7301		let consumer = broadcast.consume();
7302		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7303		let mut import = super::Import::new(broadcast, catalog.reserve());
7304
7305		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7306		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7307
7308		// The largest frame MPEG-1 Layer II can declare (384 kbps at 32 kHz), dribbled in 4
7309		// bytes at a time so it is rescanned 432 times. Billing each pass would charge ~364
7310		// KiB against a 64 KiB budget.
7311		let mut frame = vec![0xFF, 0xFD, 0xE8, 0x00];
7312		frame.resize(1728, 0xAA);
7313		for (i, chunk) in frame.chunks(4).enumerate() {
7314			import
7315				.decode(audio_pes_packet(MP2_PID, (i % 16) as u8, 90_000, chunk).as_slice())
7316				.expect("a slowly arriving frame must not exhaust the resync budget");
7317		}
7318		// Enough of the next frame to confirm the boundary.
7319		import
7320			.decode(audio_pes_packet(MP2_PID, 0, 270_000, &frame[..4]).as_slice())
7321			.unwrap();
7322		let _finished = import.finish().unwrap();
7323
7324		let frames = read_audio_frames(&consumer, &catalog).await;
7325		assert_eq!(
7326			frames.iter().map(|f| f.payload.clone()).collect::<Vec<_>>(),
7327			vec![frame.clone()],
7328			"the reassembled frame keeps its bytes"
7329		);
7330		// It began in the first PES, so it keeps that PTS rather than the one it completed under.
7331		assert_eq!(frames[0].timestamp, Timestamp::from_micros(1_000_000).unwrap());
7332	}
7333
7334	// A PID that never publishes must not hold the catalog shut for the rest of the
7335	// broadcast. Its rendition is reserved from the PMT and only consumed when the importer
7336	// is built, and `finish` takes streams by reference (moq-srt finishes the importer and
7337	// keeps it), so a reservation left alive there gates the initial catalog publish
7338	// indefinitely. A lone frame that can never be confirmed is exactly such a PID.
7339	#[tokio::test(start_paused = true)]
7340	async fn a_pid_that_never_publishes_releases_the_catalog() {
7341		const MP2_PID: u16 = 0x0061;
7342		const AAC_PID: u16 = 0x0060;
7343
7344		let mut broadcast = moq_net::broadcast::Info::new().produce();
7345		let consumer = broadcast.consume();
7346		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7347		let mut import = super::Import::new(broadcast, catalog.reserve());
7348
7349		let pmt = synth_pmt(
7350			&[(StreamType::AdtsAac, AAC_PID), (StreamType::Mpeg1Audio, MP2_PID)],
7351			false,
7352		);
7353		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7354
7355		// MP2 carries a single frame, which nothing can ever confirm, so it is dropped and
7356		// the importer for that PID is never built.
7357		import
7358			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &mp2_frame(0xAA)).as_slice())
7359			.unwrap();
7360		// AAC resolves normally.
7361		let mut aac = adts_frame(40, 0xCC);
7362		aac.extend_from_slice(&adts_frame(40, 0xDD));
7363		import
7364			.decode(audio_pes_packet(AAC_PID, 0, 90_000, &aac).as_slice())
7365			.unwrap();
7366		import.finish_in_place().unwrap();
7367
7368		// The importer is deliberately still alive here, as moq-srt leaves it after finish.
7369		let track = consumer
7370			.track(hang::catalog::Catalog::DEFAULT_NAME)
7371			.unwrap()
7372			.subscribe(
7373				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7374					moq_net::track::Start::Live {
7375						min: Some(RECORDING_MAX_AGE),
7376						max: Some(RECORDING_MAX_AGE),
7377					},
7378				)]),
7379			)
7380			.await
7381			.unwrap();
7382		let mut reader =
7383			crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data));
7384		let published = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await;
7385		assert!(
7386			matches!(published, Ok(Ok(Some(_)))),
7387			"a PID that never published held the catalog shut: {published:?}"
7388		);
7389		drop(import);
7390	}
7391
7392	/// A receiver that joins an AAC stream after its program config element (ffmpeg writes it in
7393	/// the first frame only) cannot build that track, but must not withhold the catalog for the
7394	/// rest of the program. The track joins once an element arrives, and a repeated element
7395	/// leaves its frame, since the description carries the layout.
7396	#[tokio::test(start_paused = true)]
7397	async fn aac_joined_after_its_program_config_publishes_the_rest() {
7398		const AAC_PID: u16 = 0x0060;
7399		// ffmpeg's quad layout, two channel pair elements in a program config element.
7400		let mut quad = vec![0x11, 0x80, 0x04, 0xC4, 0x04, 0x00, 0x21, 0x10, 0x0C];
7401		quad.extend_from_slice(b"Lavc63.1.101");
7402		let pce = crate::codec::aac::in_band(&quad).unwrap().program_config.unwrap();
7403		// A raw data block: the element, if given, then bytes that lead with a channel pair (ID 1).
7404		let frame = |pce: &[u8]| {
7405			let mut f = super::adts::write_header(2, 48_000, 0, pce.len() + 10)
7406				.unwrap()
7407				.to_vec();
7408			f.extend_from_slice(pce);
7409			f.resize(f.len() + 10, 0x20);
7410			f
7411		};
7412
7413		let mut broadcast = moq_net::broadcast::Info::new().produce();
7414		let consumer = broadcast.consume();
7415		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7416		let mut updates = catalog.consume().unwrap();
7417		let mut import = super::Import::new(broadcast, catalog.reserve());
7418
7419		let mut mux = Mux {
7420			out: synth_pmt(&[(StreamType::H264, VIDEO), (StreamType::AdtsAac, AAC_PID)], false),
7421			..Default::default()
7422		};
7423		mux.gop(VIDEO, 90_000);
7424		let cc = mux.cc(AAC_PID);
7425		let bare = frame(&[]);
7426		mux.out.extend(audio_pes_packet(
7427			AAC_PID,
7428			cc,
7429			90_000,
7430			&[bare.as_slice(), &bare, &bare].concat(),
7431		));
7432		import.decode(&mux.out).unwrap();
7433		assert_eq!(import.stats().streams[&AAC_PID].damaged, 0, "a join is not damage");
7434
7435		let first = kio::clock::timeout(Duration::from_millis(10), updates.next())
7436			.await
7437			.expect("the catalog waits on a track that cannot resolve")
7438			.unwrap()
7439			.unwrap()
7440			.value;
7441		assert_eq!(first.video.renditions.len(), 1);
7442		assert!(first.audio.renditions.is_empty());
7443
7444		// The element arrives, then frames without it, then a repeat.
7445		let with = frame(&pce);
7446		let cc = mux.cc(AAC_PID);
7447		let late = audio_pes_packet(AAC_PID, cc, 180_000, &[with.as_slice(), &bare, &with, &bare].concat());
7448		import.decode(&late).unwrap();
7449		let _finished = import.finish().unwrap();
7450
7451		let audio = loop {
7452			let update = kio::clock::timeout(Duration::from_millis(10), updates.next())
7453				.await
7454				.expect("the AAC track never joined")
7455				.unwrap()
7456				.unwrap()
7457				.value;
7458			if let Some(audio) = update.audio.renditions.values().next() {
7459				break audio.clone();
7460			}
7461		};
7462		assert_eq!(audio.channel_count, 4);
7463		assert_eq!(audio.description.as_deref(), Some(quad.as_slice()));
7464
7465		let frames = read_audio_frames(&consumer, &catalog).await;
7466		assert_eq!(frames.len(), 4, "only the frames from the element on");
7467		for frame in frames {
7468			assert_eq!(frame.payload.as_ref(), [0x20; 10], "the element leaves every frame");
7469		}
7470	}
7471
7472	// A program config element that changes the layout mid-stream ends the import with the
7473	// cause, after the frames ahead of it published.
7474	#[tokio::test(start_paused = true)]
7475	async fn aac_program_config_changed_mid_stream_ends_the_import() {
7476		const AAC_PID: u16 = 0x0060;
7477		// ffmpeg's quad layout: one front and one back channel pair.
7478		let mut quad = vec![0x11, 0x80, 0x04, 0xC4, 0x04, 0x00, 0x21, 0x10, 0x0C];
7479		quad.extend_from_slice(b"Lavc63.1.101");
7480		// The same two pairs, with the second moved from the back to the side.
7481		let mut side = quad.clone();
7482		side[4] = 0x40;
7483		let element = |asc: &[u8]| crate::codec::aac::in_band(asc).unwrap().program_config.unwrap();
7484		let frame = |pce: &[u8]| {
7485			let mut f = super::adts::write_header(2, 48_000, 0, pce.len() + 10)
7486				.unwrap()
7487				.to_vec();
7488			f.extend_from_slice(pce);
7489			f.resize(f.len() + 10, 0x20);
7490			f
7491		};
7492		let (with, changed, bare) = (frame(&element(&quad)), frame(&element(&side)), frame(&[]));
7493
7494		let mut broadcast = moq_net::broadcast::Info::new().produce();
7495		let consumer = broadcast.consume();
7496		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7497		let mut import = super::Import::new(broadcast, catalog.reserve());
7498
7499		let mut mux = Mux {
7500			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
7501			..Default::default()
7502		};
7503		for (pts, unit) in [
7504			(90_000, [with.as_slice(), &bare]),
7505			(180_000, [bare.as_slice(), &changed]),
7506		] {
7507			let cc = mux.cc(AAC_PID);
7508			mux.out.extend(audio_pes_packet(AAC_PID, cc, pts, &unit.concat()));
7509		}
7510		let cc = mux.cc(AAC_PID);
7511		mux.out.extend(audio_pes_packet(AAC_PID, cc, 270_000, &bare));
7512		let err = import.decode(&mux.out).expect_err("a changed layout ends the import");
7513		assert!(err.to_string().contains("changed mid-stream"), "{err}");
7514		let frames = read_audio_frames(&consumer, &catalog).await;
7515		assert_eq!(frames.len(), 3, "the frames ahead of it");
7516	}
7517
7518	// Resync is bounded: a PID carrying something other than the codec its PMT declares is a
7519	// config error, not damage, so it must still fail rather than scan forever behind an
7520	// unresolved catalog reservation (which would withhold the catalog for every track).
7521	//
7522	// The junk is seeded with header-shaped bytes because that is what defeats a naive
7523	// budget: every false positive that gets published resets it, so a stream that never
7524	// really parses would scan forever. Only confirmed frames may reset it.
7525	#[test]
7526	fn legacy_gives_up_when_nothing_ever_parses() {
7527		const MP2_PID: u16 = 0x0061;
7528
7529		let mut broadcast = moq_net::broadcast::Info::new().produce();
7530		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7531		let mut import = super::Import::new(broadcast, catalog.reserve());
7532
7533		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7534		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7535
7536		// A valid MP2 header every 16 bytes, none of which is ever a real frame boundary:
7537		// the frames they declare are 72 bytes long, which never lands on another header.
7538		let header = mp2_frame(0);
7539		let junk: Vec<u8> = (0..150)
7540			.map(|i: usize| match i % 16 {
7541				n @ 0..=3 => header[n],
7542				_ => 0xBB,
7543			})
7544			.collect();
7545
7546		let err = (0..1000)
7547			.map(|i| import.decode(audio_pes_packet(MP2_PID, (i % 16) as u8, 90_000, &junk).as_slice()))
7548			.find_map(Result::err)
7549			.expect("an unparseable stream must still fail");
7550		assert!(
7551			matches!(&err, super::Error::Malformed(msg) if msg.contains("never regained sync")),
7552			"gave up with the wrong error: {err}"
7553		);
7554	}
7555
7556	// The AAC counterpart of the above. Worth its own test rather than trusting the shared
7557	// `Resync`: this path scans for the ADTS sync byte rather than a descriptor's, and
7558	// builds its give-up error from the one `adts::Header::parse` returns.
7559	#[test]
7560	fn aac_gives_up_when_nothing_ever_parses() {
7561		const AAC_PID: u16 = 0x0060;
7562
7563		let mut broadcast = moq_net::broadcast::Info::new().produce();
7564		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7565		let mut import = super::Import::new(broadcast, catalog.reserve());
7566
7567		let pmt = synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false);
7568		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7569
7570		// A valid ADTS header every 16 bytes, none of which is ever a real frame boundary:
7571		// the 47-byte frames they declare never end on another header.
7572		let header = adts_frame(40, 0);
7573		let junk: Vec<u8> = (0..150)
7574			.map(|i: usize| match i % 16 {
7575				n if n < super::adts::MIN_HEADER_LEN => header[n],
7576				_ => 0xBB,
7577			})
7578			.collect();
7579
7580		let err = (0..1000)
7581			.map(|i| import.decode(audio_pes_packet(AAC_PID, (i % 16) as u8, 90_000, &junk).as_slice()))
7582			.find_map(Result::err)
7583			.expect("an unparseable stream must still fail");
7584		assert!(
7585			matches!(&err, super::Error::Malformed(msg) if msg.contains("never regained sync")),
7586			"gave up with the wrong error: {err}"
7587		);
7588	}
7589
7590	// ISO 13818-1 doesn't require audio frames to align with PES boundaries: a
7591	// frame split across two PES must be reassembled byte-exact, stamped with the
7592	// PTS of the PES it began in, and the next whole frame takes the new PES's PTS.
7593	#[tokio::test(start_paused = true)]
7594	async fn legacy_frame_split_across_pes_reassembles() {
7595		const MP2_PID: u16 = 0x0061;
7596
7597		let mut broadcast = moq_net::broadcast::Info::new().produce();
7598		let consumer = broadcast.consume();
7599		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7600		let mut import = super::Import::new(broadcast, catalog.reserve());
7601
7602		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7603		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7604
7605		// Two 96-byte MP2 frames with distinct payloads; frame A is cut at byte 50.
7606		let mut frame_a = vec![0xFF, 0xFD, 0x14, 0x00];
7607		frame_a.extend((4..96).map(|i| i as u8));
7608		let mut frame_b = vec![0xFF, 0xFD, 0x14, 0x00];
7609		frame_b.extend((4..96).rev().map(|i| i as u8));
7610
7611		let mut second = frame_a[50..].to_vec();
7612		second.extend_from_slice(&frame_b);
7613		import
7614			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &frame_a[..50]).as_slice())
7615			.unwrap();
7616		import
7617			.decode(audio_pes_packet(MP2_PID, 1, 270_000, &second).as_slice())
7618			.unwrap();
7619		let _finished = import.finish().unwrap();
7620
7621		let frames = read_audio_frames(&consumer, &catalog).await;
7622		assert_eq!(frames.len(), 2, "both frames must survive the split");
7623		assert_eq!(
7624			frames[0].payload.as_ref(),
7625			&frame_a[..],
7626			"frame A reassembled byte-exact"
7627		);
7628		assert_eq!(frames[1].payload.as_ref(), &frame_b[..], "frame B intact");
7629		// Frame A began in PES 1 (PTS 90000 ticks = 1 s); frame B begins in PES 2
7630		// (270000 ticks = 3 s). The legacy container normalizes to microseconds on the wire.
7631		assert_eq!(frames[0].timestamp, Timestamp::from_micros(1_000_000).unwrap());
7632		assert_eq!(frames[1].timestamp, Timestamp::from_micros(3_000_000).unwrap());
7633	}
7634
7635	// A cut inside the next frame's header (fewer bytes left than a parseable
7636	// header) must also reassemble, and the carried frame keeps the PTS derived
7637	// from the PES it began in, NOT the next PES's (whose PTS only covers frames
7638	// that begin in it).
7639	#[tokio::test(start_paused = true)]
7640	async fn legacy_header_split_keeps_origin_pts() {
7641		const MP2_PID: u16 = 0x0061;
7642
7643		let mut broadcast = moq_net::broadcast::Info::new().produce();
7644		let consumer = broadcast.consume();
7645		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
7646		let mut import = super::Import::new(broadcast, catalog.reserve());
7647
7648		let pmt = synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false);
7649		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
7650
7651		let mut frame_a = vec![0xFF, 0xFD, 0x14, 0x00];
7652		frame_a.resize(96, 0x55);
7653		let mut frame_b = vec![0xFF, 0xFD, 0x14, 0x00];
7654		frame_b.resize(96, 0x66);
7655
7656		// PES 1: frame A whole plus only 2 bytes of frame B (not even a header).
7657		let mut first = frame_a.clone();
7658		first.extend_from_slice(&frame_b[..2]);
7659		import
7660			.decode(audio_pes_packet(MP2_PID, 0, 90_000, &first).as_slice())
7661			.unwrap();
7662		// PES 2: the rest of frame B, under a far-off PTS that must NOT apply to it.
7663		import
7664			.decode(audio_pes_packet(MP2_PID, 1, 900_000, &frame_b[2..]).as_slice())
7665			.unwrap();
7666		let _finished = import.finish().unwrap();
7667
7668		let frames = read_audio_frames(&consumer, &catalog).await;
7669		assert_eq!(frames.len(), 2, "both frames must survive the header split");
7670		assert_eq!(
7671			frames[1].payload.as_ref(),
7672			&frame_b[..],
7673			"frame B reassembled byte-exact"
7674		);
7675		// Frame B began in PES 1: its PTS is frame A's plus one frame duration
7676		// (1152 samples at 48 kHz = 24 ms), not PES 2's 10 s.
7677		assert_eq!(frames[1].timestamp, Timestamp::from_micros(1_024_000).unwrap());
7678	}
7679
7680	// A cue is placed at its first section byte, independently of the video PTS.
7681	#[tokio::test(start_paused = true)]
7682	async fn scte35_cue_stamped_with_pcr_placement() {
7683		use crate::catalog::hang::{Catalog, Wire};
7684		use crate::container::Consumer;
7685		use crate::container::ts::catalog::Ext;
7686		use moq_net::Timestamp;
7687
7688		const VIDEO_PID: u16 = 0x0050;
7689
7690		let mut broadcast = moq_net::broadcast::Info::new().produce();
7691		let consumer = broadcast.consume();
7692		let catalog = crate::catalog::Producer::new(
7693			&mut broadcast,
7694			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
7695		)
7696		.unwrap();
7697		let mut import = super::Import::new(broadcast, catalog.reserve());
7698
7699		let mut bytes = bytes::BytesMut::new();
7700		bytes.extend_from_slice(&synth_pmt(
7701			&[
7702				(StreamType::Mpeg2Video, VIDEO_PID),
7703				(StreamType::Dts8ChannelLosslessAudio, 0x21),
7704			],
7705			true,
7706		));
7707		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 27_000_000));
7708		bytes.extend_from_slice(&pes_packet(VIDEO_PID, 99_000));
7709		let at = bytes.len() as u64 + 5;
7710		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
7711		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 29_700_000));
7712		import.decode(&bytes).unwrap();
7713		let expected = 1_000_000 + (at - (2 * 188 + 10)) * 100_000 / (3 * 188);
7714		let _finished = import.finish().unwrap();
7715
7716		let name = track_on(&catalog.snapshot().ext.mpegts, 0x21);
7717		let track = consumer
7718			.track(&name)
7719			.unwrap()
7720			.subscribe(
7721				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
7722					moq_net::track::Start::Live {
7723						min: Some(RECORDING_MAX_AGE),
7724						max: Some(RECORDING_MAX_AGE),
7725					},
7726				)]),
7727			)
7728			.await
7729			.unwrap();
7730		let mut reader = Consumer::new(track, Wire::legacy(crate::container::Kind::Data));
7731		let frame = kio::clock::timeout(Duration::from_secs(1), reader.read_frame())
7732			.await
7733			.expect("cue read timed out")
7734			.unwrap()
7735			.expect("a published cue frame");
7736
7737		assert_eq!(&frame.payload[..], &CUE[..], "verbatim splice_info_section");
7738		assert_ne!(frame.timestamp, Timestamp::ZERO, "cue must not stamp zero");
7739		// Placement is normalized to microseconds, independently of the video PTS.
7740		assert_eq!(
7741			Duration::try_from(frame.timestamp).unwrap(),
7742			Duration::from_micros(expected),
7743			"cue stamped at its first section byte on the PCR clock"
7744		);
7745	}
7746
7747	/// A section's header can straddle several PCRs; only the first PCR past its first byte places it.
7748	#[tokio::test(start_paused = true)]
7749	async fn section_placement_survives_fragmented_headers_and_shared_packets() {
7750		for split in [1, 2, 17] {
7751			let mut data = synth_pmt(
7752				&[
7753					(StreamType::Mpeg2Video, PCR_PID),
7754					(StreamType::Dts8ChannelLosslessAudio, 0x21),
7755				],
7756				true,
7757			);
7758			let before = data.len() as u64 + 10;
7759			data.extend(pcr_packet(PCR_PID, 27_000_000));
7760			data.extend(pes_packet(PCR_PID, 108_000));
7761			let first = [vec![0], CUE[..split].to_vec()].concat();
7762			let at = data.len() as u64 + 188 - split as u64;
7763			let first = pes_fragment(0x21, true, 0, &first);
7764			data.extend(first);
7765			let after = data.len() as u64 + 10;
7766			data.extend(pcr_packet(PCR_PID, 28_350_000));
7767			data.extend(pcr_packet(PCR_PID, 29_700_000));
7768			// A pointer finishes the partial then starts two complete sections in one packet.
7769			let tail = &CUE[split..];
7770			let shared = [tail, &CUE, &CUE].concat();
7771			let next = data.len() as u64 + 5 + tail.len() as u64;
7772			let shared = packet(true, 1, tail.len() as u8, &shared);
7773			assert_eq!(run(&[first.to_vec(), shared.clone()]), vec![CUE.to_vec(); 3]);
7774			data.extend(shared);
7775			let last = data.len() as u64 + 10;
7776			data.extend(pcr_packet(PCR_PID, 31_050_000));
7777			let (consumer, catalog, _import) = import_all(&data).unwrap();
7778			let name = track_on(&catalog.snapshot().ext.mpegts, 0x21);
7779			let frames = read_track(&consumer, &name, crate::container::Kind::Data).await;
7780			let times: Vec<_> = frames
7781				.iter()
7782				.map(|frame| frame.timestamp.as_micros().unwrap() as u64)
7783				.collect();
7784			let clock = |at: u64, before: u64, ticks: u64, after: u64| {
7785				(ticks + (at - before) * 1_350_000 / (after - before)) / 27
7786			};
7787			assert_eq!(
7788				times,
7789				vec![
7790					clock(at, before, 27_000_000, after),
7791					clock(next, after + 188, 29_700_000, last),
7792					clock(next + CUE.len() as u64, after + 188, 29_700_000, last)
7793				],
7794				"split {split}"
7795			);
7796			assert!(frames.iter().all(|frame| frame.payload.as_ref() == CUE));
7797		}
7798	}
7799
7800	/// Missing placement is counted the same way for whole PES and sections.
7801	#[tokio::test(start_paused = true)]
7802	async fn sections_without_a_pcr_interval_are_unplaced() {
7803		let mut data = synth_pmt(
7804			&[
7805				(StreamType::Mpeg2Video, PCR_PID),
7806				(StreamType::Dts8ChannelLosslessAudio, 0x21),
7807			],
7808			true,
7809		);
7810		data.extend(packet(true, 0, 0, &CUE));
7811		data.extend(pcr_packet(PCR_PID, 27_000_000));
7812		data.extend(pes_packet(PCR_PID, 108_000));
7813		data.extend(packet(true, 1, 0, &CUE));
7814		let (consumer, catalog, import) = import_all(&data).unwrap();
7815		assert_eq!(import.stats().streams[&0x21].unplaced, 2);
7816		let name = track_on(&catalog.snapshot().ext.mpegts, 0x21);
7817		assert!(
7818			read_track(&consumer, &name, crate::container::Kind::Data)
7819				.await
7820				.is_empty()
7821		);
7822	}
7823
7824	// A 0x86 PID without CUEI is ambiguous (DTS audio or a non-conformant SCTE mux):
7825	// it's classified Ignored and dropped, NOT handed to the PES reader (which aborts
7826	// on private sections, spec section 7) and NOT cataloged. The rest keeps importing.
7827	#[test]
7828	fn section_pid_without_cuei_is_dropped_not_cataloged() {
7829		use crate::catalog::hang::Catalog;
7830		use crate::container::ts::catalog::Ext;
7831
7832		const VIDEO_PID: u16 = 0x0050;
7833		const SECTION_PID: u16 = 0x0021;
7834
7835		let mut broadcast = moq_net::broadcast::Info::new().produce();
7836		// catalog::Ext (not the base catalog) makes a wrong ensure_scte() observable: it
7837		// would create a rendition, which the base catalog silently drops.
7838		let catalog = crate::catalog::Producer::new(
7839			&mut broadcast,
7840			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
7841		)
7842		.unwrap();
7843		let mut import = super::Import::new(broadcast, catalog.reserve());
7844
7845		let mut bytes = bytes::BytesMut::new();
7846		// PMT WITHOUT CUEI: the 0x86 PID must not be recognized as SCTE-35.
7847		bytes.extend_from_slice(&synth_pmt(
7848			&[
7849				(StreamType::Mpeg2Video, VIDEO_PID),
7850				(StreamType::Dts8ChannelLosslessAudio, SECTION_PID),
7851			],
7852			false,
7853		));
7854		bytes.extend_from_slice(&packet(true, 0, 0, &CUE)); // a private section on 0x21
7855		bytes.extend_from_slice(&pes_packet(VIDEO_PID, 90_000)); // valid video after it
7856		import.decode(&bytes).unwrap(); // must NOT abort
7857
7858		assert!(
7859			import.last_pts.is_some(),
7860			"video kept importing past the dropped section PID"
7861		);
7862		assert!(
7863			!catalog
7864				.snapshot()
7865				.ext
7866				.mpegts
7867				.tracks
7868				.values()
7869				.any(|track| track.pid == SECTION_PID),
7870			"a 0x86 PID without CUEI must not be cataloged"
7871		);
7872	}
7873
7874	#[test]
7875	fn tei_pusi_section_is_dropped() {
7876		// A PUSI flagged TEI must not start a section out of payload the demodulator has
7877		// already disowned. Resetting the counter is not enough: the packet itself is junk.
7878		let mut corrupt = packet(true, 0, 0, &CUE);
7879		corrupt[1] |= 0x80; // transport_error_indicator
7880		let clean = packet(true, 1, 0, &CUE);
7881		assert_eq!(
7882			run(&[corrupt, clean]),
7883			vec![CUE.to_vec()],
7884			"a section was emitted from a packet flagged corrupt"
7885		);
7886	}
7887
7888	#[test]
7889	fn duplicate_mid_section_packet_is_skipped() {
7890		// A 3-packet section with the central continuation duplicated (same cc, same
7891		// bytes): the duplicate is skipped so the section still reassembles.
7892		let section = fake_section(0xfc, 400); // 403 bytes, spans 3 packets
7893		let p1 = packet(true, 0, 0, &section[..183]);
7894		let p2 = packet(false, 1, 0, &section[183..367]);
7895		let p3 = packet(false, 2, 0, &section[367..]);
7896		assert_eq!(run(&[p1, p2.clone(), p2, p3]), vec![section]);
7897	}
7898
7899	#[test]
7900	fn duplicate_with_refreshed_clock_is_skipped() {
7901		let old = [0x00, 0x00, 0x00, 0x00, 0x7e, 0x00];
7902		let refreshed = [0x00, 0x00, 0x00, 0x01, 0x7e, 0x00];
7903		for (name, pcr, opcr) in [("PCR", Some(old), None), ("OPCR", None, Some(old))] {
7904			let section = fake_section(0xfc, 390);
7905			let p1 = packet(true, 0, 0, &section[..183]);
7906			let p2 = clock_packet(1, pcr, opcr, &section[183..359]);
7907			let duplicate = clock_packet(1, pcr.map(|_| refreshed), opcr.map(|_| refreshed), &section[183..359]);
7908			let p3 = packet(false, 2, 0, &section[359..]);
7909			assert_eq!(run(&[p1, p2, duplicate, p3]), vec![section], "refreshed {name}");
7910		}
7911	}
7912
7913	#[test]
7914	fn repeated_counter_after_fifteen_lost_packets_is_broken() {
7915		let mut continuity = Continuity::default();
7916		let previous: [u8; 188] = packet(false, 5, 0, &[0x11; 184]).try_into().unwrap();
7917		let after_loss: [u8; 188] = packet(false, 5, 0, &[0x22; 184]).try_into().unwrap();
7918
7919		assert!(matches!(continuity.observe(&previous), Continuation::Contiguous));
7920		assert!(matches!(continuity.observe(&after_loss), Continuation::Broken));
7921	}
7922
7923	#[test]
7924	fn duplicate_pusi_packet_emits_once() {
7925		// A complete cue in one PUSI packet sent twice (legal duplicate) emits once.
7926		let p = packet(true, 0, 0, &CUE);
7927		assert_eq!(run(&[p.clone(), p]), vec![CUE.to_vec()]);
7928	}
7929
7930	#[test]
7931	fn tei_continuation_drops_partial_and_resyncs() {
7932		// A continuation flagged TEI corrupts the partial: drop it, ignore the
7933		// following unaligned bytes, and resync on the next clean PUSI.
7934		let section = fake_section(0xfc, 247);
7935		let p1 = packet(true, 0, 0, &section[..183]);
7936		let mut p2 = packet(false, 1, 0, &section[183..]);
7937		p2[1] |= 0x80; // transport_error_indicator
7938		let p3 = packet(false, 2, 0, &CUE); // unaligned after the drop: must not emit
7939		let p4 = packet(true, 3, 0, &CUE); // clean PUSI: resync and emit
7940		assert_eq!(run(&[p1, p2, p3, p4]), vec![CUE.to_vec()]);
7941	}
7942
7943	/// A private-data-only program publishes its PES clock with its first media, with no PCR to wait for.
7944	#[tokio::test]
7945	async fn private_pes_only_program_publishes_its_pes_clock_with_the_first_media() {
7946		use crate::catalog::hang::Catalog;
7947		use crate::container::ts::catalog::Ext;
7948
7949		const DATA_PID: u16 = 0x0052;
7950
7951		let mut broadcast = moq_net::broadcast::Info::new().produce();
7952		let consumer = broadcast.consume();
7953		let catalog = crate::catalog::Producer::new(
7954			&mut broadcast,
7955			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
7956		)
7957		.unwrap();
7958		let provisional = catalog.snapshot().sync.clock.expect("a clock");
7959		let mut clocks = crate::container::test_util::Clocks::subscribe(&consumer).await;
7960		let mut import = super::Import::new(broadcast, catalog.reserve());
7961
7962		import
7963			.decode(&synth_pmt(&[(StreamType::Mpeg2PacketizedData, DATA_PID)], false))
7964			.unwrap();
7965		assert_eq!(catalog.snapshot().ext.mpegts.tracks.len(), 1, "the PMT was read");
7966		assert_eq!(clocks.drain(), vec![], "the PMT alone publishes nothing");
7967
7968		import
7969			.decode(&audio_pes_packet(DATA_PID, 0, 3_600 * 90_000, &[0xDE, 0xAD]))
7970			.unwrap();
7971		let anchored = catalog.snapshot().sync.clock.expect("a clock");
7972		assert_ne!(anchored, provisional, "the first PES anchors the clock");
7973		let published = clocks.drain();
7974		assert!(!published.is_empty(), "the first PES releases the catalog");
7975		assert!(published.iter().all(|clock| *clock == Some(anchored)), "{published:?}");
7976		let _finished = import.finish().unwrap();
7977	}
7978
7979	/// A TS packet on `pid` carrying only an adaptation field (no payload) that sets
7980	/// `discontinuity_indicator`: the clock packet a mux flags a timebase reset on.
7981	fn clock_break_packet(pid: u16) -> Vec<u8> {
7982		let mut p = vec![
7983			0x47,
7984			(pid >> 8) as u8 & 0x1f,
7985			(pid & 0xff) as u8,
7986			0x20,
7987			183, // adaptation_field_length: the rest of the packet
7988			0x80,
7989		];
7990		p.resize(188, 0xff);
7991		p
7992	}
7993
7994	/// Set `discontinuity_indicator` on a packet that already carries an adaptation field.
7995	fn flag_discontinuity(mut pkt: Vec<u8>) -> Vec<u8> {
7996		assert!(
7997			pkt[3] & 0x20 != 0 && pkt[4] > 0,
7998			"packet has no adaptation field to flag"
7999		);
8000		pkt[5] |= 0x80;
8001		pkt
8002	}
8003
8004	/// One PES on `pid` carrying two whole MP2 frames: enough for the second to confirm the
8005	/// first, which is what the legacy path publishes on.
8006	pub(in crate::container::ts) fn mp2_pes(pid: u16, cc: u8, pts: u64, fills: [u8; 2]) -> Vec<u8> {
8007		let mut payload = mp2_frame(fills[0]);
8008		payload.extend_from_slice(&mp2_frame(fills[1]));
8009		audio_pes_packet(pid, cc, pts, &payload)
8010	}
8011
8012	/// Read every retained frame of `name`, with the count of declared timeline breaks the consumer
8013	/// crossed reading them. Gaps are not counted: these streams carry a PES of two frames a second
8014	/// apart, and the hole after each reads as a gap.
8015	async fn read_breaks(
8016		consumer: &moq_net::broadcast::Consumer,
8017		name: &str,
8018		kind: crate::container::Kind,
8019	) -> (Vec<crate::container::Frame>, u64) {
8020		// A generous max delay: the default of zero would shed every non-latest group, the
8021		// declared breaks among them, and the subscribe start is resolved from it too, so
8022		// it has to reach back past a 30 s leap to the first frame.
8023		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
8024			moq_net::track::Start::Live {
8025				min: Some(std::time::Duration::from_secs(3600)),
8026				max: Some(std::time::Duration::from_secs(3600)),
8027			},
8028		)]);
8029		let track = consumer.track(name).unwrap().subscribe(subscription).await.unwrap();
8030		let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(kind));
8031		let mut frames = Vec::new();
8032		let mut breaks = 0;
8033		while let Ok(Ok(Some(read))) = kio::clock::timeout(std::time::Duration::from_millis(50), reader.read()).await {
8034			match read {
8035				crate::container::Read::Frame { frame, .. } => frames.push(frame),
8036				crate::container::Read::End { .. } => breaks += 1,
8037				crate::container::Read::Gap { .. } => {}
8038			}
8039		}
8040		(frames, breaks)
8041	}
8042
8043	/// Both [`two_stream_import`] renditions' frames and break counts, in catalog order.
8044	async fn read_all_breaks(
8045		consumer: &moq_net::broadcast::Consumer,
8046		catalog: &crate::catalog::Producer,
8047	) -> Vec<(Vec<crate::container::Frame>, u64)> {
8048		let names: Vec<String> = catalog.snapshot().audio.renditions.keys().cloned().collect();
8049		let mut out = Vec::new();
8050		for name in names {
8051			out.push(read_breaks(consumer, &name, crate::container::Kind::Audio).await);
8052		}
8053		assert_eq!(out.len(), 2, "both renditions must exist");
8054		out
8055	}
8056
8057	/// A two-program multiplex whose clocks sit an hour apart: program 1's MP2 on
8058	/// `0x0061` starts at 1 s, program 2's on `0x0071` at 3601 s.
8059	pub(in crate::container::ts) fn two_programs() -> Vec<u8> {
8060		let mut data = synth_programs(
8061			&[
8062				(1, 0x0100, &[(StreamType::Mpeg1Audio, 0x0061)]),
8063				(2, 0x0200, &[(StreamType::Mpeg1Audio, 0x0071)]),
8064			],
8065			false,
8066		);
8067		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8068		data.extend(mp2_pes(0x0071, 0, 3_601 * 90_000, [0xCC, 0xDD]));
8069		data
8070	}
8071
8072	#[test]
8073	fn a_multi_program_input_is_refused_before_publishing() {
8074		let mut broadcast = moq_net::broadcast::Info::new().produce();
8075		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8076		let mut import = super::Import::new(broadcast, catalog.reserve());
8077
8078		let err = import.decode(&two_programs()).unwrap_err();
8079		let super::Error::MultiplePrograms { programs } = err else {
8080			panic!("a multiplex refusal: {err}");
8081		};
8082		assert_eq!(programs, [1, 2]);
8083		assert!(catalog.snapshot().audio.renditions.is_empty(), "nothing was published");
8084	}
8085
8086	#[test]
8087	fn a_program_added_mid_stream_ends_the_import() {
8088		let mut broadcast = moq_net::broadcast::Info::new().produce();
8089		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8090		let mut import = super::Import::new(broadcast, catalog.reserve());
8091		import
8092			.decode(&synth_pmt(&[(StreamType::Mpeg1Audio, 0x0061)], false))
8093			.unwrap();
8094		import.decode(&mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB])).unwrap();
8095
8096		let err = import.decode(&two_programs()).unwrap_err();
8097		assert!(matches!(err, super::Error::MultiplePrograms { .. }), "{err}");
8098		assert_eq!(
8099			catalog.snapshot().audio.renditions.len(),
8100			1,
8101			"program 1 stays published"
8102		);
8103	}
8104
8105	#[tokio::test(start_paused = true)]
8106	async fn a_selected_program_publishes_only_its_streams_on_its_clock() {
8107		let mut broadcast = moq_net::broadcast::Info::new().produce();
8108		let consumer = broadcast.consume();
8109		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8110		let mut import = super::Import::new(broadcast, catalog.reserve()).with_program(2);
8111		import.decode(&two_programs()).unwrap();
8112		let _finished = import.finish().unwrap();
8113
8114		let snapshot = catalog.snapshot();
8115		let names: Vec<_> = snapshot.audio.renditions.keys().collect();
8116		assert_eq!(names.len(), 1, "only program 2's stream: {names:?}");
8117		let (frames, _) = read_breaks(&consumer, names[0], crate::container::Kind::Audio).await;
8118		assert!(!frames.is_empty(), "program 2 published");
8119		assert!(
8120			frames
8121				.iter()
8122				.all(|frame| frame.payload[4] == 0xCC || frame.payload[4] == 0xDD),
8123			"no program 1 frame leaks in"
8124		);
8125		assert_eq!(
8126			frames[0].timestamp.as_micros().unwrap(),
8127			3_601_000_000,
8128			"program 2's own PTS"
8129		);
8130	}
8131
8132	#[test]
8133	fn a_selected_program_the_pat_does_not_list_is_refused() {
8134		let mut broadcast = moq_net::broadcast::Info::new().produce();
8135		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8136		let mut import = super::Import::new(broadcast, catalog.reserve()).with_program(3);
8137
8138		let err = import.decode(&two_programs()).unwrap_err();
8139		let super::Error::MissingProgram { program, programs } = &err else {
8140			panic!("a missing program: {err}");
8141		};
8142		assert_eq!((*program, programs.as_slice()), (3, &[1, 2][..]));
8143		assert!(err.to_string().contains("no program 3; its PAT lists 1, 2"), "{err}");
8144	}
8145
8146	/// `section` on `pid` as the packets a mux would send, counting from `*cc`: the first
8147	/// opens it behind a pointer_field skipping `tail` (the end of an earlier section), and
8148	/// the rest carry it on.
8149	pub(in crate::container::ts) fn psi_packets(pid: u16, cc: &mut u8, tail: &[u8], section: &[u8]) -> Vec<u8> {
8150		let mut payload = vec![tail.len() as u8];
8151		payload.extend_from_slice(tail);
8152		payload.extend_from_slice(section);
8153		let mut out = Vec::new();
8154		for (i, chunk) in payload.chunks(184).enumerate() {
8155			let pusi = if i == 0 { 0x40 } else { 0 };
8156			out.extend_from_slice(&[0x47, pusi | (pid >> 8) as u8, pid as u8, 0x10 | *cc]);
8157			out.extend_from_slice(chunk);
8158			out.resize(out.len().next_multiple_of(188), 0xff);
8159			*cc = (*cc + 1) & 0x0f;
8160		}
8161		out
8162	}
8163
8164	/// A PAT section listing `(program_number, pmt_pid)`.
8165	pub(in crate::container::ts) fn pat_section(programs: &[(u16, u16)]) -> Vec<u8> {
8166		let body: Vec<u8> = programs
8167			.iter()
8168			.flat_map(|&(number, pid)| [(number >> 8) as u8, number as u8, 0xe0 | (pid >> 8) as u8, pid as u8])
8169			.collect();
8170		super::psi::section(0x00, 1, 0, 0, 0, &body)
8171	}
8172
8173	/// A PMT section listing `(stream_type, pid, es_descriptors)`, the clock on the first.
8174	pub(in crate::container::ts) fn pmt_section(program: u16, version: u8, streams: &[(u8, u16, &[u8])]) -> Vec<u8> {
8175		let pcr = streams.first().map_or(0x1fff, |&(_, pid, _)| pid);
8176		let mut body = vec![0xe0 | (pcr >> 8) as u8, pcr as u8, 0xf0, 0x00];
8177		for &(stream_type, pid, descriptors) in streams {
8178			body.extend_from_slice(&[
8179				stream_type,
8180				0xe0 | (pid >> 8) as u8,
8181				pid as u8,
8182				0xf0,
8183				descriptors.len() as u8,
8184			]);
8185			body.extend_from_slice(descriptors);
8186		}
8187		super::psi::section(0x02, program, version, 0, 0, &body)
8188	}
8189
8190	/// `section` with one bit of its CRC flipped.
8191	pub(in crate::container::ts) fn corrupt(mut section: Vec<u8>) -> Vec<u8> {
8192		*section.last_mut().unwrap() ^= 0x01;
8193		section
8194	}
8195
8196	pub(in crate::container::ts) const MP2: u8 = StreamType::Mpeg1Audio as u8;
8197
8198	/// A PAT listing fifty programs, which takes two packets, then program 50's PMT (one
8199	/// MP2 stream on `0x0061`) and one PES on it.
8200	pub(in crate::container::ts) fn fifty_programs() -> Vec<u8> {
8201		let programs: Vec<_> = (1..=50).map(|n| (n, 0x0100 + n)).collect();
8202		let pat = pat_section(&programs);
8203		let mut data = psi_packets(0, &mut 0, &[], &pat);
8204		assert_eq!(data.len(), 2 * 188, "the PAT spans two packets");
8205		data.extend(psi_packets(
8206			0x0132,
8207			&mut 0,
8208			&[],
8209			&pmt_section(50, 0, &[(MP2, 0x0061, &[])]),
8210		));
8211		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8212		data
8213	}
8214
8215	/// A PAT split into two sections, each in its own packet, listing program 1 then program
8216	/// 2, then each program's PMT (one MP2 stream) and one PES on it.
8217	pub(in crate::container::ts) fn two_section_pat() -> Vec<u8> {
8218		let mut cc = 0;
8219		let mut data = Vec::new();
8220		for (number, program) in [(0, 1u16), (1, 2)] {
8221			let entry = [0x00, program as u8, 0xe0 | program as u8, 0x00];
8222			let section = super::psi::section(0x00, 1, 0, number, 1, &entry);
8223			data.extend(psi_packets(0, &mut cc, &[], &section));
8224		}
8225		for (program, pid, fills) in [(1u16, 0x0061, [0xAA, 0xBB]), (2, 0x0071, [0xCC, 0xDD])] {
8226			let pmt = pmt_section(program, 0, &[(MP2, pid, &[])]);
8227			data.extend(psi_packets(program << 8, &mut 0, &[], &pmt));
8228			data.extend(mp2_pes(pid, 0, 90_000, fills));
8229		}
8230		data
8231	}
8232
8233	fn psi_import() -> (crate::catalog::Producer, super::Import) {
8234		let mut broadcast = moq_net::broadcast::Info::new().produce();
8235		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8236		let import = super::Import::new(broadcast, catalog.reserve());
8237		(catalog, import)
8238	}
8239
8240	#[test]
8241	fn a_pmt_spanning_two_packets_is_read_whole() {
8242		let (catalog, mut import) = psi_import();
8243		// A private descriptor long enough to push the second stream into the next packet.
8244		let mut descriptor = vec![0x80, 200];
8245		descriptor.resize(202, 0x00);
8246		let pmt = pmt_section(1, 0, &[(MP2, 0x0061, &descriptor), (MP2, 0x0062, &[])]);
8247		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100)]));
8248		data.extend(psi_packets(0x0100, &mut 0, &[], &pmt));
8249		assert_eq!(data.len(), 3 * 188, "the PMT spans two packets");
8250		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8251		data.extend(mp2_pes(0x0062, 0, 90_000, [0xCC, 0xDD]));
8252
8253		import.decode(&data).unwrap();
8254		import.finish_in_place().unwrap();
8255		assert_eq!(catalog.snapshot().audio.renditions.len(), 2, "both streams publish");
8256		assert_eq!(import.stats().crc_error, 0);
8257	}
8258
8259	#[test]
8260	fn a_pat_behind_a_nonzero_pointer_field_is_read() {
8261		let (catalog, mut import) = psi_import();
8262		let mut data = psi_packets(0, &mut 0, &[0xab; 7], &pat_section(&[(1, 0x0100)]));
8263		data.extend(psi_packets(
8264			0x0100,
8265			&mut 0,
8266			&[],
8267			&pmt_section(1, 0, &[(MP2, 0x0061, &[])]),
8268		));
8269		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8270
8271		import.decode(&data).unwrap();
8272		let _finished = import.finish().unwrap();
8273		assert_eq!(catalog.snapshot().audio.renditions.len(), 1);
8274	}
8275
8276	#[test]
8277	fn a_program_listed_in_a_pats_second_packet_is_selected() {
8278		let (catalog, import) = psi_import();
8279		let mut import = import.with_program(50);
8280		import.decode(&fifty_programs()).unwrap();
8281		let _finished = import.finish().unwrap();
8282		assert_eq!(catalog.snapshot().audio.renditions.len(), 1, "program 50 publishes");
8283
8284		// Unselected, the whole PAT is what refuses the input.
8285		let (_, mut import) = psi_import();
8286		let err = import.decode(&fifty_programs()).unwrap_err();
8287		let super::Error::MultiplePrograms { programs } = err else {
8288			panic!("a multiplex refusal: {err}");
8289		};
8290		assert_eq!(programs, (1..=50).collect::<Vec<_>>());
8291	}
8292
8293	/// A corrupt PAT and a corrupt PMT between good repetitions are each dropped and counted
8294	/// once, while the layout they would have changed holds; a later good PMT revision still
8295	/// applies.
8296	#[test]
8297	fn corrupt_psi_between_good_repetitions_is_dropped_and_counted() {
8298		let (catalog, mut import) = psi_import();
8299		let (mut pat_cc, mut pmt_cc) = (0, 0);
8300		let pat = pat_section(&[(1, 0x0100)]);
8301		let pmt = pmt_section(1, 0, &[(MP2, 0x0061, &[])]);
8302		let two = [(MP2, 0x0061, &[][..]), (MP2, 0x0062, &[][..])];
8303
8304		let mut data = psi_packets(0, &mut pat_cc, &[], &pat);
8305		data.extend(psi_packets(0x0100, &mut pmt_cc, &[], &pmt));
8306		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8307		import.decode(&data).unwrap();
8308		let units = import.stats().streams[&0x0061].units;
8309
8310		// Read, this PAT would end the unselected import with a second program, and this PMT
8311		// would add a stream.
8312		let mut data = psi_packets(0, &mut pat_cc, &[], &corrupt(pat_section(&[(1, 0x0100), (2, 0x0200)])));
8313		data.extend(psi_packets(0x0100, &mut pmt_cc, &[], &corrupt(pmt_section(1, 1, &two))));
8314		data.extend(psi_packets(0, &mut pat_cc, &[], &pat));
8315		data.extend(psi_packets(0x0100, &mut pmt_cc, &[], &pmt));
8316		data.extend(mp2_pes(0x0061, 1, 180_000, [0xAA, 0xBB]));
8317		import.decode(&data).unwrap();
8318
8319		assert_eq!(
8320			catalog.snapshot().audio.renditions.len(),
8321			1,
8322			"the corrupt PMT added nothing"
8323		);
8324		assert!(
8325			import.stats().streams[&0x0061].units > units,
8326			"the stream kept delivering"
8327		);
8328		assert_eq!(import.crc_errors(), &BTreeMap::from([(0x0100, 1)]));
8329		assert_eq!(import.demux.pat_crc_error(), 1);
8330		assert_eq!(import.stats().crc_error, 2);
8331
8332		let mut data = psi_packets(0x0100, &mut pmt_cc, &[], &pmt_section(1, 2, &two));
8333		data.extend(mp2_pes(0x0062, 0, 180_000, [0xCC, 0xDD]));
8334		import.decode(&data).unwrap();
8335		import.finish_in_place().unwrap();
8336		assert_eq!(
8337			catalog.snapshot().audio.renditions.len(),
8338			2,
8339			"the good revision applied"
8340		);
8341		assert_eq!(import.stats().crc_error, 2, "good sections count nothing");
8342	}
8343
8344	/// The positive control: with no good PAT, nothing is learned, so nothing publishes.
8345	#[test]
8346	fn a_feed_whose_only_pat_is_corrupt_publishes_nothing() {
8347		let (catalog, mut import) = psi_import();
8348		let mut data = psi_packets(0, &mut 0, &[], &corrupt(pat_section(&[(1, 0x0100)])));
8349		data.extend(psi_packets(
8350			0x0100,
8351			&mut 0,
8352			&[],
8353			&pmt_section(1, 0, &[(MP2, 0x0061, &[])]),
8354		));
8355		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
8356
8357		import.decode(&data).unwrap();
8358		import.finish_in_place().unwrap();
8359		assert!(catalog.snapshot().audio.renditions.is_empty());
8360		assert_eq!(import.stats().crc_error, 1);
8361		assert!(!import.stats().is_empty(), "a dropped section is something to report");
8362	}
8363
8364	#[test]
8365	fn adaptation_field_past_the_packet_drops_partial() {
8366		let section = fake_section(0xfc, 300);
8367		let mut malformed = packet(false, 1, 0, &section[183..]);
8368		// afc 0b11 with an adaptation_field_length reaching past the packet.
8369		malformed[3] = 0x31;
8370		malformed[4] = 200;
8371		let rest = packet(false, 2, 0, &section[183..]);
8372		assert!(run(&[packet(true, 0, 0, &section[..183]), malformed, rest]).is_empty());
8373	}
8374
8375	/// Two MP2 renditions, the first of which the PMT designates as the PCR PID.
8376	const PCR_PID: u16 = 0x0061;
8377	const PEER_PID: u16 = 0x0062;
8378
8379	fn two_stream_import() -> (moq_net::broadcast::Consumer, crate::catalog::Producer, super::Import) {
8380		let mut broadcast = moq_net::broadcast::Info::new().produce();
8381		let consumer = broadcast.consume();
8382		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8383		let mut import = super::Import::new(broadcast, catalog.reserve());
8384		let pmt = synth_pmt(
8385			&[(StreamType::Mpeg1Audio, PCR_PID), (StreamType::Mpeg1Audio, PEER_PID)],
8386			false,
8387		);
8388		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
8389		(consumer, catalog, import)
8390	}
8391
8392	#[test]
8393	fn timebase_reset_clears_unpublished_pending() {
8394		let (_, _, mut import) = two_stream_import();
8395		let payload = mp2_frame(0xAA);
8396		import
8397			.decode(audio_pes_open(PEER_PID, 0, 90_000, payload.len() * 2, &payload[..20]).as_slice())
8398			.unwrap();
8399		assert!(!import.published);
8400		assert!(!import.pending.is_empty());
8401		// The break routes once the stream shows it is no rewind.
8402		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8403		import
8404			.decode(mp2_pes(PEER_PID, 1, 20 * 90_000, [0xCC, 0xDD]).as_slice())
8405			.unwrap();
8406		assert!(import.pending.is_empty(), "old PES survived the timebase reset");
8407	}
8408
8409	#[test]
8410	fn timebase_reset_clears_si_clock() {
8411		let (_, _, mut import) = two_stream_import();
8412		import.last_pts = Some(Timestamp::from_micros(45_000_000).unwrap());
8413		import.published = true;
8414		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8415		assert!(import.last_pts.is_none(), "SI clock belongs to the old timebase");
8416	}
8417
8418	#[tokio::test(start_paused = true)]
8419	async fn timebase_reset_after_anchored_section_publication() {
8420		use crate::catalog::hang::Catalog;
8421		use crate::container::ts::catalog::Ext;
8422		let mut broadcast = moq_net::broadcast::Info::new().produce();
8423		let consumer = broadcast.consume();
8424		let catalog = crate::catalog::Producer::new(
8425			&mut broadcast,
8426			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
8427		)
8428		.unwrap();
8429		let mut import = super::Import::new(broadcast, catalog.reserve());
8430		import
8431			.decode(
8432				synth_pmt(
8433					&[
8434						(StreamType::Mpeg2Video, PCR_PID),
8435						(StreamType::Dts8ChannelLosslessAudio, 0x21),
8436					],
8437					true,
8438				)
8439				.as_slice(),
8440			)
8441			.unwrap();
8442		// Each era resumes a second on, since a track's group starts only move forward.
8443		import.decode(pcr_packet(PCR_PID, 24_300_000).as_slice()).unwrap();
8444		import.decode(packet(true, 0, 0, &CUE).as_slice()).unwrap();
8445		import.decode(pes_packet(PCR_PID, 90_000).as_slice()).unwrap();
8446		import.decode(pcr_packet(PCR_PID, 27_000_000).as_slice()).unwrap();
8447		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8448		import.decode(pcr_packet(PCR_PID, 51_300_000).as_slice()).unwrap();
8449		import.decode(packet(true, 1, 0, &CUE).as_slice()).unwrap();
8450		import.decode(pes_packet(PCR_PID, 180_000).as_slice()).unwrap();
8451		import.decode(pcr_packet(PCR_PID, 54_000_000).as_slice()).unwrap();
8452		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8453		import.decode(pcr_packet(PCR_PID, 78_300_000).as_slice()).unwrap();
8454		import.decode(packet(true, 2, 0, &CUE).as_slice()).unwrap();
8455		import.decode(pes_packet(PCR_PID, 270_000).as_slice()).unwrap();
8456		import.decode(pcr_packet(PCR_PID, 81_000_000).as_slice()).unwrap();
8457		let _finished = import.finish().unwrap();
8458		let name = track_on(&catalog.snapshot().ext.mpegts, 0x21);
8459		let (frames, breaks) = read_breaks(&consumer, &name, crate::container::Kind::Data).await;
8460		assert_eq!(frames.len(), 3);
8461		assert_eq!(
8462			breaks, 2,
8463			"each break on the data track reads once, as its declared end"
8464		);
8465	}
8466
8467	#[tokio::test(start_paused = true)]
8468	async fn data_only_pcr_era_is_shared_with_media_added_later() {
8469		use super::super::catalog::Ext;
8470		use super::super::fixture::{Flags, MS, Mux, WRAP};
8471		let mut broadcast = moq_net::broadcast::Info::new().produce();
8472		let catalog = crate::catalog::Producer::new(
8473			&mut broadcast,
8474			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
8475		)
8476		.unwrap();
8477		let mut import = super::Import::new(broadcast, catalog.reserve());
8478		let mut mux = Mux::default();
8479		mux.pat(&[(1, 0x20)])
8480			.pmt(0x20, 1, PCR_PID, &[(0x05, 0x21)], 0)
8481			.packet(PCR_PID, Flags::pcr(WRAP - 40 * MS))
8482			.section(0x21, &CUE)
8483			.packet(PCR_PID, Flags::pcr(40 * MS));
8484		import.decode(&mux.bytes()).unwrap();
8485		assert!(import.timebase.offset().is_some());
8486		assert!(!import.media_clock);
8487		let mut mux = Mux::default();
8488		mux.pmt(0x20, 1, PCR_PID, &[(0x02, 0x100), (0x05, 0x21)], 0)
8489			.pes(0x100, Flags::default(), 9_000)
8490			.fill(0x100, 1);
8491		import.decode(&mux.bytes()).unwrap();
8492		assert!(import.media_clock);
8493		assert_eq!(
8494			import.last_pts.unwrap(),
8495			Timestamp::from_scale((1 << 33) + 9_000, 90_000).unwrap()
8496		);
8497		let _finished = import.finish().unwrap();
8498	}
8499
8500	#[test]
8501	fn sections_without_a_media_anchor_follow_whole_pes_handling() {
8502		use crate::catalog::hang::Catalog;
8503		use crate::container::ts::catalog::Ext;
8504
8505		for clock in ["none", "shared offset", "clock break"] {
8506			let mut broadcast = moq_net::broadcast::Info::new().produce();
8507			let catalog = crate::catalog::Producer::new(
8508				&mut broadcast,
8509				crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
8510			)
8511			.unwrap();
8512			let mut import = super::Import::new(broadcast, catalog.reserve());
8513			import
8514				.decode(&synth_pmt(
8515					&[
8516						(StreamType::Mpeg2Video, PCR_PID),
8517						(StreamType::Dts8ChannelLosslessAudio, 0x21),
8518					],
8519					true,
8520				))
8521				.unwrap();
8522			if clock == "shared offset" {
8523				// A sibling importer can anchor the shared timebase before this source has PTS.
8524				import
8525					.timebase
8526					.anchor(Timestamp::from_micros(1_000_000).unwrap())
8527					.unwrap();
8528			} else if clock == "clock break" {
8529				import.decode(&pes_packet(PCR_PID, 90_000)).unwrap();
8530				import.decode(&clock_break_packet(PCR_PID)).unwrap();
8531			}
8532			import.decode(&pcr_packet(PCR_PID, 27_000_000)).unwrap();
8533			import.decode(&packet(true, 0, 0, &CUE)).unwrap();
8534			if clock == "none" {
8535				let err = import.finish_in_place().unwrap_err();
8536				assert!(
8537					matches!(&err, super::Error::Malformed(msg) if msg.contains("without a media timestamp")),
8538					"{clock}: {err}"
8539				);
8540			} else {
8541				import.finish_in_place().unwrap();
8542				assert!(import.sections[&0x21].held.is_empty());
8543				assert_eq!(import.stats().streams[&0x21].unplaced, 1, "{clock}: no PCR interval");
8544			}
8545			assert!(!import.published, "{clock}: no publication without an anchor");
8546		}
8547	}
8548
8549	/// A finish that fails is final: every track aborts with the cause rather than staying open,
8550	/// and later calls report it instead of finishing again or accepting input.
8551	#[tokio::test]
8552	async fn a_failed_finish_aborts_every_track() {
8553		use crate::catalog::hang::Catalog;
8554		use crate::container::ts::catalog::Ext;
8555
8556		let mut broadcast = moq_net::broadcast::Info::new().produce();
8557		let consumer = broadcast.consume();
8558		let catalog = crate::catalog::Producer::new(
8559			&mut broadcast,
8560			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
8561		)
8562		.unwrap();
8563		let mut import = super::Import::new(broadcast, catalog.reserve());
8564		import
8565			.decode(&synth_pmt(
8566				&[
8567					(StreamType::Mpeg2Video, PCR_PID),
8568					(StreamType::Dts8ChannelLosslessAudio, 0x21),
8569				],
8570				true,
8571			))
8572			.unwrap();
8573		import.decode(&pcr_packet(PCR_PID, 27_000_000)).unwrap();
8574		// A section no media timestamp ever places.
8575		import.decode(&packet(true, 0, 0, &CUE)).unwrap();
8576		let name = catalog.snapshot().ext.mpegts.tracks.keys().next().unwrap().clone();
8577		let mut track = consumer.track(&name).unwrap().subscribe(None).await.unwrap();
8578
8579		let err = import.finish_in_place().unwrap_err();
8580		assert!(
8581			matches!(&err, super::Error::Malformed(msg) if msg.contains("without a media timestamp")),
8582			"{err}"
8583		);
8584		let ended = kio::clock::timeout(Duration::from_millis(50), track.recv_group())
8585			.await
8586			.expect("the track ends");
8587		assert!(ended.is_err(), "the track aborts rather than finishing");
8588
8589		let retried = import.finish_in_place().unwrap_err();
8590		assert!(
8591			matches!(&retried, super::Error::Malformed(msg) if msg.contains("without a media timestamp")),
8592			"{retried}"
8593		);
8594		let refused = import.decode(&pcr_packet(PCR_PID, 54_000_000)).unwrap_err();
8595		assert!(
8596			matches!(&refused, super::Error::Malformed(msg) if msg.contains("without a media timestamp")),
8597			"{refused}"
8598		);
8599	}
8600
8601	#[test]
8602	fn unanchored_sections_cannot_cross_a_clock_break() {
8603		use crate::catalog::hang::Catalog;
8604		use crate::container::ts::catalog::Ext;
8605		let mut broadcast = moq_net::broadcast::Info::new().produce();
8606		let catalog = crate::catalog::Producer::new(
8607			&mut broadcast,
8608			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
8609		)
8610		.unwrap();
8611		let mut import = super::Import::new(broadcast, catalog.reserve());
8612		import
8613			.decode(&synth_pmt(
8614				&[
8615					(StreamType::Mpeg2Video, PCR_PID),
8616					(StreamType::Dts8ChannelLosslessAudio, 0x21),
8617				],
8618				true,
8619			))
8620			.unwrap();
8621		import.decode(&pcr_packet(PCR_PID, 27_000_000)).unwrap();
8622		import.decode(&packet(true, 0, 0, &CUE)).unwrap();
8623		let err = import.decode(&clock_break_packet(PCR_PID)).unwrap_err();
8624		assert!(matches!(&err, super::Error::Malformed(msg) if msg.contains("clock break without a media timestamp")));
8625		assert_eq!(import.sections[&0x21].held.len(), 1);
8626		assert!(!import.published);
8627	}
8628
8629	#[tokio::test(start_paused = true)]
8630	async fn duplicate_payload_clock_packet_declares_one_break() {
8631		let (consumer, catalog, mut import) = two_stream_import();
8632		for pid in [PCR_PID, PEER_PID] {
8633			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
8634		}
8635		let flagged = flag_discontinuity(mp2_pes(PCR_PID, 1, 180_000, [0xCC, 0xDD]));
8636		import.decode(flagged.as_slice()).unwrap();
8637		import.decode(flagged.as_slice()).unwrap();
8638		for pid in [PCR_PID, PEER_PID] {
8639			let cc = if pid == PCR_PID { 2 } else { 1 };
8640			import
8641				.decode(mp2_pes(pid, cc, 270_000, [0xEE, 0xFF]).as_slice())
8642				.unwrap();
8643		}
8644		let _finished = import.finish().unwrap();
8645		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
8646			assert_eq!(breaks, 1, "a retransmitted packet declared another break");
8647		}
8648	}
8649
8650	#[tokio::test(start_paused = true)]
8651	async fn incomplete_media_does_not_declare_another_break() {
8652		let (consumer, catalog, mut import) = two_stream_import();
8653		for pid in [PCR_PID, PEER_PID] {
8654			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
8655		}
8656		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8657		import
8658			.decode(audio_pes_packet(PEER_PID, 1, 180_000, &mp2_frame(0xCC)[..20]).as_slice())
8659			.unwrap();
8660		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8661		for pid in [PCR_PID, PEER_PID] {
8662			let cc = if pid == PCR_PID { 1 } else { 2 };
8663			import
8664				.decode(mp2_pes(pid, cc, 270_000, [0xEE, 0xFF]).as_slice())
8665				.unwrap();
8666		}
8667		let _finished = import.finish().unwrap();
8668		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
8669			assert_eq!(breaks, 1, "an incomplete frame was counted as publication");
8670		}
8671	}
8672
8673	/// The defect from #2833: a source that signals a timebase reset produced nothing on the
8674	/// exported wire, because the flag never left the demuxer. A `discontinuity_indicator` on
8675	/// the PCR PID is a *system* time-base break, so every track in the program takes one,
8676	/// including the peers carrying no flag of their own.
8677	#[tokio::test(start_paused = true)]
8678	async fn pcr_discontinuity_breaks_every_track() {
8679		let (consumer, catalog, mut import) = two_stream_import();
8680
8681		for pid in [PCR_PID, PEER_PID] {
8682			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
8683		}
8684		// The encoder restarts: the clock declares the break and the media resumes 20 s
8685		// ahead. Within the track's 30 s max age, so a subscribe still reaches
8686		// back to the first frame; the exported-clock tests cover the 30 s leap itself.
8687		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
8688		for pid in [PCR_PID, PEER_PID] {
8689			import
8690				.decode(mp2_pes(pid, 1, 90_000 + 20 * 90_000, [0xCC, 0xDD]).as_slice())
8691				.unwrap();
8692		}
8693		let _finished = import.finish().unwrap();
8694
8695		for (frames, breaks) in read_all_breaks(&consumer, &catalog).await {
8696			assert_eq!(breaks, 1, "the timebase break did not reach this track");
8697			let fills: Vec<u8> = frames.iter().map(|f| f.payload[4]).collect();
8698			assert_eq!(fills, [0xAA, 0xBB, 0xCC, 0xDD], "media either side of the break");
8699			assert_eq!(frames[2].timestamp.as_micros().unwrap(), 21_000_000, "the new timeline");
8700		}
8701	}
8702
8703	/// A backwards restart is the same signal, but a rewind: a new broadcast, so the identity
8704	/// ends at the break, once every stream stepped back, and hands the input from there on.
8705	/// The unwrapper must not read the step back as the 33-bit field wrapping, which would put
8706	/// the new timeline 26 hours out and publish it.
8707	#[tokio::test(start_paused = true)]
8708	async fn a_flagged_backwards_restart_ends_the_identity() {
8709		let (_consumer, _catalog, mut import) = two_stream_import();
8710
8711		for pid in [PCR_PID, PEER_PID] {
8712			import
8713				.decode(mp2_pes(pid, 0, 45 * 90_000, [0xAA, 0xBB]).as_slice())
8714				.unwrap();
8715		}
8716		let mut after = clock_break_packet(PCR_PID);
8717		import.decode(&after).unwrap();
8718		after.extend(mp2_pes(PCR_PID, 1, 90_000, [0xCC, 0xDD]));
8719		import.decode(&after[188..]).unwrap();
8720		after.extend(mp2_pes(PEER_PID, 1, 90_000, [0xCC, 0xDD]));
8721		let restart = import
8722			.decode_or_restart(&after[2 * 188..])
8723			.unwrap()
8724			.expect("a restart below the live edge is a new broadcast");
8725		assert_eq!(
8726			restart.step,
8727			crate::container::ts::Step::Rewind {
8728				by: Duration::from_secs(44),
8729				flagged: true
8730			}
8731		);
8732		assert_eq!(restart.remainder, after, "the new identity starts at the break");
8733		let _finished = import.finish().unwrap();
8734	}
8735
8736	/// Adaptation stuffing leaves exactly these bytes in a TS payload.
8737	fn pes_fragment(pid: u16, pusi: bool, cc: u8, data: &[u8]) -> [u8; 188] {
8738		assert!(!data.is_empty() && data.len() <= 183);
8739		let mut packet = [0xff; 188];
8740		packet[..5].copy_from_slice(&[
8741			0x47,
8742			((pid >> 8) as u8 & 0x1f) | if pusi { 0x40 } else { 0 },
8743			pid as u8,
8744			0x30 | (cc & 15),
8745			(183 - data.len()) as u8,
8746		]);
8747		if packet[4] != 0 {
8748			packet[5] = 0;
8749		}
8750		packet[188 - data.len()..].copy_from_slice(data);
8751		packet
8752	}
8753
8754	#[test]
8755	fn pes_headers_fragment_at_every_byte_boundary() {
8756		const PID: u16 = 0x50;
8757		for (optional, paired) in [(5, false), (10, true), (255, true)] {
8758			let mut header = vec![0, 0, 1, 0xe0, 0, 0, 0x80, if paired { 0xc0 } else { 0x80 }, optional];
8759			header.extend_from_slice(&pes_timestamp(if paired { 3 } else { 2 }, 90_000));
8760			if paired {
8761				header.extend_from_slice(&pes_timestamp(1, 87_000));
8762			}
8763			header.resize(9 + usize::from(optional), 0xff);
8764			let data = [0xde, 0xad, 0xbe, 0xef];
8765			for split in 1..header.len() {
8766				let mut broadcast = moq_net::broadcast::Info::new().produce();
8767				let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8768				let mut import = super::Import::new(broadcast, catalog.reserve());
8769				let pid = mpeg2ts::ts::Pid::new(PID).unwrap();
8770				import.streams.insert(pid, super::Stream::Ignored);
8771				let mut cc = 0;
8772				for part in [&header[..split], &header[split..], &data] {
8773					for chunk in part.chunks(183) {
8774						import
8775							.pes_packet(pid, &pes_fragment(PID, cc == 0, cc, chunk), 0)
8776							.unwrap();
8777						cc += 1;
8778					}
8779				}
8780				let pending = import.pending.get(&pid).expect("a split clear PES is retained");
8781				assert_eq!(pending.pts, Some(90_000), "optional={optional} split={split}");
8782				assert_eq!(pending.dts, paired.then_some(87_000));
8783				assert_eq!(pending.data, data, "optional={optional} split={split}");
8784			}
8785		}
8786	}
8787
8788	fn ignored_pes_import() -> super::Import {
8789		let mut broadcast = moq_net::broadcast::Info::new().produce();
8790		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
8791		let mut import = super::Import::new(broadcast, catalog.reserve());
8792		for raw in [0x50, 0x51] {
8793			import.streams.insert(Pid::new(raw).unwrap(), super::Stream::Ignored);
8794		}
8795		import
8796	}
8797
8798	/// A header cut short by loss or the end of input is dropped; one the muxer cut short with
8799	/// the next start ends the import.
8800	#[test]
8801	fn pes_fragmented_header_resets_on_loss_and_eof_and_ends_at_a_new_start() {
8802		let pid = Pid::new(0x50).unwrap();
8803		let header = [0, 0, 1, 0xe0, 0, 0, 0x80, 0x80, 5];
8804		for end in ["loss", "start", "eof"] {
8805			let mut import = ignored_pes_import();
8806			import
8807				.pes_packet(pid, &pes_fragment(0x50, true, 0, &header), 0)
8808				.unwrap();
8809			assert_eq!(import.headers[&pid].1.len(), 9);
8810			match end {
8811				"loss" => import.broken(pid).unwrap(),
8812				"start" => {
8813					let err = import
8814						.pes_packet(
8815							pid,
8816							&pes_fragment(0x50, true, 1, &[0, 0, 1, 0xe0, 0, 0, 0x80, 0, 0, 0xaa]),
8817							0,
8818						)
8819						.expect_err("an intact header cut short is the muxer's");
8820					assert!(err.to_string().contains("truncated at the next start"), "{err}");
8821					continue;
8822				}
8823				_ => import.finish_in_place().unwrap(),
8824			}
8825			assert!(!import.headers.contains_key(&pid));
8826			import
8827				.pes_packet(pid, &pes_fragment(0x50, false, 1, &[0xff; 5]), 0)
8828				.unwrap();
8829			assert!(
8830				!import.pending.contains_key(&pid),
8831				"orphan bytes cannot complete the lost header"
8832			);
8833		}
8834	}
8835
8836	/// Reading a file faster than real time must not choose wraps from the host clock.
8837	#[tokio::test(start_paused = true)]
8838	async fn a_fast_import_follows_pts_history_past_half_a_wrap() {
8839		let (_, catalog, mut import) = two_stream_import();
8840		for i in 0..64 {
8841			let pts = i * 900 * 90_000;
8842			import
8843				.decode(&mp2_pes(PCR_PID, i as u8, pts % (1 << 33), [1, 2]))
8844				.unwrap();
8845		}
8846		let _finished = import.finish().unwrap();
8847		assert!(!catalog.snapshot().audio.renditions.is_empty());
8848	}
8849
8850	/// A flagged jump that carries the source forward across a wrap continues its timeline: the
8851	/// PTS before the break, not the raw value after it, picks the wrap.
8852	#[tokio::test(start_paused = true)]
8853	async fn a_flagged_jump_across_a_wrap_carries_on() {
8854		let mut broadcast = moq_net::broadcast::Info::new().produce();
8855		let consumer = broadcast.consume();
8856		// Retained for a day, so a subscribe reaches every frame on both sides of the jump.
8857		let config = crate::catalog::Config::default().with_max_age(Duration::from_secs(86_400));
8858		let catalog = crate::catalog::Producer::new(&mut broadcast, config).unwrap();
8859		let mut import = super::Import::new(broadcast, catalog.reserve());
8860		let pmt = synth_pmt(
8861			&[(StreamType::Mpeg1Audio, PCR_PID), (StreamType::Mpeg1Audio, PEER_PID)],
8862			false,
8863		);
8864		import.decode(&bytes::BytesMut::from(&pmt[..])).unwrap();
8865		// Five minutes short of the wrap, then ten minutes on.
8866		let first = WRAP - 300 * 90_000;
8867		let jump = 600 * 90_000;
8868		for i in 0..20 {
8869			let mut data = Vec::new();
8870			if i == 10 {
8871				data.extend(clock_break_packet(PCR_PID));
8872			}
8873			let pts = first + i * STEP + if i >= 10 { jump } else { 0 };
8874			data.extend(source_pes(i, pts % WRAP));
8875			import.decode(&data).unwrap();
8876			tokio::time::advance(Duration::from_millis(144)).await;
8877		}
8878		let _finished = import.finish().unwrap();
8879		let all = timeline(&consumer, &catalog).await;
8880		let step = all[&21] - all[&19];
8881		assert!(
8882			(600_143_999..=600_144_001).contains(&step),
8883			"the jump adds its step: {step} us"
8884		);
8885	}
8886
8887	/// An import started just past a wrap, with the peer still before it, steps the peer back into
8888	/// the wrap before rather than a whole wrap ahead, and its PES before the clock's zero are dropped.
8889	#[tokio::test(start_paused = true)]
8890	async fn a_stream_behind_the_first_wrap_steps_back() {
8891		let (consumer, catalog, mut import) = two_stream_import();
8892		for i in 0..10 {
8893			import.decode(&source_pes(i, 4_000 + i * STEP)).unwrap();
8894			tokio::time::advance(Duration::from_millis(144)).await;
8895		}
8896		import.finish_in_place().unwrap();
8897		assert_eq!(import.stats().streams[&PEER_PID].unplaced, 1);
8898		let all = timeline(&consumer, &catalog).await;
8899		assert!(!all.contains_key(&0x80), "the peer's PES before the wrap is dropped");
8900		// The peer keeps its place, 8,000 ticks behind the PCR PID.
8901		assert_eq!(all[&0x82], (4_000 + STEP - 8_000) as i64 * 1_000_000 / 90_000);
8902		assert!(
8903			all.values().all(|&us| us < 2_000_000),
8904			"the timeline stays at the import's start: {all:?}"
8905		);
8906	}
8907
8908	/// One step of the two-stream source: a PES on each stream, 144 ms of MP2.
8909	const STEP: u64 = 12_960;
8910	/// The 33-bit PTS field's period.
8911	const WRAP: u64 = 1 << 33;
8912
8913	/// Step `i` of the two-stream source whose PCR PID presents at `pts`. The peer presents 8,000 ticks
8914	/// earlier, so near a wrap the two streams sit either side of it. Every frame has its own fill.
8915	fn source_pes(i: u64, pts: u64) -> Vec<u8> {
8916		let n = i as u8;
8917		let mut data = mp2_pes(PCR_PID, n, pts, [2 * n + 1, 2 * n + 2]);
8918		data.extend(mp2_pes(
8919			PEER_PID,
8920			n,
8921			(pts + WRAP - 8_000) % WRAP,
8922			[0x80 + 2 * n, 0x81 + 2 * n],
8923		));
8924		data
8925	}
8926
8927	/// Every frame `catalog`'s renditions published, by fill, at its timestamp in microseconds.
8928	async fn timeline(
8929		consumer: &moq_net::broadcast::Consumer,
8930		catalog: &crate::catalog::Producer,
8931	) -> BTreeMap<u8, i64> {
8932		let mut frames = BTreeMap::new();
8933		for name in catalog.snapshot().audio.renditions.keys() {
8934			for frame in read_track(consumer, name, crate::container::Kind::Audio).await {
8935				frames.insert(frame.payload[4], frame.timestamp.as_micros().unwrap() as i64);
8936			}
8937		}
8938		frames
8939	}
8940
8941	#[test]
8942	fn pes_header_duplicate_and_discontinuity_follow_the_packet_chain() {
8943		let pid = Pid::new(0x50).unwrap();
8944		let mut header = vec![0, 0, 1, 0xe0, 0, 0, 0x80, 0x80, 5];
8945		header.extend_from_slice(&pes_timestamp(2, 90_000));
8946		header.extend_from_slice(&[0xde, 0xad]);
8947		for damage in ["duplicate", "loss", "discontinuity"] {
8948			let mut import = ignored_pes_import();
8949			import.streams.remove(&pid);
8950			import.ensure_stream(pid, StreamType::AdtsAac as u8, &[]).unwrap();
8951			let first = pes_fragment(0x50, true, 0, &header[..7]);
8952			import.decode(&first).unwrap();
8953			if damage == "duplicate" {
8954				import.decode(&first).unwrap();
8955			}
8956			let mut next = pes_fragment(0x50, false, if damage == "loss" { 2 } else { 1 }, &header[7..]);
8957			if damage == "discontinuity" {
8958				next[5] = 0x80;
8959			}
8960			import.decode(&next).unwrap();
8961			if damage == "duplicate" {
8962				let super::Stream::Aac(stream) = &import.streams[&pid] else {
8963					panic!("an AAC stream");
8964				};
8965				assert_eq!(stream.tail_pts, Some(Timestamp::from_scale(90_000, 90_000).unwrap()));
8966				assert_eq!(stream.tail, [0xde, 0xad]);
8967			} else {
8968				assert!(!import.pending.contains_key(&pid));
8969			}
8970		}
8971	}
8972
8973	#[test]
8974	fn pes_special_stream_ids_assemble_without_optional_fields() {
8975		let pid = Pid::new(0x50).unwrap();
8976		for id in [0xbc, 0xbe, 0xbf, 0xf0, 0xf1, 0xf2, 0xf8, 0xff] {
8977			for split in 1..6 {
8978				let mut import = ignored_pes_import();
8979				let header = [0, 0, 1, id, 0, 3];
8980				import
8981					.pes_packet(pid, &pes_fragment(0x50, true, 0, &header[..split]), 0)
8982					.unwrap();
8983				import
8984					.pes_packet(pid, &pes_fragment(0x50, false, 1, &header[split..]), 0)
8985					.unwrap();
8986				assert_eq!(import.pending[&pid].data_len, Some(3));
8987				assert_eq!(import.pending[&pid].pts, None);
8988			}
8989		}
8990		assert_eq!(
8991			super::PesStart::parse(&[0, 0, 1, 0xbe, 0, 0]).unwrap().data_len,
8992			Some(0)
8993		);
8994	}
8995
8996	#[test]
8997	fn malformed_pes_prefix_ends_the_import_without_waiting_for_more_bytes() {
8998		let pid = Pid::new(0x50).unwrap();
8999		for bad in [&[1][..], &[0, 1][..], &[0, 0, 2][..]] {
9000			let mut import = ignored_pes_import();
9001			let err = import
9002				.pes_packet(pid, &pes_fragment(0x50, true, 0, bad), 0)
9003				.expect_err("a malformed prefix");
9004			assert!(err.to_string().contains("start code prefix"), "{err}");
9005			assert!(import.headers.is_empty());
9006		}
9007	}
9008
9009	#[test]
9010	fn pes_length_overruns_fail_before_waiting_for_the_optional_header() {
9011		let pid = Pid::new(0x50).unwrap();
9012		let mut import = ignored_pes_import();
9013		let err = import
9014			.pes_packet(
9015				pid,
9016				&pes_fragment(0x50, true, 0, &[0, 0, 1, 0xe0, 0, 4, 0x80, 0x80, 255]),
9017				0,
9018			)
9019			.expect_err("a PES length shorter than its header");
9020		assert!(err.to_string().contains("shorter than its header"), "{err}");
9021		assert!(import.headers.is_empty());
9022	}
9023
9024	#[tokio::test(start_paused = true)]
9025	async fn a_short_declared_video_pes_is_refused_at_eof_or_the_next_start() {
9026		let pid = Pid::new(0x50).unwrap();
9027		for end in ["eof", "start"] {
9028			let mut broadcast = moq_net::broadcast::Info::new().produce();
9029			let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9030			let mut import = super::Import::new(broadcast, catalog.reserve());
9031			import.ensure_stream(pid, StreamType::H264 as u8, &[]).unwrap();
9032			let data = annexb_au(true);
9033			let len = 8 + data.len() + 1;
9034			let mut pes = vec![0, 0, 1, 0xe0, (len >> 8) as u8, len as u8, 0x80, 0x80, 5];
9035			pes.extend_from_slice(&pes_timestamp(2, 90_000));
9036			pes.extend_from_slice(&data);
9037			for (cc, chunk) in pes.chunks(183).enumerate() {
9038				import
9039					.pes_packet(pid, &pes_fragment(0x50, cc == 0, cc as u8, chunk), 0)
9040					.unwrap();
9041			}
9042			if end == "eof" {
9043				import.finish_in_place().unwrap();
9044			} else {
9045				let mut header = vec![0, 0, 1, 0xe0, 0, 0, 0x80, 0x80, 5];
9046				header.extend_from_slice(&pes_timestamp(2, 180_000));
9047				import
9048					.pes_packet(pid, &pes_fragment(0x50, true, 1, &header), 0)
9049					.unwrap();
9050			}
9051			assert_eq!(
9052				import.stats().streams[&0x50].units,
9053				0,
9054				"a missing byte invalidates the declared access unit at {end}"
9055			);
9056			assert_eq!(import.stats().streams[&0x50].damaged, 1);
9057		}
9058	}
9059
9060	#[test]
9061	fn pes_retention_budget_is_shared_and_released_on_damage() {
9062		let mut import = ignored_pes_import();
9063		let first = Pid::new(0x50).unwrap();
9064		let second = Pid::new(0x51).unwrap();
9065		for pid in [first, second] {
9066			import
9067				.pes_packet(
9068					pid,
9069					&pes_fragment(pid.as_u16(), true, 0, &[0, 0, 1, 0xe0, 0, 0, 0x80, 0, 0]),
9070					0,
9071				)
9072				.unwrap();
9073			import
9074				.handle_pes_continuation(pid, &vec![0; super::STAGING_BYTES_MAX / 2])
9075				.unwrap();
9076		}
9077		assert_eq!(
9078			import.staging.bytes.load(super::Ordering::Relaxed),
9079			super::STAGING_BYTES_MAX
9080		);
9081		assert!(matches!(
9082			import.handle_pes_continuation(first, &[1]),
9083			Err(super::Error::Malformed(msg)) if msg.contains("staging exceeds")
9084		));
9085		assert_eq!(import.pending[&first].data.len(), super::STAGING_BYTES_MAX / 2);
9086		import.damage(first, &super::Error::Malformed("loss".into())).unwrap();
9087		assert_eq!(
9088			import.staging.bytes.load(super::Ordering::Relaxed),
9089			super::STAGING_BYTES_MAX / 2
9090		);
9091		import.handle_pes_continuation(second, &[1]).unwrap();
9092		drop(import.pending.remove(&second));
9093		assert_eq!(import.staging.bytes.load(super::Ordering::Relaxed), 0);
9094	}
9095
9096	#[test]
9097	fn untimed_sections_stop_at_the_shared_budget_and_release_after_a_clock() {
9098		use crate::catalog::hang::Catalog;
9099		use crate::container::ts::catalog::Ext;
9100		let mut broadcast = moq_net::broadcast::Info::new().produce();
9101		let catalog = crate::catalog::Producer::new(
9102			&mut broadcast,
9103			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
9104		)
9105		.unwrap();
9106		let mut import = super::Import::new(broadcast, catalog.reserve());
9107		import
9108			.decode(&synth_pmt(
9109				&[
9110					(StreamType::AdtsAac, 0x50),
9111					(StreamType::Dts8ChannelLosslessAudio, 0x21),
9112				],
9113				true,
9114			))
9115			.unwrap();
9116		import.decode(&pcr_packet(0x50, 27_000_000)).unwrap();
9117		for i in 0..super::STAGING_UNITS_MAX {
9118			import.decode(&packet(true, (i % 16) as u8, 0, &CUE)).unwrap();
9119		}
9120		let err = import
9121			.decode(&packet(true, (super::STAGING_UNITS_MAX % 16) as u8, 0, &CUE))
9122			.unwrap_err();
9123		assert!(err.to_string().contains(&format!(
9124			"TS staging exceeds {} buffered units",
9125			super::STAGING_UNITS_MAX
9126		)));
9127		assert_eq!(import.sections[&0x21].held.len(), super::STAGING_UNITS_MAX);
9128		assert_eq!(
9129			import.staging.bytes.load(super::Ordering::Relaxed),
9130			CUE.len() * super::STAGING_UNITS_MAX
9131		);
9132		import.decode(&pes_packet(0x50, 90_000)).unwrap();
9133		import.decode(&pcr_packet(0x50, 29_700_000)).unwrap();
9134		assert!(import.sections[&0x21].held.is_empty());
9135		assert_eq!(import.staging.bytes.load(super::Ordering::Relaxed), 0);
9136		assert_eq!(import.staging.units.load(super::Ordering::Relaxed), 0);
9137	}
9138
9139	#[test]
9140	fn section_retention_budget_counts_units_and_rolls_back_failed_reservations() {
9141		let staging = std::sync::Arc::<super::Staging>::default();
9142		let mut held = super::Retained::new(staging.clone());
9143		held.grow(10, super::STAGING_UNITS_MAX).unwrap();
9144		assert!(held.grow(100, 1).is_err());
9145		assert_eq!(staging.bytes.load(super::Ordering::Relaxed), 10);
9146		assert_eq!(staging.units.load(super::Ordering::Relaxed), super::STAGING_UNITS_MAX);
9147		held.clear();
9148		assert_eq!(staging.bytes.load(super::Ordering::Relaxed), 0);
9149		assert_eq!(staging.units.load(super::Ordering::Relaxed), 0);
9150	}
9151
9152	#[test]
9153	#[ignore = "benchmark"]
9154	#[expect(
9155		clippy::disallowed_methods,
9156		clippy::disallowed_types,
9157		reason = "the benchmark measures host CPU time"
9158	)]
9159	fn benchmark_pes_staging() {
9160		println!("pids,payload_bytes,fragmented,ns_per_pes");
9161		for pids in [1u16, 8, 64] {
9162			for size in [184, 16 * 1024, 256 * 1024] {
9163				for fragmented in [false, true] {
9164					let mut import = ignored_pes_import();
9165					for raw in 0x50..0x50 + pids {
9166						import.streams.insert(Pid::new(raw).unwrap(), super::Stream::Ignored);
9167					}
9168					let data = vec![0xaa; size];
9169					let header = [0, 0, 1, 0xe0, 0, 0, 0x80, 0, 0];
9170					let start = std::time::Instant::now();
9171					for _ in 0..16 {
9172						for raw in 0x50..0x50 + pids {
9173							let pid = Pid::new(raw).unwrap();
9174							if fragmented {
9175								import
9176									.pes_packet(pid, &pes_fragment(raw, true, 0, &header[..1]), 0)
9177									.unwrap();
9178								import
9179									.pes_packet(pid, &pes_fragment(raw, false, 1, &header[1..]), 0)
9180									.unwrap();
9181							} else {
9182								import.pes_packet(pid, &pes_fragment(raw, true, 0, &header), 0).unwrap();
9183							}
9184							for chunk in data.chunks(184) {
9185								import
9186									.handle_pes_continuation(pid, std::hint::black_box(chunk))
9187									.unwrap();
9188							}
9189							import.flush(pid).unwrap();
9190						}
9191					}
9192					println!(
9193						"{pids},{size},{fragmented},{}",
9194						start.elapsed().as_nanos() / (16 * u128::from(pids))
9195					);
9196					assert_eq!(import.staging.bytes.load(super::Ordering::Relaxed), 0);
9197				}
9198			}
9199		}
9200	}
9201
9202	/// A stream a PMT revision adds after the program's clock wrapped takes the clock's era, not
9203	/// the era its first value would start alone.
9204	#[tokio::test(start_paused = true)]
9205	async fn a_stream_added_after_a_wrap_joins_the_wrap_the_clock_is_in() {
9206		let mut broadcast = moq_net::broadcast::Info::new().produce();
9207		let consumer = broadcast.consume();
9208		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9209		let mut import = super::Import::new(broadcast, catalog.reserve());
9210		let (mut pat_cc, mut pmt_cc) = (0, 0);
9211		let mut data = psi_packets(0, &mut pat_cc, &[], &pat_section(&[(1, 0x0100)]));
9212		data.extend(psi_packets(
9213			0x0100,
9214			&mut pmt_cc,
9215			&[],
9216			&pmt_section(1, 0, &[(MP2, PCR_PID, &[])]),
9217		));
9218		import.decode(&data).unwrap();
9219
9220		let first = WRAP - 10 * STEP;
9221		for i in 0..20 {
9222			if i == 15 {
9223				let both = [(MP2, PCR_PID, &[][..]), (MP2, PEER_PID, &[][..])];
9224				let revision = psi_packets(0x0100, &mut pmt_cc, &[], &pmt_section(1, 1, &both));
9225				import.decode(&revision).unwrap();
9226			}
9227			let mut data = source_pes(i, (first + i * STEP) % WRAP);
9228			if i < 15 {
9229				data.truncate(188);
9230			}
9231			import.decode(&data).unwrap();
9232			tokio::time::advance(Duration::from_millis(144)).await;
9233		}
9234		let _finished = import.finish().unwrap();
9235
9236		let frames = timeline(&consumer, &catalog).await;
9237		let apart = frames[&31] - frames[&0x9e];
9238		assert!(
9239			(88_888..=88_889).contains(&apart),
9240			"the step's frames sit {apart} µs apart"
9241		);
9242	}
9243
9244	/// A 5-byte PES timestamp field with the 4-bit `prefix` (0b0010 PTS only, 0b0011 PTS of a
9245	/// pair, 0b0001 DTS).
9246	fn pes_timestamp(prefix: u8, t: u64) -> [u8; 5] {
9247		[
9248			(prefix << 4) | (((t >> 30) & 0x07) << 1) as u8 | 0x01,
9249			((t >> 22) & 0xff) as u8,
9250			0x01 | (((t >> 15) & 0x7f) << 1) as u8,
9251			((t >> 7) & 0xff) as u8,
9252			0x01 | ((t & 0x7f) << 1) as u8,
9253		]
9254	}
9255
9256	/// A PUSI TS packet on `pid` carrying one bounded video PES (stream_id 0xE0) with `pts`
9257	/// and, when it differs, `dts`, sized to complete on this packet.
9258	pub(in crate::container::ts) fn video_pes(pid: u16, cc: u8, pts: u64, dts: Option<u64>, payload: &[u8]) -> Vec<u8> {
9259		let mut header = Vec::new();
9260		match dts {
9261			Some(dts) => {
9262				header.extend_from_slice(&[0x80, 0xC0, 10]);
9263				header.extend_from_slice(&pes_timestamp(0b0011, pts));
9264				header.extend_from_slice(&pes_timestamp(0b0001, dts));
9265			}
9266			None => {
9267				header.extend_from_slice(&[0x80, 0x80, 5]);
9268				header.extend_from_slice(&pes_timestamp(0b0010, pts));
9269			}
9270		}
9271		let mut pes = vec![0x00, 0x00, 0x01, 0xe0];
9272		let pes_len = header.len() + payload.len();
9273		pes.push((pes_len >> 8) as u8);
9274		pes.push((pes_len & 0xff) as u8);
9275		pes.extend_from_slice(&header);
9276		pes.extend_from_slice(payload);
9277
9278		let af_len = 184 - 1 - pes.len();
9279		let mut p = vec![
9280			0x47,
9281			0x40 | ((pid >> 8) as u8 & 0x1f),
9282			(pid & 0xff) as u8,
9283			0x30 | (cc & 0x0f),
9284		];
9285		p.push(af_len as u8);
9286		if af_len > 0 {
9287			p.push(0x00);
9288			p.extend(std::iter::repeat_n(0xff, af_len - 1));
9289		}
9290		p.extend_from_slice(&pes);
9291		assert_eq!(p.len(), 188, "video PES packet must fill exactly one TS packet");
9292		p
9293	}
9294
9295	/// One 30 fps frame in 90 kHz ticks.
9296	const FRAME: u64 = 3_000;
9297
9298	/// Appends TS packets to `out`, counting the continuity counter per PID.
9299	#[derive(Default)]
9300	struct Mux {
9301		out: Vec<u8>,
9302		cc: std::collections::HashMap<u16, u8>,
9303	}
9304
9305	impl Mux {
9306		fn cc(&mut self, pid: u16) -> u8 {
9307			let cc = self.cc.entry(pid).or_default();
9308			let current = *cc;
9309			*cc = (*cc + 1) & 0x0f;
9310			current
9311		}
9312
9313		/// One four-frame closed GOP in decode order, I P B B, presenting `base + FRAME` to
9314		/// `base + 4 * FRAME`: the reference frames carry a DTS, the B-frames present as they
9315		/// decode.
9316		fn gop(&mut self, pid: u16, base: u64) {
9317			let frames = [
9318				(true, base + FRAME, Some(base)),
9319				(false, base + 4 * FRAME, Some(base + FRAME)),
9320				(false, base + 2 * FRAME, None),
9321				(false, base + 3 * FRAME, None),
9322			];
9323			for (keyframe, pts, dts) in frames {
9324				let cc = self.cc(pid);
9325				self.out
9326					.extend_from_slice(&video_pes(pid, cc, pts, dts, &annexb_au(keyframe)));
9327			}
9328		}
9329
9330		/// `count` GOPs back to back from `base`.
9331		fn gops(&mut self, pid: u16, base: u64, count: u64) {
9332			for i in 0..count {
9333				self.gop(pid, base + i * 4 * FRAME);
9334			}
9335		}
9336	}
9337
9338	/// Read every retained frame of `name` as `kind`, skipping the empty break markers.
9339	async fn read_track(
9340		consumer: &moq_net::broadcast::Consumer,
9341		name: &str,
9342		kind: crate::container::Kind,
9343	) -> Vec<crate::container::Frame> {
9344		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
9345			moq_net::track::Start::Live {
9346				min: Some(Duration::from_secs(3600)),
9347				max: Some(Duration::from_secs(3600)),
9348			},
9349		)]);
9350		let track = consumer.track(name).unwrap().subscribe(subscription).await.unwrap();
9351		let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Wire::legacy(kind));
9352		let mut frames = Vec::new();
9353		while let Ok(Ok(Some(frame))) = kio::clock::timeout(Duration::from_millis(50), reader.read_frame()).await {
9354			if !frame.payload.is_empty() {
9355				frames.push(frame);
9356			}
9357		}
9358		frames
9359	}
9360
9361	/// Import `data` with an `mpegts` catalog, failing on any import error. The importer is
9362	/// returned to keep its renditions in the catalog.
9363	fn import_all(
9364		data: &[u8],
9365	) -> super::Result<(
9366		moq_net::broadcast::Consumer,
9367		crate::catalog::Producer<Ext>,
9368		super::Import<Ext>,
9369	)> {
9370		let (consumer, catalog, mut import) = import_new();
9371		import.decode(data)?;
9372		import.finish_in_place()?;
9373		Ok((consumer, catalog, import))
9374	}
9375
9376	/// Import `data`, which must restart.
9377	fn import_restart(data: &[u8]) -> crate::container::ts::Restart {
9378		let (_consumer, _catalog, mut import) = import_new();
9379		import
9380			.decode_or_restart(data)
9381			.unwrap()
9382			.expect("the import carried on past a restart")
9383	}
9384
9385	/// An importer onto a fresh broadcast with an `mpegts` catalog.
9386	fn import_new() -> (
9387		moq_net::broadcast::Consumer,
9388		crate::catalog::Producer<Ext>,
9389		super::Import<Ext>,
9390	) {
9391		let mut broadcast = moq_net::broadcast::Info::new().produce();
9392		let consumer = broadcast.consume();
9393		let catalog = crate::catalog::Producer::new(
9394			&mut broadcast,
9395			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
9396		)
9397		.unwrap();
9398		let import = super::Import::new(broadcast, catalog.reserve());
9399		(consumer, catalog, import)
9400	}
9401
9402	use crate::container::ts::catalog::Ext;
9403
9404	/// Whether `err` is a refused timestamp rewind: the source restarted, which is a new
9405	/// broadcast rather than a continuation.
9406	fn is_rewind(err: &super::Error) -> bool {
9407		matches!(err, super::Error::Mux(err) if matches!(**err, crate::Error::TimestampRewind(_)))
9408	}
9409
9410	/// Import `data`, which must end in a refused rewind.
9411	fn import_refused(data: &[u8]) {
9412		let Err(err) = import_all(data) else {
9413			panic!("the import accepted a rewind");
9414		};
9415		assert!(is_rewind(&err), "{err:?}");
9416	}
9417
9418	/// Every frame of a group presents after every frame of the groups before it, which is what
9419	/// the producer demands. Frames within a group may still reorder (B-frames, a join that
9420	/// continues the group).
9421	fn assert_forward(frames: &[crate::container::Frame]) {
9422		let (mut ceiling, mut newest) = (None, None);
9423		for frame in frames {
9424			let ts = frame.timestamp.as_micros().unwrap();
9425			if frame.keyframe {
9426				ceiling = newest;
9427			}
9428			assert!(
9429				ceiling.is_none_or(|ceiling| ts > ceiling),
9430				"{ts} presents at or before {ceiling:?}, an earlier group's newest frame"
9431			);
9432			newest = newest.max(Some(ts));
9433		}
9434	}
9435
9436	async fn video_frames(data: &[u8]) -> Vec<crate::container::Frame> {
9437		let (consumer, catalog, _import) = import_all(data).expect("the import must survive the step back");
9438		let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone();
9439		read_track(&consumer, &name, crate::container::Kind::Video).await
9440	}
9441
9442	const VIDEO: u16 = 0x0050;
9443
9444	#[tokio::test(start_paused = true)]
9445	async fn video_pes_continuation_keeps_the_access_unit_timestamp() {
9446		let au = annexb_au(true);
9447		// Split inside the IDR, so neither PES is an independently decodable picture.
9448		let cut = au.len() - 2;
9449		let mut data = synth_pmt(&[(StreamType::H264, VIDEO)], false);
9450		data.extend(video_pes(VIDEO, 0, FRAME, None, &au[..cut]));
9451		data.extend(video_pes(VIDEO, 1, FRAME * 9, None, &au[cut..]));
9452		let frames = video_frames(&data).await;
9453		assert_eq!(frames.len(), 1);
9454		assert_eq!(frames[0].payload.as_ref(), au);
9455		assert_eq!(
9456			frames[0].timestamp.as_micros().unwrap(),
9457			u128::from(FRAME) * 1_000_000 / 90_000
9458		);
9459	}
9460
9461	#[test]
9462	fn video_pes_does_not_reuse_its_pts_for_an_untimestampable_successor() {
9463		let mut payload = annexb_au(true);
9464		payload.extend(annexb_au(false));
9465		let mut data = synth_pmt(&[(StreamType::H264, VIDEO)], false);
9466		data.extend(video_pes(VIDEO, 0, FRAME, None, &payload));
9467		let err = match import_all(&data) {
9468			Ok(_) => panic!("a second AU cannot reuse the first AU's PES PTS"),
9469			Err(err) => err,
9470		};
9471		assert!(
9472			matches!(&err, super::Error::Malformed(msg) if msg.contains("timestamp")),
9473			"timing refusal must end the import: {err}"
9474		);
9475	}
9476
9477	/// Repacketize actual encoder-produced POCs, retaining an independent PTS
9478	/// oracle from its original TS rather than deriving the expected values.
9479	#[tokio::test(start_paused = true)]
9480	async fn video_poc_repartition_preserves_frames_timestamps_and_export() {
9481		use crate::container::ts::fixture;
9482		use mpeg2ts::pes::{PesPacketReader, ReadPesPacket};
9483		use mpeg2ts::ts::TsPacketReader;
9484		use std::io::Cursor;
9485		for (kind, fixture) in [
9486			(StreamType::H264, &include_bytes!("test_data/poc-avc.ts")[..]),
9487			(StreamType::H265, &include_bytes!("test_data/poc-hevc.ts")[..]),
9488		] {
9489			let mut reader = PesPacketReader::new(TsPacketReader::new(Cursor::new(fixture)));
9490			let mut pictures = Vec::new();
9491			while let Some(pes) = reader.read_pes_packet().unwrap() {
9492				pictures.push((pes.header.pts.unwrap().as_u64(), pes.data));
9493			}
9494			assert_eq!(pictures.len(), 12);
9495			let mut baseline = None;
9496			for layout in ["single", "combined", "split", "no-clock"] {
9497				if layout == "no-clock" && kind != StreamType::H264 {
9498					continue;
9499				}
9500				let mut mux = fixture::Mux::default();
9501				mux.pat(&[(1, 0x1000)]);
9502				// fixed_frame_rate_flag + temporal_poc_flag. The AVC VUI alone
9503				// deliberately does not authorize multiplying POC by a clock tick.
9504				let descriptor = if kind == StreamType::H264 && layout != "no-clock" {
9505					&[0x2a, 2, 0x7e, 0xdf][..]
9506				} else {
9507					&[]
9508				};
9509				mux.pmt_with(0x1000, 1, VIDEO, &[(kind as u8, VIDEO, descriptor)], 0);
9510				let push = |mux: &mut fixture::Mux, pts: Option<u64>, payload: &[u8]| {
9511					let header_len = if pts.is_some() { 8 } else { 3 };
9512					let len = header_len + payload.len();
9513					let mut pes = vec![
9514						0,
9515						0,
9516						1,
9517						0xe0,
9518						(len >> 8) as u8,
9519						len as u8,
9520						0x80,
9521						if pts.is_some() { 0x80 } else { 0 },
9522						if pts.is_some() { 5 } else { 0 },
9523					];
9524					if let Some(pts) = pts {
9525						pes.extend(pes_timestamp(2, pts));
9526					}
9527					pes.extend(payload);
9528					mux.whole(VIDEO, &pes);
9529				};
9530				match layout {
9531					"single" => {
9532						for (pts, data) in &pictures {
9533							push(&mut mux, Some(*pts), data);
9534						}
9535					}
9536					"combined" | "no-clock" => {
9537						for chunk in pictures.chunks(4) {
9538							let data: Vec<u8> = chunk.iter().flat_map(|(_, data)| data.iter().copied()).collect();
9539							push(&mut mux, Some(chunk[0].0), &data);
9540						}
9541					}
9542					"split" => {
9543						for (pts, data) in &pictures {
9544							// All three required prefix bytes and the final slice body
9545							// are exercised on opposite sides of a PES boundary.
9546							for (n, chunk) in data.chunks(2).enumerate() {
9547								push(&mut mux, if n == 0 { Some(*pts) } else { None }, chunk);
9548							}
9549						}
9550					}
9551					_ => unreachable!(),
9552				}
9553				if layout == "no-clock" {
9554					// Valid AVC with fixed-rate SPS VUI still needs the TS
9555					// temporal-POC promise before numeric POC can mean time.
9556					let err = match import_all(&mux.out) {
9557						Ok(_) => panic!("SPS fixed frame rate alone cannot timestamp a later AU"),
9558						Err(err) => err,
9559					};
9560					assert!(
9561						matches!(&err, super::Error::Malformed(msg) if msg.contains("proportional")),
9562						"{err}"
9563					);
9564					continue;
9565				}
9566				let (consumer, catalog, _import) =
9567					import_all(&mux.out).unwrap_or_else(|err| panic!("{kind:?} {layout}: {err:#}"));
9568				let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone();
9569				let frames = read_track(&consumer, &name, crate::container::Kind::Video).await;
9570				let observed: Vec<_> = frames
9571					.iter()
9572					.map(|f| (f.timestamp.as_micros().unwrap(), f.keyframe, f.payload.clone()))
9573					.collect();
9574				assert_eq!(frames.len(), pictures.len(), "{kind:?} {layout}");
9575				assert_eq!(
9576					frames
9577						.iter()
9578						.map(|f| f.timestamp.as_micros().unwrap())
9579						.collect::<Vec<_>>(),
9580					pictures
9581						.iter()
9582						.map(|(pts, _)| u128::from(*pts) * 1_000_000 / 90_000)
9583						.collect::<Vec<_>>(),
9584					"{kind:?} {layout}"
9585				);
9586				match &baseline {
9587					None => baseline = Some(observed.clone()),
9588					Some(expected) => assert_eq!(&observed, expected, "{kind:?} {layout}"),
9589				}
9590				let mut export = crate::container::ts::export_test::open_export(
9591					crate::source::announced(&consumer).await,
9592					Duration::from_secs(30),
9593				)
9594				.await
9595				.unwrap()
9596				.with_replay();
9597				let mut ts = Vec::new();
9598				while let Ok(frame) = kio::clock::timeout(Duration::from_secs(100), export.next()).await {
9599					let Some(frame) = frame.unwrap() else {
9600						break;
9601					};
9602					ts.extend(frame.payload);
9603				}
9604				let roundtrip = video_frames(&ts).await;
9605				assert_eq!(
9606					roundtrip
9607						.iter()
9608						.map(|f| (f.timestamp.as_micros().unwrap(), f.keyframe, f.payload.clone()))
9609						.collect::<Vec<_>>(),
9610					observed,
9611					"export {kind:?} {layout}"
9612				);
9613			}
9614		}
9615	}
9616
9617	/// A PMT listing one PID twice routes it by the later entry, as a newer PMT would.
9618	#[tokio::test(start_paused = true)]
9619	async fn a_pmt_listing_a_pid_twice_routes_by_the_last_entry() {
9620		use crate::container::test_util::{IDR, PPS, SPS};
9621		let mut payload = Vec::new();
9622		for nal in [SPS, PPS, IDR] {
9623			payload.extend([0, 0, 0, 1]);
9624			payload.extend(nal);
9625		}
9626		let mut data = synth_pmt(&[(StreamType::AdtsAac, VIDEO), (StreamType::H264, VIDEO)], false);
9627		data.extend(video_pes(VIDEO, 0, 90_000, None, &payload));
9628		let (consumer, catalog, _import) = import_all(&data).unwrap();
9629		let snapshot = catalog.snapshot();
9630		assert!(snapshot.audio.renditions.is_empty());
9631		let name = snapshot.video.renditions.keys().next().unwrap().clone();
9632		assert_eq!(
9633			read_track(&consumer, &name, crate::container::Kind::Video).await.len(),
9634			1
9635		);
9636	}
9637
9638	/// The fault `damage` names hits one packet of a later video PES on one PID while another PID
9639	/// carries on, returning the mux and the offsets of the damaged packet and of the GOP after.
9640	fn damaged_video(damage: &str) -> (Mux, usize, usize) {
9641		let peer = VIDEO + 1;
9642		let mut mux = Mux {
9643			out: synth_pmt(&[(StreamType::H264, VIDEO), (StreamType::H264, peer)], false),
9644			..Default::default()
9645		};
9646		mux.gop(VIDEO, 90_000);
9647		if damage != "clean" {
9648			// These faults hide the next PES entirely. An AUD received ahead of
9649			// the fault proves the preceding picture complete; the AUD's own
9650			// picture remains unconfirmed and is discarded at the loss.
9651			let mut au = annexb_au(false);
9652			au.extend([0, 0, 1, 9, 0xf0]);
9653			let last = mux.out.len() - 188;
9654			mux.out[last..].copy_from_slice(&video_pes(VIDEO, 3, 90_000 + 3 * FRAME, None, &au));
9655		}
9656		mux.gop(peer, 90_000);
9657		let damaged_at = mux.out.len();
9658		mux.gop(VIDEO, 90_000 + 4 * FRAME);
9659		mux.gop(peer, 90_000 + 4 * FRAME);
9660		let packet = &mut mux.out[damaged_at..damaged_at + TsPacket::SIZE];
9661		let payload_at = 5 + usize::from(packet[4]);
9662		match damage {
9663			"pes" => packet[payload_at + 6..payload_at + 19].fill(0),
9664			"adaptation" => packet[4] = 255,
9665			"adaptation-clock" => {
9666				packet[4] = 1;
9667				packet[5] = 0x90;
9668			}
9669			"tei" => packet[1] |= 0x80,
9670			// PES_scrambling_control, as conditional access sets it.
9671			"scrambled" => packet[payload_at + 6] |= 0x10,
9672			"clean" => {}
9673			_ => unreachable!(),
9674		}
9675		assert_eq!(
9676			packet[1] & 0x80 != 0,
9677			damage == "tei",
9678			"only flagged corruption sets TEI"
9679		);
9680		let resume_at = mux.out.len();
9681		mux.gop(VIDEO, 90_000 + 8 * FRAME);
9682		mux.gop(peer, 90_000 + 8 * FRAME);
9683		(mux, damaged_at, resume_at)
9684	}
9685
9686	/// A packet the receiver flagged corrupt (`tei`) loses its unit and the dependent pictures
9687	/// while another PID carries on, and so does a PES conditional access scrambled
9688	/// (`scrambled`), refused rather than damaged. A later decode call resumes from the next
9689	/// keyframe.
9690	async fn damaged_video_recovers(damage: &str) {
9691		let peer = VIDEO + 1;
9692		let (mux, _, resume_at) = damaged_video(damage);
9693		let mut broadcast = moq_net::broadcast::Info::new().produce();
9694		let consumer = broadcast.consume();
9695		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9696		let mut import = super::Import::new(broadcast, catalog.reserve());
9697		import
9698			.decode(&mux.out[..resume_at])
9699			.expect("damage must stay local to the unit");
9700		assert_eq!(import.demux.held(), 0, "every damaged packet must be consumed");
9701		assert!(
9702			!import.pending.contains_key(&Pid::new(VIDEO).unwrap()),
9703			"no damaged PES remains"
9704		);
9705		import
9706			.decode(&mux.out[resume_at..])
9707			.expect("next keyframe must recover");
9708		import.finish_in_place().unwrap();
9709		let row = &import.stats().streams[&VIDEO];
9710		assert_eq!(
9711			(row.damaged, row.refused),
9712			(u64::from(damage == "tei"), u64::from(damage == "scrambled"))
9713		);
9714		assert_eq!(import.stats().streams[&peer].damaged, 0);
9715		for (pid, expected) in [(VIDEO, if damage == "clean" { 12 } else { 8 }), (peer, 12)] {
9716			let Stream::H264 { import: video, .. } = &import.streams[&Pid::new(pid).unwrap()] else {
9717				panic!("video route");
9718			};
9719			let frames = read_track(&consumer, video.name(), crate::container::Kind::Video).await;
9720			assert_eq!(frames.len(), expected, "published pictures on PID {pid}");
9721			if pid == VIDEO && damage != "clean" {
9722				assert!(frames[4].keyframe, "recovery starts at a keyframe");
9723				assert_eq!(
9724					frames[4].timestamp.as_micros().unwrap(),
9725					u128::from(90_000 + 9 * FRAME) * 1_000_000 / 90_000
9726				);
9727			}
9728		}
9729	}
9730
9731	/// An intact, unflagged packet whose PES header or adaptation field does not parse ends the
9732	/// import with the cause, after the pictures ahead of it, and counts no damage. The clock
9733	/// bits a malformed field announces never reach the program clock.
9734	#[tokio::test(start_paused = true)]
9735	async fn malformed_headers_end_the_import() {
9736		for (damage, cause) in [
9737			("pes", "PES header"),
9738			("adaptation", "adaptation field"),
9739			("adaptation-clock", "adaptation field"),
9740		] {
9741			let (mux, damaged_at, _) = damaged_video(damage);
9742			let mut broadcast = moq_net::broadcast::Info::new().produce();
9743			let consumer = broadcast.consume();
9744			let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9745			let mut import = super::Import::new(broadcast, catalog.reserve());
9746			let before = import.decode(&mux.out[..damaged_at]).map(|_| import.last_pts);
9747			let err = import.decode(&mux.out[damaged_at..]).expect_err(damage);
9748			assert!(err.to_string().contains(cause), "{damage}: {err}");
9749			assert_eq!(import.last_pts, before.unwrap(), "{damage} moved the clock");
9750			let stats = import.stats();
9751			assert!(stats.streams.values().all(|stream| stream.damaged == 0), "{damage}");
9752			let Stream::H264 { import: video, .. } = &import.streams[&Pid::new(VIDEO).unwrap()] else {
9753				panic!("video route");
9754			};
9755			let frames = read_track(&consumer, video.name(), crate::container::Kind::Video).await;
9756			assert_eq!(frames.len(), 4, "{damage}: the pictures an AUD proved whole");
9757		}
9758	}
9759
9760	/// PES boundaries need not fall on NALs, so the first PES after a continuity break can open
9761	/// inside a NAL that began in the lost one. Its bytes up to the next start code are dropped,
9762	/// not decoded, and the stream recovers at its next keyframe.
9763	#[tokio::test(start_paused = true)]
9764	async fn a_pes_opening_mid_nal_after_a_break_is_dropped() {
9765		let mut mux = Mux {
9766			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
9767			..Default::default()
9768		};
9769		mux.gop(VIDEO, 90_000);
9770		// The PES holding the NAL's start is lost, and the next carries only its tail.
9771		mux.cc(VIDEO);
9772		let cc = mux.cc(VIDEO);
9773		mux.out.extend(video_pes(
9774			VIDEO,
9775			cc,
9776			90_000 + 5 * FRAME,
9777			None,
9778			&[0x9a, 0xbc, 0xde, 0xf0],
9779		));
9780		mux.gop(VIDEO, 90_000 + 8 * FRAME);
9781
9782		let mut broadcast = moq_net::broadcast::Info::new().produce();
9783		let consumer = broadcast.consume();
9784		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9785		let mut import = super::Import::new(broadcast, catalog.reserve());
9786		import
9787			.decode(&mux.out)
9788			.expect("a NAL's lost start is loss, not a decode error");
9789		import.finish_in_place().unwrap();
9790		let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone();
9791		let frames = read_track(&consumer, &name, crate::container::Kind::Video).await;
9792		// Nothing proved the first GOP's last picture whole before the break, so it goes too.
9793		assert_eq!(frames.len(), 7, "both GOPs, around the break");
9794	}
9795
9796	/// A NAL that does not parse ends the import with the cause, wherever it sits in its
9797	/// access unit, after the pictures ahead of it published.
9798	#[tokio::test(start_paused = true)]
9799	async fn undecodable_nal_ends_the_import() {
9800		// A forbidden_zero_bit set on the IDR slice, on a trailing NAL, and on a NAL in the AU
9801		// after a valid IDR that an AUD proved whole and so already published.
9802		let mut forbidden = annexb_au(true);
9803		let nal = forbidden
9804			.windows(5)
9805			.position(|bytes| bytes[..4] == [0, 0, 0, 1] && bytes[4] & 0x1f == 5)
9806			.unwrap();
9807		forbidden[nal + 4] |= 0x80;
9808		let mut trailing = annexb_au(true);
9809		trailing.extend_from_slice(&[0, 0, 0, 1, 0xe1, 0x80]);
9810		let mut queued = annexb_au(true);
9811		queued.extend_from_slice(&[0, 0, 0, 1, 0x09, 0xf0, 0, 0, 0, 1, 0xe1, 0x80, 0, 0, 0, 1, 0x41, 0x9a]);
9812		for (au, published) in [(forbidden, 4), (trailing, 4), (queued, 5)] {
9813			let mut mux = Mux {
9814				out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
9815				..Default::default()
9816			};
9817			mux.gop(VIDEO, 90_000);
9818			let cc = mux.cc(VIDEO);
9819			mux.out
9820				.extend(video_pes(VIDEO, cc, 90_000 + 5 * FRAME, Some(90_000 + 4 * FRAME), &au));
9821			mux.gop(VIDEO, 90_000 + 8 * FRAME);
9822
9823			let mut broadcast = moq_net::broadcast::Info::new().produce();
9824			let consumer = broadcast.consume();
9825			let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9826			let mut import = super::Import::new(broadcast, catalog.reserve());
9827			let err = import.decode(&mux.out).expect_err("an undecodable NAL ends the import");
9828			assert!(err.to_string().contains("forbidden"), "{err}");
9829			let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone();
9830			let frames = read_track(&consumer, &name, crate::container::Kind::Video).await;
9831			assert_eq!(frames.len(), published, "the pictures ahead of it");
9832			assert_eq!(
9833				import.stats().streams[&VIDEO].damaged,
9834				0,
9835				"a decode error is not damage"
9836			);
9837		}
9838	}
9839
9840	#[tokio::test(start_paused = true)]
9841	async fn damaged_tei_recovers() {
9842		damaged_video_recovers("tei").await;
9843	}
9844
9845	#[tokio::test(start_paused = true)]
9846	async fn scrambled_pes_is_refused_until_clear() {
9847		damaged_video_recovers("scrambled").await;
9848	}
9849
9850	#[tokio::test(start_paused = true)]
9851	async fn clean_video_has_no_damage() {
9852		damaged_video_recovers("clean").await;
9853	}
9854
9855	/// A keyframe whose inline SPS does not parse ends the import with the cause, after the
9856	/// pictures ahead of it published.
9857	fn malformed_sps_ends_the_import(stream_type: StreamType) {
9858		let (params, idr, delta): (&[&[u8]], &[u8], &[u8]) = match stream_type {
9859			StreamType::H264 => {
9860				use crate::container::test_util::{IDR, PPS, SPS};
9861				(&[SPS, PPS], IDR, &[0x41, 0x9a, 0x00, 0x01])
9862			}
9863			StreamType::H265 => {
9864				use crate::codec::h265::fixtures::{PPS, SPS, VPS};
9865				(&[VPS, SPS, PPS], &[0x26, 0x01, 0x80, 0xaa], &[0x02, 0x01, 0x80, 0x33])
9866			}
9867			_ => unreachable!(),
9868		};
9869		let au = |nals: &[&[u8]]| {
9870			let mut out = Vec::new();
9871			for nal in nals {
9872				out.extend_from_slice(&[0, 0, 0, 1]);
9873				out.extend_from_slice(nal);
9874			}
9875			out
9876		};
9877		let mut keyframe = params.to_vec();
9878		keyframe.push(idr);
9879		// The SPS keeps its NAL header and loses the rest.
9880		let mut damaged = keyframe.clone();
9881		damaged[params.len() - 2] = &params[params.len() - 2][..2];
9882		let units = [au(&keyframe), au(&[delta]), au(&damaged), au(&[delta])];
9883		let mut data = synth_pmt(&[(stream_type, VIDEO)], false);
9884		for (cc, unit) in units.iter().enumerate() {
9885			let pts = 90_000 + cc as u64 * FRAME;
9886			data.extend(video_pes(VIDEO, cc as u8, pts, None, unit));
9887		}
9888
9889		let mut broadcast = moq_net::broadcast::Info::new().produce();
9890		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9891		let mut import = super::Import::new(broadcast, catalog.reserve());
9892		import.decode(&data).expect_err("a malformed SPS ends the import");
9893		assert_eq!(import.stats().streams[&VIDEO].units, 2);
9894	}
9895
9896	#[test]
9897	fn malformed_h264_sps_ends_the_import() {
9898		malformed_sps_ends_the_import(StreamType::H264);
9899	}
9900
9901	#[test]
9902	fn malformed_h265_sps_ends_the_import() {
9903		malformed_sps_ends_the_import(StreamType::H265);
9904	}
9905
9906	#[test]
9907	fn adaptation_lengths_obey_the_packet_control() {
9908		for (control, length, valid) in [
9909			(0b10, 0, false),
9910			(0b10, 182, false),
9911			(0b10, 183, true),
9912			(0b10, 184, false),
9913			(0b11, 0, true),
9914			(0b11, 182, true),
9915			(0b11, 183, false),
9916			(0b11, 184, false),
9917		] {
9918			let mut packet: [u8; TsPacket::SIZE] = clock_break_packet(VIDEO).try_into().unwrap();
9919			packet[3] = control << 4;
9920			packet[4] = length;
9921			packet[5] = 0;
9922			assert_eq!(
9923				super::adaptation_valid(&packet),
9924				valid,
9925				"control={control:b} length={length}"
9926			);
9927		}
9928	}
9929
9930	/// A malformed adaptation field on a carried PID or the clock's ends the import before its
9931	/// clock bits are read; one on a PID the import does not carry is not read at all.
9932	#[test]
9933	fn invalid_adaptation_fields_end_the_import_on_media_and_clock_pids() {
9934		// Clear of the PMT PID and every stream, so only the clock reads it.
9935		const PCR: u16 = 0x0200;
9936		const IGNORED: u16 = 0x0300;
9937		// Lengths the packet control forbids, and a PCR flag on a field too short to hold it.
9938		let faults: [(u8, u8, &[u8]); 4] = [(0b10, 0, &[]), (0b10, 182, &[]), (0b11, 183, &[]), (0b10, 1, &[0x90])];
9939		for pid in [VIDEO, PCR, IGNORED] {
9940			for (control, length, field) in faults {
9941				let mut mux = Mux {
9942					out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
9943					..Default::default()
9944				};
9945				mux.gop(VIDEO, 90_000);
9946				let mut broadcast = moq_net::broadcast::Info::new().produce();
9947				let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9948				let mut import = super::Import::new(broadcast, catalog.reserve());
9949				import.decode(&mux.out).unwrap();
9950				import.pcr_pid = Some(Pid::new(PCR).unwrap());
9951				import.streams.insert(Pid::new(IGNORED).unwrap(), Stream::Ignored);
9952				let last_pts = import.last_pts;
9953				assert!(last_pts.is_some());
9954
9955				let mut packet = clock_break_packet(pid);
9956				packet[3] = control << 4;
9957				packet[4] = length;
9958				packet[5..5 + field.len()].copy_from_slice(field);
9959				let case = format!("pid={pid} control={control:b} length={length}");
9960				if pid == IGNORED {
9961					import.decode(&packet).expect(&case);
9962				} else {
9963					let err = import.decode(&packet).expect_err(&case);
9964					assert!(err.to_string().contains("adaptation field"), "{case}: {err}");
9965				}
9966				assert_eq!(import.last_pts, last_pts, "{case} moved the clock");
9967				assert!(
9968					import.stats().streams.values().all(|stream| stream.damaged == 0),
9969					"{case}"
9970				);
9971			}
9972		}
9973	}
9974
9975	/// A PCR extension counts to 299: one past it at the top of the clock reads past the
9976	/// wrap, so the field is malformed and ends the import before any clock step reads it.
9977	#[test]
9978	fn a_pcr_extension_past_299_ends_the_import() {
9979		const PCR: u16 = 0x0200;
9980		let mut mux = Mux {
9981			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
9982			..Default::default()
9983		};
9984		mux.gop(VIDEO, 90_000);
9985		let mut broadcast = moq_net::broadcast::Info::new().produce();
9986		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
9987		let mut import = super::Import::new(broadcast, catalog.reserve());
9988		import.decode(&mux.out).unwrap();
9989		import.pcr_pid = Some(Pid::new(PCR).unwrap());
9990		import.decode(&pcr_packet(PCR, 27_000_000)).unwrap();
9991
9992		// The largest base, and an extension of 511.
9993		let mut packet = pcr_packet(PCR, 0);
9994		packet[6..12].fill(0xff);
9995		assert_eq!(super::pcr(&packet.clone().try_into().unwrap()), None);
9996		let err = import.decode(&packet).unwrap_err();
9997		assert!(err.to_string().contains("adaptation field"), "{err}");
9998	}
9999
10000	/// A malformed PES start ends the import after the AU a codec boundary already completed in
10001	/// the preceding unbounded PES published.
10002	#[test]
10003	fn malformed_pes_start_ends_the_import_after_the_unit_before_it() {
10004		let mut broadcast = moq_net::broadcast::Info::new().produce();
10005		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10006		let mut import = super::Import::new(broadcast, catalog.reserve());
10007		let unbounded = |cc, pts, keyframe| {
10008			let mut au = annexb_au(keyframe);
10009			if keyframe {
10010				au.extend([0, 0, 1, 9, 0xf0]);
10011			}
10012			let mut packet = video_pes(VIDEO, cc, pts, None, &au);
10013			let start = 5 + usize::from(packet[4]);
10014			packet[start + 4..start + 6].fill(0);
10015			packet
10016		};
10017		let mut data = synth_pmt(&[(StreamType::H264, VIDEO)], false);
10018		data.extend(unbounded(0, 90_000, true));
10019		let mut damaged = unbounded(1, 90_000 + FRAME, false);
10020		let start = 5 + usize::from(damaged[4]);
10021		damaged[start + 6..start + 19].fill(0);
10022		data.extend(damaged);
10023		let err = import
10024			.decode(&data)
10025			.expect_err("a malformed PES header ends the import");
10026		assert!(err.to_string().contains("PES header on PID"), "{err}");
10027		assert_eq!(import.stats().streams[&VIDEO].damaged, 0);
10028		assert_eq!(
10029			import.stats().streams[&VIDEO].units,
10030			1,
10031			"the keyframe before the malformed header"
10032		);
10033	}
10034
10035	/// A flagged clock break that sets PUSI on an adaptation-only packet starts no PES, so it
10036	/// proves nothing whole: the unbounded picture open across it is cut short and dropped.
10037	#[test]
10038	fn flagged_break_without_payload_drops_the_open_picture() {
10039		let mut broadcast = moq_net::broadcast::Info::new().produce();
10040		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10041		let mut import = super::Import::new(broadcast, catalog.reserve());
10042		let unbounded = |cc, pts, keyframe| {
10043			let mut au = annexb_au(keyframe);
10044			if keyframe {
10045				au.extend([0, 0, 1, 9, 0xf0]);
10046			}
10047			let mut packet = video_pes(VIDEO, cc, pts, None, &au);
10048			let start = 5 + usize::from(packet[4]);
10049			packet[start + 4..start + 6].fill(0);
10050			packet
10051		};
10052		let mut data = synth_pmt(&[(StreamType::H264, VIDEO)], false);
10053		data.extend(unbounded(0, 90_000, true));
10054		data.extend(unbounded(1, 90_000 + FRAME, false));
10055		let mut flagged = clock_break_packet(VIDEO);
10056		flagged[1] |= 0x40;
10057		flagged[3] |= 1;
10058		data.extend(flagged);
10059		import.decode(&data).unwrap();
10060		import.finish_in_place().unwrap();
10061		assert_eq!(
10062			import.stats().streams[&VIDEO].units,
10063			1,
10064			"only the keyframe the AUD proved whole"
10065		);
10066	}
10067
10068	/// A malformed unbounded PES drained at EOF ends the finish with the cause.
10069	#[test]
10070	fn malformed_final_access_unit_fails_the_finish() {
10071		let mut au = annexb_au(true);
10072		let nal = au
10073			.windows(5)
10074			.position(|bytes| bytes[..4] == [0, 0, 0, 1] && bytes[4] & 0x1f == 5)
10075			.unwrap();
10076		au[nal + 4] |= 0x80;
10077		let mut broadcast = moq_net::broadcast::Info::new().produce();
10078		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10079		let mut import = super::Import::new(broadcast, catalog.reserve());
10080		let mut packet = video_pes(VIDEO, 0, 90_000, None, &au);
10081		let start = 5 + usize::from(packet[4]);
10082		packet[start + 4..start + 6].fill(0);
10083		let mut data = synth_pmt(&[(StreamType::H264, VIDEO)], false);
10084		data.extend(packet);
10085		import.decode(&data).expect("the PES has not ended yet");
10086		import.finish_in_place().expect_err("the final AU does not decode");
10087		assert!(catalog.snapshot().video.renditions.is_empty());
10088	}
10089
10090	/// An invalid trailing Opus control header ends the import before any packet of its PES
10091	/// is published.
10092	#[test]
10093	fn malformed_opus_pes_ends_the_import_unpublished() {
10094		let mut broadcast = moq_net::broadcast::Info::new().produce();
10095		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10096		let mut import = super::Import::new(broadcast, catalog.reserve());
10097		import
10098			.ensure_stream(
10099				Pid::new(VIDEO).unwrap(),
10100				0x06,
10101				&[super::catalog::Descriptor {
10102					tag: 0x05,
10103					data: bytes::Bytes::from_static(b"Opus"),
10104				}],
10105			)
10106			.unwrap();
10107		let good = [0x7f, 0xe0, 3, 0xf8, 0xff, 0xfe];
10108		let mut bad = good.to_vec();
10109		bad.push(0x7f);
10110		let mut data = Vec::new();
10111		for (cc, payload) in [(0, good.as_slice()), (1, bad.as_slice()), (2, good.as_slice())] {
10112			data.extend(video_pes(VIDEO, cc, 90_000 + u64::from(cc) * FRAME, None, payload));
10113		}
10114		import.decode(&data).expect_err("a malformed Opus PES ends the import");
10115		assert_eq!(import.stats().streams[&VIDEO].units, 1, "only the PES ahead of it");
10116	}
10117
10118	/// A break closes the video group where its content stops, not a GOP later at the next
10119	/// keyframe. An open GOP's leading pictures present below that keyframe, so an end marker
10120	/// there would sit past them and the exporter refused them as a rewind.
10121	#[tokio::test(start_paused = true)]
10122	async fn damaged_video_closes_its_group_at_the_break() {
10123		use mpeg2ts::ts::{ReadTsPacket, TsPacketReader, TsPayload};
10124
10125		const MS: u64 = 90;
10126		let at = |ms: u64| 90_000 + ms * MS;
10127		let mut mux = Mux {
10128			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10129			..Default::default()
10130		};
10131		// A closed GOP whose third picture is damaged, then an open GOP whose leading B-frame
10132		// presents below its IDR.
10133		let pictures = [
10134			(true, at(0), None),
10135			(false, at(40), None),
10136			(false, at(80), None),
10137			(true, at(1200), Some(at(1000))),
10138			(false, at(1040), None),
10139			(false, at(1280), Some(at(1080))),
10140		];
10141		let mut damaged_at = 0;
10142		for (i, (keyframe, pts, dts)) in pictures.into_iter().enumerate() {
10143			if i == 2 {
10144				damaged_at = mux.out.len();
10145			}
10146			let cc = mux.cc(VIDEO);
10147			mux.out.extend_from_slice(&video_pes(VIDEO, cc, pts, dts, &{
10148				let mut au = annexb_au(keyframe);
10149				if i == 1 {
10150					au.extend([0, 0, 1, 9, 0xf0]);
10151				}
10152				au
10153			}));
10154		}
10155		mux.out[damaged_at + 1] |= 0x80;
10156
10157		let mut broadcast = moq_net::broadcast::Info::new().produce();
10158		let consumer = broadcast.consume();
10159		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10160		let mut import = super::Import::new(broadcast, catalog.reserve());
10161		import.decode(&mux.out).unwrap();
10162		import.finish_in_place().unwrap();
10163		assert_eq!(import.stats().streams[&VIDEO].damaged, 1);
10164
10165		// Each group as published, its empty end marker included.
10166		let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone();
10167		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
10168			moq_net::track::Start::Live {
10169				min: Some(Duration::from_secs(3600)),
10170				max: Some(Duration::from_secs(3600)),
10171			},
10172		)
10173		.with_order(moq_net::track::Order::Ascending)]);
10174		let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap();
10175		let mut groups = Vec::new();
10176		while let Some(mut group) = track.recv_group().await.unwrap() {
10177			let mut frames = Vec::new();
10178			while let Some(mut frame) = group.next_frame().await.unwrap() {
10179				let frame = hang::container::Frame::decode(frame.read_all().await.unwrap()).unwrap();
10180				frames.push((frame.timestamp.as_micros().unwrap(), frame.payload.is_empty()));
10181			}
10182			groups.push(frames);
10183		}
10184		let us = |ms: u64| u128::from(at(ms)) * 1_000_000 / 90_000;
10185		assert_eq!(
10186			groups,
10187			[
10188				vec![(us(0), false), (us(40), false), (us(80), true)],
10189				vec![(us(1200), false), (us(1040), false), (us(1280), false)],
10190			],
10191			"the first group ends at the break, one frame after its last picture"
10192		);
10193
10194		let mut exporter = crate::container::ts::export_test::open_export(
10195			crate::source::announced(&consumer).await,
10196			Duration::from_secs(30),
10197		)
10198		.await
10199		.unwrap()
10200		.with_replay();
10201		let mut ts = Vec::new();
10202		while let Ok(res) = kio::clock::timeout(Duration::from_secs(100), exporter.next()).await {
10203			let Some(frame) = res.expect("the exporter must take the open GOP after the break") else {
10204				break;
10205			};
10206			ts.extend_from_slice(&frame.payload);
10207		}
10208		let mut reader = TsPacketReader::new(std::io::Cursor::new(ts));
10209		let mut pictures = 0;
10210		while let Some(packet) = reader.read_ts_packet().unwrap() {
10211			pictures += usize::from(matches!(packet.payload, Some(TsPayload::PesStart(_))));
10212		}
10213		assert_eq!(pictures, 5, "every picture either side of the break is exported");
10214	}
10215
10216	/// #3798's join: a new IDR presents below the last P-frame on a continuous clock, since
10217	/// the B-frames before it presented earlier than the P-frame decoded ahead of them. It
10218	/// continues the old content's group, so the next group still presents after all of it.
10219	#[tokio::test(start_paused = true)]
10220	async fn h264_join_below_a_p_frame_continues_the_group() {
10221		let mut mux = Mux {
10222			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10223			..Default::default()
10224		};
10225		mux.gops(VIDEO, 90_000, 2);
10226		// The last P-frame presented at 90_000 + 8 * FRAME; the join lands a frame short.
10227		mux.gops(VIDEO, 90_000 + 6 * FRAME, 2);
10228		let frames = video_frames(&mux.out).await;
10229		assert_eq!(frames.len(), 16, "every picture either side of the join");
10230		let groups = frames.iter().filter(|frame| frame.keyframe).count();
10231		assert_eq!(groups, 3, "the join's IDR continues the group it overlaps");
10232		assert_forward(&frames);
10233	}
10234
10235	/// A join whose IDR lands past the old content, followed by leading pictures: the one that
10236	/// would present at or before the old content's newest frame is dropped, with the leading
10237	/// pictures decoding after it, which may reference it. The pictures after the IDR publish.
10238	#[tokio::test(start_paused = true)]
10239	async fn h264_join_drops_a_leading_picture_before_the_old_content_ends() {
10240		let mut mux = Mux {
10241			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10242			..Default::default()
10243		};
10244		// The old content's newest frame presents at `base + 4 * FRAME` and decodes last at
10245		// `base + 3 * FRAME`.
10246		let base = 90_000 + 4 * FRAME;
10247		mux.gops(VIDEO, 90_000, 2);
10248		for (keyframe, pts, dts) in [
10249			(true, base + 7 * FRAME, base + 3 * FRAME + 1_000),
10250			(false, base + 4 * FRAME, base + 3 * FRAME + 2_000),
10251			(false, base + 6 * FRAME, base + 4 * FRAME),
10252			(false, base + 9 * FRAME, base + 5 * FRAME),
10253			(false, base + 8 * FRAME, base + 6 * FRAME),
10254		] {
10255			let cc = mux.cc(VIDEO);
10256			mux.out
10257				.extend_from_slice(&video_pes(VIDEO, cc, pts, Some(dts), &annexb_au(keyframe)));
10258		}
10259		let frames = video_frames(&mux.out).await;
10260		let micros = |ticks: u64| u128::from(ticks) * 1_000_000 / 90_000;
10261		let joined: Vec<u128> = frames[8..]
10262			.iter()
10263			.map(|frame| frame.timestamp.as_micros().unwrap())
10264			.collect();
10265		assert_eq!(
10266			joined,
10267			[base + 7 * FRAME, base + 9 * FRAME, base + 8 * FRAME].map(micros)
10268		);
10269		assert_forward(&frames);
10270	}
10271
10272	/// An encoder restart that declares the new clock on the PCR PID still restarts lower
10273	/// than the live edge: a new broadcast, not a continuation, from the break on.
10274	#[tokio::test(start_paused = true)]
10275	async fn h264_flagged_backward_restart_ends_the_identity() {
10276		let mut mux = Mux {
10277			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10278			..Default::default()
10279		};
10280		mux.gops(VIDEO, 45 * 90_000, 2);
10281		let at = mux.out.len();
10282		mux.out.extend_from_slice(&clock_break_packet(VIDEO));
10283		mux.gops(VIDEO, 90_000, 2);
10284		let restart = import_restart(&mux.out);
10285		assert!(
10286			matches!(restart.step, crate::container::ts::Step::Rewind { flagged: true, .. }),
10287			"{restart:?}"
10288		);
10289		assert_eq!(restart.remainder, mux.out[at..]);
10290	}
10291
10292	/// The same restart unflagged, as a looping playout wraps to the top of its file.
10293	#[tokio::test(start_paused = true)]
10294	async fn h264_unflagged_backward_restart_is_refused() {
10295		let mut mux = Mux {
10296			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10297			..Default::default()
10298		};
10299		mux.gops(VIDEO, 45 * 90_000, 2);
10300		mux.gops(VIDEO, 90_000, 2);
10301		import_refused(&mux.out);
10302	}
10303
10304	/// A flagged break that leaps forward is not a rewind: the new timeline publishes.
10305	#[tokio::test(start_paused = true)]
10306	async fn h264_flagged_forward_restart_publishes() {
10307		let mut mux = Mux {
10308			out: synth_pmt(&[(StreamType::H264, VIDEO)], false),
10309			..Default::default()
10310		};
10311		mux.gops(VIDEO, 90_000, 2);
10312		// A codec boundary, not the following clock marker, vouches for the
10313		// final picture on the old timeline.
10314		let mut last = annexb_au(false);
10315		last.extend([0, 0, 1, 9, 0xf0]);
10316		let at = mux.out.len() - 188;
10317		mux.out[at..].copy_from_slice(&video_pes(VIDEO, 7, 90_000 + 7 * FRAME, None, &last));
10318		mux.out.extend_from_slice(&clock_break_packet(VIDEO));
10319		// Inside the track's 30 s max age, so the reader still reaches the first pass.
10320		mux.gops(VIDEO, 20 * 90_000, 2);
10321		let frames = video_frames(&mux.out).await;
10322		assert_eq!(frames.len(), 16);
10323		assert_forward(&frames);
10324	}
10325
10326	/// Legacy audio wrapping to the top of a looping file is a restart.
10327	#[tokio::test(start_paused = true)]
10328	async fn legacy_loop_wrap_is_refused() {
10329		const MP2_PID: u16 = 0x0061;
10330		let mut mux = Mux {
10331			out: synth_pmt(&[(StreamType::Mpeg1Audio, MP2_PID)], false),
10332			..Default::default()
10333		};
10334		// One PES is two 72 ms MP2 frames.
10335		const PES_TICKS: u64 = 2 * 72 * 90;
10336		for _ in 0..2 {
10337			for i in 0..4 {
10338				let cc = mux.cc(MP2_PID);
10339				mux.out
10340					.extend_from_slice(&mp2_pes(MP2_PID, cc, 90_000 + i * PES_TICKS, [0xAA, 0xBB]));
10341			}
10342		}
10343		import_refused(&mux.out);
10344	}
10345
10346	/// A looping file whose audio runs past the loop period restarts a frame below the last
10347	/// frame published: a restart like any other.
10348	#[tokio::test(start_paused = true)]
10349	async fn aac_loop_overlapping_the_edge_is_refused() {
10350		const AAC_PID: u16 = 0x0060;
10351		// 1024 samples at 48 kHz, in 90 kHz ticks.
10352		const AAC_FRAME: u64 = 1024 * 90_000 / 48_000;
10353		let mut mux = Mux {
10354			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
10355			..Default::default()
10356		};
10357		for pass in 0..2u64 {
10358			for i in 0..4u64 {
10359				let mut payload = adts_frame(17, 0xA0 | i as u8);
10360				payload.extend_from_slice(&adts_frame(17, 0xB0 | i as u8));
10361				let cc = mux.cc(AAC_PID);
10362				let pts = 90_000 + pass * 6 * AAC_FRAME + i * 2 * AAC_FRAME;
10363				mux.out.extend_from_slice(&audio_pes_packet(AAC_PID, cc, pts, &payload));
10364			}
10365		}
10366		import_refused(&mux.out);
10367	}
10368
10369	/// A join a millisecond below the start of the last frame published is a restart, as it was
10370	/// when each frame was its own group, even though it lands inside the last PES's group.
10371	#[tokio::test(start_paused = true)]
10372	async fn aac_join_inside_the_last_pes_is_refused() {
10373		const AAC_PID: u16 = 0x0060;
10374		// 1024 samples at 48 kHz, in 90 kHz ticks.
10375		const AAC_FRAME: u64 = 1024 * 90_000 / 48_000;
10376		let mut mux = Mux {
10377			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
10378			..Default::default()
10379		};
10380		for (pts, fill) in [(90_000, 0xA0), (90_000 + 2 * AAC_FRAME - 90, 0xB0)] {
10381			let mut payload = Vec::new();
10382			for i in 0..3 {
10383				payload.extend_from_slice(&adts_frame(17, fill | i));
10384			}
10385			let cc = mux.cc(AAC_PID);
10386			mux.out.extend_from_slice(&audio_pes_packet(AAC_PID, cc, pts, &payload));
10387		}
10388		import_refused(&mux.out);
10389	}
10390
10391	/// A PES never splits across groups, so the transport, which sends a track's newest group
10392	/// first, cannot deliver a PES's frames newest first: a group closes at the end of the PES that
10393	/// brings it to 100 ms, here every second 64 ms PES, though the join falls inside it.
10394	#[tokio::test(start_paused = true)]
10395	async fn aac_groups_close_at_a_pes_end() {
10396		const AAC_PID: u16 = 0x0060;
10397		// 1024 samples at 48 kHz, in 90 kHz ticks.
10398		const AAC_FRAME: u64 = 1024 * 90_000 / 48_000;
10399		let mut mux = Mux {
10400			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
10401			..Default::default()
10402		};
10403		for pes in 0..5u8 {
10404			let mut payload = Vec::new();
10405			for i in 0..3 {
10406				payload.extend_from_slice(&adts_frame(17, (0x10 * (pes + 1)) | i));
10407			}
10408			let cc = mux.cc(AAC_PID);
10409			let pts = 90_000 + u64::from(pes) * 3 * AAC_FRAME;
10410			mux.out.extend_from_slice(&audio_pes_packet(AAC_PID, cc, pts, &payload));
10411		}
10412		let (consumer, catalog, _import) = import_all(&mux.out).unwrap();
10413
10414		let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
10415		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
10416			moq_net::track::Start::Live {
10417				min: Some(Duration::from_secs(3600)),
10418				max: Some(Duration::from_secs(3600)),
10419			},
10420		)
10421		.with_order(moq_net::track::Order::Ascending)]);
10422		let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap();
10423		let mut groups = Vec::new();
10424		while let Ok(Ok(Some(mut group))) = kio::clock::timeout(Duration::from_millis(50), track.recv_group()).await {
10425			let mut fills = Vec::new();
10426			while let Some(mut frame) = group.next_frame().await.unwrap() {
10427				let frame = hang::container::Frame::decode(frame.read_all().await.unwrap()).unwrap();
10428				fills.extend(frame.payload.first().copied());
10429			}
10430			groups.push(fills);
10431		}
10432		assert_eq!(
10433			groups,
10434			[
10435				vec![0x10, 0x11, 0x12, 0x20, 0x21, 0x22],
10436				vec![0x30, 0x31, 0x32, 0x40, 0x41, 0x42],
10437				vec![0x50, 0x51, 0x52],
10438			]
10439		);
10440	}
10441
10442	/// A continuity break closes the open group at its last intact frame, though it holds under
10443	/// 100 ms, so the PES recovered after it opens a fresh group rather than joining stale audio.
10444	#[tokio::test(start_paused = true)]
10445	async fn aac_group_closes_at_a_continuity_break() {
10446		const AAC_PID: u16 = 0x0060;
10447		// 1024 samples at 48 kHz, in 90 kHz ticks.
10448		const AAC_FRAME: u64 = 1024 * 90_000 / 48_000;
10449		let mut mux = Mux {
10450			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
10451			..Default::default()
10452		};
10453		for pes in 0..3u8 {
10454			let mut payload = Vec::new();
10455			for i in 0..3 {
10456				payload.extend_from_slice(&adts_frame(17, (0x10 * (pes + 1)) | i));
10457			}
10458			// A packet lost before the second PES, while the open group holds 64 ms.
10459			if pes == 1 {
10460				mux.cc(AAC_PID);
10461			}
10462			let cc = mux.cc(AAC_PID);
10463			let pts = 90_000 + u64::from(pes) * 3 * AAC_FRAME;
10464			mux.out.extend_from_slice(&audio_pes_packet(AAC_PID, cc, pts, &payload));
10465		}
10466		let (consumer, catalog, _import) = import_all(&mux.out).unwrap();
10467
10468		let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
10469		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
10470			moq_net::track::Start::Live {
10471				min: Some(Duration::from_secs(3600)),
10472				max: Some(Duration::from_secs(3600)),
10473			},
10474		)
10475		.with_order(moq_net::track::Order::Ascending)]);
10476		let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap();
10477		let mut groups = Vec::new();
10478		while let Ok(Ok(Some(mut group))) = kio::clock::timeout(Duration::from_millis(50), track.recv_group()).await {
10479			let mut fills = Vec::new();
10480			while let Some(mut frame) = group.next_frame().await.unwrap() {
10481				let frame = hang::container::Frame::decode(frame.read_all().await.unwrap()).unwrap();
10482				fills.extend(frame.payload.first().copied());
10483			}
10484			groups.push(fills);
10485		}
10486		assert_eq!(
10487			groups,
10488			[vec![0x10, 0x11, 0x12], vec![0x20, 0x21, 0x22, 0x30, 0x31, 0x32]],
10489			"{groups:x?}"
10490		);
10491	}
10492
10493	/// A frame without a PTS is stamped by the producer, which checks only where groups start, so
10494	/// each keeps a group of its own, unlike the PES that carries a PTS after them.
10495	#[tokio::test(start_paused = true)]
10496	async fn aac_untimed_frames_keep_a_group_each() {
10497		const AAC_PID: u16 = 0x0060;
10498		let mut mux = Mux {
10499			out: synth_pmt(&[(StreamType::AdtsAac, AAC_PID)], false),
10500			..Default::default()
10501		};
10502		let mut payload = Vec::new();
10503		for i in 0..3 {
10504			payload.extend_from_slice(&adts_frame(17, 0xA0 | i));
10505		}
10506		let cc = mux.cc(AAC_PID);
10507		// The same PES with its PTS flag cleared: header length 0, five fewer bytes of PES.
10508		let mut untimed = audio_pes_packet(AAC_PID, cc, 0, &payload);
10509		let pes = untimed.iter().position(|&b| b == 0xc0).unwrap() - 3;
10510		let len = u16::from_be_bytes([untimed[pes + 4], untimed[pes + 5]]) - 5;
10511		untimed[pes + 4..pes + 6].copy_from_slice(&len.to_be_bytes());
10512		untimed[pes + 7] = 0x00;
10513		untimed[pes + 8] = 0x00;
10514		untimed.drain(pes + 9..pes + 14);
10515		// Refill the adaptation field so the packet stays 188 bytes.
10516		untimed[4] += 5;
10517		untimed.splice(6..6, std::iter::repeat_n(0xff, 5));
10518		mux.out.extend_from_slice(&untimed);
10519		let (consumer, catalog, _import) = import_all(&mux.out).unwrap();
10520
10521		let name = catalog.snapshot().audio.renditions.keys().next().unwrap().clone();
10522		let subscription = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
10523			moq_net::track::Start::Live {
10524				min: Some(Duration::from_secs(3600)),
10525				max: Some(Duration::from_secs(3600)),
10526			},
10527		)
10528		.with_order(moq_net::track::Order::Ascending)]);
10529		let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap();
10530		let mut groups = Vec::new();
10531		while let Ok(Ok(Some(mut group))) = kio::clock::timeout(Duration::from_millis(50), track.recv_group()).await {
10532			let mut fills = Vec::new();
10533			while let Some(mut frame) = group.next_frame().await.unwrap() {
10534				let frame = hang::container::Frame::decode(frame.read_all().await.unwrap()).unwrap();
10535				fills.extend(frame.payload.first().copied());
10536			}
10537			groups.push(fills);
10538		}
10539		assert_eq!(groups, [vec![0xA0], vec![0xA1], vec![0xA2]]);
10540	}
10541
10542	/// PCR placement advances independently of the video's B-frame presentation reorder.
10543	#[tokio::test(start_paused = true)]
10544	async fn section_after_a_b_frame_publishes_forward() {
10545		const CUE_PID: u16 = 0x0021;
10546		let mut mux = Mux {
10547			out: synth_pmt(
10548				&[
10549					(StreamType::H264, VIDEO),
10550					(StreamType::Dts8ChannelLosslessAudio, CUE_PID),
10551				],
10552				true,
10553			),
10554			..Default::default()
10555		};
10556		// Two GOPs back to back.
10557		for gop in 0..2 {
10558			let base = 90_000 + gop * 4 * FRAME;
10559			for (index, (keyframe, pts, dts)) in [
10560				(true, base + FRAME, Some(base)),
10561				(false, base + 4 * FRAME, Some(base + FRAME)),
10562				(false, base + 2 * FRAME, None),
10563			]
10564			.into_iter()
10565			.enumerate()
10566			{
10567				mux.out
10568					.extend_from_slice(&pcr_packet(VIDEO, (base + index as u64 * FRAME) * 300));
10569				let cc = mux.cc(VIDEO);
10570				mux.out
10571					.extend_from_slice(&video_pes(VIDEO, cc, pts, dts, &annexb_au(keyframe)));
10572				// `packet` builds on the cue PID.
10573				let cc = mux.cc(CUE_PID);
10574				mux.out.extend_from_slice(&packet(true, cc, 0, &CUE));
10575			}
10576		}
10577		let (consumer, catalog, _import) = import_all(&mux.out).expect("a cue after a B-frame must not end the import");
10578		let name = catalog.snapshot().ext.mpegts.tracks.keys().next().unwrap().clone();
10579		let frames = read_track(&consumer, &name, crate::container::Kind::Data).await;
10580		assert_eq!(frames.len(), 6, "every cue publishes");
10581		assert_forward(&frames);
10582		// The next GOP's cues follow the video rather than piling up on the edge.
10583		assert!(
10584			frames[3].timestamp.as_micros().unwrap() > frames[2].timestamp.as_micros().unwrap(),
10585			"the cues did not move with the video: {:?}",
10586			frames
10587				.iter()
10588				.map(|f| f.timestamp.as_micros().unwrap())
10589				.collect::<Vec<_>>()
10590		);
10591	}
10592
10593	/// An adaptation-only clock packet on `pid` carrying `ticks` of the 27 MHz PCR.
10594	fn pcr_packet(pid: u16, ticks: u64) -> Vec<u8> {
10595		let (base, ext) = (ticks / 300, ticks % 300);
10596		let mut p = vec![
10597			0x47,
10598			(pid >> 8) as u8 & 0x1f,
10599			(pid & 0xff) as u8,
10600			0x20,
10601			183,
10602			0x10,
10603			(base >> 25) as u8,
10604			(base >> 17) as u8,
10605			(base >> 9) as u8,
10606			(base >> 1) as u8,
10607			((base as u8 & 1) << 7) | 0x7e | (ext >> 8) as u8,
10608			ext as u8,
10609		];
10610		p.resize(188, 0xff);
10611		p
10612	}
10613
10614	/// The catalog goes out with the first media, and a constant-rate source gains its `muxRate` as
10615	/// an update once a window measures it; a variable-rate one never does.
10616	#[test]
10617	fn first_ts_catalog_gains_the_mux_rate_as_an_update() {
10618		use crate::catalog::hang::Catalog;
10619		use crate::container::ts::catalog::Ext;
10620
10621		for cbr in [true, false] {
10622			let mut broadcast = moq_net::broadcast::Info::new().produce();
10623			let catalog = crate::catalog::Producer::new(
10624				&mut broadcast,
10625				crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
10626			)
10627			.unwrap();
10628			let mut updates = catalog.consume().unwrap();
10629			let mut import = super::Import::new(broadcast, catalog.reserve());
10630			import
10631				.decode(&synth_pmt(&[(StreamType::Mpeg2PacketizedData, PCR_PID)], false))
10632				.unwrap();
10633			import.decode(&pes_packet(PCR_PID, 90_000)).unwrap();
10634			let waiter = kio::Waiter::noop();
10635			let std::task::Poll::Ready(Ok(Some(moq_json::Timed { value: first, .. }))) = updates.poll_next(&waiter)
10636			else {
10637				panic!("the catalog waited for a rate measurement");
10638			};
10639			assert_eq!(first.ext.mpegts.mux_rate, None);
10640
10641			for i in 0..=50 {
10642				let mut bytes = pcr_packet(PCR_PID, i * 27_000_000 / 25);
10643				let stuffing = if cbr || i < 25 { 99 } else { 19 };
10644				for _ in 0..stuffing {
10645					bytes.extend_from_slice(&super::super::export::NULL_PACKET);
10646				}
10647				import.decode(&bytes).unwrap();
10648			}
10649			let mut latest = None;
10650			while let std::task::Poll::Ready(Ok(Some(update))) = updates.poll_next(&waiter) {
10651				latest = Some(update);
10652			}
10653			assert_eq!(
10654				latest.map(|update| update.value.ext.mpegts.mux_rate),
10655				cbr.then_some(Some(3_760_000)),
10656				"a window's rate arrives as an update, a variable one publishes nothing"
10657			);
10658		}
10659	}
10660
10661	/// A catalog that already records a rate, as a restarted import's carries its predecessor's,
10662	/// goes out with the first media, and the first window still refines the rate.
10663	#[test]
10664	fn a_measured_ts_catalog_goes_out_with_the_first_media() {
10665		use crate::catalog::hang::Catalog;
10666		use crate::container::ts::catalog::Ext;
10667
10668		let mut broadcast = moq_net::broadcast::Info::new().produce();
10669		let mut initial = Catalog::<Ext>::default();
10670		initial.ext.mpegts.mux_rate = Some(3_000_000);
10671		let catalog =
10672			crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default().with_catalog(initial))
10673				.unwrap();
10674		let mut updates = catalog.consume().unwrap();
10675		let mut import = super::Import::new(broadcast, catalog.reserve());
10676		import
10677			.decode(&synth_pmt(&[(StreamType::Mpeg2PacketizedData, PCR_PID)], false))
10678			.unwrap();
10679		import.decode(&pes_packet(PCR_PID, 90_000)).unwrap();
10680		let waiter = kio::Waiter::noop();
10681		let std::task::Poll::Ready(Ok(Some(moq_json::Timed { value: first, .. }))) = updates.poll_next(&waiter) else {
10682			panic!("a measured catalog waited for a window");
10683		};
10684		assert_eq!(first.ext.mpegts.mux_rate, Some(3_000_000));
10685
10686		for i in 0..=50 {
10687			let mut bytes = pcr_packet(PCR_PID, i * 27_000_000 / 25);
10688			for _ in 0..99 {
10689				bytes.extend_from_slice(&super::super::export::NULL_PACKET);
10690			}
10691			import.decode(&bytes).unwrap();
10692		}
10693		assert_eq!(
10694			catalog.snapshot().ext.mpegts.mux_rate,
10695			Some(3_760_000),
10696			"the window refines the rate"
10697		);
10698	}
10699
10700	/// The catalog follows the clock: a stable multiplex rate is recorded, a source that
10701	/// stops holding it clears the record, a fresh stable window records it again, and a
10702	/// declared time-base break clears it at once.
10703	#[test]
10704	fn mux_rate_follows_the_clock() {
10705		use crate::catalog::hang::Catalog;
10706		use crate::container::ts::catalog::Ext;
10707
10708		let mut broadcast = moq_net::broadcast::Info::new().produce();
10709		let catalog = crate::catalog::Producer::new(
10710			&mut broadcast,
10711			crate::catalog::Config::default().with_catalog(Catalog::<Ext>::default()),
10712		)
10713		.unwrap();
10714		let mut import = super::Import::new(broadcast, catalog.reserve());
10715		import
10716			.decode(&synth_pmt(&[(StreamType::Mpeg1Audio, PCR_PID)], false))
10717			.unwrap();
10718
10719		// 40 ms PCR intervals; `stuffing(i)` packets of null padding after the i-th clock.
10720		const INTERVAL: u64 = 27_000_000 / 25;
10721		let mut ticks = 0;
10722		let mut feed = |import: &mut super::Import<Ext>, seconds: u64, stuffing: &dyn Fn(u64) -> usize| {
10723			for i in 0..seconds * 25 {
10724				let mut bytes = pcr_packet(PCR_PID, ticks);
10725				for _ in 0..stuffing(i) {
10726					bytes.extend_from_slice(&super::super::export::NULL_PACKET);
10727				}
10728				import.decode(&bytes).unwrap();
10729				ticks += INTERVAL;
10730			}
10731		};
10732		let rate = || catalog.snapshot().ext.mpegts.mux_rate;
10733
10734		// 100 packets per 40 ms: 3.76 Mb/s, byte-locked.
10735		feed(&mut import, 3, &|_| 99);
10736		assert_eq!(rate(), Some(3_760_000), "a stable window records the rate");
10737
10738		// The stuffing comes and goes: nothing agrees with the record any more. Windows
10739		// are 2 s and the feeds are not aligned to them, so allow one straddling window
10740		// (which still holds intervals at the old rate) before the next full one clears.
10741		feed(&mut import, 4, &|i| if (i / 5) % 2 == 0 { 10 } else { 90 });
10742		assert_eq!(rate(), None, "an unstable window clears the record");
10743
10744		feed(&mut import, 4, &|_| 99);
10745		assert_eq!(rate(), Some(3_760_000), "a fresh stable window records it again");
10746
10747		import.decode(&clock_break_packet(PCR_PID)).unwrap();
10748		assert_eq!(rate(), None, "a time-base break clears the record at once");
10749	}
10750
10751	/// The same flag on an elementary PID declares only that the continuity counter jumped.
10752	/// The partial it interrupts is dropped, as ever, but the program clock is untouched, so
10753	/// no track takes a break and the peer PID never notices.
10754	#[tokio::test(start_paused = true)]
10755	async fn elementary_discontinuity_is_not_a_timebase_break() {
10756		let (consumer, catalog, mut import) = two_stream_import();
10757
10758		for pid in [PCR_PID, PEER_PID] {
10759			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
10760		}
10761		import
10762			.decode(flag_discontinuity(mp2_pes(PEER_PID, 5, 180_000, [0xCC, 0xDD])).as_slice())
10763			.unwrap();
10764		import
10765			.decode(mp2_pes(PCR_PID, 1, 180_000, [0xCC, 0xDD]).as_slice())
10766			.unwrap();
10767		let _finished = import.finish().unwrap();
10768
10769		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
10770			assert_eq!(breaks, 0, "a counter jump is not a program timebase reset");
10771		}
10772	}
10773
10774	/// A counter gap on the PCR PID with no flag anywhere is loss, not a signalled reset: the
10775	/// partial goes, the clock stays.
10776	#[tokio::test(start_paused = true)]
10777	async fn a_counter_gap_is_not_a_timebase_break() {
10778		let (consumer, catalog, mut import) = two_stream_import();
10779
10780		for pid in [PCR_PID, PEER_PID] {
10781			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
10782		}
10783		// cc 1 -> 7 on the clock's own PID.
10784		import
10785			.decode(mp2_pes(PCR_PID, 7, 180_000, [0xCC, 0xDD]).as_slice())
10786			.unwrap();
10787		let _finished = import.finish().unwrap();
10788
10789		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
10790			assert_eq!(breaks, 0, "lost packets are not a signalled clock reset");
10791		}
10792	}
10793
10794	/// The 33-bit PTS field wraps every 26.5 hours with nothing set anywhere, and that is
10795	/// correct: it is unwrapped into a continuous timeline rather than declared a break.
10796	#[tokio::test(start_paused = true)]
10797	async fn a_timestamp_rollover_is_not_a_timebase_break() {
10798		let (consumer, catalog, mut import) = two_stream_import();
10799
10800		const FIELD: u64 = 1 << 33;
10801		for pid in [PCR_PID, PEER_PID] {
10802			import
10803				.decode(mp2_pes(pid, 0, FIELD - 90_000, [0xAA, 0xBB]).as_slice())
10804				.unwrap();
10805			import.decode(mp2_pes(pid, 1, 90_000, [0xCC, 0xDD]).as_slice()).unwrap();
10806		}
10807		let _finished = import.finish().unwrap();
10808
10809		for (frames, breaks) in read_all_breaks(&consumer, &catalog).await {
10810			assert_eq!(breaks, 0, "a rollover is not a break");
10811			let stamps: Vec<u128> = frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect();
10812			assert!(
10813				stamps.windows(2).all(|pair| pair[0] < pair[1]),
10814				"the rollover broke the timeline: {stamps:?}"
10815			);
10816		}
10817	}
10818
10819	/// A mux may flag every packet it emits until the new clock is established, and a clock
10820	/// packet is retransmitted freely. Consecutive markers with no media between them are one
10821	/// break, or a downstream re-acquires once per packet.
10822	#[tokio::test(start_paused = true)]
10823	async fn repeated_flags_declare_one_break() {
10824		let (consumer, catalog, mut import) = two_stream_import();
10825
10826		for pid in [PCR_PID, PEER_PID] {
10827			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
10828		}
10829		for _ in 0..4 {
10830			import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
10831		}
10832		for pid in [PCR_PID, PEER_PID] {
10833			import
10834				.decode(mp2_pes(pid, 1, 180_000, [0xCC, 0xDD]).as_slice())
10835				.unwrap();
10836		}
10837		let _finished = import.finish().unwrap();
10838
10839		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
10840			assert_eq!(breaks, 1, "each flagged packet declared its own break");
10841		}
10842	}
10843
10844	/// The demodulator disowned the packet, so nothing in it is evidence, the adaptation
10845	/// field included. Line noise that happens to set the bit must not break every track in
10846	/// the program.
10847	#[tokio::test(start_paused = true)]
10848	async fn a_corrupt_packet_declares_no_break() {
10849		let (consumer, catalog, mut import) = two_stream_import();
10850
10851		for pid in [PCR_PID, PEER_PID] {
10852			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
10853		}
10854		// transport_error_indicator, on a clock packet that also sets the discontinuity flag.
10855		let mut corrupt = clock_break_packet(PCR_PID);
10856		corrupt[1] |= 0x80;
10857		import.decode(corrupt.as_slice()).unwrap();
10858		for pid in [PCR_PID, PEER_PID] {
10859			import
10860				.decode(mp2_pes(pid, 1, 180_000, [0xCC, 0xDD]).as_slice())
10861				.unwrap();
10862		}
10863		let _finished = import.finish().unwrap();
10864
10865		for (_, breaks) in read_all_breaks(&consumer, &catalog).await {
10866			assert_eq!(breaks, 0, "a corrupt packet's adaptation field was trusted");
10867		}
10868	}
10869
10870	/// A flag arriving before anything has been published breaks nothing: a capture joining
10871	/// mid-stream lands on whatever the mux is flagging at the time, and there is no timeline
10872	/// behind it to cut.
10873	#[tokio::test(start_paused = true)]
10874	async fn a_break_before_any_media_is_ignored() {
10875		let (consumer, catalog, mut import) = two_stream_import();
10876
10877		import.decode(clock_break_packet(PCR_PID).as_slice()).unwrap();
10878		for pid in [PCR_PID, PEER_PID] {
10879			import.decode(mp2_pes(pid, 0, 90_000, [0xAA, 0xBB]).as_slice()).unwrap();
10880		}
10881		let _finished = import.finish().unwrap();
10882
10883		for (frames, breaks) in read_all_breaks(&consumer, &catalog).await {
10884			assert_eq!(breaks, 0, "nothing had been published to break from");
10885			assert!(!frames.is_empty(), "the media after the flag still publishes");
10886		}
10887	}
10888
10889	/// Each reset stimulus has eight PES packets of two 72 ms MP2 frames.
10890	const RESET_PES: u64 = 8;
10891	const RESET_PES_TICKS: u64 = 2 * 72 * 90;
10892	const RESET_LEAP_TICKS: u64 = 30 * 90_000;
10893
10894	/// Drain queued media on its existing deadlines, stopping when the live export is idle.
10895	async fn exported_discontinuities(
10896		exporter: &mut crate::container::ts::Export<crate::catalog::Consumer>,
10897	) -> (usize, usize) {
10898		let waiter = kio::Waiter::noop();
10899		let mut frames = 0;
10900		let mut flagged = 0;
10901		loop {
10902			match exporter.poll_next(&waiter) {
10903				std::task::Poll::Ready(Ok(Some(frame))) => {
10904					frames += 1;
10905					flagged += frame
10906						.payload
10907						.as_chunks::<188>()
10908						.0
10909						.iter()
10910						.filter(|p| p[3] & 0x20 != 0 && p[4] > 0 && p[5] & 0x80 != 0)
10911						.count();
10912				}
10913				std::task::Poll::Ready(Ok(None)) => break,
10914				std::task::Poll::Ready(Err(err)) => panic!("exporter error: {err}"),
10915				std::task::Poll::Pending => {
10916					let Some(deadline) = exporter.next_due() else { break };
10917					kio::clock::sleep_until(deadline).await;
10918				}
10919			}
10920		}
10921		(frames, flagged)
10922	}
10923
10924	/// Import `before`, re-export the broadcast to MPEG-TS until it has gone out, then import
10925	/// `after` and count the exported packets whose adaptation field sets
10926	/// `discontinuity_indicator`.
10927	async fn export_discontinuities(before: &[u8], after: &[u8]) -> usize {
10928		let mut broadcast = moq_net::broadcast::Info::new().produce();
10929		let consumer = broadcast.consume();
10930		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
10931		let mut import = super::Import::new(broadcast, catalog.reserve());
10932		import.decode(&bytes::BytesMut::from(before)).unwrap();
10933
10934		// Retain the complete stimulus span, the 30 s leap included: less sheds earlier
10935		// groups and their boundary. Queued media is drained on its deadlines, without
10936		// generating output through an arbitrary silence before feeding the next phase.
10937		let delay = std::time::Duration::from_millis((RESET_LEAP_TICKS + RESET_PES * RESET_PES_TICKS) / 90);
10938		let mut exporter =
10939			crate::container::ts::export_test::open_export(crate::source::announced(&consumer).await, delay)
10940				.await
10941				.unwrap()
10942				.with_replay();
10943		// A discontinuity before anything went out moves no clock, so the media before the
10944		// boundary goes out first, as it would live.
10945		let (frames, before_flags) = exported_discontinuities(&mut exporter).await;
10946		assert!(frames > 0, "media before the boundary must reach the output");
10947		import.decode(&bytes::BytesMut::from(after)).unwrap();
10948		let _finished = import.finish().unwrap();
10949		let (frames, after_flags) = exported_discontinuities(&mut exporter).await;
10950		assert!(frames > 0, "media after the boundary must reach the output");
10951		before_flags + after_flags
10952	}
10953
10954	/// The end-to-end shape the #2833 stimulus campaign graded: source, MoQ frames, exported
10955	/// TS. A +30 s leap the source declared must come out declared, where before the flag
10956	/// died in the demuxer and a downstream saw the leap as an unsignalled timebase change,
10957	/// i.e. a stream error. The same leap with nothing set at the source stays unflagged:
10958	/// the exporter reports what the source declared, and does not infer a break from a
10959	/// timestamp step.
10960	#[tokio::test(start_paused = true)]
10961	async fn a_signalled_reset_reaches_the_exported_clock() {
10962		const PID: u16 = 0x0061;
10963
10964		let media = |ts: &mut Vec<u8>, cc: &mut u8, base: u64| {
10965			for i in 0..RESET_PES {
10966				ts.extend_from_slice(&mp2_pes(PID, *cc, base + i * RESET_PES_TICKS, [0xAA, 0xBB]));
10967				*cc = (*cc + 1) & 0x0f;
10968			}
10969		};
10970
10971		let mut cc = 0;
10972		let mut before = synth_pmt(&[(StreamType::Mpeg1Audio, PID)], false);
10973		media(&mut before, &mut cc, 90_000);
10974		let mut signalled = clock_break_packet(PID);
10975		let mut unsignalled = Vec::new();
10976		let mut peer_cc = cc;
10977		media(&mut signalled, &mut cc, 90_000 + RESET_LEAP_TICKS);
10978		media(&mut unsignalled, &mut peer_cc, 90_000 + RESET_LEAP_TICKS);
10979
10980		assert_eq!(
10981			export_discontinuities(&before, &signalled).await,
10982			1,
10983			"the declared reset never reached the exported clock"
10984		);
10985		assert_eq!(
10986			export_discontinuities(&before, &unsignalled).await,
10987			0,
10988			"a leap the source did not declare must not be flagged"
10989		);
10990	}
10991
10992	/// A shared forward boundary is one program break. Every rendition joins the new
10993	/// generation, so the clock flags it once however many tracks declared the marker.
10994	#[tokio::test(start_paused = true)]
10995	async fn a_shared_forward_boundary_resets_once_per_rendition() {
10996		let mut stimulus = synth_pmt(
10997			&[(StreamType::Mpeg1Audio, PCR_PID), (StreamType::Mpeg1Audio, PEER_PID)],
10998			false,
10999		);
11000		let media = |ts: &mut Vec<u8>, cc: &mut u8, base: u64| {
11001			for i in 0..RESET_PES {
11002				for pid in [PCR_PID, PEER_PID] {
11003					ts.extend_from_slice(&mp2_pes(pid, *cc, base + i * RESET_PES_TICKS, [0xAA, 0xBB]));
11004				}
11005				*cc = (*cc + 1) & 0x0f;
11006			}
11007		};
11008
11009		let mut cc = 0;
11010		media(&mut stimulus, &mut cc, 90_000);
11011		let mut after = clock_break_packet(PCR_PID);
11012		media(&mut after, &mut cc, 90_000 + RESET_LEAP_TICKS);
11013
11014		assert_eq!(
11015			export_discontinuities(&stimulus, &after).await,
11016			1,
11017			"one flag per program break"
11018		);
11019	}
11020
11021	/// A PMT-configured track is ready at its first PTS, with its PID already in the first
11022	/// catalog. Its bounded PES need not have delivered any payload yet.
11023	#[tokio::test(start_paused = true)]
11024	async fn a_configured_track_releases_the_catalog_at_its_pes_header() {
11025		use super::super::catalog::Ext;
11026		const PID: u16 = 0x62;
11027		let mut broadcast = moq_net::broadcast::Info::new().produce();
11028		let mut initial = crate::catalog::hang::Catalog::<Ext>::default();
11029		initial.ext.mpegts.mux_rate = Some(400_000);
11030		let catalog =
11031			crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default().with_catalog(initial))
11032				.unwrap();
11033		let mut published = catalog.consume().unwrap();
11034		let mut import = super::Import::new(broadcast, catalog.reserve());
11035		let mut tables = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x100)]));
11036		tables.extend(psi_packets(
11037			0x100,
11038			&mut 0,
11039			&[],
11040			&pmt_section(1, 0, &[(0x06, PID, &[5, 4, b'O', b'p', b'u', b's'])]),
11041		));
11042		import.decode(&tables).unwrap();
11043		assert!(
11044			published.poll_next(&kio::Waiter::noop()).is_pending(),
11045			"the clock is not anchored"
11046		);
11047		let body = [0x7f, 0xe0, 3, 0xf8, 0xff, 0xfe];
11048		let mut header = vec![0, 0, 1, 0xbd, 0, 8 + body.len() as u8, 0x80, 0x80, 5];
11049		header.extend_from_slice(&pes_timestamp(2, 90_000));
11050		import.decode(&pes_fragment(PID, true, 0, &header)).unwrap();
11051		let std::task::Poll::Ready(Ok(Some(moq_json::Timed { value: first, .. }))) =
11052			published.poll_next(&kio::Waiter::noop())
11053		else {
11054			panic!("the known config and final clock release the catalog at the header");
11055		};
11056		let name = first.audio.renditions.keys().next().unwrap();
11057		assert_eq!(
11058			first.ext.mpegts.tracks[name].pid, PID,
11059			"the first snapshot carries the PID"
11060		);
11061		assert_eq!(
11062			first.sync.clock,
11063			catalog.snapshot().sync.clock,
11064			"the first snapshot carries the anchored clock"
11065		);
11066		import.decode(&pes_fragment(PID, false, 1, &body)).unwrap();
11067		let _finished = import.finish().unwrap();
11068	}
11069
11070	fn opus_extension(body: &[u8]) -> Vec<super::catalog::Descriptor> {
11071		vec![super::catalog::Descriptor {
11072			tag: 0x7f,
11073			data: bytes::Bytes::copy_from_slice(body),
11074		}]
11075	}
11076
11077	fn mapping(config: &crate::codec::opus::Config) -> (u8, u8, u8, Vec<u8>) {
11078		let mapping = config.mapping.expect("a channel mapping");
11079		(
11080			mapping.family(),
11081			mapping.streams(),
11082			mapping.coupled(),
11083			mapping.table().to_vec(),
11084		)
11085	}
11086
11087	/// Codes at 0x80 and above are the Opus-in-TS draft table, not a stereo guess.
11088	/// The 6-channel 0x81 body is the descriptor gstreamer writes for family 255
11089	/// (`[0x81, 6, 255, 160, 20, 229]`); the other bodies are hand-built from that table.
11090	#[test]
11091	fn opus_channel_codes_keep_their_layout() {
11092		let ext = |body: &[u8]| super::opus_config(&opus_extension(body));
11093
11094		let missing = super::opus_config(&[]).unwrap();
11095		assert_eq!(missing.channel_count, 2);
11096		assert!(missing.mapping.is_none(), "no descriptor stays family 0 stereo");
11097
11098		let plain = ext(&[0x80, 6]).unwrap();
11099		assert_eq!(plain.channel_count, 6);
11100		assert_eq!(mapping(&plain), (1, 4, 2, vec![0, 4, 1, 2, 3, 5]));
11101
11102		// 0x80: two independent mono streams, not one coupled stereo stream.
11103		let dual = ext(&[0x80, 0x80]).unwrap();
11104		assert_eq!(dual.channel_count, 2);
11105		assert_eq!(mapping(&dual), (255, 2, 0, vec![0, 1]));
11106
11107		// 0x82: ffmpeg's `0x80 | channels` uncoupled family 1 table.
11108		let uncoupled = ext(&[0x80, 0x82]).unwrap();
11109		assert_eq!(uncoupled.channel_count, 2);
11110		assert_eq!(mapping(&uncoupled), (1, 2, 0, vec![0, 1]));
11111
11112		let wide = ext(&[0x80, 0x88]).unwrap();
11113		assert_eq!(wide.channel_count, 8);
11114		assert_eq!(mapping(&wide), (1, 8, 0, vec![0, 1, 2, 3, 4, 5, 6, 7]));
11115
11116		// gstreamer, 6 uncoupled channels, family 255.
11117		let gst = ext(&[0x80, 0x81, 6, 255, 160, 20, 229]).unwrap();
11118		assert_eq!(gst.channel_count, 6);
11119		assert_eq!(mapping(&gst), (255, 6, 0, vec![0, 1, 2, 3, 4, 5]));
11120
11121		// Hand-built 5.1 Vorbis table: streams 4, coupled 2, map {0,4,1,2,3,5}.
11122		let surround = ext(&[0x80, 0x81, 6, 1, 0x68, 0x42, 0x9d]).unwrap();
11123		assert_eq!(surround.channel_count, 6);
11124		assert_eq!(mapping(&surround), (1, 4, 2, vec![0, 4, 1, 2, 3, 5]));
11125
11126		// Silence is the all-ones field (1 bit here), stored as 255 in the OpusHead.
11127		let silent = ext(&[0x80, 0x81, 2, 255, 0x10]).unwrap();
11128		assert_eq!(silent.channel_count, 2);
11129		assert_eq!(mapping(&silent), (255, 1, 0, vec![0, 255]));
11130
11131		let mono = ext(&[0x80, 0x81, 1, 0]).unwrap();
11132		assert_eq!(mono.channel_count, 1);
11133		assert!(mono.mapping.is_none());
11134	}
11135
11136	#[test]
11137	fn a_reserved_or_unparseable_opus_channel_code_is_refused() {
11138		let err = |body: &[u8]| {
11139			super::opus_config(&opus_extension(body))
11140				.expect_err("this code must not import")
11141				.to_string()
11142		};
11143
11144		for code in [0x09_u8, 0x7f, 0x89, 0xff] {
11145			let message = err(&[0x80, code]);
11146			assert!(message.contains("reserved"), "{code:#04x}: {message}");
11147		}
11148		assert!(err(&[0x80]).contains("no channel_config_code"));
11149		assert!(err(&[0x80, 0x81]).contains("truncated"));
11150		assert!(err(&[0x80, 0x81, 0, 1]).contains("channel_count is zero"));
11151		assert!(err(&[0x80, 0x81, 3, 0]).contains("family 0"));
11152		assert!(err(&[0x80, 0x81, 2, 0, 0]).contains("trailing"));
11153		assert!(err(&[0x80, 0x82, 0]).contains("trailing"));
11154		// Nonzero pad bits on the silence layout above (0x10 with the pad set).
11155		assert!(err(&[0x80, 0x81, 2, 255, 0x1f]).contains("reserved bits"));
11156		// Mapping index 2 with only two coded channels, and not the silence value.
11157		assert!(err(&[0x80, 0x81, 2, 255, 0x84]).contains("mapping"));
11158		// gstreamer's 4 uncoupled channels: `g_bit_storage` widths at a power of two.
11159		assert!(err(&[0x80, 0x81, 4, 255, 0x60, 0x14, 0xc0]).contains("trailing"));
11160	}
11161
11162	/// PAT/PMT for an MP2 PID plus an Opus PID whose extension body is `extension`.
11163	fn opus_program(extension: &[u8]) -> Vec<u8> {
11164		let mut descriptors = vec![0x05, 4, b'O', b'p', b'u', b's', 0x7f, extension.len() as u8];
11165		descriptors.extend_from_slice(extension);
11166		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100)]));
11167		data.extend(psi_packets(
11168			0x0100,
11169			&mut 0,
11170			&[],
11171			&pmt_section(
11172				1,
11173				0,
11174				&[
11175					(StreamType::Mpeg1Audio as u8, 0x0061, &[]),
11176					(StreamType::Mpeg2PacketizedData as u8, 0x0062, &descriptors),
11177				],
11178			),
11179		));
11180		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
11181		data
11182	}
11183
11184	fn import_program(data: &[u8]) -> crate::catalog::hang::Catalog {
11185		let mut broadcast = moq_net::broadcast::Info::new().produce();
11186		let catalog = crate::catalog::Producer::new(&mut broadcast, crate::catalog::Config::default()).unwrap();
11187		let mut import = super::Import::new(broadcast, catalog.reserve());
11188		import.decode(data).unwrap();
11189		let _finished = import.finish().unwrap();
11190		catalog.snapshot()
11191	}
11192
11193	/// A 0x81 descriptor reaches the catalog as its real OpusHead, beside the other track.
11194	#[test]
11195	fn an_explicit_opus_channel_code_publishes_its_head() {
11196		// gstreamer's 6-channel family 255 descriptor, in a hand-built program.
11197		let catalog = import_program(&opus_program(&[0x80, 0x81, 6, 255, 160, 20, 229]));
11198		assert_eq!(catalog.audio.renditions.len(), 2, "MP2 and Opus both publish");
11199
11200		let opus = catalog
11201			.audio
11202			.renditions
11203			.values()
11204			.find(|audio| audio.codec.to_string() == "opus")
11205			.expect("the Opus track");
11206		assert_eq!(opus.channel_count, 6);
11207		let head = crate::codec::opus::Config::parse(&mut opus.description.as_deref().expect("an OpusHead")).unwrap();
11208		assert_eq!(head.channel_count, 6);
11209		let map = head.mapping.expect("family 255");
11210		assert_eq!(map.family(), 255);
11211		assert_eq!((map.streams(), map.coupled()), (6, 0));
11212		assert_eq!(map.table(), &[0, 1, 2, 3, 4, 5]);
11213	}
11214
11215	/// A reserved code drops that PID. The program's other audio still imports.
11216	#[test]
11217	fn a_reserved_opus_channel_code_drops_only_that_stream() {
11218		let catalog = import_program(&opus_program(&[0x80, 0xff]));
11219		assert_eq!(catalog.audio.renditions.len(), 1, "only the MP2 track");
11220		let audio = catalog.audio.renditions.values().next().unwrap();
11221		assert_eq!(audio.codec.to_string(), "mp2");
11222	}
11223
11224	/// Repeated PMTs are quiet, while streams added by a later PMT get their own report.
11225	#[test]
11226	#[tracing_test::traced_test]
11227	fn pmt_reports_each_new_stream_once() {
11228		use crate::container::ts::psi::{Es, Pmt};
11229		let mut broadcast = moq_net::broadcast::Info::new().produce();
11230		let catalog = crate::catalog::Producer::new(
11231			&mut broadcast,
11232			crate::catalog::Config::default()
11233				.with_catalog(crate::catalog::hang::Catalog::<crate::container::ts::catalog::Ext>::default()),
11234		)
11235		.unwrap();
11236		let mut import = super::Import::new(broadcast, catalog.reserve());
11237		let mut pmt = Pmt {
11238			program_number: 1,
11239			pcr_pid: Some(Pid::new(0x100).unwrap()),
11240			program_info: Vec::new(),
11241			streams: [0x1b, 0x06, 0x05, 0x86, 0x02]
11242				.into_iter()
11243				.enumerate()
11244				.map(|(index, stream_type)| Es {
11245					stream_type,
11246					pid: Pid::new(0x100 + index as u16).unwrap(),
11247					descriptors: Vec::new(),
11248				})
11249				.collect(),
11250		};
11251		import.handle_pmt(pmt.clone()).unwrap();
11252		import.handle_pmt(pmt.clone()).unwrap();
11253		pmt.streams.push(Es {
11254			stream_type: 0x0f,
11255			pid: Pid::new(0x105).unwrap(),
11256			descriptors: Vec::new(),
11257		});
11258		import.handle_pmt(pmt).unwrap();
11259		let _finished = import.finish().unwrap();
11260		logs_assert(|lines| {
11261			let streams: Vec<_> = lines
11262				.iter()
11263				.filter(|line| line.contains("TS elementary stream"))
11264				.collect();
11265			if streams.len() != 6 {
11266				return Err(format!("expected one report per new stream, got {streams:?}"));
11267			}
11268			for (pid, stream_type, outcome, carriage) in [
11269				(256, 0x1b, "track", "decoded"),
11270				(257, 0x06, "verbatim", "pesPacket"),
11271				(258, 0x05, "verbatim", "section"),
11272				(259, 0x86, "dropped", "none"),
11273				(260, 0x02, "verbatim", "pesPacket"),
11274				(261, 0x0f, "track", "decoded"),
11275			] {
11276				if !streams.iter().any(|line| {
11277					line.contains(&format!("pid={pid} "))
11278						&& line.contains(&format!("stream_type={stream_type} "))
11279						&& line.contains(&format!("outcome=\"{outcome}\""))
11280						&& line.contains(&format!("carriage=\"{carriage}\""))
11281				}) {
11282					return Err(format!("missing {outcome} report for PID {pid}: {streams:?}"));
11283				}
11284			}
11285			Ok(())
11286		});
11287	}
11288
11289	/// A later PMT that changes a PID's route reports it again: a private PES promoted once a
11290	/// PCR appears, and a section PID refused without one remapped to a decoded codec.
11291	#[test]
11292	#[tracing_test::traced_test]
11293	fn pmt_reports_route_changes() {
11294		use crate::container::ts::psi::{Es, Pmt};
11295		let mut broadcast = moq_net::broadcast::Info::new().produce();
11296		let catalog = crate::catalog::Producer::new(
11297			&mut broadcast,
11298			crate::catalog::Config::default()
11299				.with_catalog(crate::catalog::hang::Catalog::<crate::container::ts::catalog::Ext>::default()),
11300		)
11301		.unwrap();
11302		let mut import = super::Import::new(broadcast, catalog.reserve());
11303		let pmt = |pcr_pid: Option<u16>, section_type: u8| Pmt {
11304			program_number: 1,
11305			pcr_pid: pcr_pid.map(|pid| Pid::new(pid).unwrap()),
11306			program_info: Vec::new(),
11307			streams: vec![
11308				Es {
11309					stream_type: 0x06,
11310					pid: Pid::new(0x100).unwrap(),
11311					descriptors: Vec::new(),
11312				},
11313				Es {
11314					stream_type: section_type,
11315					pid: Pid::new(0x101).unwrap(),
11316					descriptors: Vec::new(),
11317				},
11318			],
11319		};
11320		import.handle_pmt(pmt(None, 0x05)).unwrap();
11321		import.handle_pmt(pmt(Some(0x100), 0x0f)).unwrap();
11322		import.handle_pmt(pmt(Some(0x100), 0x0f)).unwrap();
11323		let _finished = import.finish().unwrap();
11324		logs_assert(|lines| {
11325			let streams: Vec<_> = lines
11326				.iter()
11327				.filter(|line| line.contains("TS elementary stream"))
11328				.collect();
11329			let expected = [
11330				(256, 0x06, "dropped", "none"),
11331				(257, 0x05, "dropped", "none"),
11332				(256, 0x06, "verbatim", "pesPacket"),
11333				(257, 0x0f, "track", "decoded"),
11334			];
11335			if streams.len() != expected.len() {
11336				return Err(format!("expected one report per route, got {streams:?}"));
11337			}
11338			for (line, (pid, stream_type, outcome, carriage)) in streams.iter().zip(expected) {
11339				if !(line.contains(&format!("pid={pid} "))
11340					&& line.contains(&format!("stream_type={stream_type} "))
11341					&& line.contains(&format!("outcome=\"{outcome}\""))
11342					&& line.contains(&format!("carriage=\"{carriage}\"")))
11343				{
11344					return Err(format!("expected {outcome}/{carriage} for PID {pid}, got {line}"));
11345				}
11346			}
11347			Ok(())
11348		});
11349	}
11350
11351	/// Section routes refuse a missing PCR PID, then return when a later PMT supplies one.
11352	#[tokio::test(start_paused = true)]
11353	async fn a_pmt_naming_or_dropping_the_pcr_reroutes_sections() {
11354		use crate::container::ts::psi::{Es, Pmt};
11355		for stream_type in [0x05, 0x86] {
11356			let mut broadcast = moq_net::broadcast::Info::new().produce();
11357			let consumer = broadcast.consume();
11358			let catalog = crate::catalog::Producer::new(
11359				&mut broadcast,
11360				crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11361			)
11362			.unwrap();
11363			let mut import = super::Import::new(broadcast, catalog.reserve());
11364			let pid = Pid::new(0x21).unwrap();
11365			let pmt = |pcr_pid| Pmt {
11366				program_number: 1,
11367				pcr_pid,
11368				program_info: vec![super::catalog::Descriptor {
11369					tag: 5,
11370					data: bytes::Bytes::from_static(b"CUEI"),
11371				}],
11372				streams: vec![
11373					Es {
11374						stream_type: 0x02,
11375						pid: Pid::new(PCR_PID).unwrap(),
11376						descriptors: Vec::new(),
11377					},
11378					Es {
11379						stream_type,
11380						pid,
11381						descriptors: Vec::new(),
11382					},
11383				],
11384			};
11385			import.handle_pmt(pmt(None)).unwrap();
11386			import.handle_pmt(pmt(None)).unwrap();
11387			assert_eq!(import.stats().streams[&0x21].refused, 1, "once per refused route");
11388			assert!(catalog.snapshot().ext.mpegts.tracks.is_empty());
11389			assert!(matches!(import.streams[&pid], super::Stream::Ignored));
11390			import.handle_pmt(pmt(Some(Pid::new(PCR_PID).unwrap()))).unwrap();
11391			let name = track_on(&catalog.snapshot().ext.mpegts, 0x21);
11392			let data = [
11393				pcr_packet(PCR_PID, 27_000_000),
11394				pes_packet(PCR_PID, 99_000),
11395				packet(true, 0, 0, &CUE),
11396				pcr_packet(PCR_PID, 29_700_000),
11397				pcr_packet(PCR_PID, 32_400_000),
11398			]
11399			.concat();
11400			import.decode(&data).unwrap();
11401			let track = consumer
11402				.track(&name)
11403				.unwrap()
11404				.subscribe(
11405					moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
11406						moq_net::track::Start::Live {
11407							min: Some(RECORDING_MAX_AGE),
11408							max: Some(RECORDING_MAX_AGE),
11409						},
11410					)]),
11411				)
11412				.await
11413				.unwrap();
11414			let mut reader = crate::container::Consumer::new(
11415				track,
11416				crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
11417			);
11418			assert_eq!(reader.read_frame().await.unwrap().unwrap().payload.as_ref(), CUE);
11419			import.handle_pmt(pmt(None)).unwrap();
11420			assert_eq!(import.stats().streams[&0x21].refused, 2);
11421			assert!(
11422				reader.read_frame().await.is_err(),
11423				"losing the PCR ends the track with an error"
11424			);
11425			assert!(catalog.snapshot().ext.mpegts.tracks.is_empty());
11426			import.handle_pmt(pmt(Some(Pid::new(PCR_PID).unwrap()))).unwrap();
11427			let next = track_on(&catalog.snapshot().ext.mpegts, 0x21);
11428			assert_ne!(next, name, "restoring a stream publishes a new track");
11429			let _finished = import.finish().unwrap();
11430		}
11431	}
11432
11433	/// A PID refused as private PES for want of a PCR routes again when a later PMT gives it a
11434	/// type that needs no PCR, though the program still has none.
11435	#[test]
11436	fn an_unclocked_pid_reassigned_to_a_decoded_type_routes_again() {
11437		use crate::container::ts::psi::{Es, Pmt};
11438		let mut broadcast = moq_net::broadcast::Info::new().produce();
11439		let catalog = crate::catalog::Producer::new(
11440			&mut broadcast,
11441			crate::catalog::Config::default()
11442				.with_catalog(crate::catalog::hang::Catalog::<crate::container::ts::catalog::Ext>::default()),
11443		)
11444		.unwrap();
11445		let mut import = super::Import::new(broadcast, catalog.reserve());
11446		let pid = Pid::new(0x104).unwrap();
11447		let pmt = |stream_type| Pmt {
11448			program_number: 1,
11449			pcr_pid: None,
11450			program_info: Vec::new(),
11451			streams: vec![Es {
11452				stream_type,
11453				pid,
11454				descriptors: Vec::new(),
11455			}],
11456		};
11457		import.handle_pmt(pmt(0x06)).unwrap();
11458		assert!(matches!(import.streams[&pid], super::Stream::Ignored));
11459		import.handle_pmt(pmt(0x06)).unwrap();
11460		assert_eq!(import.stats().streams[&0x104].refused, 1, "refused once, not per PMT");
11461		import.handle_pmt(pmt(StreamType::H264 as u8)).unwrap();
11462		assert!(matches!(import.streams[&pid], super::Stream::H264 { .. }));
11463	}
11464
11465	/// A PMT that changes a decoded stream's ES descriptors, here an audio language retag,
11466	/// finishes its track: its rendition and `mpegts` entry leave the catalog, and the next PES
11467	/// opens a rendition under a new name whose entry records the revised descriptors.
11468	#[test]
11469	fn a_relabelled_decoded_stream_reopens_under_a_new_name() {
11470		use crate::container::ts::psi::{Es, Pmt};
11471		const AUDIO_PID: u16 = 0x0061;
11472		let mut broadcast = moq_net::broadcast::Info::new().produce();
11473		let catalog = crate::catalog::Producer::new(
11474			&mut broadcast,
11475			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11476		)
11477		.unwrap();
11478		let mut import = super::Import::new(broadcast, catalog.reserve());
11479		let pmt = |language: &'static [u8]| Pmt {
11480			program_number: 1,
11481			pcr_pid: Some(Pid::new(AUDIO_PID).unwrap()),
11482			program_info: Vec::new(),
11483			streams: vec![Es {
11484				stream_type: MP2,
11485				pid: Pid::new(AUDIO_PID).unwrap(),
11486				descriptors: vec![super::catalog::Descriptor {
11487					tag: 0x0a,
11488					data: bytes::Bytes::from_static(language),
11489				}],
11490			}],
11491		};
11492		let language = |catalog: &crate::catalog::hang::Catalog<Ext>, name: &str| {
11493			catalog.ext.mpegts.tracks[name].descriptors[0].data.clone()
11494		};
11495
11496		import.handle_pmt(pmt(b"eng\0")).unwrap();
11497		// The legacy path publishes once a later PES confirms the frames before it.
11498		import.decode(&mp2_pes(AUDIO_PID, 0, 90_000, [0xAA, 0xBB])).unwrap();
11499		import.decode(&mp2_pes(AUDIO_PID, 1, 180_000, [0xAA, 0xBB])).unwrap();
11500		let before = catalog.snapshot();
11501		let old = before
11502			.audio
11503			.renditions
11504			.keys()
11505			.next()
11506			.expect("the MP2 rendition")
11507			.clone();
11508		assert_eq!(language(&before, &old).as_ref(), b"eng\0");
11509
11510		import.handle_pmt(pmt(b"fra\0")).unwrap();
11511		let between = catalog.snapshot();
11512		assert!(
11513			between.audio.renditions.is_empty(),
11514			"the old rendition left the catalog"
11515		);
11516		assert!(between.ext.mpegts.tracks.is_empty(), "the old entry left the catalog");
11517
11518		import.decode(&mp2_pes(AUDIO_PID, 2, 270_000, [0xCC, 0xDD])).unwrap();
11519		import.decode(&mp2_pes(AUDIO_PID, 3, 360_000, [0xCC, 0xDD])).unwrap();
11520		let after = catalog.snapshot();
11521		let new = after
11522			.audio
11523			.renditions
11524			.keys()
11525			.next()
11526			.expect("the relabelled rendition")
11527			.clone();
11528		assert_ne!(new, old);
11529		assert_eq!(language(&after, &new).as_ref(), b"fra\0");
11530		let _finished = import.finish().unwrap();
11531	}
11532
11533	/// The program descriptors follow each PMT revision in place, and adding or removing the
11534	/// 'CUEI' registration reroutes the 0x86 PID: carried as cues under it, dropped without it,
11535	/// and carried under a new name when it returns.
11536	#[test]
11537	fn program_descriptors_follow_the_pmt_and_reroute_the_cue_pid() {
11538		use crate::container::ts::psi::{Es, Pmt};
11539		const CUE_PID: u16 = 0x0021;
11540		let mut broadcast = moq_net::broadcast::Info::new().produce();
11541		let catalog = crate::catalog::Producer::new(
11542			&mut broadcast,
11543			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11544		)
11545		.unwrap();
11546		let mut import = super::Import::new(broadcast, catalog.reserve());
11547		let descriptor = |tag, data: &'static [u8]| super::catalog::Descriptor {
11548			tag,
11549			data: bytes::Bytes::from_static(data),
11550		};
11551		let pmt = |program_info: Vec<super::catalog::Descriptor>| Pmt {
11552			program_number: 1,
11553			pcr_pid: Some(Pid::new(PCR_PID).unwrap()),
11554			program_info,
11555			streams: vec![
11556				Es {
11557					stream_type: StreamType::Mpeg2Video as u8,
11558					pid: Pid::new(PCR_PID).unwrap(),
11559					descriptors: Vec::new(),
11560				},
11561				Es {
11562					stream_type: StreamType::Dts8ChannelLosslessAudio as u8,
11563					pid: Pid::new(CUE_PID).unwrap(),
11564					descriptors: Vec::new(),
11565				},
11566			],
11567		};
11568		let cues = || {
11569			let tracks = catalog.snapshot().ext.mpegts.tracks;
11570			tracks
11571				.into_iter()
11572				.find(|(_, track)| track.pid == CUE_PID)
11573				.map(|(name, _)| name)
11574		};
11575
11576		let cuei = vec![descriptor(0x05, b"CUEI")];
11577		import.handle_pmt(pmt(cuei.clone())).unwrap();
11578		assert_eq!(catalog.snapshot().ext.mpegts.program_descriptors, cuei);
11579		let first = cues().expect("cues under CUEI");
11580
11581		let private = vec![descriptor(0x80, &[0xaa, 0xbb])];
11582		import.handle_pmt(pmt(private.clone())).unwrap();
11583		assert_eq!(catalog.snapshot().ext.mpegts.program_descriptors, private);
11584		assert_eq!(cues(), None, "without CUEI the PID is not cues");
11585		assert!(matches!(
11586			import.streams.get(&Pid::new(CUE_PID).unwrap()),
11587			Some(super::Stream::Ignored)
11588		));
11589
11590		import.handle_pmt(pmt(cuei.clone())).unwrap();
11591		assert_eq!(catalog.snapshot().ext.mpegts.program_descriptors, cuei);
11592		let second = cues().expect("cues under CUEI again");
11593		assert_ne!(second, first, "the returning cue stream gets a new name");
11594
11595		import.handle_pmt(pmt(Vec::new())).unwrap();
11596		assert!(catalog.snapshot().ext.mpegts.program_descriptors.is_empty());
11597	}
11598
11599	/// A PAT that names the program under another `transport_stream_id`, or a single-program
11600	/// import's PAT naming another program, refuses the import: the carried SI describes the
11601	/// first. A repeated PAT does not.
11602	#[test]
11603	fn a_pat_naming_another_identity_refuses_the_import() {
11604		use crate::container::ts::psi::{Association, Pat};
11605		let pat = |transport_stream_id, program_number| Pat {
11606			transport_stream_id,
11607			programs: vec![Association {
11608				program_number,
11609				pmt_pid: Pid::new(0x20).unwrap(),
11610			}],
11611		};
11612		for (selected, transport_stream_id, program_number) in [(None, 2, 1), (None, 1, 2), (Some(1), 2, 1)] {
11613			let (_catalog, import) = psi_import();
11614			let mut import = match selected {
11615				Some(program) => import.with_program(program),
11616				None => import,
11617			};
11618			import.handle_pat(&pat(1, 1)).unwrap();
11619			import.handle_pat(&pat(1, 1)).unwrap();
11620			let err = import
11621				.handle_pat(&pat(transport_stream_id, program_number))
11622				.expect_err("another identity is refused");
11623			assert!(
11624				matches!(&err, super::Error::Unsupported(msg) if msg.contains("identity")),
11625				"{err}"
11626			);
11627		}
11628	}
11629
11630	/// A PAT that moves the PMT to another PID moves the import with it: the catalog records
11631	/// the new PID, the PMT there revises the program, and the old PID no longer speaks for it.
11632	#[test]
11633	fn a_moved_pmt_is_followed() {
11634		use super::super::fixture::Mux;
11635		let mut broadcast = moq_net::broadcast::Info::new().produce();
11636		let catalog = crate::catalog::Producer::new(
11637			&mut broadcast,
11638			crate::catalog::Config::default()
11639				.with_catalog(crate::catalog::hang::Catalog::<crate::container::ts::catalog::Ext>::default()),
11640		)
11641		.unwrap();
11642		let mut import = super::Import::new(broadcast, catalog.reserve());
11643		let pmt_pid = || {
11644			catalog
11645				.snapshot()
11646				.ext
11647				.mpegts
11648				.program
11649				.as_ref()
11650				.map(|program| program.pmt_pid)
11651		};
11652
11653		let mut mux = Mux::default();
11654		mux.pat(&[(1, 0x100)]).pmt(0x100, 1, 0x61, &[(MP2, 0x61)], 0);
11655		mux.out.extend(mp2_pes(0x61, 0, 90_000, [0xAA, 0xBB]));
11656		import.decode(&std::mem::take(&mut mux.out)).unwrap();
11657		assert_eq!(pmt_pid(), Some(0x100));
11658
11659		mux.pat(&[(1, 0x200)])
11660			.pmt(0x200, 1, 0x61, &[(MP2, 0x61), (MP2, 0x62)], 0)
11661			.pmt(0x100, 1, 0x61, &[], 0);
11662		mux.out.extend(mp2_pes(0x61, 1, 108_000, [0xAA, 0xBB]));
11663		mux.out.extend(mp2_pes(0x62, 0, 108_000, [0xCC, 0xDD]));
11664		import.decode(&mux.out).unwrap();
11665		let _finished = import.finish().unwrap();
11666		assert_eq!(pmt_pid(), Some(0x200));
11667		assert_eq!(
11668			catalog.snapshot().audio.renditions.len(),
11669			2,
11670			"the PMT on the new PID adds a stream, and the one on the old PID removes none"
11671		);
11672	}
11673
11674	/// A section-framed PID the PMT drops keeps its stats row, so what it delivered stays counted.
11675	#[test]
11676	fn a_dropped_section_route_keeps_its_stats_row() {
11677		const VIDEO_PID: u16 = 0x0050;
11678		let mut broadcast = moq_net::broadcast::Info::new().produce();
11679		let catalog = crate::catalog::Producer::new(
11680			&mut broadcast,
11681			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11682		)
11683		.unwrap();
11684		let mut import = super::Import::new(broadcast, catalog.reserve());
11685		let streams = [
11686			(StreamType::Mpeg2Video, VIDEO_PID),
11687			(StreamType::Dts8ChannelLosslessAudio, 0x21),
11688		];
11689		let mut bytes = synth_pmt(&streams, true);
11690		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 27_000_000));
11691		bytes.extend_from_slice(&pes_packet(VIDEO_PID, 99_000));
11692		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
11693		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 29_700_000));
11694		bytes.extend_from_slice(&synth_pmt(&streams[..1], true));
11695		import.decode(&bytes).unwrap();
11696
11697		let row = &import.stats().streams[&0x21];
11698		assert_eq!((row.units, row.quiet), (1, None));
11699	}
11700
11701	/// A PMT dropping a section PID before any media timestamp anchors the clock refuses the
11702	/// import, as end of input does, rather than drop the section it holds.
11703	#[test]
11704	fn a_section_route_dropped_before_the_media_clock_refuses_the_import() {
11705		const VIDEO_PID: u16 = 0x0050;
11706		let mut broadcast = moq_net::broadcast::Info::new().produce();
11707		let catalog = crate::catalog::Producer::new(
11708			&mut broadcast,
11709			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11710		)
11711		.unwrap();
11712		let mut import = super::Import::new(broadcast, catalog.reserve());
11713		let streams = [
11714			(StreamType::Mpeg2Video, VIDEO_PID),
11715			(StreamType::Dts8ChannelLosslessAudio, 0x21),
11716		];
11717		let mut bytes = synth_pmt(&streams, true);
11718		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 27_000_000));
11719		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
11720		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 29_700_000));
11721		import.decode(&bytes).unwrap();
11722
11723		let err = import.decode(&synth_pmt(&streams[..1], true)).unwrap_err();
11724		assert!(
11725			matches!(&err, super::Error::Malformed(msg) if msg.contains("without a media timestamp")),
11726			"{err:#}"
11727		);
11728		assert!(import.sections.contains_key(&0x21), "the route is left for `abort`");
11729	}
11730
11731	/// A PMT dropping a section PID past a lone PCR ends it as end of input would: the section
11732	/// no PCR interval places is counted unplaced.
11733	#[test]
11734	fn a_section_route_dropped_past_a_lone_pcr_counts_its_section_unplaced() {
11735		const VIDEO_PID: u16 = 0x0050;
11736		let mut broadcast = moq_net::broadcast::Info::new().produce();
11737		let catalog = crate::catalog::Producer::new(
11738			&mut broadcast,
11739			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11740		)
11741		.unwrap();
11742		let mut import = super::Import::new(broadcast, catalog.reserve());
11743		let streams = [
11744			(StreamType::Mpeg2Video, VIDEO_PID),
11745			(StreamType::Dts8ChannelLosslessAudio, 0x21),
11746		];
11747		let mut bytes = synth_pmt(&streams, true);
11748		bytes.extend_from_slice(&pcr_packet(VIDEO_PID, 27_000_000));
11749		bytes.extend_from_slice(&pes_packet(VIDEO_PID, 99_000));
11750		bytes.extend_from_slice(&packet(true, 0, 0, &CUE));
11751		bytes.extend_from_slice(&synth_pmt(&streams[..1], true));
11752		import.decode(&bytes).unwrap();
11753
11754		let row = &import.stats().streams[&0x21];
11755		assert_eq!((row.units, row.unplaced), (0, 1));
11756		assert!(!import.sections.contains_key(&0x21));
11757	}
11758
11759	/// A PID decoded as audio, then revised to private sections, then dropped, reports the
11760	/// section route it ended on.
11761	#[test]
11762	fn a_dropped_route_reports_the_route_it_ended_on() {
11763		use crate::container::ts::psi::{Es, Pmt};
11764		const AUDIO_PID: u16 = 0x0062;
11765		let mut broadcast = moq_net::broadcast::Info::new().produce();
11766		let catalog = crate::catalog::Producer::new(
11767			&mut broadcast,
11768			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11769		)
11770		.unwrap();
11771		let mut import = super::Import::new(broadcast, catalog.reserve());
11772		let pmt = |streams: &[u8]| Pmt {
11773			program_number: 1,
11774			pcr_pid: Some(Pid::new(PCR_PID).unwrap()),
11775			program_info: Vec::new(),
11776			streams: streams
11777				.iter()
11778				.map(|&stream_type| Es {
11779					stream_type,
11780					pid: Pid::new(AUDIO_PID).unwrap(),
11781					descriptors: Vec::new(),
11782				})
11783				.collect(),
11784		};
11785
11786		import.handle_pmt(pmt(&[MP2])).unwrap();
11787		import.decode(&mp2_pes(AUDIO_PID, 0, 90_000, [0xAA, 0xBB])).unwrap();
11788		import.decode(&mp2_pes(AUDIO_PID, 1, 180_000, [0xAA, 0xBB])).unwrap();
11789		import.handle_pmt(pmt(&[0x05])).unwrap();
11790		import.handle_pmt(pmt(&[])).unwrap();
11791
11792		let row = &import.stats().streams[&AUDIO_PID];
11793		assert_eq!((row.track.as_str(), row.class), (".ts", super::stats::Class::Data));
11794	}
11795
11796	/// Ending a self-describing audio route drains the frame it held for a successor, and its
11797	/// counters include that frame.
11798	#[test]
11799	fn a_dropped_audio_route_counts_the_frame_its_end_drains() {
11800		use crate::container::ts::psi::{Es, Pmt};
11801		let mut broadcast = moq_net::broadcast::Info::new().produce();
11802		let catalog = crate::catalog::Producer::new(
11803			&mut broadcast,
11804			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11805		)
11806		.unwrap();
11807		let mut import = super::Import::new(broadcast, catalog.reserve());
11808		let pmt = |streams: Vec<Es>| Pmt {
11809			program_number: 1,
11810			pcr_pid: Some(Pid::new(PCR_PID).unwrap()),
11811			program_info: Vec::new(),
11812			streams,
11813		};
11814		let audio = Es {
11815			stream_type: MP2,
11816			pid: Pid::new(PCR_PID).unwrap(),
11817			descriptors: Vec::new(),
11818		};
11819
11820		// The second frame spans two PES, so it begins in a carried tail and is held for a
11821		// successor header that never comes.
11822		let (mut head, second) = (mp2_frame(0xAA), mp2_frame(0xBB));
11823		head.extend_from_slice(&second[..36]);
11824		import.handle_pmt(pmt(vec![audio])).unwrap();
11825		import.decode(&audio_pes_packet(PCR_PID, 0, 90_000, &head)).unwrap();
11826		import
11827			.decode(&audio_pes_packet(PCR_PID, 1, 92_160, &second[36..]))
11828			.unwrap();
11829		assert_eq!(import.stats().streams[&PCR_PID].unconfirmed, 0);
11830		import.handle_pmt(pmt(Vec::new())).unwrap();
11831
11832		assert_eq!(import.stats().streams[&PCR_PID].unconfirmed, 1);
11833	}
11834
11835	/// A source revising its PMT without end holds only its live routes: each revision ends a
11836	/// decoded or verbatim route, refuses one for a lost PCR, or rewrites the program descriptors,
11837	/// and none leaves its track's HLS records or catalog entry behind.
11838	#[test]
11839	fn pmt_churn_keeps_flat_state() {
11840		use crate::container::ts::psi::{Es, Pmt};
11841		// Each round of three revisions ends where it started.
11842		const ROUNDS: u32 = 333;
11843		let mut broadcast = moq_net::broadcast::Info::new().produce();
11844		let catalog = crate::catalog::Producer::new(
11845			&mut broadcast,
11846			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11847		)
11848		.unwrap();
11849		let mut import = super::Import::new(broadcast, catalog.reserve());
11850		let pmt = |revision: u32| {
11851			// A decoded H.264 route, a private PES route, then the same one refused for want of a PCR.
11852			let (stream_type, pcr) = match revision % 3 {
11853				0 => (StreamType::H264 as u8, true),
11854				1 => (0x06, true),
11855				_ => (0x06, false),
11856			};
11857			Pmt {
11858				program_number: 1,
11859				pcr_pid: pcr.then(|| Pid::new(PCR_PID).unwrap()),
11860				program_info: vec![super::catalog::Descriptor {
11861					tag: 0x80,
11862					data: bytes::Bytes::copy_from_slice(&revision.to_be_bytes()),
11863				}],
11864				streams: vec![Es {
11865					stream_type,
11866					pid: Pid::new(0x0062).unwrap(),
11867					descriptors: Vec::new(),
11868				}],
11869			}
11870		};
11871		let state = |import: &super::Import<Ext>| {
11872			let snapshot = catalog.snapshot();
11873			(
11874				snapshot.ext.mpegts.tracks.len(),
11875				import.streams.len() + import.sections.len() + import.listed.len() + import.retired_stats.len(),
11876			)
11877		};
11878
11879		for revision in 0..6 {
11880			import.handle_pmt(pmt(revision)).unwrap();
11881		}
11882		let settled = state(&import);
11883		for revision in 6..3 * ROUNDS {
11884			import.handle_pmt(pmt(revision)).unwrap();
11885		}
11886		assert_eq!(state(&import), settled);
11887	}
11888
11889	/// The first PMT records its program descriptors over whatever the catalog held, even when it
11890	/// carries none.
11891	#[test]
11892	fn the_first_pmt_records_its_program_descriptors_even_when_empty() {
11893		use crate::container::ts::psi::{Es, Pmt};
11894		let mut broadcast = moq_net::broadcast::Info::new().produce();
11895		let mut catalog = crate::catalog::Producer::new(
11896			&mut broadcast,
11897			crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
11898		)
11899		.unwrap();
11900		catalog
11901			.modify(catalog.next_timestamp())
11902			.unwrap()
11903			.ext
11904			.mpegts
11905			.program_descriptors = vec![super::catalog::Descriptor {
11906			tag: 0x80,
11907			data: bytes::Bytes::from_static(&[0xaa]),
11908		}];
11909		let mut import = super::Import::new(broadcast, catalog.reserve());
11910		import
11911			.handle_pmt(Pmt {
11912				program_number: 1,
11913				pcr_pid: Some(Pid::new(PCR_PID).unwrap()),
11914				program_info: Vec::new(),
11915				streams: vec![Es {
11916					stream_type: StreamType::Mpeg2Video as u8,
11917					pid: Pid::new(PCR_PID).unwrap(),
11918					descriptors: Vec::new(),
11919				}],
11920			})
11921			.unwrap();
11922
11923		assert!(catalog.snapshot().ext.mpegts.program_descriptors.is_empty());
11924	}
11925}