Skip to main content

moq_mux/container/ts/
export.rs

1//! MPEG-TS muxer.
2//!
3//! [`Export`] subscribes to a MoQ broadcast and produces MPEG-TS: PAT/PMT program
4//! tables and PES packets, packetized into 188-byte TS packets, with a PCR on a
5//! fixed media-time grid. Output is sliced on that grid rather than per media
6//! frame (the schedule): each [`Frame`] is one slot, opened by its PCR, plus the
7//! bytes belonging to it. At a multiplex rate the PCR rides the adaptation field
8//! of the clock PID's packet when one can open the slot; otherwise it takes an
9//! adaptation-field-only packet of its own. Each frame is stamped at the slot
10//! boundary, so the clock a receiver recovers from byte
11//! position agrees with the values, and a pacing caller releases each slot at
12//! the instant it asserts. Video is carried as Annex-B, audio as ADTS AAC.
13//!
14//! Every frame is muxed a fixed delay after its release time, its decode time less its
15//! send-ahead ([`Export::new`]), so tracks interleave in one order whatever the
16//! arrival skew between them, and the output keeps the source's pace.
17//!
18//! Video flows through `ExportSource`, which normalizes every H.264/H.265
19//! source to length-prefixed NALU plus a resolved avcC/hvcC (parsing the
20//! parameter sets out of an Annex-B bitstream, or taking the catalog
21//! `description` for a length-prefixed one). The muxer then does one
22//! length-prefixed -> Annex-B conversion, re-injecting the parameter sets as
23//! inline NALs on every keyframe. CMAF tracks are rejected with a clear error.
24
25use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
26use std::task::Poll;
27use std::time::Duration;
28
29use bytes::Bytes;
30use hang::catalog::{AudioCodec, AudioConfig, Container, VideoCodec, VideoConfig};
31use mpeg2ts::es::StreamId;
32use mpeg2ts::es::StreamType;
33use mpeg2ts::time::Timestamp as TsTimestamp;
34use mpeg2ts::ts::payload::{Bytes as TsBytes, Pat, Pes, Section};
35use mpeg2ts::ts::{
36	AdaptationField, ContinuityCounter, Pid, ProgramAssociation, TransportScramblingControl, TsHeader, TsPacket,
37	TsPacketWriter, TsPayload, VersionNumber, WriteTsPacket,
38};
39
40use moq_net::Timestamp;
41use rustc_hash::FxHashMap;
42
43use super::catalog::Catalog as _;
44use super::error::{Context, Error, Result, bail_unsupported, ensure, ensure_supported, malformed, unsupported};
45use crate::catalog::Stream;
46use crate::catalog::hang::Catalog;
47use crate::codec::annexb::InBandCodec;
48use crate::codec::video::{Hrd, Reorder};
49use crate::codec::{aac, annexb, opus};
50use crate::container::consumer::Event;
51use crate::container::declared::DeclaredClock;
52use crate::container::decode::{DecodeClock, MAX_REORDER, Settle};
53use crate::container::{ExportSource, Frame};
54use crate::jitter::{self, Arrival, Push};
55
56use super::adts;
57use super::catalog;
58use super::psi;
59use super::schedule::{self, Buffer, Schedule};
60
61/// PID of the single program's PMT.
62const PMT_PID: u16 = 0x1000;
63/// First elementary-stream PID; each track gets the next one.
64const FIRST_ES_PID: u16 = 0x1001;
65/// Re-emit PAT/PMT at least this often (wall-clock of the media) for tune-in.
66const PSI_INTERVAL: Duration = Duration::from_millis(500);
67/// The cadence of changed SI snapshots, bounding how fast a revising publisher
68/// can make the mux re-emit its tables. Clock revisions use an absolute grid;
69/// ordinary SI measures from the last emission. The import side
70/// debounces its own snapshot cuts (`si::DEBOUNCE`), but export consumes any
71/// catalog-named snapshot track, so the bound cannot live only there; this one is
72/// enforced on the media timeline. Clamped to the entry's own interval, so a
73/// table asking for faster repetition than this still gets it.
74const SI_REVISION_INTERVAL: Duration = Duration::from_secs(1);
75/// Emit a PCR on every crossing of this media-time grid ([`Schedule`]).
76/// TR 101 290 V1.4.1 flags a gap over 100 ms; broadcast muxes emit every 25-40 ms.
77pub(super) const PCR_INTERVAL: Duration = Duration::from_millis(25);
78/// A null packet: PID 0x1FFF, payload only, all stuffing. Its continuity counter
79/// is don't-care (ISO 13818-1), so one template serves every one.
80pub(super) const NULL_PACKET: [u8; TsPacket::SIZE] = {
81	let mut packet = [0xff; TsPacket::SIZE];
82	packet[0] = 0x47;
83	packet[1] = 0x1f;
84	packet[2] = 0xff;
85	packet[3] = 0x10;
86	packet
87};
88/// Upper bound on an accepted multiplex rate, in bits per second: far above any
89/// broadcast contribution multiplex, while bounding one slot's null allocation
90/// to a few megabytes. Zero and anything past it are refused where they enter,
91/// leaving the output unpadded.
92const MAX_MUX_RATE: u64 = 1_000_000_000;
93
94/// A multiplex rate from the builder override or the (untrusted) catalog is only
95/// worth padding to when it is a real rate: zero pads nothing, and anything past
96/// [`MAX_MUX_RATE`] would allocate unbounded nulls per slot. Invalid rates are
97/// refused, leaving the output unpadded.
98fn sanitize_mux_rate(rate: u64) -> Option<u64> {
99	(1..=MAX_MUX_RATE).contains(&rate).then_some(rate)
100}
101
102/// The multiplex a source that recorded `rate` is padded to: a packet a slot more, for the
103/// export's own framing. Every slot carries a clock, and a PES holds no more than the decoder
104/// buffer, where a source may clock only each PES and pack more: FFmpeg's default audio has no
105/// nulls and a clock only every 186 ms, so its recorded rate has no room for either.
106fn padded(rate: u64) -> u64 {
107	rate.saturating_add(schedule::PACKET)
108}
109
110/// The rate a multiplex needs when its delay is too short to send audio a slot ahead: each slot
111/// then carries the AAC its own decode times hold, as much as two frames, beside a clock and
112/// tables. Sent further ahead, the audio spreads over slots and needs no floor.
113fn audio_floor(catalog: &Catalog<impl catalog::Catalog>) -> u64 {
114	let packets: u64 = catalog
115		.audio
116		.renditions
117		.iter()
118		.filter(|(_, config)| matches!(config.codec, AudioCodec::AAC(_)))
119		.filter_map(|(name, config)| {
120			// The catalog is untrusted: no frame outgrows the decoder buffer that holds it.
121			let size = audio_buffer(config, &audio_kind(config, name).ok()?).size?;
122			let frame = (config.bitrate? / 8 * 1024 / u64::from(config.sample_rate.max(1))).min(size as u64);
123			let pes = 2 * frame + (adts::MIN_HEADER_LEN + PES_PREFIX_LEN + PES_OPTIONAL_LEN) as u64;
124			Some(pes.div_ceil(schedule::PAYLOAD as u64))
125		})
126		.fold(0, u64::saturating_add);
127	match packets {
128		0 => 0,
129		packets => packets
130			.saturating_add(3)
131			.saturating_mul(schedule::PACKET)
132			.min(MAX_MUX_RATE),
133	}
134}
135
136/// Subscribe to a broadcast and produce an MPEG-TS byte stream.
137///
138/// Use [`poll_next`](Self::poll_next) to pull one [`Frame`] per PCR grid slot: its `payload`
139/// is the TS packets belonging to that slot, stamped at the slot's boundary. The
140/// leading PAT/PMT rides on the first frame (so it inherits a real timestamp), and
141/// is re-emitted at video keyframes and periodically for mid-stream tune-in. SI and
142/// whole PES or sections wait until a PCR interval has followed it, since a reader
143/// places them on the program clock and the PMT is what names it.
144/// Returns `None` once the catalog ends and its media drains. Finishing only the media
145/// tracks keeps it waiting for catalog updates. A publisher that leaves instead fails the
146/// export with its cause once what was already buffered has gone out on schedule.
147///
148/// A rendition the catalog moves to another track (a new `track` or `broadcast`) goes on out
149/// of its PID from the new track's first sync frame past what was read, when the PMT can
150/// announce it unchanged; one that goes back in time fails the export.
151pub struct Export<S: Stream>
152where
153	S::Ext: catalog::Catalog,
154{
155	program: Program<S>,
156	jitter: jitter::Buffer<TrackKey, Queued>,
157	held: Option<jitter::Ready<TrackKey, Queued>>,
158	pending: Option<Box<Program<S>>>,
159	next_program: u64,
160	active_program: u64,
161	follow_until: Option<kio::clock::Instant>,
162	follow_timer: Option<std::pin::Pin<Box<kio::clock::Sleep>>>,
163	/// When a read last found nothing more due: the output had caught up then ([`Self::shed`]).
164	caught_up: Option<kio::clock::Instant>,
165}
166
167/// Input and mux state belonging to one publisher identity. The release clock
168/// stays on the export so a replacement cannot discard the program still playing.
169struct Program<S: Stream>
170where
171	S::Ext: catalog::Catalog,
172{
173	id: u64,
174	expected: Vec<TrackKey>,
175	expected_changed: bool,
176	source: crate::Source,
177	/// Kept once read no further, for its format, which a follower subscribes a return with,
178	/// until a follow runs out on it: a replacement is then selected, and the subscription goes.
179	catalog: Option<S>,
180	/// A snapshot arrived on `catalog` since it was subscribed.
181	cataloged: bool,
182	feed: Feed,
183	/// The identity of the broadcast being exported, `None` for one not resolved through an
184	/// origin.
185	identity: Option<moq_net::Identity>,
186	/// The PMT `version_number` the program's first tables go out at, advanced by each switch to
187	/// another identity so a demux that caches tables by version reads the new ones.
188	version: VersionNumber,
189	/// The PAT's, advanced by each switch alike.
190	pat_version: VersionNumber,
191	/// After a switch to another identity, the PIDs whose first packet is queued flagging the
192	/// break. `None` for an export that never switched.
193	flagged: Option<HashSet<u16>>,
194	/// How long after its decode time each frame goes out.
195	delay: Duration,
196	/// Jitter-buffer generation of the program being muxed; a newer one rewinds it.
197	generation: u64,
198
199	tracks: HashMap<String, Track>,
200	/// SI muxed with frames still packed, which rides ahead of the next unit queued, so it
201	/// goes out in the order it was written.
202	tables: Vec<u8>,
203	/// The program tables are due ahead of the next unit queued.
204	psi_due: bool,
205	/// The program tables changed, so the next frame muxed is a tune-in point that leads with them.
206	revised: bool,
207	/// The next continuity counter per PID, numbered as packets go out.
208	counters: FxHashMap<u16, u8>,
209	/// PMT program-level descriptors captured on import, re-emitted in the PMT.
210	program_descriptors: Vec<catalog::Descriptor>,
211	/// Transport/service identity captured on import, used to rebuild a consistent
212	/// PAT/PMT. `None` for a media-only source, so a minimal identity is synthesized.
213	program: Option<catalog::Program>,
214	/// Standalone SI subscriptions, keyed by `(PID, table_id)` from the catalog's
215	/// `mpegts.si` map. Each reduces its snapshot track into the section set
216	/// re-emitted verbatim on its PID at its own cadence. Opaque: export never
217	/// parses a table it carries.
218	si: BTreeMap<(u16, u8), SiTrack>,
219	/// Timestamp of the last emitted frame, stamped onto the trailing SI flush.
220	last_timestamp: Option<Timestamp>,
221	/// The trailing SI flush ran (once, just before end of stream).
222	si_flushed: bool,
223
224	/// Program tables, built once the track layout is known and revised as it changes.
225	psi: Option<Psi>,
226	/// Media timestamp of the last PAT/PMT emission ([`due`]).
227	last_psi: Option<Timestamp>,
228	/// Program generation being muxed; source counters are local to each rendition.
229	epoch: u64,
230	/// Generation of the last returned frame, updated only at the output boundary.
231	emitted_epoch: u64,
232	pcr_discontinuity: bool,
233	/// Lays the muxed packets onto the PCR grid.
234	schedule: Schedule,
235	/// Read each track from the oldest group the delay still reaches, rather than the live
236	/// edge: a test exporting a broadcast it wrote whole.
237	replay: bool,
238	/// Wakes the export when the next grid slot is due on the jitter buffer's clock.
239	slot_timer: Option<std::pin::Pin<Box<kio::clock::Sleep>>>,
240	/// Output frames ready to hand out, one per grid slot, each with what it tells
241	/// [`Export::stats`] once returned.
242	queue: VecDeque<(Frame, Tally)>,
243	/// The rate to pad the output to with null packets, in bits per second: the
244	/// builder override when set, else the catalog's recorded multiplex rate, else
245	/// none and the output is unpadded ([`Schedule`]).
246	mux_rate: Option<u64>,
247	mux_rate_override: Option<u64>,
248	/// The rate the last program tables carried to the schedule, which pads to it from there.
249	led_rate: Option<u64>,
250	/// The decode time, in nanoseconds, from which the tables carry [`Self::mux_rate`] rather
251	/// than [`Self::led_rate`]: a rate that sends audio further ahead waits for the frames keyed
252	/// for it.
253	rate_from: Option<u128>,
254	/// The newest catalog snapshot while the export waits for the rate a TS import has yet to
255	/// measure: the tracks are subscribed once it ends, so the export joins the media as it is
256	/// then, not on frames that went stale during the wait.
257	held_catalog: Option<Catalog<S::Ext>>,
258	/// Until when that wait lasts, set by the first snapshot that records no rate.
259	rate_until: Option<kio::clock::Instant>,
260	rate_wait: Duration,
261	rate_timer: Option<std::pin::Pin<Box<kio::clock::Sleep>>>,
262	/// Tune-in point: the first video keyframe's timestamp, captured when the program
263	/// tables are built. Non-video frames before it are dropped so the keyframe leads
264	/// the stream.
265	///
266	/// MPEG-TS carries the H.264/H.265 parameter sets in-band on the keyframe (unlike
267	/// RTMP/CMAF, which carry the codec config out-of-band in the header). On a
268	/// mid-stream join the audio source can start over a second before the oldest
269	/// cached video keyframe; emitting that lead audio first would bury the parameter
270	/// sets behind an audio-only preamble, and a live decoder probing the stream gives
271	/// up before it ever configures video. `None` until the tables are built, and for
272	/// programs with no video track (nothing to align to).
273	video_start: Option<Timestamp>,
274	/// The jitter buffer key of the first video frame out since `video_start` was set.
275	/// Until one has gone, what the other tracks release is dropped: a video track whose
276	/// start group went stale before it went out starts at its next keyframe instead
277	/// ([`jitter::Buffer`]).
278	video_out: Option<Timestamp>,
279	/// Frames dropped before the jitter buffer: ahead of the first video keyframe, or of their
280	/// codec config.
281	trimmed: u64,
282	/// Each elementary stream's access units and silence on the PCR returned ([`Export::stats`]).
283	liveness: super::import::Liveness,
284}
285/// Where a program's input stands.
286enum Feed {
287	/// Reading catalog updates.
288	Live,
289	/// The publisher ended the catalog.
290	Ended,
291	/// The input stopped ([`Export::retire`]), with why the publisher left if it did, reported
292	/// once the output it buffered has gone out.
293	Retired(Option<crate::Error>),
294}
295
296/// What a queued output frame tells [`Export::stats`], applied only once the frame is
297/// returned: a rewind drops the queue unwritten.
298struct Tally {
299	/// The frame's PCR in 27 MHz ticks, and whether a declared marker, rewind, or program
300	/// switch started a new time base.
301	pcr: (u64, bool),
302	/// The PID of each access unit whose packets begin in the frame.
303	units: Vec<u16>,
304	/// The last program tables to finish in the frame.
305	tables: Option<Laid>,
306	/// The payload of the frames whose units finish in the frame, counted once it goes out.
307	charges: Vec<schedule::Charge>,
308}
309
310/// A video frame waiting on a decode clock, with the codec config it was read under.
311type Held = (Pending, Option<Bytes>);
312
313/// A frame read from its source.
314struct Pending {
315	frame: Frame,
316	/// How many marker groups had declared a break in the track's timeline when the frame
317	/// was read.
318	restart: u64,
319	/// How many times its playhead had jumped (a skipped group, or a restart) when the frame
320	/// was read.
321	skip: u64,
322	/// How many of those jumps cut a group short ([`ExportSource::cuts`]).
323	cut: u64,
324	/// When it landed in this node's cache ([`moq_net::frame::Frame::created`]), so a stall
325	/// that holds the export back too does not hide that it came late.
326	arrived: kio::clock::Instant,
327	/// When it was read.
328	read: kio::clock::Instant,
329}
330
331/// A frame waiting in the jitter buffer, with what it needs from the moment it was read.
332struct Queued {
333	frame: Frame,
334	/// When the frame decodes: its DTS, else its PTS.
335	decode: Timestamp,
336	/// Where the jitter buffer orders it ([`Track::release_key`]).
337	key: Timestamp,
338	/// Authored decode timestamp, as [`PesUnit::dts`].
339	dts: Option<u64>,
340	/// The avcC/hvcC the frame was read under, for video.
341	description: Option<Bytes>,
342	/// The PES it may share ([`Track::pack_start`]).
343	pes: Option<PesStart>,
344	/// Counts its payload once the unit carrying it goes out.
345	bill: moq_net::stats::Bill,
346}
347
348/// The PES an audio frame may share ([`Track::pack_start`]): the place of its first frame on
349/// the media timeline, and its [`Track::psi_slot`].
350type PesStart = (u128, Option<u128>);
351
352#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
353struct TrackKey {
354	program: u64,
355	name: String,
356}
357impl TrackKey {
358	fn new(program: u64, name: &str) -> Self {
359		Self {
360			program,
361			name: name.to_string(),
362		}
363	}
364}
365
366struct Track {
367	key: TrackKey,
368	source: ExportSource,
369	/// The first frame, held until the program tables are built.
370	pending: Option<Pending>,
371	/// When the source was subscribed. Nothing it delivers reached the export before then,
372	/// however long the cache held it.
373	subscribed: kio::clock::Instant,
374	/// The latest frame arrival or observed loss, which settles frames held for their DTS.
375	latest: kio::clock::Instant,
376	/// The marker count the decode clock runs under.
377	restart: u64,
378	/// The marker, skip and cut counts of the sources the track read before this one, so the
379	/// counts keep rising across a resubscription.
380	base: (u64, u64, u64),
381	/// How many unmarked steps back the track's timeline took ([`Self::steps_back`]), each
382	/// counted as a marker of its own.
383	steps: u64,
384	/// The highest PTS read on the track's timeline, and the marker count it was read under.
385	high: Option<(u64, Timestamp)>,
386	read: Read,
387	pid: u16,
388	/// The PMT lists it: from its first frame out until its last has gone and the catalog has
389	/// dropped it. Its PID, kind and descriptors stay as listed.
390	listed: bool,
391	/// The catalog lists it.
392	cataloged: bool,
393	/// Frames released while its PID still carries the stream before it, which go out once
394	/// that stream's last has.
395	parked: VecDeque<Queued>,
396	kind: Kind,
397	/// PMT ES-level descriptors to re-announce, captured verbatim on import (language,
398	/// registration, ...). Empty for non-TS sources; AC-3/E-AC-3 then synthesize one.
399	descriptors: Vec<catalog::Descriptor>,
400	/// Authors each video frame's DTS, holding the frames until it can, for a rendition that
401	/// declares no `reorder`.
402	clock: DecodeClock<Held>,
403	/// The current group's clock, when its rendition declared `reorder` at the group's start.
404	/// A trimmed leading picture holds its slot as `None`.
405	declared: Option<DeclaredClock<Option<Held>>>,
406	/// The source group that clock runs for.
407	declared_group: Option<u64>,
408	/// Loss counter at the last read, excluding declared ends.
409	recovery_gap: Option<u64>,
410	/// Leading pictures below the recovery keyframe have unavailable references, and whether
411	/// the track queued frames ahead of that keyframe, so dropping them leaves a hole.
412	leading_floor: Option<(Timestamp, bool)>,
413	/// The source's cut count at the last frame queued. A cut since clears what a track that
414	/// has not started holds.
415	held: Option<u64>,
416	/// The source ended a group, cleanly or cut. The next group presents after every picture
417	/// of this one, its leading pictures included, so the end settles each DTS the clock holds:
418	/// waiting on the next group instead would make what this one delivered late behind a hole
419	/// upstream. Settled once the source has nothing more right now, so a track's end, read
420	/// with its last group's, still takes the end of the stream's settlement.
421	settle: bool,
422	/// The PTS of the last keyframe queued, which leading pictures present before.
423	keyframe: Option<Timestamp>,
424	/// What the catalog and the SPS declare about the video's reordering.
425	timing: Timing,
426	/// The receiver's buffers for an audio or verbatim track; video's come from [`Timing`].
427	buffer: Option<Buffer>,
428	/// The audio frames muxed into a PES that has yet to go out.
429	pack: Option<Pack>,
430	/// The last frame's decode time, its jitter buffer key ([`Self::release_key`]) and the PES
431	/// it may share.
432	released: Option<(Timestamp, Timestamp, Option<PesStart>)>,
433}
434
435/// Whether a track still reads its source.
436#[derive(Clone, Copy, PartialEq, Eq)]
437enum Read {
438	Live,
439	/// Read to its end: the source ended, the program retired, or a track listed on its PID
440	/// replaced it.
441	Ended,
442	/// The catalog withdrew it before the PMT listed it. A return under the same name reads it on.
443	Withdrawn,
444	/// [`Export::follow`] left it on the ended broadcast. The returned catalog resubscribes it.
445	Stale,
446}
447
448/// Shared program state needed while reading one track.
449struct Input<'a> {
450	waiting_for_header: bool,
451	video_start: Option<Timestamp>,
452	jitter: &'a mut jitter::Buffer<TrackKey, Queued>,
453	/// Counts the frames dropped ahead of the tune-in point or their codec config.
454	trimmed: &'a mut u64,
455}
456
457impl Track {
458	/// A track reading `source`, its PID filled in by the catalog.
459	fn new(source: ExportSource, kind: Kind) -> Self {
460		Self {
461			key: TrackKey::default(),
462			source,
463			pending: None,
464			subscribed: kio::clock::now(),
465			latest: kio::clock::Instant::ZERO,
466			restart: 0,
467			base: (0, 0, 0),
468			steps: 0,
469			high: None,
470			read: Read::Live,
471			pid: 0,
472			listed: false,
473			cataloged: true,
474			parked: VecDeque::new(),
475			kind,
476			descriptors: Vec::new(),
477			clock: DecodeClock::default(),
478			declared: None,
479			declared_group: None,
480			recovery_gap: None,
481			leading_floor: None,
482			held: None,
483			settle: false,
484			keyframe: None,
485			timing: Timing::default(),
486			buffer: None,
487			pack: None,
488			released: None,
489		}
490	}
491
492	/// Queue a frame read from the source in the jitter buffer, once its decode time is known.
493	///
494	/// The decode clock runs here, as frames are read, because the deadline is on decode time:
495	/// reordered video arrives in decode order with PTS 0, 120, 40, 80, so a PTS deadline would
496	/// strand a B-frame behind its reference or send it first.
497	fn queue(&mut self, name: &str, pending: Pending, jitter: &mut jitter::Buffer<TrackKey, Queued>) -> Result<()> {
498		if pending.restart != self.restart {
499			// A marker declared a break in the timeline, or it stepped back unmarked
500			// ([`Self::steps_back`]), so the decode clock restarts too, and the last keyframe,
501			// on the timeline left behind, no longer marks what leads it.
502			self.release(name, jitter, true)?;
503			self.restart = pending.restart;
504			self.clock = DecodeClock::default();
505			// The step changes the timeline, not the group's declared reorder bound.
506			self.declared = self.declared.take().map(DeclaredClock::restart);
507			self.keyframe = None;
508			self.leading_floor = None;
509		}
510		let Kind::Video(stream_type) = self.kind else {
511			return self.push(name, pending, None, None, jitter);
512		};
513		// A declared endpoint increments both counters; only delivery loss arms recovery.
514		let gap = pending.skip.saturating_sub(pending.restart);
515		let recover = self.recovery_gap.replace(gap).is_none_or(|previous| previous != gap);
516		if pending.frame.keyframe {
517			let ahead = self.held == Some(pending.cut);
518			self.leading_floor = recover.then_some((pending.frame.timestamp, ahead));
519		}
520		let leading = self
521			.leading_floor
522			.is_some_and(|(floor, _)| pending.frame.timestamp < floor)
523			&& !radl(stream_type, self.source.description(), &pending.frame);
524		if let Some((_, ahead)) = self.leading_floor
525			&& leading
526		{
527			jitter.lose(&self.key, ahead);
528			// It still takes its slot, so the group's other frames decode where they do on an
529			// exporter that kept it.
530			return match &mut self.declared {
531				Some(clock) => {
532					clock.push(None, to_ticks(pending.frame.timestamp), pending.frame.timestamp)?;
533					self.release(name, jitter, false)
534				}
535				None => Ok(()),
536			};
537		}
538		self.held = Some(pending.cut);
539		if pending.frame.keyframe {
540			self.timing.describe(stream_type, self.source.description(), name);
541			// A group decodes on its own clock at the depth its rendition declares now. The
542			// inferred clock spans groups, so it is only flushed when a declaration replaces it.
543			let depth = self.timing.reorder;
544			if self.declared.is_some() || depth.is_some() {
545				self.release(name, jitter, true)?;
546			}
547			self.declared = depth.map(DeclaredClock::new);
548			// The frame was just read, or is the first, held while the source read no further.
549			self.declared_group = self.source.group();
550		}
551		let source = pending.frame.timestamp;
552		let pts = to_ticks(source);
553		let (arrived, bytes) = (pending.arrived, pending.frame.payload.len());
554		let item = (pending, self.source.description().cloned());
555		match &mut self.declared {
556			Some(clock) => clock.push(Some(item), pts, source)?,
557			None => self.clock.push(item, pts, arrived, bytes),
558		}
559		self.release(name, jitter, false)
560	}
561
562	/// Count a frame that steps the track's timeline back with no marker as a marker of its own,
563	/// where a reorder bound proves no valid reordering explains it.
564	///
565	/// Audio presents in decode order, so any frame below one read before it is out of order.
566	/// Video reorders within only the catalog `reorder` its rendition declares, so the frame must
567	/// also follow more frames than that in presentation order ([`DeclaredClock::reorders_past`]).
568	/// Video that declares none is left as it is: its decode clock infers reordering from the
569	/// timestamps, so nothing tells a step back from a reorder deeper than any it has seen, and a
570	/// guess would restart a healthy stream.
571	///
572	/// The jitter buffer would not see the step: the group's declared clock would refuse the frame
573	/// and fail the export, and audio with slack left would decode before the frames ahead of it
574	/// on the same clock, which the output's buffers cannot carry. As a marker, the step restarts
575	/// the decode clock and opens a new generation, as one the source declared would. A placed
576	/// frame's timestamp is its arrival rather than its decode time, so it never steps.
577	fn steps_back(&mut self, pending: &mut Pending) {
578		if self.kind.placed() {
579			return;
580		}
581		let pts = pending.frame.timestamp;
582		let high = (self.high).and_then(|(restart, high)| (restart == pending.restart).then_some(high));
583		let stepped = high.is_some_and(|high| pts < high)
584			&& match self.kind {
585				Kind::Video(_) => (self.declared)
586					.as_ref()
587					.is_some_and(|clock| clock.reorders_past(to_ticks(pts))),
588				_ => true,
589			};
590		if stepped {
591			tracing::debug!(track = %self.key.name, ?pts, ?high, "unmarked step back; restarting the timeline");
592			self.steps += 1;
593			pending.restart += 1;
594			pending.skip += 1;
595		}
596		let high = high
597			.filter(|_| !stepped)
598			.map_or(pts, |high| crate::container::later(high, pts));
599		self.high = Some((pending.restart, high));
600	}
601
602	/// Read within the jitter window, or hold the first frame until the program tables are built.
603	///
604	/// Returns the track's own failure, which ended it, apart from the export's errors: the
605	/// export decides whether it outlives that ([`Export::survive`]).
606	fn fill(&mut self, name: &str, waiter: &kio::Waiter, input: &mut Input<'_>) -> crate::Result<Option<crate::Error>> {
607		if self.key.name.is_empty() {
608			self.key.name = name.to_string();
609		}
610		if self.pending.is_some() || self.read != Read::Live {
611			return Ok(None);
612		}
613		let is_video = matches!(self.kind, Kind::Video(_));
614		// A placed frame is judged at release, against the keyframe's departure ([`Export::leads_video`]).
615		let aligned = !is_video && !self.kind.placed();
616		let mut lost = None;
617		loop {
618			if !input.waiting_for_header && input.jitter.full(&self.key, waiter) {
619				let _ = self.source.poll_received(waiter);
620				break;
621			}
622			let event = match self.source.poll_event(waiter) {
623				// The track failed: it ends like a finished one, and the export decides whether that
624				// ends it too ([`Export::survive`]).
625				Poll::Ready(Err(err)) if self.source.lost() => {
626					self.read = Read::Ended;
627					lost = Some(err);
628					break;
629				}
630				event => event?,
631			};
632			match event {
633				Poll::Ready(Some(Event::Frame { frame, arrived })) => {
634					if is_video && frame.keyframe && input.waiting_for_header {
635						tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "keyframe", now = ?kio::clock::now(), program = self.key.program, ?arrived);
636					}
637					let arrived = arrived.max(self.subscribed);
638					// The frame settles what its group's end left held, so they are ready as it lands.
639					self.latest = self.latest.max(arrived);
640					if std::mem::take(&mut self.settle) && !input.waiting_for_header {
641						self.release(name, input.jitter, true)?;
642					}
643					// A track waits for its codec config before the PMT can list it.
644					if (input.waiting_for_header || !self.listed) && !self.source.header_ready() {
645						*input.trimmed += 1;
646						continue;
647					}
648					// Media is timed: a scale-less track's unscaled key has no time to mux at. Refused
649					// here, so every frame the exporter holds has one (see [`nanos`]).
650					if frame.timestamp.scale().is_none() {
651						return Err(moq_net::Error::TimestampMismatch.into());
652					}
653					let mut pending = Pending {
654						frame,
655						restart: self.base.0 + self.source.markers() + self.steps,
656						skip: self.base.1 + self.source.skips() + self.steps,
657						cut: self.base.2 + self.source.cuts(),
658						arrived,
659						read: kio::clock::now(),
660					};
661					self.steps_back(&mut pending);
662					// A new timeline must reach the reset before tune-in alignment can drop it.
663					if let Some(start) = input.video_start
664						&& aligned && pending.restart == self.restart
665						&& pending.frame.timestamp < start
666					{
667						*input.trimmed += 1;
668						continue;
669					}
670					if input.waiting_for_header {
671						self.pending = Some(pending);
672						break;
673					}
674					self.queue(name, pending, input.jitter)?;
675				}
676				// A cut settles what the decode clock holds of the group it left short now, not with
677				// the next group, which may arrive after those frames were due, or with the stream's end.
678				Poll::Ready(Some(Event::Cut { observed })) => {
679					self.latest = self.latest.max(observed);
680					self.settle = input.waiting_for_header;
681					if !input.waiting_for_header {
682						self.release(name, input.jitter, true)?;
683					}
684				}
685				Poll::Ready(Some(Event::GroupEnd)) => self.settle = true,
686				Poll::Ready(Some(Event::FrameEnd { .. })) => {}
687				Poll::Ready(None) => {
688					self.read = Read::Ended;
689					break;
690				}
691				Poll::Pending => {
692					if std::mem::take(&mut self.settle) && !input.waiting_for_header {
693						self.release(name, input.jitter, true)?;
694					}
695					break;
696				}
697			}
698		}
699		// Nothing more can come in below the frames still held for their DTS.
700		if self.read == Read::Ended && !input.waiting_for_header {
701			self.release(name, input.jitter, true)?;
702		}
703		Ok(lost)
704	}
705
706	/// The samples an audio frame of `payload` lasts and their rate, if it may share a PES with
707	/// the frames around it: one whole frame of audio whose receiver removes each frame from
708	/// its buffer at the frame's own decode time.
709	fn samples(&self, payload: &[u8]) -> Option<(u64, u32)> {
710		let parse = match &self.kind {
711			Kind::Aac { config, .. } => return (config.sample_rate > 0).then_some((1024, config.sample_rate)),
712			Kind::Adts { .. } => {
713				let header = adts::Header::parse(payload).ok()?;
714				return Some((1024 * u64::from(header.blocks), header.sample_rate));
715			}
716			Kind::Mp2 { .. } => crate::codec::mp2::parse_header,
717			Kind::Ac3 => crate::codec::ac3::parse_header,
718			Kind::Eac3 => crate::codec::eac3::parse_header,
719			_ => return None,
720		};
721		let header = parse(payload).ok()?;
722		(header.len == payload.len() && header.sample_rate > 0 && header.samples > 0)
723			.then_some((header.samples, header.sample_rate))
724	}
725
726	/// The receiver's buffers for the track's PID, if the T-STD gives it any.
727	fn buffer(&self) -> Option<Buffer> {
728		match self.kind {
729			Kind::Video(_) => self.timing.buffer(),
730			_ => self.buffer,
731		}
732	}
733
734	/// The bytes a PES of the track has for its frames, and how many frames of `len` bytes
735	/// that holds: B holds the PES header with the frames (ISO 13818-1 2.4.2.3).
736	fn fit(&self, len: usize) -> (usize, u128) {
737		let size = self
738			.buffer()
739			.and_then(|buffer| buffer.size)
740			.unwrap_or(0)
741			.saturating_sub(PES_PREFIX_LEN + PES_OPTIONAL_LEN);
742		(size, (size / len.max(1)).max(1) as u128)
743	}
744
745	/// The PSI repetition slot a PES of the track keeps to, if any. AAC with a program config
746	/// element repeats it in the first frame it muxes after the tables, which go out on
747	/// [`due`]'s grid; a PES that spanned a boundary of the grid could be muxed after the tables
748	/// and still go out ahead of them, where a receiver tuning in at the tables misses it.
749	fn psi_slot(&self, timestamp: Timestamp) -> Option<u128> {
750		matches!(&self.kind, Kind::Aac { config, .. } if config.program_config.is_some())
751			.then(|| slot(timestamp, PSI_INTERVAL))
752	}
753
754	/// The PES [`Export::pack`] may cut a frame of `payload` presented at `timestamp` into under
755	/// `delay`, if it packs the frame: as many frames as B holds from a place on the media
756	/// timeline that is a multiple of them, cut again where they would span more than half the
757	/// delay and at each [`Self::psi_slot`].
758	fn pack_start(&self, payload: &[u8], timestamp: Timestamp, delay: Duration) -> Option<PesStart> {
759		let (samples, rate) = self.samples(payload).filter(|_| !delay.is_zero())?;
760		let len = match self.kind {
761			Kind::Aac { .. } => adts::MIN_HEADER_LEN + payload.len(),
762			_ => payload.len(),
763		};
764		let place = place(timestamp, samples, rate);
765		let behind = place % self.fit(len).1;
766		let frame = 1_000_000_000 * u128::from(samples) / u128::from(rate);
767		let spans = (delay / 2).as_nanos() / frame.max(1) + 1;
768		Some((place - behind % spans, self.psi_slot(timestamp)))
769	}
770
771	/// How long a receiver takes to pass one of the track's packets on, so its last packet has
772	/// to arrive that long before it decodes. A packet's bytes reach a decoder buffer only once
773	/// they have drained through the T-STD buffers ahead of it (ISO 13818-1 2.4.2); without it
774	/// a unit whose DTS sits on a PCR slot boundary, as a source's own 25 fps timestamps put
775	/// every fifth frame, arrives complete only after it decodes.
776	fn drain(&self) -> Duration {
777		self.buffer().unwrap_or(Buffer::SYSTEM).drain()
778	}
779
780	/// How far ahead of its decode time the track's units may go out under `delay`: as far
781	/// as [`schedule::ahead`] lets them, and nothing without a delay or for a placed frame,
782	/// whose timestamp is when it goes out.
783	fn ahead(&self, delay: Duration) -> Duration {
784		// A placed frame goes out at its placement, never ahead of it.
785		if delay.is_zero() || self.kind.placed() {
786			return Duration::ZERO;
787		}
788		let slots = schedule::ahead(self.buffer().as_ref(), schedule::slot(delay.as_nanos()));
789		PCR_INTERVAL * u32::try_from(slots).unwrap_or(u32::MAX)
790	}
791
792	/// Where the jitter buffer orders a frame decoding at `decode` under `delay`: at its release
793	/// time, [`Self::ahead`] before its decode time, so it reaches the schedule as the first slot
794	/// it may ride is laid, and a slot goes out the delay after the source's clock rather than a
795	/// delay later still. Keys run a delay past release times, which no send-ahead exceeds, so a
796	/// frame near the start of the timeline is not cut short of its send-ahead. The clock anchors
797	/// on the track sent latest against these keys, so every track keeps the whole delay to
798	/// arrive in. A send-ahead that grew (a new SPS declaring a larger CPB) releases no frame
799	/// before the one ahead of it.
800	///
801	/// An audio frame that shares a PES with the frame released before it takes that frame's
802	/// key, so the whole PES is in hand when its first slot is laid; the first frame released
803	/// of a PES (a joiner's may not be the PES's first) keeps its own. That costs no latency.
804	/// A TS source sends a PES's frames together, so they lose nothing. One that sends audio
805	/// at its decode time sends the later frames behind their key, so the clock still anchors
806	/// on the first, and they have that much less of the delay to arrive in.
807	fn release_key(
808		&mut self,
809		decode: Timestamp,
810		delay: Duration,
811		frame: &Frame,
812	) -> Result<(Timestamp, Option<PesStart>)> {
813		let lead = delay.saturating_sub(self.ahead(delay));
814		let key = Duration::try_from(decode)?
815			.checked_add(lead)
816			.context("MPEG-TS decode time past the end of the timeline")?;
817		let mut key = Timestamp::try_from(key)?;
818		let start = self.pack_start(&frame.payload, frame.timestamp, delay);
819		if let Some((last, previous, shared)) = self.released
820			&& decode >= last
821		{
822			key = match start.is_some() && shared == start {
823				true => previous,
824				false => crate::container::later(key, previous),
825			};
826		}
827		self.released = Some((decode, key, start));
828		Ok((key, start))
829	}
830
831	/// Queue every held video frame whose DTS is settled or that is overdue
832	/// ([`DecodeClock::settle`]), or all of them when `flush`.
833	///
834	/// A held frame is ready no earlier than the frame or observed loss that settled it,
835	/// so it is judged as arriving then. Frames held through a silence,
836	/// such as a dead publisher's last frames settled only by its replacement's, are late by the
837	/// silence: the jitter buffer drops them, where their own arrival would queue them behind a
838	/// schedule that has already gone past them. Nothing settles the frames still held when the
839	/// track ends, so they keep their own arrival and go out late if they must.
840	fn release(&mut self, name: &str, jitter: &mut jitter::Buffer<TrackKey, Queued>, flush: bool) -> Result<()> {
841		if let Some(mut clock) = self.declared.take() {
842			let released = (|| {
843				while let Some((item, dts, pts)) = clock.pop(flush)? {
844					let Some((mut pending, description)) = item else {
845						continue;
846					};
847					// A tie the clock moved presents on the tick it moved to: the least microsecond
848					// that `to_ticks` reads back as that tick.
849					if to_ticks(pending.frame.timestamp) != pts {
850						let micros =
851							u64::try_from((u128::from(pts) * 100).div_ceil(9)).map_err(|_| moq_net::TimeOverflow)?;
852						pending.frame.timestamp = Timestamp::from_micros(micros)?;
853					}
854					if self.read == Read::Live {
855						pending.arrived = pending.arrived.max(self.latest);
856					}
857					self.push(name, pending, Some(dts), description, jitter)?;
858				}
859				Ok::<_, Error>(())
860			})();
861			self.declared = Some(clock);
862			released?;
863		}
864		let (delay, lookahead) = self.timing.inferred();
865		let lookahead = lookahead.max(self.timing.jitter);
866		loop {
867			let settle = match flush {
868				true => Settle::All,
869				false => self
870					.clock
871					.settle(lookahead, self.latest, jitter.delay(), jitter::MAX_BYTES),
872			};
873			let Some(((mut pending, description), dts)) = self.clock.pop(lookahead, delay, settle) else {
874				break;
875			};
876			if self.read == Read::Live {
877				pending.arrived = pending.arrived.max(self.latest);
878			}
879			self.push(name, pending, Some(dts.into()), description, jitter)?;
880		}
881		Ok(())
882	}
883
884	/// Queue a frame decoding at `dts` (signed 90 kHz ticks), else at its PTS.
885	///
886	/// A DTS before the timeline's zero, a declared group's leading frames at its start, wraps
887	/// into the 33-bit wire field like any other, and is scheduled from zero: the few ticks it
888	/// precedes zero by are below anything the T-STD resolves.
889	fn push(
890		&mut self,
891		name: &str,
892		pending: Pending,
893		dts: Option<i128>,
894		description: Option<Bytes>,
895		jitter: &mut jitter::Buffer<TrackKey, Queued>,
896	) -> Result<()> {
897		let Pending {
898			frame,
899			restart,
900			arrived,
901			read,
902			..
903		} = pending;
904		let dts = dts.filter(|&dts| dts != i128::from(to_ticks(frame.timestamp)));
905		let decode = dts
906			.and_then(|ticks| Timestamp::from_scale(u64::try_from(ticks.max(0)).ok()?, 90_000).ok())
907			.unwrap_or(frame.timestamp);
908		// Two's complement, so the 33-bit mask wraps a DTS before zero as it would a later one.
909		let dts = dts.map(|ticks| ticks as u64);
910		let (key, pes) = self.release_key(decode, jitter.delay(), &frame)?;
911		let video = matches!(self.kind, Kind::Video(_));
912		let leading = match self.kind {
913			Kind::Video(stream_type) => {
914				!frame.keyframe
915					&& self.keyframe.is_some_and(|keyframe| frame.timestamp < keyframe)
916					&& !radl(stream_type, description.as_ref(), &frame)
917			}
918			_ => false,
919		};
920		if video && frame.keyframe {
921			self.keyframe = Some(frame.timestamp);
922		}
923		// Video, MPEG-1/2 carried whole among it, resumes only at a keyframe, since its other
924		// pictures reference earlier ones.
925		let sync = frame.keyframe || self.kind.class() != super::stats::Class::Video;
926		// Replaying anchors on the first frame, and the tracks arrive together rather than each
927		// sent ahead by its send-ahead: judged as arriving that much earlier, as a live source
928		// sends it, every track's first frames are on the clock whichever anchors it.
929		let ahead = match jitter.replaying() {
930			true => (Duration::try_from(decode)? + jitter.delay()).saturating_sub(Duration::try_from(key)?),
931			false => Duration::ZERO,
932		};
933		// Logical clocks can begin at zero. Shift both readings by the same representable amount so
934		// their ordering survives even when the full replay lead would precede the clock's origin.
935		let ahead = ahead.min(arrived.duration_since(kio::clock::Instant::ZERO));
936		let ahead = ahead.min(read.duration_since(kio::clock::Instant::ZERO));
937		let arrival = Arrival {
938			arrived: arrived.saturating_sub(ahead),
939			read: read.saturating_sub(ahead),
940			decode: key.try_into()?,
941			restart,
942			sync,
943			leading,
944			bytes: frame.payload.len() + self.key.name.len(),
945			item: Queued {
946				frame,
947				decode,
948				key,
949				dts,
950				description,
951				pes,
952				bill: self.source.bill(),
953			},
954		};
955		if jitter.push(self.key.clone(), arrival)? == Push::Late {
956			tracing::warn!(
957				track = %name,
958				dropped = jitter.dropped(),
959				trimmed = jitter.trimmed(),
960				"frame missed its deadline; dropped"
961			);
962		}
963		Ok(())
964	}
965}
966
967/// What a video rendition declares about its reordering, which bounds its [`DecodeClock`].
968#[derive(Default)]
969struct Timing {
970	/// The catalog `jitter` in 90 kHz ticks: the most any frame decodes before it is presented.
971	jitter: u64,
972	/// The catalog `framerate`: the picture period for an SPS that declares no fixed rate.
973	framerate: Option<f64>,
974	/// The avcC/hvcC [`Self::declared`] and [`Self::hrd`] were read from.
975	description: Option<Bytes>,
976	declared: Option<Reorder>,
977	/// The stream's level limits, from the catalog codec.
978	level: Option<Level>,
979	/// The reorder depth the catalog declares, which clocks each group on its own.
980	reorder: Option<usize>,
981	/// The HRD its SPS declares.
982	hrd: Option<Hrd>,
983}
984
985impl Timing {
986	/// Take the rendition's timing from a catalog snapshot, before or after the program
987	/// tables are written.
988	fn configure(&mut self, config: &VideoConfig, name: &str) -> crate::Result<()> {
989		self.jitter = config.jitter.map_or(0, |t| (t.as_micros() * 90_000 / 1_000_000) as u64);
990		self.framerate = config.framerate.filter(|fps| fps.is_finite() && *fps > 0.0);
991		self.level = Some(video_level(config, name));
992		self.reorder = crate::container::declared::depth(config)?;
993		Ok(())
994	}
995
996	/// Read the reorder depth from the codec config a keyframe is carried with.
997	fn describe(&mut self, stream_type: StreamType, description: Option<&Bytes>, name: &str) {
998		if self.description.as_ref() == description {
999			return;
1000		}
1001		self.description = description.cloned();
1002		self.declared = description.and_then(|d| declared_reorder(stream_type, d));
1003		self.hrd = description.and_then(|d| declared_hrd(stream_type, d));
1004		tracing::debug!(track = %name, reorder = ?self.inferred(), "video reordering declared");
1005	}
1006
1007	/// The receiver's buffers (H.222.0 2.14.3.1, 2.17.2): EB is the HRD's CPB, else the
1008	/// level's; the transport buffer drains at Rx, scaled from the HRD's BitRate or else the
1009	/// level's; and MB passes payload on into EB at the level's Rbx whatever the HRD declares.
1010	/// EB reaches the HRD's buffer delay ahead, else what the level's CPB holds at its top rate.
1011	fn buffer(&self) -> Option<Buffer> {
1012		let level = self.level?;
1013		let (bit_rate, cpb) = match self.hrd {
1014			Some(hrd) => (hrd.bit_rate, hrd.cpb_size),
1015			None => (level.bit_rate, level.cpb),
1016		};
1017		Some(Buffer {
1018			rate: bit_rate.saturating_mul(level.factor) / 1_000,
1019			leak: Some(level.leak),
1020			size: Some(usize::try_from(cpb / 8).unwrap_or(usize::MAX)),
1021			transport: 512,
1022			reach: self.buffer_delay().unwrap_or_else(|| fill(level.cpb, level.leak)),
1023		})
1024	}
1025
1026	/// How long the HRD's CPB takes to fill at its rate: how far ahead of its decode time the
1027	/// source may send a picture, so the export has to as well.
1028	fn buffer_delay(&self) -> Option<Duration> {
1029		self.hrd.map(|hrd| fill(hrd.cpb_size, hrd.bit_rate))
1030	}
1031
1032	/// The least reorder delay and lookahead the SPS declares, in ticks, so two exporters agree
1033	/// on them from their first keyframe whatever reordering each has seen.
1034	///
1035	/// The delay is the SPS's depth in pictures, at its picture period or the catalog
1036	/// `framerate`'s. A frame can be presented up to `2^depth - 1` pictures below one decoded
1037	/// before it (a B-pyramid that deep), which bounds the lookahead the catalog `jitter`
1038	/// gives when it is not published.
1039	fn inferred(&self) -> (u64, u64) {
1040		let Some(declared) = self.declared else {
1041			return (0, 0);
1042		};
1043		let (delay, lookahead) = declared.timing(self.framerate);
1044		(delay.min(MAX_REORDER), lookahead.min(MAX_REORDER))
1045	}
1046}
1047
1048#[derive(Clone, PartialEq)]
1049enum Kind {
1050	/// Video carries its TS stream type (H.264 = 0x1B, H.265 = 0x24).
1051	Video(StreamType),
1052	/// AAC, framed as ADTS. A `channel_config` of 0 defers the layout to a program config
1053	/// element, which leads the first raw data block after each PAT/PMT, so a receiver that tunes
1054	/// in at the tables can decode from there. `repeat` marks that the next frame carries it.
1055	Aac { config: aac::InBand, repeat: bool },
1056	/// Description-less AAC carries its ADTS framing in each frame, so frames pass through as
1057	/// they are. The catalog's profile, rate, and channels are kept only so [`Export::rebind`]
1058	/// refuses a rendition announced differently, as it does for [`Kind::Aac`]'s config.
1059	Adts {
1060		profile: u8,
1061		sample_rate: u32,
1062		channels: u32,
1063	},
1064	/// Opus (private stream_type 0x06). Each frame is one Opus packet, prefixed with
1065	/// the Opus-in-TS access-unit control header and announced with the 'Opus'
1066	/// registration plus DVB extension descriptor. `channel_config_code` is a plain
1067	/// code that descriptor can name, never a count clamped into range.
1068	Opus { channel_config_code: u8 },
1069	/// MP2, carried verbatim. The sample rate picks the stream type on the way
1070	/// out (0x03 vs 0x04).
1071	Mp2 { sample_rate: u32 },
1072	/// AC-3 (ATSC stream_type 0x81), carried verbatim.
1073	Ac3,
1074	/// E-AC-3 (ATSC stream_type 0x87), carried verbatim.
1075	Eac3,
1076	/// An undecoded elementary stream carried as private sections (SCTE-35, ...),
1077	/// re-announced in the PMT with its recorded `stream_type`.
1078	Verbatim { stream_type: u8 },
1079	/// An undecoded elementary stream whose frames are whole PES packets, written unchanged
1080	/// and sent at their timestamp, the source's placement ([`catalog::PesPacket`]).
1081	PesPacket { stream_type: u8 },
1082}
1083
1084impl Kind {
1085	/// The `stream_type` the PMT announces it as.
1086	fn stream_type(&self) -> u8 {
1087		match self {
1088			Kind::Video(stream_type) => *stream_type as u8,
1089			Kind::Aac { .. } | Kind::Adts { .. } => StreamType::AdtsAac as u8,
1090			// Opus rides private-data PES; the registration + extension descriptors tell the
1091			// demuxer it's Opus.
1092			Kind::Opus { .. } => 0x06,
1093			// Half-rate MPEG-2 BC audio (< 32 kHz) re-announces as 0x04; the full rates are
1094			// MPEG-1 (0x03). The catalog sample rate came from the frame header, so the mapping
1095			// is faithful.
1096			Kind::Mp2 { sample_rate } if *sample_rate < 32000 => StreamType::Mpeg2HalvedSampleRateAudio as u8,
1097			Kind::Mp2 { .. } => StreamType::Mpeg1Audio as u8,
1098			Kind::Ac3 => StreamType::DolbyDigitalUpToSixChannelAudio as u8,
1099			Kind::Eac3 => StreamType::DolbyDigitalPlusUpTo16ChannelAudioForAtsc as u8,
1100			Kind::Verbatim { stream_type, .. } | Kind::PesPacket { stream_type } => *stream_type,
1101		}
1102	}
1103
1104	/// The PMT ES descriptors announcing it when import captured none: the ATSC Dolby
1105	/// registration, so a fresh (non-TS) AC-3/E-AC-3 track is announced the way the import
1106	/// path expects, and Opus's registration and channel configuration.
1107	fn descriptors(&self) -> Vec<catalog::Descriptor> {
1108		match self {
1109			Kind::Ac3 => vec![registration(b"AC-3")],
1110			Kind::Eac3 => vec![registration(b"EAC3")],
1111			Kind::Opus { channel_config_code } => opus_descriptors(*channel_config_code),
1112			_ => Vec::new(),
1113		}
1114	}
1115
1116	/// Its timestamp is arrival on the program clock, rather than a decode deadline.
1117	fn placed(&self) -> bool {
1118		matches!(self, Self::PesPacket { .. } | Self::Verbatim { .. })
1119	}
1120
1121	/// The track suffix [`Import`](super::Import) gives a PID carrying this kind, so a stream's
1122	/// row is named alike at both edges.
1123	fn suffix(&self) -> &'static str {
1124		match self {
1125			Kind::Video(StreamType::H265) => ".hev1",
1126			Kind::Video(_) => ".avc3",
1127			Kind::Aac { .. } | Kind::Adts { .. } => ".aac",
1128			Kind::Opus { .. } => ".opus",
1129			Kind::Mp2 { .. } => ".mp2",
1130			Kind::Ac3 => ".ac3",
1131			Kind::Eac3 => ".eac3",
1132			Kind::Verbatim { .. } | Kind::PesPacket { .. } => ".ts",
1133		}
1134	}
1135
1136	/// The classification [`Import`](super::Import) would give this PID, so a row is graded
1137	/// alike at both edges.
1138	fn class(&self) -> super::stats::Class {
1139		match self {
1140			// MPEG-1/2 video rides whole, but paces the program as decoded video does.
1141			Kind::Video(_)
1142			| Kind::PesPacket {
1143				stream_type: 0x01 | 0x02,
1144			} => super::stats::Class::Video,
1145			Kind::Aac { .. } | Kind::Adts { .. } | Kind::Opus { .. } | Kind::Mp2 { .. } | Kind::Ac3 | Kind::Eac3 => {
1146				super::stats::Class::Audio
1147			}
1148			Kind::Verbatim { .. } | Kind::PesPacket { .. } => super::stats::Class::Data,
1149		}
1150	}
1151}
1152
1153/// The program tables: the PAT, fixed for the program's life but for its network entry and the
1154/// PID it names for the PMT, and the PMT, which lists the streams on the air. The schedule lays
1155/// them as they stand when each copy begins to go out ([`Schedule::set_psi`]), so a change is one
1156/// update of this state, and a revision overtaken before any copy of it began takes no version.
1157struct Psi {
1158	/// The source's `transport_stream_id`, so the rebuilt PAT stays consistent with the carried SI.
1159	transport_stream_id: u16,
1160	/// What the PMT says now.
1161	pmt: psi::Pmt,
1162	/// PID the PMT rides on: the source's original (preserved from the service
1163	/// record) or the synthesized [`PMT_PID`] for a media-only source.
1164	pmt_pid: u16,
1165	/// The PID the catalog moved the PMT to, which it takes once no copy of the tables is on its
1166	/// way ([`Export::follow_pmt`]).
1167	moving: Option<u16>,
1168	/// The PIDs the PMT rode before, which no stream takes: a receiver may still read them as
1169	/// the PMT's.
1170	left: Vec<u16>,
1171	/// The PMT the last tables handed to the schedule listed: the streams the next copy adds.
1172	led: Option<psi::Pmt>,
1173	/// The tables last set on the schedule, and the PIDs they flag a break on.
1174	stated: Option<(Laid, Vec<u16>)>,
1175	/// The tables of the last copy to begin going out, whose version the next change follows.
1176	laid: Option<Laid>,
1177	/// The tables of each copy begun and not yet finished, oldest first.
1178	sending: VecDeque<Laid>,
1179	/// The last tables returned.
1180	out: Option<Laid>,
1181}
1182
1183/// Program tables as a copy of them goes out: the PMT and the PAT, each at its version.
1184#[derive(Clone)]
1185struct Laid {
1186	version: VersionNumber,
1187	pmt: psi::Pmt,
1188	/// The PID the PAT names for the PMT, which the PMT rides.
1189	pmt_pid: u16,
1190	/// Whether the PAT lists the network entry, pointing at the NIT the export carries.
1191	network: bool,
1192	pat_version: VersionNumber,
1193	pat: Bytes,
1194}
1195
1196impl Psi {
1197	/// The PID the PMT names for the clock.
1198	fn pcr_pid(&self) -> Option<u16> {
1199		self.pmt.pcr_pid.map(|pid| pid.as_u16())
1200	}
1201
1202	/// The PID the clock rides alone, which no stream may take.
1203	fn own_clock(&self) -> Option<u16> {
1204		self.pcr_pid()
1205			.filter(|&pcr| self.pmt.streams.iter().all(|es| es.pid.as_u16() != pcr))
1206	}
1207
1208	/// The tables as they stand, listing the network entry when `network`. Each table that
1209	/// differs from the last laid goes out at the version after that one's own, `first` (the PMT's
1210	/// and the PAT's) before any has: the PAT changes only with its network entry or PMT PID.
1211	fn current(&self, network: bool, first: (VersionNumber, VersionNumber)) -> Result<Laid> {
1212		let next = |mut version: VersionNumber| {
1213			version.increment();
1214			version
1215		};
1216		let (version, pat_version, pat) = match &self.laid {
1217			Some(laid) => {
1218				let version = match laid.pmt == self.pmt {
1219					true => laid.version,
1220					false => next(laid.version),
1221				};
1222				match laid.network == network && laid.pmt_pid == self.pmt_pid {
1223					true => (version, laid.pat_version, Some(laid.pat.clone())),
1224					false => (version, next(laid.pat_version), None),
1225				}
1226			}
1227			None => (first.0, first.1, None),
1228		};
1229		let pat = match pat {
1230			Some(pat) => pat,
1231			None => encode_pat(
1232				self.transport_stream_id,
1233				self.pmt.program_number,
1234				self.pmt_pid,
1235				network,
1236				pat_version,
1237			)?,
1238		};
1239		Ok(Laid {
1240			version,
1241			pmt: self.pmt.clone(),
1242			pmt_pid: self.pmt_pid,
1243			network,
1244			pat_version,
1245			pat,
1246		})
1247	}
1248}
1249
1250/// The DVB NIT's PID (ETSI EN 300 468 5.1.3), the network PID the PAT's program 0 names.
1251const NIT_PID: u16 = 0x0010;
1252/// The `table_id` of the NIT describing the delivering network.
1253const NIT_ACTUAL: u8 = 0x40;
1254
1255/// The PAT for the exported program at `version`, listing the network PID as program 0 first when
1256/// the export carries the NIT (ISO/IEC 13818-1 2.4.4.3), which a receiver otherwise cannot find.
1257fn encode_pat(
1258	transport_stream_id: u16,
1259	program_number: u16,
1260	pmt_pid: u16,
1261	network: bool,
1262	version: VersionNumber,
1263) -> Result<Bytes> {
1264	let network = network.then(|| ProgramAssociation {
1265		program_num: 0,
1266		program_map_pid: Pid::new(NIT_PID).expect("a valid PID"),
1267	});
1268	let program = ProgramAssociation {
1269		program_num: program_number,
1270		program_map_pid: Pid::new(pmt_pid)?,
1271	};
1272	psi::encode_pat(&Pat {
1273		transport_stream_id,
1274		version_number: version,
1275		table: network.into_iter().chain([program]).collect(),
1276	})
1277}
1278
1279/// Per-frame PES descriptor (everything but the payload bytes).
1280struct PesUnit {
1281	pid: u16,
1282	is_video: bool,
1283	keyframe: bool,
1284	timestamp: Timestamp,
1285	/// Authored decode timestamp for a reordered (B-frame) video frame, in continuous
1286	/// (unwrapped) 90 kHz ticks (wrapped to the wire field in `write_pes`). `Some` only when
1287	/// it differs from the PTS; the PES then carries both PTS and DTS.
1288	dts: Option<u64>,
1289	/// Explicit PES stream_id (Opus); `None` derives it from `is_video`.
1290	stream_id: Option<u8>,
1291}
1292
1293/// Consecutive audio frames muxed into one PES still to go out ([`Export::pack`]).
1294struct Pack {
1295	/// The first frame's PES fields: its PTS times the frames after it too.
1296	unit: PesUnit,
1297	/// When the first frame decodes, the PES's deadline.
1298	decode: Timestamp,
1299	/// The PES its frames share ([`Track::pack_start`]).
1300	start: Option<PesStart>,
1301	/// The frames' elementary stream bytes.
1302	payload: Vec<u8>,
1303	/// Each frame's decode nanoseconds and bytes, which leave the decoder buffer as it decodes.
1304	frames: Vec<(u128, usize)>,
1305	/// What each frame's payload counts once the PES goes out.
1306	charges: Vec<schedule::Charge>,
1307	/// The frames' samples so far, and their sample rate.
1308	samples: u64,
1309	rate: u32,
1310}
1311
1312impl Pack {
1313	/// When the frame after the last presents, in microseconds, if the frames run on without
1314	/// a gap.
1315	fn end(&self) -> u128 {
1316		nanos(self.unit.timestamp) / 1_000 + u128::from(self.samples) * 1_000_000 / u128::from(self.rate)
1317	}
1318}
1319
1320/// One SI entry's subscription: resolves the snapshot track named by the catalog,
1321/// reduces complete groups into the current section set and repeats it on its cadence.
1322/// Clock tables hold one future snapshot on the media grid, leaving later groups on the
1323/// subscription rather than collecting revisions ahead of the media.
1324struct SiTrack {
1325	source: crate::Source,
1326	/// The catalog's track name for this entry, so a catalog update that repoints
1327	/// the entry at a different track (a restarted publisher) is detected and the
1328	/// subscription rebuilt rather than left repeating the old track's sections.
1329	track: String,
1330	interval: Option<Duration>,
1331	clock: bool,
1332	state: SiState,
1333	/// The reduced newest *complete* group: what emission re-transmits.
1334	active: super::si::Snapshot,
1335	/// A group still being read; only a complete snapshot may become active or staged,
1336	/// so a torn half-received snapshot is never emitted.
1337	pending: Option<(moq_net::group::Consumer, super::si::Snapshot, Timestamp)>,
1338	/// One complete clock revision waiting for its stamped position.
1339	future: Option<SiRevision>,
1340	/// Furthest media position already muxed, so a late revision waits for the next slot.
1341	position: Option<Timestamp>,
1342	/// A promoted snapshot changed `active` and has not hit the wire yet: emit on
1343	/// the revision floor ([`SI_REVISION_INTERVAL`]) instead of waiting out the
1344	/// repetition interval. For a clock table (TDT/TOT) the cadence is the content,
1345	/// so holding a revision to the interval delivers the time seconds late and can
1346	/// re-assert an already-sent value (#2934).
1347	dirty: bool,
1348	/// Media timestamp of the last emission ([`Export::mux`]).
1349	last_emit: Option<Timestamp>,
1350	/// The same budget the media sources use, asked of the SI track's publisher, and
1351	/// capped by that publisher's max age. A snapshot table needs only its newest group,
1352	/// which never goes stale. A clock table (TDT/TOT) needs every revision to stay on
1353	/// the subscription until media reaches its stamped slot ([`Self::advance`]), so the
1354	/// TS importer's SI tracks declare their catalog's media max age ([`super::si::track_info`]).
1355	max_age: Duration,
1356}
1357
1358/// A complete clock snapshot and its placement, kept separate from the last emitted value.
1359struct SiRevision {
1360	snapshot: super::si::Snapshot,
1361	timestamp: Timestamp,
1362	/// Media already muxed when this snapshot completed. A late value cannot occupy that slot.
1363	after: Option<Timestamp>,
1364}
1365
1366/// The SI subscription's lifecycle, mirroring `ExportSource`'s but reading raw
1367/// snapshot groups instead of timestamp-paced container frames.
1368enum SiState {
1369	/// Waiting for the catalog broadcast to resolve; the track (by name) is
1370	/// subscribed once it does.
1371	Requesting(crate::Binding, String),
1372	/// Waiting for the subscription to resolve.
1373	Subscribing(kio::Pending<moq_net::track::Subscribing>),
1374	/// The resolved subscription, reading snapshot groups. Boxed: a reader is far larger
1375	/// than the other states.
1376	Active {
1377		track: Box<moq_net::track::Ordered>,
1378		_priority: crate::source::Priority,
1379	},
1380	/// The track ended or failed; retain the last complete snapshot on its cadence.
1381	Done,
1382}
1383
1384impl SiTrack {
1385	fn new(source: &crate::Source, (table_id, entry): (u8, &catalog::SiEntry), max_age: Duration) -> Self {
1386		// An entry read from the inline catalog form has its sections in hand and
1387		// no track to subscribe to: it starts (and stays) where an ended track ends
1388		// up, re-emitting a fixed snapshot on its interval.
1389		let (state, active) = if entry.sections.is_empty() {
1390			(
1391				SiState::Requesting(source.request_catalog(), entry.track.clone()),
1392				Default::default(),
1393			)
1394		} else {
1395			(SiState::Done, Self::inline(entry))
1396		};
1397		Self {
1398			source: source.clone(),
1399			track: entry.track.clone(),
1400			interval: entry.interval,
1401			clock: is_clock_table(table_id),
1402			state,
1403			// Inline sections are a snapshot that has not hit the wire yet, which a
1404			// clock table only sends as a revision.
1405			dirty: !active.is_empty(),
1406			active,
1407			pending: None,
1408			future: None,
1409			position: None,
1410			last_emit: None,
1411			max_age,
1412		}
1413	}
1414
1415	/// The snapshot an inline-form entry's sections reduce to.
1416	fn inline(entry: &catalog::SiEntry) -> super::si::Snapshot {
1417		let mut snapshot = super::si::Snapshot::default();
1418		for section in &entry.sections {
1419			snapshot.apply(section);
1420		}
1421		snapshot
1422	}
1423
1424	/// Read ordinary SI into `active`, or stage one clock revision. Never returns
1425	/// an error: SI is auxiliary, so a failed or ended track logs and keeps the last
1426	/// snapshot rather than killing the mux.
1427	fn poll(&mut self, waiter: &kio::Waiter) {
1428		if self.future.is_some() {
1429			return;
1430		}
1431		if matches!(self.state, SiState::Requesting(..)) {
1432			// Scope the borrow of `self.state` so the transitions below can assign it.
1433			let resolved = {
1434				let SiState::Requesting(pending, name) = &self.state else {
1435					unreachable!("just matched Requesting");
1436				};
1437				match pending.poll_broadcast(waiter) {
1438					Poll::Ready(Ok(broadcast)) => Ok((broadcast, name.clone())),
1439					Poll::Ready(Err(err)) => Err(err),
1440					Poll::Pending => return,
1441				}
1442			};
1443			self.state = match resolved {
1444				Ok((broadcast, name)) => match broadcast.track(&name) {
1445					Ok(track) => SiState::Subscribing(track.subscribe(self.source.subscription(
1446						moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
1447							moq_net::track::Start::Live {
1448								min: Some(self.max_age),
1449								max: Some(self.max_age),
1450							},
1451						)]),
1452					))),
1453					Err(err) => {
1454						tracing::warn!(%err, track = %name, "SI track unavailable; carrying the last snapshot");
1455						SiState::Done
1456					}
1457				},
1458				Err(err) => {
1459					tracing::warn!(%err, "SI broadcast unavailable; carrying the last snapshot");
1460					SiState::Done
1461				}
1462			};
1463		}
1464
1465		if matches!(self.state, SiState::Subscribing(_)) {
1466			let resolved = {
1467				let SiState::Subscribing(pending) = &self.state else {
1468					unreachable!("just matched Subscribing");
1469				};
1470				match pending.poll_ok(waiter) {
1471					Poll::Ready(result) => result.and_then(|track| {
1472						let priority = self.source.control(track.control())?;
1473						Ok((track, priority))
1474					}),
1475					Poll::Pending => return,
1476				}
1477			};
1478			self.state = match resolved {
1479				Ok((track, priority)) => SiState::Active {
1480					track: Box::new(track.ordered()),
1481					_priority: priority,
1482				},
1483				Err(err) => {
1484					tracing::warn!(%err, "SI subscription failed; carrying the last snapshot");
1485					SiState::Done
1486				}
1487			};
1488		}
1489
1490		let mut ended = false;
1491		if let SiState::Active { track, .. } = &mut self.state {
1492			while !self.clock || self.pending.is_none() {
1493				// Ordinary SI uses the latest snapshot. A clock revision must stay in
1494				// order until media reaches its stamp, including an incomplete group.
1495				match track.poll_next_group(waiter) {
1496					// SI carries the last snapshot over a group given up on.
1497					Poll::Ready(Ok(Some(group))) => {
1498						self.pending = Some((group, Default::default(), Timestamp::ZERO));
1499					}
1500					Poll::Ready(Ok(None)) => {
1501						ended = true;
1502						break;
1503					}
1504					Poll::Ready(Err(err)) => {
1505						tracing::warn!(%err, "SI track failed; carrying the last snapshot");
1506						ended = true;
1507						break;
1508					}
1509					Poll::Pending => break,
1510				}
1511			}
1512		}
1513		if ended {
1514			self.state = SiState::Done;
1515		}
1516
1517		// Read the pending group to its end, then promote it wholesale: emitting a
1518		// half-received snapshot would re-introduce the torn state the group
1519		// boundary exists to prevent.
1520		while let Some((group, snapshot, timestamp)) = &mut self.pending {
1521			let (promote, drop_pending) = match group.poll_read_frame(waiter) {
1522				Poll::Ready(Ok(Some(frame))) => {
1523					snapshot.apply(&frame.payload);
1524					// A scale-less track's frames carry no time, so its revision stays at zero.
1525					if frame.timestamp.scale().is_some() {
1526						*timestamp = crate::container::later(*timestamp, frame.timestamp);
1527					}
1528					(false, false)
1529				}
1530				Poll::Ready(Ok(None)) => (true, false),
1531				Poll::Ready(Err(err)) => {
1532					tracing::warn!(%err, "SI group failed; carrying the last snapshot");
1533					(false, true)
1534				}
1535				Poll::Pending => break,
1536			};
1537			if promote {
1538				let (_, snapshot, timestamp) = self.pending.take().unwrap();
1539				if self.clock {
1540					self.future = Some(SiRevision {
1541						snapshot,
1542						timestamp,
1543						after: self.position,
1544					});
1545					break;
1546				}
1547				// A repeated group (the same section set re-published) is not a change:
1548				// treating it as one would turn the source's snapshot cadence into extra
1549				// wire repetitions.
1550				self.dirty |= snapshot != self.active;
1551				self.active = snapshot;
1552			} else if drop_pending {
1553				self.pending = None;
1554			}
1555		}
1556	}
1557
1558	/// Promote clock revisions whose grid slot media has reached. Reading stops at one
1559	/// future snapshot, so replay preserves revisions without an exporter-owned queue.
1560	fn advance(&mut self, timestamp: Timestamp) {
1561		if !self.clock {
1562			return;
1563		}
1564		let interval = SI_REVISION_INTERVAL.min(self.interval.unwrap_or(PSI_INTERVAL));
1565		loop {
1566			self.poll(&kio::Waiter::noop());
1567			let Some(revision) = &self.future else { break };
1568			if !interval.is_zero() {
1569				let stamped = nanos(revision.timestamp).div_ceil(interval.as_nanos());
1570				let at = revision
1571					.after
1572					.map_or(stamped, |after| stamped.max(slot(after, interval) + 1));
1573				if slot(timestamp, interval) < at {
1574					break;
1575				}
1576			} else if timestamp < revision.timestamp {
1577				break;
1578			}
1579			let SiRevision { snapshot, .. } = self.future.take().unwrap();
1580			self.dirty |= snapshot != self.active;
1581			self.active = snapshot;
1582		}
1583		self.position = Some(
1584			self.position
1585				.map_or(timestamp, |position| crate::container::later(position, timestamp)),
1586		);
1587	}
1588
1589	/// Take a due snapshot, keeping revisions and repeats on their respective cadence.
1590	fn emit(&mut self, timestamp: Timestamp) -> Option<Vec<Bytes>> {
1591		self.advance(timestamp);
1592		let interval = self.interval.unwrap_or(PSI_INTERVAL);
1593		let floor = SI_REVISION_INTERVAL.min(interval);
1594		let revision = self.dirty
1595			&& if self.clock {
1596				due(timestamp, self.last_emit, floor)
1597			} else {
1598				si_due(timestamp, self.last_emit, floor)
1599			};
1600		// A declared interval is the table's limit. The sections go out with the frame they are
1601		// muxed ahead of, up to its send-ahead late on the media timeline, so they repeat at
1602		// half of it.
1603		let cadence = self.interval.map_or(PSI_INTERVAL, |limit| limit / 2);
1604		let repeat = !self.clock && due(timestamp, self.last_emit, cadence);
1605		if self.active.is_empty() || !(revision || repeat) {
1606			return None;
1607		}
1608		self.dirty = false;
1609		// A zero interval can emit on a reordered PTS. Keep the anchor ahead of it,
1610		// or raising the interval later could credit that reorder span as elapsed time.
1611		self.last_emit = Some(
1612			self.last_emit
1613				.map_or(timestamp, |last| crate::container::later(last, timestamp)),
1614		);
1615		Some(self.active.sections().cloned().collect())
1616	}
1617}
1618
1619impl<S: Stream> Program<S>
1620where
1621	S::Ext: catalog::Catalog,
1622{
1623	fn new(mut source: crate::Source, catalog: S, delay: Duration) -> Self {
1624		source.isolate();
1625		// The jitter buffer drops what a join trims or what arrives late, so only what goes out counts.
1626		source.bill();
1627		let identity = source.broadcast().info().identity.clone();
1628		Self {
1629			id: 0,
1630			expected: Vec::new(),
1631			expected_changed: false,
1632			source,
1633			catalog: Some(catalog),
1634			cataloged: false,
1635			feed: Feed::Live,
1636			identity,
1637			version: VersionNumber::default(),
1638			pat_version: VersionNumber::default(),
1639			flagged: None,
1640			tables: Vec::new(),
1641			psi_due: false,
1642			revised: false,
1643			delay,
1644			generation: 0,
1645			tracks: HashMap::new(),
1646			counters: FxHashMap::default(),
1647			program_descriptors: Vec::new(),
1648			program: None,
1649			si: BTreeMap::new(),
1650			last_timestamp: None,
1651			si_flushed: false,
1652			psi: None,
1653			last_psi: None,
1654			epoch: 0,
1655			emitted_epoch: 0,
1656			pcr_discontinuity: false,
1657			schedule: Schedule::new(delay),
1658			slot_timer: None,
1659			replay: false,
1660			queue: VecDeque::new(),
1661			liveness: Default::default(),
1662			video_start: None,
1663			video_out: None,
1664			trimmed: 0,
1665			mux_rate: None,
1666			mux_rate_override: None,
1667			led_rate: None,
1668			rate_from: None,
1669			held_catalog: None,
1670			rate_until: None,
1671			rate_wait: super::mux_rate::WAIT,
1672			rate_timer: None,
1673		}
1674	}
1675}
1676impl<S: Stream> Export<S>
1677where
1678	S::Ext: catalog::Catalog,
1679{
1680	/// Export `source` as MPEG-TS, driving track subscriptions from `catalog`.
1681	///
1682	/// The caller chooses the catalog format and rendition selection on any [`Stream`].
1683	/// The stream remains owned until the export is dropped or follows another broadcast;
1684	/// concrete catalog consumers release their subscription and decoder when they end.
1685	///
1686	/// Mux each frame `delay` after its release time, like an SRT receiver's TSBPD: its
1687	/// decode time less its send-ahead.
1688	///
1689	/// The send-ahead comes out of the same budget. A frame may go out up to the delay
1690	/// ahead of its decode time, as far as its PID's decoder buffer holds and as early as the
1691	/// receiver's buffers admit, so a heavy passage rides the slots before it. Its release
1692	/// time is that far before its decode time, so it is muxed just as the first slot it may
1693	/// ride is laid, and each slot goes out the delay after its own time on the source's
1694	/// clock rather than a delay later still.
1695	///
1696	/// The clock is acquired before anything goes out: frames are held until every expected
1697	/// track has delivered (two delays at most) and a track starts a new group, or for a delay
1698	/// at most once all have. The track sent latest against its release time sets the clock,
1699	/// so a joiner runs at the delay from its first output and every frame has the whole delay
1700	/// to arrive in. A source that sends its video its send-ahead
1701	/// early, as a TS mux does, is trailed by the delay; one that sends every track at its
1702	/// decode time, by the delay and the video's send-ahead. The output then keeps the
1703	/// source's pace and muxes every track in `(release time, PID)` order whatever the
1704	/// arrival skew between them. A frame that arrives after its deadline is dropped, and a
1705	/// video track that dropped one resumes at its next keyframe. A source whose clock runs
1706	/// further off ours than 13818-1 lets the PCR follow fails the export once it has used half
1707	/// the delay, where a brief network stall only drops what it made late. Every track is
1708	/// subscribed with the whole delay as its max, so a relay resets a group only once it is that
1709	/// old; a live export joins at the edge, and a replay reaches back the whole delay. The export skips a stalled group once it falls the whole delay behind the
1710	/// newest content (see [`Consumer`](crate::container::Consumer)), so a stall shorter than the
1711	/// delay loses nothing, while a group whose tail never arrives makes the start of the next one
1712	/// late.
1713	///
1714	/// With a multiplex rate, a frame that cannot arrive by its decode time fails the export,
1715	/// as does video whose HRD declares a buffer delay past the delay.
1716	///
1717	/// A zero `delay` holds nothing and sends each frame by its decode time.
1718	pub fn new(source: crate::Source, catalog: S, delay: Duration) -> Self {
1719		let program = Program::new(source, catalog, delay);
1720		Self {
1721			program,
1722			jitter: jitter::Buffer::new(delay),
1723			held: None,
1724			pending: None,
1725			next_program: 1,
1726			active_program: 0,
1727			follow_until: None,
1728			follow_timer: None,
1729			caught_up: None,
1730		}
1731	}
1732
1733	/// Pad the output with null packets to `mux_rate` bits per second, whatever the
1734	/// catalog records, which is used as given. Without this the catalog's `mpegts.muxRate`
1735	/// decides, a packet a slot faster for the export's own clock and framing, and a catalog
1736	/// without one leaves the output unpadded.
1737	///
1738	/// Zero and absurd rates are refused with a warning, leaving the output
1739	/// unpadded rather than allocating unbounded nulls.
1740	pub fn with_mux_rate(mut self, mux_rate: u64) -> Self {
1741		if sanitize_mux_rate(mux_rate).is_none() {
1742			tracing::warn!(mux_rate, "ignoring invalid MPEG-TS multiplex rate override");
1743		}
1744		self.program.mux_rate_override = Some(mux_rate);
1745		self.program.mux_rate = sanitize_mux_rate(mux_rate);
1746		self.program.led_rate = self.program.mux_rate;
1747		self.program.schedule.set_rate(self.program.mux_rate);
1748		self
1749	}
1750
1751	/// Start at once on a catalog that records no rate, for a test whose clock a wait would move.
1752	#[cfg(test)]
1753	pub(super) fn without_rate_wait(mut self) -> Self {
1754		self.program.rate_wait = Duration::ZERO;
1755		self
1756	}
1757
1758	/// Read each track from the oldest group the delay still reaches instead of the live
1759	/// edge, and anchor the clock on the first frame instead of acquiring it, for a test that
1760	/// writes a broadcast whole before exporting it.
1761	#[cfg(test)]
1762	pub(super) fn with_replay(mut self) -> Self {
1763		self.program.replay = true;
1764		self.jitter = jitter::Buffer::new(self.program.delay).replay();
1765		self
1766	}
1767
1768	/// Get the next muxed frame.
1769	///
1770	/// Each [`Frame`] carries one slice of the PCR grid in `payload`: the clock
1771	/// packets that slice opens with, followed by the muxed bytes belonging to it.
1772	/// With a [delay](Self::new), each slice is handed over at its time on the
1773	/// jitter buffer's clock, which follows the source's, so a sink writes it as it
1774	/// comes. It is stamped with the media time that slice starts at, for a transport
1775	/// that stamps its own delivery, and `keyframe` marks the slice a video keyframe
1776	/// begins in. The leading PAT/PMT rides on the first slice, and is
1777	/// re-emitted at video keyframes and periodically for mid-stream tune-in.
1778	/// Returns `None` when the broadcast ends. `duration` is always `None`: the
1779	/// muxer has no use for it.
1780	#[cfg_attr(feature = "async", kio::wrapper)]
1781	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
1782		let poll = self.poll_frame(waiter);
1783		if poll.is_pending() {
1784			self.caught_up = Some(kio::clock::now());
1785		}
1786		poll
1787	}
1788
1789	fn poll_frame(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
1790		if self.pending.is_some() {
1791			self.stop_old(waiter)?;
1792		}
1793		if let Err(err) = self.prepare(waiter) {
1794			self.leave(err)?;
1795		}
1796		if self.pending.is_some() {
1797			loop {
1798				if let Err(err) = self.prepare_pending(waiter) {
1799					// A replacement that leaves before it commits is no switch: the old program
1800					// plays on, and a later replacement gets its own follow window.
1801					if self.jitter.is_committed()
1802						|| matches!(self.program.feed, Feed::Retired(_))
1803						|| !super::follower::left(&err)
1804					{
1805						return Poll::Ready(Err(err));
1806					}
1807					tracing::warn!(%err, "replacement left before it went out, keeping the old program");
1808					self.cancel_pending();
1809					self.program.source.priority(0)?;
1810					self.follow_until = None;
1811					self.follow_timer = None;
1812					break;
1813				}
1814				self.stop_old(waiter)?;
1815				let Poll::Ready(ready) = self.jitter.poll_pending(waiter) else {
1816					break;
1817				};
1818				let mut pending = self.pending.take().expect("an acquiring program");
1819				std::mem::swap(&mut self.program, pending.as_mut());
1820				let kind = self
1821					.program
1822					.tracks
1823					.get(&ready.track.name)
1824					.context("missing incoming track")?
1825					.kind
1826					.clone();
1827				let leading = self.leads_video(&kind, &ready.item);
1828				let waiting = !leading
1829					&& self.program.video_out.is_none()
1830					&& self
1831						.program
1832						.tracks
1833						.values()
1834						.any(|track| matches!(track.kind, Kind::Video(_)));
1835				if !leading && !waiting {
1836					// A future queued video start can still be cut. Own its Ready
1837					// before selecting the program, and recheck held audio against it.
1838					for held in self.jitter.take_pending() {
1839						let kind = self
1840							.program
1841							.tracks
1842							.get(&held.track.name)
1843							.context("missing held track")?
1844							.kind
1845							.clone();
1846						if held.generation != ready.generation || self.leads_video(&kind, &held.item) {
1847							self.jitter.discard(&held);
1848						} else {
1849							self.jitter.hold_pending(held);
1850						}
1851					}
1852				}
1853				std::mem::swap(&mut self.program, pending.as_mut());
1854				self.pending = Some(pending);
1855				if leading {
1856					self.jitter.discard(&ready);
1857					continue;
1858				}
1859				if waiting {
1860					self.jitter.hold_pending(ready);
1861					continue;
1862				}
1863				for (name, track) in &mut self.program.tracks {
1864					track.release(name, &mut self.jitter, true)?;
1865				}
1866				tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "commit-program", now = ?kio::clock::now(), old = self.program.id, new = ready.track.program, generation = ready.generation, pts = ?ready.item.frame.timestamp, key = ?ready.item.key, decode = ?ready.item.decode);
1867				self.jitter.commit(ready)?;
1868				break;
1869			}
1870		}
1871
1872		// Once every source has ended, the tail goes out late if it must: the end of the
1873		// stream is not a missed deadline.
1874		self.program.schedule.set_ended(
1875			!self.program.tracks.is_empty()
1876				&& self
1877					.program
1878					.tracks
1879					.values_mut()
1880					.all(|track| track.read != Read::Live || track.source.poll_received(waiter).is_ready()),
1881		);
1882
1883		// 4. Mux each frame the jitter buffer lets go (the first carries the buffered
1884		// PAT/PMT), then lay out every grid slot whose time has come ([`Self::lay_due`]).
1885		// A shed makes room in each source's jitter window, so read them again.
1886		if self.program.queue.is_empty()
1887			&& self.shed()
1888			&& let Err(err) = self.fill(waiter)
1889		{
1890			self.leave(err)?;
1891		}
1892		loop {
1893			if let Some(out) = self.pop() {
1894				return Poll::Ready(Ok(Some(out)));
1895			}
1896			self.settle()?;
1897			let ready = match self.held.take() {
1898				Some(ready) => ready,
1899				None => match self.jitter.poll_next(waiter) {
1900					Poll::Ready(ready) => ready,
1901					Poll::Pending => break,
1902				},
1903			};
1904			let switching = self.pending.as_ref().is_some_and(|next| ready.track.program == next.id);
1905			if switching {
1906				let mut pending = self.pending.take().expect("the ready program");
1907				std::mem::swap(&mut self.program, pending.as_mut());
1908				let kind = self
1909					.program
1910					.tracks
1911					.get(&ready.track.name)
1912					.context("missing incoming track")?
1913					.kind
1914					.clone();
1915				let leading = self.leads_video(&kind, &ready.item);
1916				std::mem::swap(&mut self.program, pending.as_mut());
1917				self.pending = Some(pending);
1918				if leading {
1919					self.jitter.discard(&ready);
1920					continue;
1921				}
1922			}
1923			if switching && (!self.program.schedule.is_empty() || self.packing()) {
1924				self.lay(None)?;
1925				self.held = Some(ready);
1926				continue;
1927			}
1928			if switching {
1929				self.adopt(&ready)?;
1930			}
1931			if ready.generation > self.program.generation {
1932				if !self.program.schedule.is_empty() || self.packing() {
1933					// A boundary ends valid media rather than reneging it.
1934					// Return that tail under the old generation before adopting the new one.
1935					self.lay(None)?;
1936					self.held = Some(ready);
1937					continue;
1938				}
1939				self.rewind();
1940				self.program.generation = ready.generation;
1941			}
1942			debug_assert!(
1943				ready.generation >= self.program.generation,
1944				"the jitter buffer released an older generation after a newer one"
1945			);
1946			if ready.track.program != self.program.id {
1947				return Poll::Ready(Err(malformed!("a queued frame outlived its publisher program").into()));
1948			}
1949			let name = ready.track.name.clone();
1950			let kind = self.program.tracks.get(&name).context("missing track")?.kind.clone();
1951			if self.leads_video(&kind, &ready.item) {
1952				self.jitter.discard(&ready);
1953			} else {
1954				self.program.last_timestamp = Some(ready.item.frame.timestamp);
1955				let decode = nanos(ready.item.decode);
1956				self.lay_before(nanos(ready.item.key))?;
1957				match self.list(&name)? {
1958					true => self.mux(&name, ready.item)?,
1959					false => self
1960						.program
1961						.tracks
1962						.get_mut(&name)
1963						.expect("a listed track")
1964						.parked
1965						.push_back(ready.item),
1966				}
1967				if self.program.delay.is_zero() {
1968					// Without a clock to lay slots on, a frame settles every slot before its own: a
1969					// later frame decodes no earlier, so it can be due no earlier than this, less the
1970					// longest drain of any track.
1971					let drain = self.max_drain();
1972					self.lay(Some(schedule::slot(decode.saturating_sub(drain.as_nanos()))))?;
1973				}
1974			}
1975			if self.program.queue.is_empty() && !self.jitter.is_committed() {
1976				// Releasing a due frame opens room in its source. Read it before parking:
1977				// a zero-delay slot may need another frame to prove the slot is complete.
1978				let track = self.program.tracks.get_mut(&name).expect("the released frame's track");
1979				let live = track.read == Read::Live;
1980				let filled = track.fill(
1981					&name,
1982					waiter,
1983					&mut Input {
1984						waiting_for_header: false,
1985						video_start: self.program.video_start,
1986						jitter: &mut self.jitter,
1987						trimmed: &mut self.program.trimmed,
1988					},
1989				);
1990				let ended = live && track.read != Read::Live;
1991				if let Err(err) = filled.and_then(|lost| lost.map_or(Ok(()), |err| self.survive(&name, err))) {
1992					self.leave(err)?;
1993				}
1994				if ended || matches!(self.program.feed, Feed::Retired(_)) {
1995					self.program.schedule.set_ended(
1996						self.program
1997							.tracks
1998							.values_mut()
1999							.all(|track| track.read != Read::Live || track.source.poll_received(waiter).is_ready()),
2000					);
2001				}
2002			}
2003		}
2004		// A PES's frames leave the jitter buffer together, under its first frame's key
2005		// ([`Track::release_key`]), so with none due its pack is whole, and without slots
2006		// running on an empty schedule nothing else would send it on before it is due.
2007		if self.program.schedule.is_empty() {
2008			self.flush_packs(|_, _| true)?;
2009		}
2010		self.lay_due(waiter)?;
2011		self.settle()?;
2012		if let Some(out) = self.pop() {
2013			return Poll::Ready(Ok(Some(out)));
2014		}
2015
2016		// 5. Once every track has drained, nothing more can ride the slots still open, so
2017		// they go out: at their times on the clock, or at once without one. That's
2018		// independent of the catalog: a retained track finishes while the broadcast stays
2019		// live, and holding its tail until the catalog closed would strand it indefinitely.
2020		let drained = !self.program.tracks.is_empty()
2021			&& self
2022				.program
2023				.tracks
2024				.values()
2025				.all(|t| t.read != Read::Live && t.parked.is_empty())
2026			&& self.jitter.is_empty()
2027			&& self.held.is_none();
2028		if drained {
2029			if self.slot_due().is_none() {
2030				self.lay(None)?;
2031			}
2032			if let Some(out) = self.pop() {
2033				return Poll::Ready(Ok(Some(out)));
2034			}
2035			if !self.program.schedule.is_empty() {
2036				return Poll::Pending;
2037			}
2038			// SI emission rides media frames, so a snapshot that arrived behind the
2039			// last one gets one trailing flush before the stream ends.
2040			if !matches!(self.program.feed, Feed::Live) && !self.program.si_flushed {
2041				self.program.si_flushed = true;
2042				if let Some(out) = self.write_si_tail()? {
2043					return Poll::Ready(Ok(Some(out)));
2044				}
2045			}
2046		}
2047
2048		let pending_ended = !self.jitter.is_committed()
2049			&& self.pending.as_ref().is_some_and(|pending| {
2050				let finished = !matches!(pending.feed, Feed::Live)
2051					&& (pending.tracks.is_empty() || pending.tracks.values().all(|track| track.read != Read::Live));
2052				let no_video_start = pending.video_out.is_none()
2053					&& pending
2054						.tracks
2055						.values()
2056						.any(|track| matches!(track.kind, Kind::Video(_)))
2057					&& pending
2058						.tracks
2059						.values()
2060						.filter(|track| matches!(track.kind, Kind::Video(_)))
2061						.all(|track| !self.jitter.holds(&track.key));
2062				finished && (self.jitter.pending_empty() || no_video_start)
2063			});
2064		if pending_ended
2065			&& (drained || self.program.tracks.is_empty())
2066			&& self.program.schedule.is_empty()
2067			&& self.program.queue.is_empty()
2068		{
2069			return Poll::Ready(Ok(None));
2070		}
2071
2072		// End of stream once the catalog is closed too: nothing more can appear.
2073		if self.pending.is_none()
2074			&& !matches!(self.program.feed, Feed::Live)
2075			&& (drained || self.program.tracks.is_empty())
2076		{
2077			return Poll::Ready(match &mut self.program.feed {
2078				Feed::Retired(left) => left.take().map_or(Ok(None), Err),
2079				Feed::Live | Feed::Ended => Ok(None),
2080			});
2081		}
2082
2083		Poll::Pending
2084	}
2085
2086	/// Return the next queued frame, committing what it carries to the output boundary.
2087	fn pop(&mut self) -> Option<Frame> {
2088		let (out, tally) = self.program.queue.pop_front()?;
2089		if let Some(tables) = tally.tables
2090			&& let Some(psi) = &mut self.program.psi
2091		{
2092			psi.out = Some(tables);
2093		}
2094		self.program.emitted_epoch = self.program.epoch;
2095		let (pcr, discontinuity) = tally.pcr;
2096		if discontinuity {
2097			self.program.liveness.discontinuity();
2098		}
2099		self.program.liveness.written_pcr(pcr);
2100		for pid in tally.units {
2101			self.program.liveness.delivered(pid, 1);
2102		}
2103		for (bill, bytes) in tally.charges {
2104			bill.deliver(bytes);
2105		}
2106		Some(out)
2107	}
2108
2109	/// The trailing SI frame for end of stream. Ordinary tables repeat once; clock
2110	/// values keep their stamped placement and never re-assert an already emitted time.
2111	fn write_si_tail(&mut self) -> Result<Option<Frame>> {
2112		if self.program.psi.is_none() {
2113			return Ok(None);
2114		}
2115		let timestamp = self.program.last_timestamp.unwrap_or(Timestamp::ZERO);
2116		let pending: Vec<(u16, Vec<Bytes>)> = self
2117			.program
2118			.si
2119			.iter_mut()
2120			.filter_map(|((pid, _), si)| {
2121				let sections = if si.clock {
2122					si.emit(timestamp)?
2123				} else if !si.active.is_empty() {
2124					si.active.sections().cloned().collect()
2125				} else {
2126					return None;
2127				};
2128				Some((*pid, sections))
2129			})
2130			.collect();
2131		if pending.is_empty() {
2132			return Ok(None);
2133		}
2134		let mut out = Vec::new();
2135		for (pid, sections) in pending {
2136			for section in &sections {
2137				self.write_section(&mut out, pid, section)?;
2138			}
2139		}
2140		self.number(&mut out);
2141		Ok(Some(Frame {
2142			timestamp,
2143			decode: None,
2144			duration: None,
2145			payload: Bytes::from(out),
2146			keyframe: false,
2147		}))
2148	}
2149
2150	fn prepare_pending(&mut self, waiter: &kio::Waiter) -> crate::Result<()> {
2151		let mut pending = self.pending.take().expect("a selected program");
2152		std::mem::swap(&mut self.program, pending.as_mut());
2153		let result = self.prepare(waiter);
2154		std::mem::swap(&mut self.program, pending.as_mut());
2155		self.pending = Some(pending);
2156		result.map(|_| ())
2157	}
2158
2159	fn selected(&self) -> &Program<S> {
2160		self.pending.as_deref().unwrap_or(&self.program)
2161	}
2162
2163	fn prepare(&mut self, waiter: &kio::Waiter) -> crate::Result<bool> {
2164		if matches!(self.program.feed, Feed::Retired(_))
2165			|| (self.program.id == self.active_program && self.jitter.is_committed())
2166		{
2167			return Ok(true);
2168		}
2169		// 1. Drain catalog updates, discovering the track layout.
2170		while matches!(self.program.feed, Feed::Live)
2171			&& let Some(catalog) = self.program.catalog.as_mut()
2172		{
2173			match catalog.poll_next(waiter)? {
2174				Poll::Ready(Some(snapshot)) => {
2175					self.program.cataloged = true;
2176					self.program.held_catalog = Some(snapshot.value);
2177				}
2178				Poll::Ready(None) => {
2179					self.program.feed = Feed::Ended;
2180					break;
2181				}
2182				Poll::Pending => break,
2183			}
2184		}
2185		if let Some(mut snapshot) = self.program.held_catalog.take() {
2186			if self.awaiting_rate(&mut snapshot, waiter) {
2187				self.program.held_catalog = Some(snapshot);
2188			} else {
2189				self.update_catalog(snapshot)?;
2190			}
2191		}
2192
2193		// 1b. Drive the SI subscriptions. Ordinary SI updates its active set; clock
2194		// revisions wait for their stamped media position in `mux`.
2195		//
2196		// Deliberately not part of the first-frame gate below: nothing in SI is
2197		// something a TS stream cannot begin without (the PAT/PMT are built locally,
2198		// and receivers acquire the service layer mid-stream by design), whereas
2199		// gating on it would let a catalog entry that never delivers (a stale
2200		// announce naming a dead track) hold the programme dark. An entry that
2201		// resolves late simply starts emitting on its cadence from then on, at most
2202		// one subscription round-trip behind the media.
2203		for si in self.program.si.values_mut() {
2204			si.poll(waiter);
2205		}
2206
2207		if self.program.expected_changed {
2208			if self.program.id == self.active_program {
2209				self.jitter.expect(self.program.expected.clone());
2210				self.program.expected_changed = false;
2211			} else if self.jitter.has_pending() || self.jitter.is_committed() {
2212				self.jitter.expect_pending(
2213					self.program.tracks.values().map(|track| track.key.clone()),
2214					self.program.expected.clone(),
2215				);
2216				self.program.expected_changed = false;
2217			}
2218		}
2219
2220		// 2. Read each source within its jitter window, or before the program tables
2221		// are built, hold one per track.
2222		self.fill(waiter)?;
2223
2224		// 3. Build the program tables once the layout is resolved and every
2225		// track's codec config is ready. The tables aren't emitted here: PSI has
2226		// no media time of its own, so `mux` prepends them to the first frame's
2227		// packets instead, letting the leading PAT/PMT inherit a real timestamp.
2228		if self.program.psi.is_none() {
2229			if self.program.tracks.is_empty() {
2230				return Ok(false);
2231			}
2232			if !self.header_ready() || !self.video_ready() {
2233				// Hold all output (tables and audio alike) until codec configs resolve
2234				// and, when the program has a video rendition, its first keyframe is
2235				// buffered: the stream must begin on that keyframe so the in-band
2236				// parameter sets lead it. An audio-only program has nothing to wait for.
2237				return Ok(false);
2238			}
2239			self.build_psi()?;
2240			// Anchor tune-in to the first video keyframe and drop any non-video frame
2241			// already buffered ahead of it (see `video_start`).
2242			self.program.video_start = self.first_video_pts();
2243			if let Some(start) = self.program.video_start {
2244				for track in self.program.tracks.values_mut() {
2245					if !matches!(track.kind, Kind::Video(_))
2246						&& !track.kind.placed()
2247						&& track.pending.as_ref().is_some_and(|p| p.frame.timestamp < start)
2248					{
2249						track.pending = None;
2250						self.program.trimmed += 1;
2251					}
2252				}
2253			}
2254			if self.program.id != self.active_program && !self.jitter.has_pending() && !self.jitter.is_committed() {
2255				tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "prepared", now = ?kio::clock::now(), program = self.program.id, old = self.active_program, tracks = self.program.tracks.len(), video_start = ?self.program.video_start);
2256				self.jitter.start(
2257					self.program.tracks.values().map(|track| track.key.clone()),
2258					self.program.expected.clone(),
2259				);
2260				self.program.expected_changed = false;
2261			}
2262
2263			// Hand the held frames to the jitter buffer in arrival order, so the
2264			// earliest anchors its clock, then read on.
2265			let mut held: Vec<(kio::clock::Instant, String)> = self
2266				.program
2267				.tracks
2268				.iter()
2269				.filter_map(|(name, t)| t.pending.as_ref().map(|p| (p.arrived, name.clone())))
2270				.collect();
2271			held.sort();
2272			for (_, name) in held {
2273				let track = self.program.tracks.get_mut(&name).unwrap();
2274				let pending = track.pending.take().unwrap();
2275				track.queue(&name, pending, &mut self.jitter)?;
2276			}
2277			self.fill(waiter)?;
2278		}
2279
2280		Ok(true)
2281	}
2282
2283	/// Whether the first catalog waits for the rate a TS import is still measuring, which only a
2284	/// padded output reads. The wait ends with the rate or at its deadline, whichever comes first.
2285	fn awaiting_rate(&mut self, catalog: &mut Catalog<S::Ext>, waiter: &kio::Waiter) -> bool {
2286		let program = &mut self.program;
2287		// A catalog that ended gains no rate.
2288		if program.mux_rate_override.is_some()
2289			|| program.psi.is_some()
2290			|| !program.tracks.is_empty()
2291			|| !matches!(program.feed, Feed::Live)
2292		{
2293			return false;
2294		}
2295		// A catalog without the section came from no TS import.
2296		let measuring = catalog
2297			.ext
2298			.mpegts_mut()
2299			.is_some_and(|mpegts| mpegts.mux_rate.is_none() && !mpegts.is_empty());
2300		if !measuring {
2301			program.rate_timer = None;
2302			return false;
2303		}
2304		let until = *program
2305			.rate_until
2306			.get_or_insert_with(|| kio::clock::now().saturating_add(program.rate_wait));
2307		if kio::clock::now() >= until {
2308			program.rate_timer = None;
2309			return false;
2310		}
2311		let timer = program
2312			.rate_timer
2313			.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(until)));
2314		// An elapsed deadline is ready on this first poll, so a wait never ends without a waker.
2315		if waiter.poll_future(timer.as_mut()).is_ready() {
2316			program.rate_timer = None;
2317			return false;
2318		}
2319		true
2320	}
2321
2322	/// The program playing failed with `err`. Only a publisher that left is survivable: its
2323	/// input stops at once, as a follow that runs out stops it, but what it already buffered
2324	/// goes out on schedule. Without a replacement, the export then reports `err`. A
2325	/// [`Follower`](super::Follower) carries on into the same identity returning meanwhile
2326	/// ([`Self::departed`]), whose tracks read on from where they stopped while that output
2327	/// plays out, and otherwise waits for a return only after the old output has ended.
2328	///
2329	/// The program keeps its catalog, whose format the follower subscribes a return with.
2330	fn leave(&mut self, err: crate::Error) -> crate::Result<()> {
2331		if !super::follower::left(&err) {
2332			return Err(err);
2333		}
2334		tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "left", now = ?kio::clock::now(), program = self.program.id, committed = self.jitter.is_committed(), %err);
2335		let left = self.pending.is_none().then_some(err);
2336		self.follow_timer = None;
2337		self.follow_until = None;
2338		self.retire(left)
2339	}
2340
2341	fn stop_old(&mut self, waiter: &kio::Waiter) -> crate::Result<()> {
2342		if matches!(self.program.feed, Feed::Retired(_)) {
2343			return Ok(());
2344		}
2345
2346		let expired = self.follow_until.is_some_and(|until| kio::clock::now() >= until);
2347		if !expired {
2348			if let Some(until) = self.follow_until {
2349				let timer = self
2350					.follow_timer
2351					.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(until)));
2352				if timer.deadline() != until {
2353					timer.as_mut().reset(until);
2354				}
2355				let _ = waiter.poll_future(timer.as_mut());
2356			}
2357			return Ok(());
2358		}
2359		tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow-expired", now = ?kio::clock::now(), program = self.program.id, committed = self.jitter.is_committed());
2360		self.follow_timer = None;
2361		self.follow_until = None;
2362		self.program.catalog = None;
2363		self.retire(None)
2364	}
2365
2366	/// Stop the program's input, reporting `left` once what it already buffered has gone out,
2367	/// unless a committed replacement's switch drops it.
2368	fn retire(&mut self, left: Option<crate::Error>) -> crate::Result<()> {
2369		self.program.feed = Feed::Retired(left);
2370		for (name, track) in &mut self.program.tracks {
2371			if track.read == Read::Live {
2372				if !self.jitter.is_committed() {
2373					track.release(name, &mut self.jitter, true)?;
2374				}
2375				track.source.stop();
2376				track.read = Read::Ended;
2377			}
2378		}
2379		for si in self.program.si.values_mut() {
2380			si.state = SiState::Done;
2381		}
2382		Ok(())
2383	}
2384
2385	fn adopt(&mut self, ready: &jitter::Ready<TrackKey, Queued>) -> crate::Result<()> {
2386		let Some(pending) = self.pending.as_ref() else {
2387			return Ok(());
2388		};
2389		if ready.track.program != pending.id {
2390			return Ok(());
2391		}
2392		let mut next = self.pending.take().expect("checked above");
2393		tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "adopt", now = ?kio::clock::now(), old = self.program.id, new = next.id, generation = ready.generation, old_pts = ?self.program.last_timestamp, new_pts = ?ready.item.frame.timestamp, new_key = ?ready.item.key);
2394		let out = self
2395			.program
2396			.psi
2397			.as_ref()
2398			.and_then(|psi| psi.out.as_ref())
2399			.map(|laid| (laid.version, laid.pat_version));
2400		(next.version, next.pat_version) = out.unwrap_or((self.program.version, self.program.pat_version));
2401		next.epoch = self.program.epoch;
2402		next.emitted_epoch = self.program.emitted_epoch;
2403		if out.is_some() {
2404			next.version.increment();
2405			next.pat_version.increment();
2406			next.epoch += 1;
2407			next.flagged = Some(HashSet::new());
2408			next.pcr_discontinuity = true;
2409		}
2410		// Tables were prepared under the incoming layout, but no packet has left it yet.
2411		next.psi = None;
2412		self.active_program = next.id;
2413		self.jitter.adopted();
2414		self.program = *next;
2415		self.program.generation = ready.generation;
2416		self.follow_until = None;
2417		self.follow_timer = None;
2418		self.build_psi()?;
2419		Ok(())
2420	}
2421
2422	/// Read each source within its jitter window.
2423	///
2424	/// Before the program tables are built, each track holds its first frame instead,
2425	/// and slices that arrive before their codec config resolves are dropped: a receiver
2426	/// joining mid-GOP can't use them, and parking them would stop us polling for the
2427	/// keyframe that carries the parameter sets. [`ExportSource`] has already transformed
2428	/// Annex-B input into length-prefixed form and resolved the avcC/hvcC.
2429	fn fill(&mut self, waiter: &kio::Waiter) -> crate::Result<()> {
2430		let mut input = Input {
2431			waiting_for_header: self.program.psi.is_none(),
2432			video_start: self.program.video_start,
2433			jitter: &mut self.jitter,
2434			trimmed: &mut self.program.trimmed,
2435		};
2436		let mut lost = Vec::new();
2437		for (name, track) in &mut self.program.tracks {
2438			if let Some(err) = track.fill(name, waiter, &mut input)? {
2439				lost.push((name.clone(), err));
2440			}
2441		}
2442		lost.into_iter().try_for_each(|(name, err)| self.survive(&name, err))
2443	}
2444
2445	/// Whether the export outlives the failure of track `name`, which [`Track::fill`] ended.
2446	///
2447	/// While another track still reads, only that rendition ends: a publisher that loses a
2448	/// source, such as a microphone, may list a replacement, which joins like any new rendition.
2449	/// With nothing left reading, the failure is the program's, as before.
2450	fn survive(&self, name: &str, err: crate::Error) -> crate::Result<()> {
2451		if !self.program.tracks.values().any(|track| track.read == Read::Live) {
2452			return Err(err);
2453		}
2454		tracing::warn!(track = name, %err, "rendition failed; the export keeps its other media");
2455		Ok(())
2456	}
2457
2458	fn update_catalog(&mut self, mut catalog: Catalog<S::Ext>) -> Result<()> {
2459		// The MPEG-TS section lives in the extension. The trait only exposes
2460		// `mpegts_mut`, and this snapshot is owned, so clone it out (`()` yields the
2461		// empty default: no verbatim streams, no preserved PIDs/descriptors).
2462		let mpegts = catalog.ext.mpegts_mut().cloned().unwrap_or_default();
2463		reject_ambiguous_tracks(&catalog, &mpegts)?;
2464		self.program.source.retain_selectable(&mut catalog);
2465
2466		self.program.program_descriptors = mpegts.program_descriptors.clone();
2467		self.program.program = mpegts.program.clone();
2468		// An explicit override wins even when it is refused (leaving the output
2469		// unpadded), so a bad flag cannot silently fall back to the catalog rate.
2470		let mux_rate = match self.program.mux_rate_override {
2471			Some(override_rate) => sanitize_mux_rate(override_rate),
2472			None => mpegts
2473				.mux_rate
2474				.and_then(|rate| {
2475					sanitize_mux_rate(rate).or_else(|| {
2476						tracing::warn!(mux_rate = rate, "ignoring invalid MPEG-TS multiplex rate in catalog");
2477						None
2478					})
2479				})
2480				.map(padded)
2481				// Audio goes out at most half the delay ahead (`audio_reach`).
2482				.map(|rate| match self.program.delay < 2 * PCR_INTERVAL {
2483					true => rate.max(audio_floor(&catalog)),
2484					false => rate,
2485				})
2486				.and_then(sanitize_mux_rate),
2487		};
2488		// A revision is one boundary: the rate rides the next tables out.
2489		let previous = self.program.mux_rate;
2490		if mux_rate != previous {
2491			self.program.mux_rate = mux_rate;
2492			self.program.revised = true;
2493		}
2494		if self.program.psi.is_none() {
2495			self.program.led_rate = self.program.mux_rate;
2496			self.program.schedule.set_rate(self.program.mux_rate);
2497		}
2498
2499		// Reconcile the SI subscriptions with the catalog's map. Entries may appear
2500		// after the PAT/PMT is built (a table acquired late): they ride standalone
2501		// PIDs outside the program, so unlike the elementary tracks below they are
2502		// not part of the latched layout.
2503		self.program
2504			.si
2505			.retain(|key, _| mpegts.si.get(&key.0).is_some_and(|t| t.contains_key(&key.1)));
2506		reject_colliding_si_pids(&mpegts, self.pmt_pid(), &[])?;
2507		for (pid, tables) in mpegts.si.iter() {
2508			for (table_id, entry) in tables.iter() {
2509				match self.program.si.get_mut(&(*pid, *table_id)) {
2510					// A repointed entry (same key, new track) rebuilds the subscription:
2511					// the old track is a restarted or replaced publisher's leftover, and
2512					// staying attached would repeat its stale sections forever. The last
2513					// snapshot carries across so emission never goes dark mid-swap.
2514					Some(existing) if existing.track != entry.track => {
2515						let mut replacement =
2516							SiTrack::new(&self.program.source, (*table_id, entry), self.program.delay);
2517						// An inline entry already holds its snapshot; only a track entry
2518						// has nothing to emit until its first group lands.
2519						if replacement.active.is_empty() {
2520							replacement.active = std::mem::take(&mut existing.active);
2521							replacement.dirty = existing.dirty;
2522						} else {
2523							replacement.dirty = replacement.active != existing.active;
2524						}
2525						replacement.last_emit = existing.last_emit;
2526						replacement.position = existing.position;
2527						*existing = replacement;
2528					}
2529					Some(existing) => {
2530						existing.interval = entry.interval;
2531						// Inline sections arrive with the catalog itself, so a revised
2532						// table shows up here rather than on a track.
2533						if !entry.sections.is_empty() {
2534							let snapshot = SiTrack::inline(entry);
2535							if existing.active != snapshot {
2536								existing.active = snapshot;
2537								existing.dirty = true;
2538							}
2539						}
2540					}
2541					None => {
2542						self.program.si.insert(
2543							(*pid, *table_id),
2544							SiTrack::new(&self.program.source, (*table_id, entry), self.program.delay),
2545						);
2546					}
2547				}
2548			}
2549		}
2550
2551		// The desired track set: media renditions plus the verbatim streams.
2552		let mut active: BTreeMap<String, ()> = BTreeMap::new();
2553		for name in catalog.video.renditions.keys() {
2554			active.insert(name.clone(), ());
2555		}
2556		for name in catalog.audio.renditions.keys() {
2557			active.insert(name.clone(), ());
2558		}
2559		for (name, track) in mpegts.tracks.iter() {
2560			if track.verbatim.is_some() || track.pes_packet.is_some() {
2561				active.insert(name.clone(), ());
2562			}
2563		}
2564
2565		if self.program.psi.is_some() {
2566			self.resubscribe(&catalog, &mpegts)?;
2567			self.rebind(&catalog)?;
2568			// A listed track keeps its PID, kind and descriptors, which its packets went out
2569			// under, even when the catalog moves it to another track: a stream the source
2570			// revises comes under a new name. The timing is not fixed: a `jitter` or
2571			// `framerate` published after the tables still sizes the decode clock.
2572			for (name, config) in catalog.video.renditions.iter() {
2573				if let Some(track) = self.program.tracks.get_mut(name).filter(|track| track.listed) {
2574					track.timing.configure(config, name)?;
2575				}
2576			}
2577			// A track that leaves the catalog is read to its own end. A publisher retires a
2578			// rendition as its track finishes or drops, and the catalog update races that end
2579			// on another stream, so the leaving cannot say which it was. The track's end does:
2580			// a finish ends it cleanly, and a drop is the error the export reports. One the PMT
2581			// does not list yet is read no further, so a publisher that never ends what it
2582			// withdraws leaves nothing behind but what it already sent, which still goes out. A
2583			// name that returns before that is gone is the same stream, so it is read on.
2584			for (name, track) in self.program.tracks.iter_mut() {
2585				track.cataloged = active.contains_key(name);
2586				match track.read {
2587					Read::Withdrawn if track.cataloged => track.read = Read::Live,
2588					Read::Live if !track.cataloged && !track.listed => {
2589						track.release(name, &mut self.jitter, true)?;
2590						track.read = Read::Withdrawn;
2591					}
2592					_ => {}
2593				}
2594			}
2595			self.revise()?;
2596			self.move_pmt(&mpegts)?;
2597		}
2598
2599		// Assign a PID to every desired track the PMT does not list yet: prefer the original
2600		// recorded in the `mpegts` section, then fill the rest from FIRST_ES_PID. The importer
2601		// fills PIDs, descriptors, and stream_ids across several catalog publishes, so this runs
2602		// every snapshot until the PMT lists the track, which is *refreshed*, not latched from
2603		// the first (partial) snapshot. A recorded PID may take over one a stream the catalog
2604		// dropped still drains on ([`Self::list`]); any other PID the PMT lists is taken.
2605		let pmt_pid = self.pmt_pid();
2606		let mut taken: Vec<u16> = vec![0x0000, 0x1FFF];
2607		taken.extend(self.pmt_pids());
2608		// The clock's own PID is taken, unless it waits for the track on it to list (a retag's
2609		// replacement, [`Self::revise`]): that track alone may keep it.
2610		let clock = self.program.psi.as_ref().and_then(|psi| psi.own_clock());
2611		let holder = clock.and_then(|pid| {
2612			(self.program.tracks.iter())
2613				.find(|(_, track)| track.cataloged && !track.listed && track.pid == pid)
2614				.map(|(name, _)| name.clone())
2615		});
2616		let reserved =
2617			|name: &str, pid: u16| holder.as_deref().is_some_and(|holder| holder != name) && Some(pid) == clock;
2618		if holder.is_none() {
2619			taken.extend(clock);
2620		}
2621		taken.extend(
2622			self.program
2623				.tracks
2624				.values()
2625				.filter(|t| t.listed && t.cataloged)
2626				.map(|t| t.pid),
2627		);
2628		let draining: Vec<u16> = self
2629			.program
2630			.tracks
2631			.values()
2632			.filter(|t| t.listed && !t.cataloged)
2633			.map(|t| t.pid)
2634			.collect();
2635		let joining: Vec<&String> = active
2636			.keys()
2637			.filter(|name| self.program.tracks.get(*name).is_none_or(|track| !track.listed))
2638			.collect();
2639		let mut pids: BTreeMap<String, u16> = BTreeMap::new();
2640		for &name in &joining {
2641			if let Some(pid) = mpegts.tracks.get(name).map(|t| t.pid)
2642				&& !taken.contains(&pid)
2643				&& !reserved(name, pid)
2644			{
2645				taken.push(pid);
2646				pids.insert(name.clone(), pid);
2647			}
2648		}
2649		for &name in &joining {
2650			if !pids.contains_key(name) {
2651				let mut pid = FIRST_ES_PID;
2652				while taken.contains(&pid) || draining.contains(&pid) || reserved(name, pid) {
2653					pid += 1;
2654				}
2655				taken.push(pid);
2656				pids.insert(name.clone(), pid);
2657			}
2658		}
2659		let es_pids: Vec<u16> = taken
2660			.iter()
2661			.chain(&draining)
2662			.copied()
2663			.filter(|&pid| pid >= 0x10 && pid != 0x1FFF)
2664			.collect();
2665		reject_colliding_si_pids(&mpegts, pmt_pid, &es_pids)?;
2666
2667		// Reuse each joining track's source (and any pending frame) by name; refresh its PID,
2668		// kind, and descriptors from this snapshot, and start over on one the catalog moved to
2669		// another track. Before the tables, drop tracks no longer present; after them, a track
2670		// the catalog dropped stays until what it holds is gone ([`Self::settle`]).
2671		let mut old: HashMap<String, Track> = self
2672			.program
2673			.tracks
2674			.extract_if(|name, track| !track.listed && active.contains_key(name))
2675			.collect();
2676		if self.program.psi.is_none() {
2677			self.program.tracks.clear();
2678		}
2679		for (name, config) in catalog.video.renditions.iter() {
2680			let Some(&pid) = pids.get(name) else {
2681				continue;
2682			};
2683			let kind = video_kind(config, name)?;
2684			let reused = old
2685				.remove(name)
2686				.filter(|track| track.source.reads(&self.program.source, name, config));
2687			let mut track = match reused {
2688				Some(track) => track,
2689				None => {
2690					match ExportSource::for_video(&self.program.source, name, config, subscribed(self.program.delay))?
2691						.map(|s| at_edge(skipping(s, self.program.delay), self.program.replay))
2692					{
2693						Some(source) => Track::new(source, kind.clone()),
2694						None => continue,
2695					}
2696				}
2697			};
2698			track.kind = kind;
2699			track.timing.configure(config, name)?;
2700			self.refresh(name, track, pid, track_descriptors(&mpegts, name));
2701		}
2702		for (name, config) in catalog.audio.renditions.iter() {
2703			let Some(&pid) = pids.get(name) else {
2704				continue;
2705			};
2706			let kind = audio_kind(config, name)?;
2707			let reused = old
2708				.remove(name)
2709				.filter(|track| track.source.reads(&self.program.source, name, config));
2710			let mut track = match reused {
2711				Some(track) => track,
2712				None => {
2713					match ExportSource::for_audio(&self.program.source, name, config, subscribed(self.program.delay))?
2714						.map(|s| at_edge(skipping(s, self.program.delay), self.program.replay))
2715					{
2716						Some(source) => Track::new(source, kind.clone()),
2717						None => continue,
2718					}
2719				}
2720			};
2721			track.buffer = Some(audio_buffer(config, &kind));
2722			track.kind = kind;
2723			self.refresh(name, track, pid, track_descriptors(&mpegts, name));
2724		}
2725		for (name, entry) in mpegts.tracks.iter() {
2726			let Some(&pid) = pids.get(name) else {
2727				continue;
2728			};
2729			let kind = match (&entry.verbatim, &entry.pes_packet) {
2730				(Some(verbatim), _) => Kind::Verbatim {
2731					stream_type: verbatim.stream_type,
2732				},
2733				(None, Some(pes)) => Kind::PesPacket {
2734					stream_type: pes.stream_type,
2735				},
2736				(None, None) => continue,
2737			};
2738			let mut track = match old.remove(name) {
2739				Some(track) => track,
2740				None => Track::new(
2741					stream_edge(
2742						skipping(
2743							ExportSource::for_stream(&self.program.source, name, subscribed(self.program.delay))?,
2744							self.program.delay,
2745						),
2746						&kind,
2747						self.program.replay,
2748					),
2749					kind.clone(),
2750				),
2751			};
2752			track.buffer = verbatim_buffer(&kind, &entry.descriptors);
2753			track.kind = kind;
2754			self.refresh(name, track, pid, entry.descriptors.clone());
2755		}
2756		// Every audio track follows the rate, a listed one too. Once the clock is anchored, a frame
2757		// keyed further ahead has that much less of the delay to arrive in, so the send-ahead grows
2758		// by no more than the frames have had to spare over the last second (or since the anchor,
2759		// in the first), less a slot. Until then it grows freely, as before the tables: what it
2760		// takes comes out of the delay, and no send-ahead reaches past half of it.
2761		//
2762		// Frames already keyed for less send-ahead would reach the new rate with too little of
2763		// it, so a rate that sends audio further ahead waits twice that send-ahead past the
2764		// newest frame keyed: the frames keyed after it catch up to the new send-ahead within it
2765		// ([`Track::release_key`]), and the frames keyed before it are due by the time the first
2766		// of those goes out.
2767		let window = schedule::slot(self.program.delay.as_nanos());
2768		// A replacement acquires its own clock beside the one playing, so it reads its own engine.
2769		let engine = match self.program.id == self.active_program {
2770			true => Some(&*self.jitter),
2771			false => self.jitter.replacement_engine(),
2772		};
2773		let engine = engine.filter(|_| self.program.psi.is_some());
2774		let spare = match engine.and_then(|engine| engine.spare_seen()) {
2775			None => self.program.delay,
2776			Some(seen) => {
2777				Duration::try_from_secs_f64(seen).map_or(Duration::ZERO, |seen| seen.saturating_sub(PCR_INTERVAL))
2778			}
2779		};
2780		// The least spare over a whole second below a slot: the delay is shorter than the source
2781		// sends its audio ahead, not a moment's late arrival.
2782		let short = engine
2783			.and_then(|engine| engine.margin())
2784			.filter(|&margin| margin < PCR_INTERVAL.as_secs_f64());
2785		let mut grown = Duration::ZERO;
2786		for (name, track) in self.program.tracks.iter_mut() {
2787			if let Some(buffer) = track
2788				.buffer
2789				.as_mut()
2790				.filter(|_| track.kind.class() == super::stats::Class::Audio)
2791			{
2792				// Only a new rate or a new track moves it, so the margin is spent once.
2793				let fresh = buffer.reach == audio_reach(buffer, None, self.program.delay);
2794				if self.program.mux_rate == previous && !fresh {
2795					continue;
2796				}
2797				let before = audio_reach(buffer, previous, self.program.delay).min(buffer.reach);
2798				let reach = audio_reach(buffer, self.program.mux_rate, self.program.delay);
2799				let before = Buffer {
2800					reach: before,
2801					..*buffer
2802				};
2803				// A rate that needs the audio further ahead than such a delay lets it go would miss its
2804				// deadlines.
2805				let wanted = Buffer { reach, ..*buffer };
2806				if let Some(margin) = short.filter(|_| self.program.mux_rate != previous)
2807					&& schedule::ahead(Some(&wanted), window) > schedule::ahead(Some(&before), window)
2808				{
2809					bail_unsupported!(
2810						"MPEG-TS multiplex rate {} b/s arrived mid-stream, but the {:?} delay is shorter than the source sends audio track '{name}' ahead: its frames had {:.0} ms to spare over the last second, less than the {:?} slot sending it ahead for the rate takes; raise the delay",
2811						self.program.mux_rate.unwrap_or_default(),
2812						self.program.delay,
2813						margin * 1e3,
2814						PCR_INTERVAL,
2815					);
2816				}
2817				buffer.reach = reach.min(before.reach + spare);
2818				if schedule::ahead(Some(buffer), window) > schedule::ahead(Some(&before), window) {
2819					grown = grown.max(buffer.reach);
2820				}
2821			}
2822		}
2823		if !grown.is_zero() && self.program.psi.is_some() {
2824			let newest = self
2825				.program
2826				.tracks
2827				.values()
2828				.filter_map(|track| track.released)
2829				.map(|(decode, ..)| nanos(decode))
2830				.max();
2831			self.program.rate_from = newest.map(|decode| decode + 2 * grown.as_nanos() + PCR_INTERVAL.as_nanos());
2832		}
2833		// The clock anchors on whichever track a source sends latest against its decode time
2834		// (audio just in time while video runs most of a second ahead), so it waits to hear
2835		// from each continuous one: audio, video, and the passthrough streams the schedule
2836		// models (DVB AC-3, teletext). Not from sparse ones such as SCTE-35, subtitles or ID3,
2837		// which would hold every join for the full bound.
2838		let continuous = self
2839			.program
2840			.tracks
2841			.iter()
2842			.filter(|(_, track)| track.read == Read::Live)
2843			.filter(|(_, track)| track.kind.class() != super::stats::Class::Data || track.buffer.is_some());
2844		self.program.expected = continuous.map(|(_, track)| track.key.clone()).collect();
2845		self.program.expected_changed = true;
2846		Ok(())
2847	}
2848
2849	/// Keep `track` under `name` with this snapshot's PID and descriptors.
2850	fn refresh(&mut self, name: &str, mut track: Track, pid: u16, descriptors: Vec<catalog::Descriptor>) {
2851		track.key = TrackKey::new(self.program.id, name);
2852		track.pid = pid;
2853		track.descriptors = descriptors;
2854		self.program.tracks.insert(name.to_string(), track);
2855	}
2856
2857	/// Point each stale track this snapshot lists at the returned broadcast.
2858	///
2859	/// The PIDs and PMT stay as announced. A track the returned catalog does not list stays
2860	/// stale, silent on its PID. The same identity carries the same content, so each track reads
2861	/// on right after the last frame it read ([`ExportSource::resuming`]): nothing is replayed,
2862	/// and a frame that comes too late drops as any other does. A track that read nothing starts
2863	/// at the live edge instead, its playhead jumping from wherever the old subscription stopped,
2864	/// so its first frame counts as a skip: late frames drop, and a leap ahead opens a new
2865	/// generation.
2866	fn resubscribe(&mut self, catalog: &Catalog<S::Ext>, mpegts: &catalog::Mpegts) -> Result<()> {
2867		let delay = self.program.delay;
2868		let replay = self.program.replay;
2869		for (name, track) in self.program.tracks.iter_mut() {
2870			if track.read != Read::Stale {
2871				continue;
2872			}
2873			let mut resume = track.source.resume();
2874			// A flush settled the group's decode clock before its reordering was known, so the
2875			// rest of the group may not fit it: read on from the next group instead.
2876			let cut = track.declared.as_ref().is_some_and(DeclaredClock::forced)
2877				&& track.declared_group.is_some_and(|group| resume.past_group(group));
2878			let resumed = |source: ExportSource| match resume.read() {
2879				true => source.resuming(&resume),
2880				false => at_edge(source, replay),
2881			};
2882			let source = if let Some(config) = catalog.video.renditions.get(name) {
2883				ExportSource::for_video(&self.program.source, name, config, subscribed(delay))?
2884					.map(|s| resumed(skipping(s, delay)))
2885			} else if let Some(config) = catalog.audio.renditions.get(name) {
2886				ExportSource::for_audio(&self.program.source, name, config, subscribed(delay))?
2887					.map(|s| resumed(skipping(s, delay)))
2888			} else if mpegts
2889				.tracks
2890				.get(name)
2891				.is_some_and(|t| t.verbatim.is_some() || t.pes_packet.is_some())
2892			{
2893				let source = ExportSource::for_stream(&self.program.source, name, subscribed(delay))?;
2894				let kind = track.kind.clone();
2895				Some(match resume.read() {
2896					true => skipping(source, delay).resuming(&resume),
2897					false => stream_edge(skipping(source, delay), &kind, replay),
2898				})
2899			} else {
2900				None
2901			};
2902			let Some(source) = source else {
2903				continue;
2904			};
2905			// A new subscription at the edge counts as cutting whatever group the old one was
2906			// reading, as does reading on past the rest of it; one that reads on counts its own.
2907			let jumped = u64::from(!resume.read() || cut);
2908			track.base.0 += track.source.markers();
2909			track.base.1 += track.source.skips() + jumped;
2910			track.base.2 += track.source.cuts() + jumped;
2911			track.source = source;
2912			track.subscribed = kio::clock::now();
2913			track.read = Read::Live;
2914		}
2915		Ok(())
2916	}
2917
2918	/// Move each listed track whose rendition the catalog moved to another track or broadcast
2919	/// onto it. One the PMT does not list yet starts over on the new track instead.
2920	///
2921	/// The PID, PMT and lane stay as announced, and so does the kind the track's frames are
2922	/// framed under as they go out, so the new track must have the same kind: an AAC track keeps
2923	/// its configuration. Video parameter sets ride with each frame and may change. The new
2924	/// source continues the old one ([`ExportSource::continuing`]), and the frames the old one
2925	/// left held for their DTS go out first.
2926	fn rebind(&mut self, catalog: &Catalog<S::Ext>) -> Result<()> {
2927		let delay = self.program.delay;
2928		for (name, track) in self.program.tracks.iter_mut().filter(|(_, track)| track.listed) {
2929			let (source, kind) = if let Some(config) = catalog.video.renditions.get(name) {
2930				if track.source.reads(&self.program.source, name, config) {
2931					continue;
2932				}
2933				let source = ExportSource::for_video(&self.program.source, name, config, subscribed(delay))?
2934					.map(|s| skipping(s, delay));
2935				(source, video_kind(config, name)?)
2936			} else if let Some(config) = catalog.audio.renditions.get(name) {
2937				if track.source.reads(&self.program.source, name, config) {
2938					continue;
2939				}
2940				let source = ExportSource::for_audio(&self.program.source, name, config, subscribed(delay))?
2941					.map(|s| skipping(s, delay));
2942				(source, audio_kind(config, name)?)
2943			} else {
2944				continue;
2945			};
2946			let Some(source) = source else {
2947				continue;
2948			};
2949			let same = match (&kind, &track.kind) {
2950				(Kind::Aac { config, .. }, Kind::Aac { config: old, .. }) => config == old,
2951				(kind, old) => kind == old,
2952			};
2953			ensure_supported!(
2954				same,
2955				"TS track layout changed after PAT/PMT was emitted: '{name}' moved to a track announced differently"
2956			);
2957			track.release(name, &mut self.jitter, true)?;
2958			track.clock = DecodeClock::default();
2959			track.declared = None;
2960			track.source = source.continuing(&track.source);
2961			track.read = Read::Live;
2962			track.subscribed = kio::clock::now();
2963		}
2964		Ok(())
2965	}
2966
2967	/// How many frames were dropped for missing their deadline.
2968	#[cfg(test)]
2969	pub(super) fn dropped(&self) -> u64 {
2970		self.jitter.dropped()
2971	}
2972
2973	/// Snapshot the access units each elementary stream has written, how long each has been
2974	/// quiet on the PCR the output carries, and how the release clock is keeping up with the
2975	/// source.
2976	///
2977	/// A track stalled upstream stops advancing its row while the PSI and the other PIDs
2978	/// keep flowing, which nothing graded on the output bytes alone can see. The rows are
2979	/// empty until the program tables are built. Cheap enough to poll per frame.
2980	pub fn stats(&self) -> super::stats::Export {
2981		let mut stats = super::stats::Export {
2982			release: super::stats::Release::of(&self.jitter),
2983			..Default::default()
2984		};
2985		stats.release.trimmed += self.program.trimmed;
2986		stats.release.gaps = self
2987			.program
2988			.tracks
2989			.values()
2990			.map(|track| {
2991				let skips = track.base.1 + track.source.skips();
2992				skips - (track.base.0 + track.source.markers())
2993			})
2994			.sum();
2995		if self.program.psi.is_none() {
2996			return stats;
2997		}
2998		for track in self.program.tracks.values().filter(|track| track.listed) {
2999			let (units, quiet) = self.program.liveness.stream(track.pid);
3000			let row = super::stats::Stream {
3001				track: track.kind.suffix().to_string(),
3002				class: track.kind.class(),
3003				units,
3004				quiet,
3005				..Default::default()
3006			};
3007			stats.streams.insert(track.pid, row);
3008		}
3009		stats
3010	}
3011
3012	/// How many access units are waiting in the jitter buffer or a decode clock.
3013	#[cfg(test)]
3014	pub(super) fn buffered(&self) -> usize {
3015		self.jitter.len()
3016			+ self
3017				.program
3018				.tracks
3019				.values()
3020				.map(|track| track.clock.len())
3021				.sum::<usize>()
3022	}
3023
3024	/// How many tracks the export carries, listed or not.
3025	#[cfg(test)]
3026	pub(super) fn tracks(&self) -> usize {
3027		self.program.tracks.len()
3028	}
3029
3030	/// `pid`'s access units and how long it has been quiet, as [`Self::stats`] reads them.
3031	#[cfg(test)]
3032	pub(super) fn liveness(&self, pid: u16) -> (u64, Option<Duration>) {
3033		self.program.liveness.stream(pid)
3034	}
3035
3036	/// The track the PMT lists on `pid`.
3037	#[cfg(test)]
3038	pub(super) fn listed_on(&self, pid: u16) -> Option<&str> {
3039		self.program
3040			.tracks
3041			.iter()
3042			.find(|(_, track)| track.listed && track.pid == pid)
3043			.map(|(name, _)| name.as_str())
3044	}
3045
3046	/// Take the next frame due out of the jitter buffer and hold it, as a generation boundary
3047	/// holds the new generation's first frame behind the old one's tail. Returns its PID.
3048	#[cfg(test)]
3049	pub(super) fn hold_next(&mut self) -> Option<u16> {
3050		let Poll::Ready(ready) = self.jitter.poll_next(&kio::Waiter::noop()) else {
3051			return None;
3052		};
3053		let pid = self.program.tracks.get(&ready.track.name)?.pid;
3054		self.held = Some(ready);
3055		Some(pid)
3056	}
3057
3058	#[cfg(test)]
3059	pub(super) fn holding_replacement(&self) -> bool {
3060		self.held
3061			.as_ref()
3062			.is_some_and(|ready| self.pending.as_ref().is_some_and(|next| ready.track.program == next.id))
3063	}
3064
3065	/// When the next queued frame is due, or the next grid slot while media is queued or
3066	/// every source has finished and the tail runs out.
3067	#[cfg(test)]
3068	pub(super) fn next_due(&self) -> Option<kio::clock::Instant> {
3069		let finished =
3070			!self.program.tracks.is_empty() && self.program.tracks.values().all(|track| track.read != Read::Live);
3071		let slot = self
3072			.slot_due()
3073			.filter(|_| self.program.schedule.queued() || self.packing() || finished)
3074			.map(|(_, at)| at);
3075		self.jitter.next_deadline().into_iter().chain(slot).min()
3076	}
3077
3078	/// The discontinuity counter of the most recently returned output frame.
3079	/// Compare across reads and re-anchor pacing when it changes. Renditions have
3080	/// independent source counters; this counter describes the emitted program.
3081	pub fn discontinuity(&self) -> u64 {
3082		self.program.emitted_epoch
3083	}
3084
3085	pub(super) fn source(&self) -> &crate::Source {
3086		&self.selected().source
3087	}
3088
3089	/// The identity of the broadcast being exported, `None` for one not resolved through an
3090	/// origin.
3091	pub(super) fn identity(&self) -> Option<&moq_net::Identity> {
3092		self.selected().identity.as_ref()
3093	}
3094
3095	/// Carry on into `broadcast`, using the caller's replacement `catalog` stream.
3096	///
3097	/// The same stream (an equal identity) continues: the program and
3098	/// its PSI carry on, and its catalog resubscribes each track as it lists it, so a gap is a
3099	/// skip like any other. A track it adds or drops revises the PMT, as any catalog update
3100	/// does.
3101	///
3102	/// Another identity, or a broadcast without one, opens a fresh jitter generation.
3103	/// [`Follower`](super::Follower) keeps feeding the old program until the new clock and
3104	/// first media are usable, bounded by its follow window. Then what the old program
3105	/// already released goes out before the new PMT, and what it still buffers is dropped,
3106	/// so the new program keeps its own delay. The new PMT has advanced table versions,
3107	/// every PID's first packet flags the break, and each stream starts on a keyframe. No
3108	/// timestamps are aligned.
3109	pub fn follow(mut self, broadcast: moq_net::broadcast::Consumer, catalog: S) -> Result<Self, crate::Error> {
3110		self.followed(&broadcast, catalog, Duration::ZERO)?;
3111		Ok(self)
3112	}
3113
3114	/// Why the publisher of the program playing left, while what it buffered still goes out
3115	/// before the export reports it ([`Self::leave`]).
3116	pub(super) fn departed(&self) -> Option<&crate::Error> {
3117		match &self.program.feed {
3118			Feed::Retired(left) if self.pending.is_none() => left.as_ref(),
3119			Feed::Live | Feed::Ended | Feed::Retired(_) => None,
3120		}
3121	}
3122
3123	/// Leave the identity carried on into while what it buffered went out, which went before
3124	/// serving its catalog: as if its publisher left with `err` ([`Self::leave`]).
3125	pub(super) fn depart(&mut self, err: crate::Error) -> crate::Result<()> {
3126		self.leave(err)
3127	}
3128
3129	/// Whether the catalog this export last subscribed has delivered a snapshot.
3130	pub(super) fn cataloged(&self) -> bool {
3131		self.selected().cataloged
3132	}
3133
3134	/// [`Self::follow`], once `broadcast`'s catalog is subscribed.
3135	pub(super) fn followed(
3136		&mut self,
3137		broadcast: &moq_net::broadcast::Consumer,
3138		catalog: S,
3139		follow: Duration,
3140	) -> Result<(), crate::Error> {
3141		tracing::debug!(target: "moq_mux::container::ts::handoff", phase = "follow", now = ?kio::clock::now(), program = self.program.id, pending = ?self.pending.as_ref().map(|pending| pending.id), old_identity = ?self.program.identity, new_identity = ?broadcast.info().identity, ?follow);
3142		if self.pending.is_some()
3143			&& self.program.identity.is_some()
3144			&& broadcast.info().identity == self.program.identity
3145		{
3146			self.cancel_pending();
3147			self.program.source.priority(0)?;
3148			self.follow_until = None;
3149			self.follow_timer = None;
3150		}
3151		let same = self.selected().identity.is_some() && broadcast.info().identity == self.selected().identity;
3152		if !same {
3153			self.cancel_pending();
3154			let next = self.replacement(self.program.source.switched(broadcast), catalog);
3155			self.pending = Some(Box::new(next));
3156			self.follow_until
3157				.get_or_insert_with(|| kio::clock::now().saturating_add(follow));
3158			return Ok(());
3159		}
3160		if let Some(mut pending) = self.pending.take() {
3161			pending.source.pin(broadcast);
3162			if pending.psi.is_none() {
3163				if self
3164					.held
3165					.as_ref()
3166					.is_some_and(|ready| ready.track.program == pending.id)
3167				{
3168					self.held = None;
3169				}
3170				self.jitter.cancel();
3171				let next = self.replacement(pending.source, catalog);
3172				self.pending = Some(Box::new(next));
3173			} else {
3174				std::mem::swap(&mut self.program, pending.as_mut());
3175				let resumed = self.resume(catalog);
3176				std::mem::swap(&mut self.program, pending.as_mut());
3177				self.pending = Some(pending);
3178				resumed?;
3179			}
3180			return Ok(());
3181		}
3182		self.program.source.pin(broadcast);
3183		if self.program.psi.is_none() {
3184			self.program = self.replacement(self.program.source.clone(), catalog);
3185			self.active_program = self.program.id;
3186			self.held = None;
3187			self.jitter = jitter::Buffer::new(self.program.delay);
3188			#[cfg(test)]
3189			if self.program.replay {
3190				self.jitter = jitter::Buffer::new(self.program.delay).replay();
3191			}
3192			return Ok(());
3193		}
3194		self.resume(catalog)
3195	}
3196
3197	fn cancel_pending(&mut self) {
3198		if let Some(previous) = self.pending.take() {
3199			if self
3200				.held
3201				.as_ref()
3202				.is_some_and(|ready| ready.track.program == previous.id)
3203			{
3204				self.held = None;
3205			}
3206			self.jitter.cancel();
3207		}
3208	}
3209
3210	fn replacement(&mut self, source: crate::Source, catalog: S) -> Program<S> {
3211		let mut next = Program::new(source, catalog, self.program.delay);
3212		next.id = self.next_program;
3213		self.next_program += 1;
3214		next.replay = self.program.replay;
3215		next.mux_rate_override = self.program.mux_rate_override;
3216		next.rate_wait = self.program.rate_wait;
3217		next
3218	}
3219
3220	fn resume(&mut self, catalog: S) -> Result<(), crate::Error> {
3221		self.program.catalog = Some(catalog);
3222		self.program.cataloged = false;
3223		self.program.feed = Feed::Live;
3224		self.program.si_flushed = false;
3225		for si in self.program.si.values_mut() {
3226			si.track.clear();
3227		}
3228		for (name, track) in &mut self.program.tracks {
3229			track.release(name, &mut self.jitter, true)?;
3230			track.read = Read::Stale;
3231		}
3232		Ok(())
3233	}
3234
3235	/// Whether a frame of `kind` released now presents ahead of the video keyframe the stream
3236	/// begins on (`video_start`), and so is dropped. A video track whose start group
3237	/// went stale before it went out starts at its next keyframe instead
3238	/// ([`jitter::Buffer`]), so until video goes out the start is the earliest frame a video
3239	/// track holds, and with none held, everything leads the keyframe yet to arrive. Video goes
3240	/// out further ahead of its decode time than the other tracks, so what they release before
3241	/// it presents ahead of it too.
3242	///
3243	/// A placed frame has no presentation to compare: it goes out at its placement, so it is
3244	/// dropped only when that comes before the keyframe departs. Both are release times a
3245	/// delay before their jitter buffer keys, so it compares keys, and keeps whatever goes
3246	/// out beside or after the keyframe even when its PTS is earlier.
3247	fn leads_video(&mut self, kind: &Kind, queued: &Queued) -> bool {
3248		let Some(start) = self.program.video_start else {
3249			return false;
3250		};
3251		if matches!(kind, Kind::Video(_)) {
3252			if self.program.video_out.is_none() {
3253				self.program.video_out = Some(queued.key);
3254				self.program.video_start = Some(crate::container::later(start, queued.frame.timestamp));
3255			}
3256			return false;
3257		}
3258		let placed = kind.placed();
3259		if let Some(departed) = self.program.video_out {
3260			return match placed {
3261				true => queued.key < departed,
3262				false => queued.frame.timestamp < start,
3263			};
3264		}
3265		let next = self
3266			.program
3267			.tracks
3268			.iter()
3269			.filter(|(_, track)| matches!(track.kind, Kind::Video(_)))
3270			.filter_map(|(_, track)| self.jitter.peek(&track.key))
3271			.map(|next| match placed {
3272				true => next.key,
3273				false => crate::container::later(next.frame.timestamp, start),
3274			})
3275			.reduce(crate::container::earlier);
3276		let at = match placed {
3277			true => queued.key,
3278			false => queued.frame.timestamp,
3279		};
3280		next.is_none_or(|next| at < next)
3281	}
3282
3283	/// Discard what has not gone out and restart the program clock. Every rendition
3284	/// joins the new generation: no track is fenced across a declared marker, since a
3285	/// latency skip on one track says nothing about another's timeline. The continuity
3286	/// counters run on, since they number only what went out.
3287	fn rewind(&mut self) {
3288		self.program.epoch += 1;
3289		self.program.schedule.clear();
3290		// A break flag queued on a PID that has not gone out yet was just dropped with it.
3291		if let Some(flagged) = &mut self.program.flagged {
3292			flagged.clear();
3293		}
3294		self.program.queue.clear();
3295		self.program.last_psi = None;
3296		for si in self.program.si.values_mut() {
3297			si.last_emit = None;
3298			si.position = None;
3299			if let Some(revision) = &mut si.future {
3300				revision.after = None;
3301			}
3302		}
3303		self.program.video_start = None;
3304		self.program.pcr_discontinuity = true;
3305		self.program.tables.clear();
3306		if let Some(psi) = &mut self.program.psi {
3307			psi.sending.clear();
3308			psi.laid = psi.out.clone();
3309			psi.led = psi.out.as_ref().map(|laid| laid.pmt.clone());
3310		}
3311		for track in self.program.tracks.values_mut() {
3312			track.pack = None;
3313			track.parked.clear();
3314		}
3315	}
3316
3317	/// Header is ready when a track, and every track still reading, has resolved its codec
3318	/// config through its [`ExportSource`] (from the catalog `description`, or built by the
3319	/// transform). A track that ended before its config holds nothing back.
3320	fn header_ready(&self) -> bool {
3321		let tracks = &self.program.tracks;
3322		tracks.values().any(|t| t.source.header_ready())
3323			&& tracks.values().all(|t| t.read != Read::Live || t.source.header_ready())
3324	}
3325
3326	/// Every video track has buffered its first frame (the keyframe) or finished.
3327	/// The tables wait for this so the tune-in point (`video_start`) can be
3328	/// read from the keyframe before any audio is emitted ahead of it. A program
3329	/// with no video track is trivially ready.
3330	fn video_ready(&self) -> bool {
3331		self.program
3332			.tracks
3333			.values()
3334			.filter(|t| matches!(t.kind, Kind::Video(_)))
3335			.all(|t| t.pending.is_some() || t.read != Read::Live)
3336	}
3337
3338	/// The smallest timestamp among the video tracks' buffered frames: the first
3339	/// video keyframe, since pre-keyframe video frames are dropped before the tables
3340	/// are built. `None` when no video track has a buffered frame (audio-only program).
3341	fn first_video_pts(&self) -> Option<Timestamp> {
3342		self.program
3343			.tracks
3344			.values()
3345			.filter(|t| matches!(t.kind, Kind::Video(_)))
3346			.filter_map(|t| t.pending.as_ref().map(|p| p.frame.timestamp))
3347			.reduce(crate::container::earlier)
3348	}
3349
3350	/// Whether `pid`'s next packet is its first since a switch to another identity, so it has
3351	/// to flag the break. The PCR PID's first packet always opens a slot with its PCR, flagged
3352	/// on its own ([`Self::lay`]).
3353	fn breaks(&mut self, pid: u16) -> bool {
3354		let owes = self.owes_break(pid);
3355		if owes && let Some(flagged) = &mut self.program.flagged {
3356			flagged.insert(pid);
3357		}
3358		owes
3359	}
3360
3361	/// Whether `pid`'s next packet has to flag the break ([`Self::breaks`]), without spending it.
3362	fn owes_break(&self, pid: u16) -> bool {
3363		let pcr = self.program.psi.as_ref().and_then(Psi::pcr_pid);
3364		self.program.flagged.as_ref().is_some_and(|flagged| {
3365			Some(pid) != pcr && !self.program.counters.contains_key(&pid) && !flagged.contains(&pid)
3366		})
3367	}
3368
3369	/// PID the PMT rides on: the source's original (preserved in the service record),
3370	/// or the synthesized [`PMT_PID`] for a media-only source or an invalid (zero) value.
3371	/// Once the tables are built they move only behind a PAT naming the new PID
3372	/// ([`Self::move_pmt`]).
3373	fn pmt_pid(&self) -> u16 {
3374		if let Some(psi) = &self.program.psi {
3375			return psi.pmt_pid;
3376		}
3377		self.program
3378			.program
3379			.as_ref()
3380			.map(|s| s.pmt_pid)
3381			.filter(|&pid| pid != 0)
3382			.unwrap_or(PMT_PID)
3383	}
3384
3385	/// The PIDs no stream takes for the PMT's sake: the one it rides, the one it is moving to,
3386	/// and the ones it rode before.
3387	fn pmt_pids(&self) -> Vec<u16> {
3388		let mut pids = vec![self.pmt_pid()];
3389		if let Some(psi) = &self.program.psi {
3390			pids.extend(psi.moving);
3391			pids.extend(&psi.left);
3392		}
3393		pids
3394	}
3395
3396	/// Follow a catalog that moves the PMT to another PID: the PAT of the next tables names it,
3397	/// at the PAT's next version ([`Psi::current`]). A move onto a PID a stream the catalog
3398	/// dropped still drains on waits for it ([`Self::follow_pmt`]); one onto a PID the catalog
3399	/// gives a stream or SI, the clock's own PID, or no PID at all is refused, as is a catalog
3400	/// that gives the PID to a stream while the move waits. A catalog that records no PID keeps
3401	/// the PMT where it is.
3402	fn move_pmt(&mut self, mpegts: &catalog::Mpegts) -> Result<()> {
3403		let Some(pid) = self.program.program.as_ref().map(|s| s.pmt_pid).filter(|&pid| pid != 0) else {
3404			// The catalog no longer asks for a move, so drop one that is still waiting.
3405			if let Some(psi) = self.program.psi.as_mut() {
3406				psi.moving = None;
3407			}
3408			return Ok(());
3409		};
3410		let Some(psi) = self.program.psi.as_mut() else {
3411			return Ok(());
3412		};
3413		if pid == psi.pmt_pid {
3414			psi.moving = None;
3415			return Ok(());
3416		}
3417		let psi = &*psi;
3418		ensure_supported!(pid < 0x1fff, "TS export cannot move the PMT to PID {pid:#06x}");
3419		let taken = psi.own_clock() == Some(pid)
3420			|| mpegts.si.contains_key(&pid)
3421			|| self
3422				.program
3423				.tracks
3424				.values()
3425				.any(|track| track.cataloged && track.pid == pid);
3426		ensure_supported!(
3427			!taken,
3428			"TS export cannot move the PMT from PID {:#06x} to {pid:#06x}, which another stream rides",
3429			psi.pmt_pid
3430		);
3431		self.program.psi.as_mut().expect("checked above").moving = Some(pid);
3432		self.follow_pmt()
3433	}
3434
3435	/// Move the PMT to the PID the catalog moved it to once no copy of the tables is on its way,
3436	/// so each copy goes out whole on the PID its PAT names, and no stream is left on the PID,
3437	/// and lead the next frame with them. Every copy not yet begun takes the move.
3438	fn follow_pmt(&mut self) -> Result<()> {
3439		let Some(psi) = self.program.psi.as_mut() else {
3440			return Ok(());
3441		};
3442		let Some(pid) = psi.moving else {
3443			return Ok(());
3444		};
3445		if !psi.sending.is_empty() || self.program.tracks.values().any(|track| track.pid == pid) {
3446			return Ok(());
3447		}
3448		psi.moving = None;
3449		let old = std::mem::replace(&mut psi.pmt_pid, pid);
3450		psi.left.retain(|&left| left != pid);
3451		psi.left.push(old);
3452		tracing::debug!(from = old, to = pid, "moving the PMT");
3453		self.program.schedule.set_tables(pid);
3454		self.program.schedule.forget(old);
3455		self.program.revised = true;
3456		self.restate()
3457	}
3458
3459	/// Build the PAT/PMT once every track's PID and codec is known.
3460	fn build_psi(&mut self) -> Result<()> {
3461		// A track that ended before its codec config never carries a frame, so the PMT leaves it out.
3462		for track in self.program.tracks.values_mut() {
3463			track.listed = track.read == Read::Live || track.source.header_ready();
3464		}
3465		let pcr_pid = self.pick_clock()?;
3466		let pmt = self.program_map(pcr_pid)?;
3467
3468		// Preserve the source's program identity so the rebuilt PAT stays consistent with the
3469		// carried SI; synthesize a minimal identity otherwise.
3470		let pmt_pid = self.pmt_pid();
3471		let transport_stream_id = self
3472			.program
3473			.program
3474			.as_ref()
3475			.map(|s| s.transport_stream_id)
3476			.unwrap_or(1);
3477
3478		self.program.schedule.set_tables(pmt_pid);
3479		self.program.schedule.set_clock(pcr_pid);
3480		// A reader of the first tables has no program clock yet. Tables that take over from
3481		// an earlier program's flag a break in the clock it already reads instead.
3482		if !self.program.pcr_discontinuity {
3483			self.program.schedule.open();
3484		}
3485		for track in self.program.tracks.values().filter(|track| track.listed) {
3486			self.program.liveness.register(track.pid);
3487		}
3488		self.program.psi = Some(Psi {
3489			transport_stream_id,
3490			pmt,
3491			pmt_pid,
3492			moving: None,
3493			left: Vec::new(),
3494			led: None,
3495			stated: None,
3496			laid: None,
3497			sending: VecDeque::new(),
3498			out: None,
3499		});
3500		self.program.psi_due = true;
3501		Ok(())
3502	}
3503
3504	/// Whether the catalog carries a NIT on its PID, which the PAT then points a receiver at.
3505	fn carries_nit(&self) -> bool {
3506		self.program.si.contains_key(&(NIT_PID, NIT_ACTUAL))
3507	}
3508
3509	/// The PID to carry the clock: the first video track's, else the first audio track's, else
3510	/// one used by nothing else, since sparse data cannot carry the clock's cadence.
3511	fn pick_clock(&self) -> Result<u16> {
3512		let mut tracks: Vec<&Track> = self.program.tracks.values().filter(|t| t.listed).collect();
3513		tracks.sort_by_key(|t| t.pid);
3514		tracks
3515			.iter()
3516			.find(|t| matches!(t.kind, Kind::Video(_)))
3517			.or_else(|| {
3518				tracks.iter().find(|t| {
3519					matches!(
3520						t.kind,
3521						Kind::Aac { .. }
3522							| Kind::Adts { .. } | Kind::Opus { .. }
3523							| Kind::Mp2 { .. } | Kind::Ac3
3524							| Kind::Eac3
3525					)
3526				})
3527			})
3528			.map(|t| t.pid)
3529			.or_else(|| {
3530				let pmt_pids = self.pmt_pids();
3531				(FIRST_ES_PID..0x1fff).find(|pid| {
3532					!pmt_pids.contains(pid)
3533						&& self.program.tracks.values().all(|track| track.pid != *pid)
3534						&& self.program.si.keys().all(|(si, _)| si != pid)
3535				})
3536			})
3537			.context("TS export has no unused PID for the PCR")
3538	}
3539
3540	/// The PMT listing every listed track in PID order, with the clock on `pcr_pid`.
3541	fn program_map(&self, pcr_pid: u16) -> Result<psi::Pmt> {
3542		let mut tracks: Vec<&Track> = self.program.tracks.values().filter(|t| t.listed).collect();
3543		tracks.sort_by_key(|t| t.pid);
3544
3545		let streams = tracks
3546			.iter()
3547			.map(|t| {
3548				// Prefer the descriptors captured verbatim on import.
3549				let descriptors = match t.descriptors.is_empty() {
3550					true => t.kind.descriptors(),
3551					false => t.descriptors.clone(),
3552				};
3553				Ok(super::psi::Es {
3554					stream_type: t.kind.stream_type(),
3555					pid: Pid::new(t.pid)?,
3556					descriptors,
3557				})
3558			})
3559			.collect::<Result<Vec<_>>>()?;
3560
3561		// Re-emit the captured program-level descriptors. With none (a non-TS source),
3562		// derive the SCTE-35 'CUEI' registration when a 0x86 verbatim stream is present.
3563		let program_info = if !self.program.program_descriptors.is_empty() {
3564			self.program.program_descriptors.clone()
3565		} else if tracks.iter().any(|t| {
3566			// Only derive CUEI for section-framed 0x86 (SCTE-35); a whole-PES 0x86
3567			// (e.g. DTS audio) must not advertise SCTE-35 section signaling.
3568			matches!(&t.kind, Kind::Verbatim { stream_type: 0x86 })
3569		}) {
3570			vec![registration(b"CUEI")]
3571		} else {
3572			Vec::new()
3573		};
3574
3575		// A revision stays on the program the PAT went out naming.
3576		let program_number = match &self.program.psi {
3577			Some(psi) => psi.pmt.program_number,
3578			None => self
3579				.program
3580				.program
3581				.as_ref()
3582				.map(|s| s.program_number)
3583				.filter(|&id| id != 0)
3584				.unwrap_or(1),
3585		};
3586		Ok(super::psi::Pmt {
3587			program_number,
3588			pcr_pid: Some(Pid::new(pcr_pid)?),
3589			program_info,
3590			streams,
3591		})
3592	}
3593
3594	/// Rebuild the PMT from the listed tracks, leading the next frame muxed when it changed. The
3595	/// clock stays on its PID unless the stream carrying it retired with no track the catalog
3596	/// lists taking the PID over: a rendition the source reopens (a language retag) can retire
3597	/// before the one replacing it lists with its first frame.
3598	fn revise(&mut self) -> Result<()> {
3599		let Some(psi) = self.program.psi.as_ref() else {
3600			return Ok(());
3601		};
3602		let current = psi.pcr_pid().context("PMT without a clock")?;
3603		let kept = psi.own_clock() == Some(current)
3604			|| (self.program.tracks.values()).any(|track| track.pid == current && (track.listed || track.cataloged));
3605		let pcr_pid = match kept {
3606			true => current,
3607			false => self.pick_clock()?,
3608		};
3609		let pmt = self.program_map(pcr_pid)?;
3610		let psi = self.program.psi.as_mut().expect("checked above");
3611		if pmt != psi.pmt {
3612			psi.pmt = pmt;
3613			self.program.revised = true;
3614			self.restate()?;
3615		}
3616		Ok(())
3617	}
3618
3619	/// List `name` in the PMT ahead of its first frame: `false` while it waits for its PID,
3620	/// which a stream the catalog dropped still holds. That stream is no longer read, so only
3621	/// what it already holds drains ahead of this one ([`Self::settle`]).
3622	fn list(&mut self, name: &str) -> Result<bool> {
3623		let track = self.program.tracks.get(name).context("missing track")?;
3624		if track.listed {
3625			return Ok(true);
3626		}
3627		if !track.parked.is_empty() {
3628			return Ok(false);
3629		}
3630		let pid = track.pid;
3631		if let Some((holder, track)) = self
3632			.program
3633			.tracks
3634			.iter_mut()
3635			.find(|(other, track)| track.listed && track.pid == pid && other.as_str() != name)
3636		{
3637			if track.read == Read::Live {
3638				track.release(holder, &mut self.jitter, true)?;
3639			}
3640			// Replaced, so neither a return of its name nor a same-identity return reads it on.
3641			track.read = Read::Ended;
3642			return Ok(false);
3643		}
3644		self.program.tracks.get_mut(name).expect("checked above").listed = true;
3645		self.program.liveness.register(pid);
3646		self.revise()?;
3647		Ok(true)
3648	}
3649
3650	/// Retire each track the catalog dropped once nothing of it is left to go out, and list
3651	/// the tracks that waited for its PID ([`Self::list`]).
3652	fn settle(&mut self) -> Result<()> {
3653		if self.program.psi.is_none() {
3654			return Ok(());
3655		}
3656		let gone: Vec<String> = self
3657			.program
3658			.tracks
3659			.iter()
3660			.filter(|(_, track)| {
3661				// A track the same identity's return has yet to resubscribe stays, silent on its PID.
3662				!track.cataloged
3663					&& matches!(track.read, Read::Ended | Read::Withdrawn)
3664					&& track.pack.is_none()
3665					&& track.parked.is_empty()
3666					&& !self.jitter.holds(&track.key)
3667					&& self.held.as_ref().is_none_or(|held| held.track != track.key)
3668					&& !(track.listed && self.program.schedule.holds(track.pid))
3669			})
3670			.map(|(name, _)| name.clone())
3671			.collect();
3672		let mut changed = false;
3673		for name in gone {
3674			let track = self.program.tracks.remove(&name).expect("collected above");
3675			self.jitter.forget(&TrackKey::new(self.program.id, &name));
3676			if track.listed {
3677				self.program.liveness.retire(track.pid);
3678				self.program.schedule.forget(track.pid);
3679				changed = true;
3680			}
3681		}
3682		// A freed PID goes to the track that has waited for it longest; the rest wait their turn.
3683		let mut waiting: Vec<(Timestamp, &String, u16)> = self
3684			.program
3685			.tracks
3686			.iter()
3687			.filter_map(|(name, track)| Some((track.parked.front()?.key, name, track.pid)))
3688			.collect();
3689		waiting.sort_by(|a, b| {
3690			(a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)).then_with(|| (a.1, a.2).cmp(&(b.1, b.2)))
3691		});
3692		let mut claimed: Vec<u16> = self
3693			.program
3694			.tracks
3695			.values()
3696			.filter(|t| t.listed)
3697			.map(|t| t.pid)
3698			.collect();
3699		let mut free = Vec::new();
3700		for (_, name, pid) in waiting {
3701			if !claimed.contains(&pid) {
3702				claimed.push(pid);
3703				free.push(name.clone());
3704			}
3705		}
3706		for name in &free {
3707			let track = self.program.tracks.get_mut(name).expect("collected above");
3708			track.listed = true;
3709			self.program.liveness.register(track.pid);
3710			changed = true;
3711		}
3712		if changed {
3713			self.revise()?;
3714			// A move may have waited for a stream that just retired.
3715			self.follow_pmt()?;
3716		}
3717		for name in free {
3718			let parked = std::mem::take(&mut self.program.tracks.get_mut(&name).expect("collected above").parked);
3719			for queued in parked {
3720				self.mux(&name, queued)?;
3721			}
3722		}
3723		Ok(())
3724	}
3725
3726	/// The buffers the schedule holds `track`'s PID to: audio reaches as far ahead as the rate the
3727	/// tables last carried lets it, which is what the schedule pads to, while the frames are keyed
3728	/// for a rate still waiting on them ([`Program::rate_from`]).
3729	fn scheduled(&self, track: &Track) -> Option<Buffer> {
3730		let mut buffer = track.buffer()?;
3731		if track.kind.class() == super::stats::Class::Audio {
3732			buffer.reach = audio_reach(&buffer, self.program.led_rate, self.program.delay).min(buffer.reach);
3733		}
3734		Some(buffer)
3735	}
3736
3737	/// Hand the program tables to the schedule ahead of the next unit, decoding at `decode`, if
3738	/// they are due.
3739	fn lead_tables(&mut self, decode: Timestamp) -> Result<()> {
3740		if !std::mem::take(&mut self.program.psi_due) {
3741			return Ok(());
3742		}
3743		let rate = match self.program.rate_from {
3744			Some(from) if nanos(decode) < from => self.program.led_rate,
3745			_ => {
3746				self.program.rate_from = None;
3747				self.program.mux_rate
3748			}
3749		};
3750		if std::mem::replace(&mut self.program.led_rate, rate) != rate {
3751			let buffers: Vec<_> = self
3752				.program
3753				.tracks
3754				.values()
3755				// A track waiting for its PID takes its buffer there when it lists ([`Self::push_unit`]).
3756				.filter(|track| track.listed && track.kind.class() == super::stats::Class::Audio)
3757				.filter_map(|track| Some((track.pid, self.scheduled(track)?)))
3758				.collect();
3759			for (pid, buffer) in buffers {
3760				self.program.schedule.set_buffer(pid, buffer);
3761			}
3762		}
3763		// A rewind may have dropped the copy a move waited for.
3764		self.follow_pmt()?;
3765		self.restate()?;
3766		let psi = self.program.psi.as_mut().context("PSI not built")?;
3767		let added: Vec<u16> = psi
3768			.pmt
3769			.streams
3770			.iter()
3771			.filter(|es| psi.led.as_ref().is_none_or(|pmt| !pmt.streams.contains(es)))
3772			.map(|es| es.pid.as_u16())
3773			.collect();
3774		psi.led = Some(psi.pmt.clone());
3775		self.program.schedule.lead(super::schedule::Tables { rate, added });
3776		Ok(())
3777	}
3778
3779	/// Set the program tables as they stand on the schedule, which every copy of them still to
3780	/// begin lays. A NIT acquired or lost after the tables went out revises the PAT's network
3781	/// entry, at the PAT's next version. The first copy after a switch to another
3782	/// identity flags the break on each table PID that owes one ([`Self::breaks`]).
3783	fn restate(&mut self) -> Result<()> {
3784		let network = self.carries_nit();
3785		let psi = self.program.psi.as_ref().context("PSI not built")?;
3786		let tables = psi.current(network, (self.program.version, self.program.pat_version))?;
3787		let pmt_pid = psi.pmt_pid;
3788		let clock = psi.pcr_pid().context("PMT without a clock")?;
3789		let section = super::psi::encode_pmt(&tables.pmt, tables.version)?;
3790		let breaks: Vec<u16> = [Pid::PAT, pmt_pid]
3791			.into_iter()
3792			.filter(|&pid| self.owes_break(pid))
3793			.collect();
3794		let encode = |flag: &dyn Fn(u16) -> bool| -> Result<Vec<u8>> {
3795			let mut packets = Vec::new();
3796			section_packets(&mut packets, Pid::PAT, &tables.pat, flag(Pid::PAT))?;
3797			section_packets(&mut packets, pmt_pid, &section, flag(pmt_pid))?;
3798			Ok(packets)
3799		};
3800		let packets = encode(&|_| false)?;
3801		let flagged = match breaks.is_empty() {
3802			true => None,
3803			false => Some(encode(&|pid| breaks.contains(&pid))?),
3804		};
3805		self.program.schedule.set_psi(super::schedule::Psi {
3806			packets,
3807			flagged,
3808			clock,
3809		});
3810		self.program.psi.as_mut().expect("checked above").stated = Some((tables, breaks));
3811		Ok(())
3812	}
3813
3814	/// Packetize one media frame and queue it on the [`Schedule`], re-emitting PAT/PMT
3815	/// before video keyframes (and periodically) so receivers can tune in mid-stream.
3816	fn mux(&mut self, name: &str, queued: Queued) -> Result<()> {
3817		let Queued {
3818			frame,
3819			decode,
3820			dts,
3821			description,
3822			pes,
3823			bill,
3824			..
3825		} = queued;
3826		let charge = (bill, frame.payload.len() as u64);
3827		let track = self.program.tracks.get(name).context("missing track")?;
3828		let kind = &track.kind;
3829		let is_video = matches!(kind, Kind::Video(_));
3830		// Refresh PSI at keyframes, MPEG-1/2 video's carried whole among them, or after the
3831		// interval lapses, and lead with a revision.
3832		let tune_in = frame.keyframe && kind.class() == super::stats::Class::Video;
3833		let cadence = tune_in || due(frame.timestamp, self.program.last_psi, PSI_INTERVAL);
3834		let psi = std::mem::take(&mut self.program.revised) || cadence;
3835		if psi {
3836			// A receiver tunes in at the tables, so each AAC PID's next frame repeats its program
3837			// config element. Its older frames go on ahead of the tables, so that frame starts a
3838			// PES rather than following raw blocks that lack the element.
3839			self.flush_packs(
3840				|track, _| matches!(&track.kind, Kind::Aac { config, .. } if config.program_config.is_some()),
3841			)?;
3842			for track in self.program.tracks.values_mut() {
3843				if let Kind::Aac { repeat, .. } = &mut track.kind {
3844					*repeat = true;
3845				}
3846			}
3847		}
3848		let track = self.program.tracks.get_mut(name).context("missing track")?;
3849		let pid = track.pid;
3850		let kind = track.kind.clone();
3851		if let Kind::Aac { repeat, .. } = &mut track.kind {
3852			*repeat = false;
3853		}
3854		let keyframe = frame.keyframe;
3855		let pce = matches!(kind, Kind::Aac { repeat: true, .. });
3856		let es_payload = es_payload(&kind, description.as_ref(), &frame, pce)?;
3857
3858		let mut out = Vec::with_capacity(TsPacket::SIZE);
3859
3860		if cadence {
3861			self.program.last_psi = Some(frame.timestamp);
3862		}
3863
3864		// Clock revisions wait for their stamped position on the revision grid, independent
3865		// of arrival or join time. Ordinary SI keeps its revision floor and absolute repeat
3866		// cadence. Clock values never repeat unchanged: that would re-assert an old time.
3867		let pending: Vec<(u16, Vec<Bytes>)> = self
3868			.program
3869			.si
3870			.iter_mut()
3871			.filter_map(|((pid, _), si)| si.emit(frame.timestamp).map(|sections| (*pid, sections)))
3872			.collect();
3873		for (pid, sections) in pending {
3874			self.program.schedule.set_buffer(pid, Buffer::SYSTEM);
3875			for section in &sections {
3876				self.write_section(&mut out, pid, section)?;
3877			}
3878		}
3879		// A reader drops SI it cannot place on the program clock, so while the opening's PCR
3880		// interval may still be ahead of the unit this frame goes in, the schedule holds the SI
3881		// for it rather than the media it would lead.
3882		if self.program.schedule.clocking() {
3883			self.program.schedule.push_clocked(std::mem::take(&mut out));
3884		}
3885
3886		// The tables lead the unit that carries this frame, behind whatever went before it.
3887		if kind.placed() {
3888			self.program.psi_due |= psi;
3889			return self.place(name, (&frame, charge), out);
3890		}
3891		match es_payload {
3892			None => unreachable!("only a placed track carries no elementary payload"),
3893			Some(es_payload) => {
3894				let unit = PesUnit {
3895					pid,
3896					is_video,
3897					keyframe,
3898					timestamp: frame.timestamp,
3899					dts,
3900					stream_id: stream_id(&kind),
3901				};
3902				// Only a delay leaves the frames time to wait for the ones after them.
3903				let track = self.program.tracks.get(name).context("missing track")?;
3904				if let Some((samples, rate)) = track.samples(&es_payload).filter(|_| !self.program.delay.is_zero()) {
3905					return self.pack(
3906						name,
3907						unit,
3908						decode,
3909						(psi, out),
3910						(es_payload, charge),
3911						(samples, rate, pes),
3912					);
3913				}
3914				self.flush(name)?;
3915				self.program.psi_due |= psi;
3916				self.write_pes(&mut out, &unit, &es_payload)?;
3917			}
3918		}
3919		self.program.schedule.bill(charge);
3920		self.push_unit(name, pid, decode, out, keyframe, Vec::new())
3921	}
3922
3923	/// Queue a whole PES or section unchanged on `name`'s PID behind `tables`, its
3924	/// first byte going out at the frame's timestamp, the source's placement, and no earlier.
3925	///
3926	/// A PID the T-STD models holds the PES's bytes in its decoder buffer until they decode,
3927	/// timed by the PTS in its header. For DVB Dolby audio that times only the first access
3928	/// unit that begins in it, so each one after counts on from there and leaves at its own time.
3929	/// The bytes ahead of the first end a frame an earlier PES began; they leave with it,
3930	/// which only overstates what the buffer holds. A PES without a PTS holds nothing there.
3931	/// The frame's `charge` counts once the unit goes out, unless it was dropped as malformed.
3932	fn place(&mut self, name: &str, (frame, charge): (&Frame, schedule::Charge), tables: Vec<u8>) -> Result<()> {
3933		let track = self.program.tracks.get(name).context("missing track")?;
3934		let pes = match track.kind {
3935			Kind::PesPacket { stream_type } => Some(
3936				PesPacket::parse(&frame.payload, stream_type)
3937					.map_err(|err| malformed!("MPEG-TS track '{name}' carries a malformed PES packet: {err}"))?,
3938			),
3939			Kind::Verbatim { .. } => None,
3940			_ => unreachable!("a placed track"),
3941		};
3942		let pid = track.pid;
3943		let place = nanos(frame.timestamp);
3944		// Its first access unit decodes at the DTS, which a reordered picture carries ahead of its PTS.
3945		let decode = pes
3946			.as_ref()
3947			.and_then(|pes| pes.dts.or(pes.pts))
3948			.map(|ticks| unwrap_pts(ticks, frame.timestamp));
3949		let dolby = Dolby::described(&track.descriptors)
3950			.filter(|_| matches!(track.kind, Kind::PesPacket { stream_type: 0x06 }));
3951		let frames = match (&pes, decode, dolby) {
3952			(Some(pes), Some(decode), Some(codec)) => dolby_removals(codec, &frame.payload[pes.payload..], decode),
3953			_ => Vec::new(),
3954		};
3955		let buffer = track.buffer();
3956		let mut out = std::mem::take(&mut self.program.tables);
3957		out.extend_from_slice(&tables);
3958		let prefix = match pes {
3959			Some(_) => {
3960				self.write_pes_packet(&mut out, pid, &frame.payload)?;
3961				self.program.schedule.bill(charge);
3962				0
3963			}
3964			None => {
3965				if self.write_section(&mut out, pid, &frame.payload)? {
3966					self.program.schedule.bill(charge);
3967				}
3968				1
3969			}
3970		};
3971		if let Some(buffer) = buffer {
3972			self.program.schedule.set_buffer(pid, buffer);
3973		}
3974		self.lead_tables(frame.timestamp)?;
3975		self.program.schedule.push_placed(
3976			pid,
3977			(place, decode.unwrap_or(place)),
3978			prefix,
3979			out,
3980			frame.keyframe,
3981			frames,
3982		)?;
3983		Ok(())
3984	}
3985
3986	/// Mux an audio frame into `name`'s PES, sending the PES on first if the frame cannot join
3987	/// it, and leave the program tables due (`psi`) and the SI muxed ahead of it to ride the
3988	/// next unit queued. A PES carries
3989	/// frames while they run on from its PTS without a gap and fit the PID's decoder buffer
3990	/// whole with its header, so it arrives by its first frame's decode time as one frame
3991	/// would, and they span at most half the delay: its frames leave the jitter buffer with
3992	/// its first ([`Track::release_key`]), so each keeps at least that much of the delay to
3993	/// arrive in.
3994	///
3995	/// A PES carries only frames that left the jitter buffer together ([`Track::pack_start`]),
3996	/// so it is whole however often the exporter is polled, and exporters of the broadcast that
3997	/// joined at different frames still cut the same PESs from the first that starts one, like
3998	/// [`due`].
3999	fn pack(
4000		&mut self,
4001		name: &str,
4002		unit: PesUnit,
4003		decode: Timestamp,
4004		(psi, tables): (bool, Vec<u8>),
4005		(payload, charge): (Vec<u8>, schedule::Charge),
4006		(samples, rate, start): (u64, u32, Option<PesStart>),
4007	) -> Result<()> {
4008		let budget = self.budget().as_nanos();
4009		let track = self.program.tracks.get(name).context("missing track")?;
4010		let (size, fit) = track.fit(payload.len());
4011		let place = place(unit.timestamp, samples, rate);
4012		// A PTS is a whole 90 kHz tick, so the frames run on within one of where they end.
4013		let joins = start.is_some()
4014			&& track.pack.as_ref().is_some_and(|pack| {
4015				pack.start == start
4016					&& pack.rate == rate
4017					&& pack.payload.len() + payload.len() <= size
4018					&& nanos(decode).saturating_sub(nanos(pack.decode)) <= budget
4019					&& pack.end().abs_diff(nanos(unit.timestamp) / 1_000) <= 12
4020			});
4021		if !joins {
4022			self.flush(name)?;
4023		}
4024		self.program.psi_due |= psi;
4025		self.program.tables.extend_from_slice(&tables);
4026		let track = self.program.tracks.get_mut(name).context("missing track")?;
4027		let pack = track.pack.get_or_insert(Pack {
4028			unit,
4029			decode,
4030			start,
4031			payload: Vec::new(),
4032			frames: Vec::new(),
4033			charges: Vec::new(),
4034			samples: 0,
4035			rate,
4036		});
4037		pack.frames.push((nanos(decode), payload.len()));
4038		pack.charges.push(charge);
4039		pack.payload.extend_from_slice(&payload);
4040		pack.samples += samples;
4041		// The next frame starts a PES of its own anyway.
4042		if (place + 1).is_multiple_of(fit) {
4043			self.flush(name)?;
4044		}
4045		Ok(())
4046	}
4047
4048	/// Send `name`'s packed frames on as one PES.
4049	fn flush(&mut self, name: &str) -> Result<()> {
4050		let Some(pack) = self.program.tracks.get_mut(name).and_then(|track| track.pack.take()) else {
4051			return Ok(());
4052		};
4053		let Pack {
4054			unit,
4055			decode,
4056			payload,
4057			frames,
4058			charges,
4059			..
4060		} = pack;
4061		let mut out = Vec::new();
4062		self.write_pes(&mut out, &unit, &payload)?;
4063		for charge in charges {
4064			self.program.schedule.bill(charge);
4065		}
4066		self.push_unit(name, unit.pid, decode, out, unit.keyframe, frames)
4067	}
4068
4069	/// Send on, in decode order, the packed frames of each track for which `done` holds, given
4070	/// the track and the slot its first frame is due in.
4071	fn flush_packs(&mut self, done: impl Fn(&Track, u128) -> bool) -> Result<()> {
4072		let mut due: Vec<(Timestamp, String)> = self
4073			.program
4074			.tracks
4075			.iter()
4076			.filter_map(|(name, track)| {
4077				let pack = track.pack.as_ref()?;
4078				let by = nanos(pack.decode).saturating_sub(track.drain().as_nanos());
4079				done(track, schedule::slot(by)).then(|| (pack.decode, name.clone()))
4080			})
4081			.collect();
4082		due.sort_by(|a, b| (a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)).then_with(|| a.1.cmp(&b.1)));
4083		for (_, name) in due {
4084			self.flush(&name)?;
4085		}
4086		Ok(())
4087	}
4088
4089	/// Queue one unit of `name`'s packets on `pid`, decoding at `decode`, on the [`Schedule`],
4090	/// behind the tables still waiting: with `frames`, each packed frame's decode nanoseconds
4091	/// and bytes.
4092	fn push_unit(
4093		&mut self,
4094		name: &str,
4095		pid: u16,
4096		decode: Timestamp,
4097		out: Vec<u8>,
4098		keyframe: bool,
4099		frames: Vec<(u128, usize)>,
4100	) -> Result<()> {
4101		let mut tables = std::mem::take(&mut self.program.tables);
4102		let out = match tables.is_empty() {
4103			true => out,
4104			false => {
4105				tables.extend_from_slice(&out);
4106				tables
4107			}
4108		};
4109		let track = self.program.tracks.get(name).context("missing track")?;
4110		// A padded output cannot burst a picture late, so a CPB that the source may fill to
4111		// its declared buffer delay needs that much send-ahead, all of it out of the delay.
4112		if self.program.mux_rate.is_some()
4113			&& let Some(needs) = track.timing.buffer_delay()
4114		{
4115			let slots = schedule::slot(needs.as_nanos());
4116			ensure_supported!(
4117				slots <= schedule::slot(self.program.delay.as_nanos()),
4118				"MPEG-TS video on PID {pid} declares a {needs:.3?} decoder buffer delay (its HRD's CPB over its bit rate), past what a {:?} delay sends it ahead; raise the delay to {:?}",
4119				self.program.delay,
4120				PCR_INTERVAL * u32::try_from(slots).unwrap_or(u32::MAX),
4121			);
4122		}
4123		let by = nanos(decode).saturating_sub(track.drain().as_nanos());
4124		self.lead_tables(decode)?;
4125		let track = self.program.tracks.get(name).context("missing track")?;
4126		if let Some(buffer) = self.scheduled(track) {
4127			self.program.schedule.set_buffer(pid, buffer);
4128		}
4129		self.program.schedule.push_frames(
4130			pid,
4131			super::schedule::Timing {
4132				by,
4133				decode: nanos(decode),
4134			},
4135			out,
4136			keyframe,
4137			frames,
4138		)?;
4139		Ok(())
4140	}
4141
4142	/// The longest any track's receiver takes to pass one of its packets on.
4143	fn max_drain(&self) -> Duration {
4144		self.program.tracks.values().map(Track::drain).max().unwrap_or_default()
4145	}
4146
4147	/// When the next grid slot is due on the jitter buffer's clock: once every frame that could
4148	/// ride it has gone out of the jitter buffer, so its contents depend on the frames alone,
4149	/// never on when they arrived, and the output keeps the clock's pace while media is queued
4150	/// (in the schedule or still in the jitter buffer) or still to decode. `None` without a
4151	/// delay, where frames settle the slots instead.
4152	fn slot_due(&self) -> Option<(u128, kio::clock::Instant)> {
4153		let (known, settled) = self.slot_settled()?;
4154		let settled = Timestamp::from_micros(u64::try_from(settled / 1_000).ok()?).ok()?;
4155		// The tail of the generation still going out keeps its own clock after the next is acquired.
4156		let settled = jitter::Decode::try_from(settled).ok()?;
4157		Some((known, self.jitter.at(self.program.generation, settled)?))
4158	}
4159
4160	/// The `known` that settles the next grid slot, and the jitter buffer key, in nanoseconds,
4161	/// by which every frame that could ride it has gone out of the jitter buffer. Keys run a
4162	/// delay past release times ([`Track::release_key`]).
4163	fn slot_settled(&self) -> Option<(u128, u128)> {
4164		if self.program.delay.is_zero()
4165			|| self.program.psi.is_none()
4166			|| (self.program.schedule.is_empty()
4167				&& !self.packing()
4168				&& (self.jitter.is_empty()
4169					|| (self.pending.is_some()
4170						&& !self.program.tracks.values().any(|track| self.jitter.holds(&track.key)))))
4171		{
4172			return None;
4173		}
4174		let (_, known) = self.program.schedule.upcoming()?;
4175		Some((
4176			known,
4177			known * PCR_INTERVAL.as_nanos() + self.max_drain().as_nanos() + self.program.delay.as_nanos(),
4178		))
4179	}
4180
4181	/// Whether a track holds frames packed for a PES still to go out.
4182	fn packing(&self) -> bool {
4183		self.program.tracks.values().any(|track| track.pack.is_some())
4184	}
4185
4186	/// Lay out every grid slot settled before a frame keyed `key` in the jitter buffer goes
4187	/// out, so frames and slots follow each other in the same order however often the
4188	/// exporter is polled.
4189	fn lay_before(&mut self, key: u128) -> Result<()> {
4190		while let Some((known, _)) = self.slot_settled().filter(|&(_, settled)| settled < key) {
4191			self.lay(Some(known))?;
4192		}
4193		Ok(())
4194	}
4195
4196	/// Half the delay: how long a PES of packed frames may span, and how far a padded output may
4197	/// fall behind before it sheds.
4198	fn budget(&self) -> Duration {
4199		self.program.delay / 2
4200	}
4201
4202	/// Shed what a padded output fell more than [`Self::budget`] behind on, as when its sink
4203	/// blocks or drains slower than the multiplex rate. Every slot it missed would otherwise go
4204	/// out at once, and the frames it left unread would reach the jitter buffer as late as a
4205	/// source clock running far slow. Instead it drops what is due by now and resumes the grid
4206	/// on the media still to come, flagging the jump as a PCR discontinuity.
4207	///
4208	/// It is behind by how long the jitter buffer's front has been overdue since a read last
4209	/// caught up: a frame held back while the output keeps up (for the program's tables, or a
4210	/// generation still going out) is no lag of the sink's, and a source that fell silent leaves
4211	/// nothing overdue.
4212	/// Returns whether it shed.
4213	fn shed(&mut self) -> bool {
4214		// Once every source has ended, the tail goes out late if it must.
4215		if self.program.mux_rate.is_none() || self.held.is_some() || self.program.schedule.ended() {
4216			return false;
4217		}
4218		let (Some(due), Some(caught_up)) = (self.jitter.front_deadline(), self.caught_up) else {
4219			return false;
4220		};
4221		let behind = kio::clock::now().saturating_duration_since(due.max(caught_up));
4222		if behind <= self.budget() {
4223			return false;
4224		}
4225		tracing::warn!(?behind, "MPEG-TS output fell behind its multiplex rate, shedding");
4226		self.jitter.shed(kio::clock::now());
4227		self.rewind();
4228		true
4229	}
4230
4231	/// Lay out every grid slot whose time has come, and wake when the next one is due.
4232	fn lay_due(&mut self, waiter: &kio::Waiter) -> Result<()> {
4233		while let Some((known, at)) = self.slot_due() {
4234			if kio::clock::now() < at {
4235				let timer = self
4236					.program
4237					.slot_timer
4238					.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(at)));
4239				if timer.deadline() != at {
4240					timer.as_mut().reset(at);
4241				}
4242				if waiter.poll_future(timer.as_mut()).is_pending() {
4243					return Ok(());
4244				}
4245			}
4246			self.lay(Some(known))?;
4247		}
4248		self.program.slot_timer = None;
4249		Ok(())
4250	}
4251
4252	/// Lay out every grid slot the schedule has settled, one [`Frame`] each: `known` is
4253	/// the first slot a frame still to be muxed could be due in, or `None` when nothing
4254	/// more is coming.
4255	///
4256	/// Each frame opens with its slot's PCR: at a multiplex rate, in the adaptation field of
4257	/// the clock PID's packet when one can go out there, else in a clock packet of its own.
4258	/// At a multiplex rate its value is the time of its own byte position at the rate, so a
4259	/// consumer holding only the byte stream (which is every MPEG-TS tool) recovers the same
4260	/// clock the values assert. Each frame is stamped at its slot boundary, so a pacing
4261	/// caller releases the clock at the instant it asserts.
4262	///
4263	/// The PCR's value never comes from the PES units: a PCR sampled from the DTS would
4264	/// step with the frame cadence, and no downstream CBR stage can repair that, because a
4265	/// groomer can only place the clock samples it receives. So the PCR follows its own
4266	/// grid instead: slots on the media timeline, shared by every exporter of the
4267	/// broadcast, like [`due`].
4268	fn lay(&mut self, known: Option<u128>) -> Result<()> {
4269		if self.program.psi.is_none() {
4270			return Ok(());
4271		}
4272		if known.is_none() {
4273			self.flush_packs(|_, _| true)?;
4274		}
4275		let lead = schedule::slot(self.budget().as_nanos());
4276		loop {
4277			// A PES of packed frames goes out half the delay before its first is due, so it
4278			// has that long to reach the decoder.
4279			if known.is_some()
4280				&& let Some((index, _)) = self.program.schedule.upcoming()
4281			{
4282				self.flush_packs(|_, due| due <= index + lead)?;
4283			}
4284			let Some(slot) = self.program.schedule.next(known)? else {
4285				break;
4286			};
4287			let clock = pcr_packet(slot.clock.context("a slot without a clock PID")?, slot.pcr)?;
4288			let pmt_pid = self.pmt_pid();
4289			let mut payload = slot.layout(&clock, pmt_pid, &NULL_PACKET);
4290			// The slot opens with its PCR, in the clock packet or the clock PID's packet that
4291			// carries it, whose adaptation field flags the break.
4292			let discontinuity = std::mem::take(&mut self.program.pcr_discontinuity);
4293			if discontinuity || slot.discontinuity {
4294				payload[5] |= 0x80;
4295			}
4296			self.number(&mut payload);
4297			let frame = Frame {
4298				timestamp: slot_stamp(slot.index)?,
4299				decode: None,
4300				duration: None,
4301				payload: Bytes::from(payload),
4302				keyframe: slot.keyframe,
4303			};
4304			let psi = self.program.psi.as_mut().expect("checked above");
4305			// Each copy begun laid the tables as they stood, and the first spent the breaks they flag.
4306			let mut spent = Vec::new();
4307			if slot.begun > 0 {
4308				let (tables, breaks) = psi.stated.clone().context("program tables laid but never set")?;
4309				psi.sending.extend(std::iter::repeat_n(tables.clone(), slot.begun));
4310				psi.laid = Some(tables);
4311				spent = breaks;
4312			}
4313			let tables = (0..slot.tables).filter_map(|_| psi.sending.pop_front()).last();
4314			// Skipped slots retain the source timeline, so silence statistics include the jump.
4315			let tally = Tally {
4316				pcr: (slot.pcr, discontinuity),
4317				units: slot.units,
4318				tables,
4319				charges: slot.charges,
4320			};
4321			self.program.queue.push_back((frame, tally));
4322			if !spent.is_empty() {
4323				if let Some(flagged) = &mut self.program.flagged {
4324					flagged.extend(spent);
4325				}
4326				self.restate()?;
4327			}
4328			// The copies a move waited for may have finished.
4329			self.follow_pmt()?;
4330		}
4331		Ok(())
4332	}
4333
4334	/// Number the continuity counters of packets about to go out. A packet without a
4335	/// payload (a clock packet) repeats the counter before it (ISO 13818-1 2.4.3.3); before
4336	/// anything has gone out on its PID, any value starts a valid run.
4337	fn number(&mut self, packets: &mut [u8]) {
4338		for packet in packets.as_chunks_mut::<{ TsPacket::SIZE }>().0 {
4339			let pid = u16::from(packet[1] & 0x1f) << 8 | u16::from(packet[2]);
4340			if pid == 0x1FFF {
4341				continue;
4342			}
4343			let next = self.program.counters.entry(pid).or_default();
4344			let cc = match packet[3] & 0x10 != 0 {
4345				true => std::mem::replace(next, (*next + 1) & ContinuityCounter::MAX),
4346				false => next.wrapping_sub(1) & ContinuityCounter::MAX,
4347			};
4348			packet[3] = (packet[3] & 0xf0) | cc;
4349		}
4350	}
4351
4352	/// Packetize a PES payload into 188-byte TS packets.
4353	fn write_pes(&mut self, out: &mut Vec<u8>, unit: &PesUnit, payload: &[u8]) -> Result<()> {
4354		let flag = self.breaks(unit.pid);
4355		pes_packets(out, unit, payload, flag)
4356	}
4357
4358	/// Packetize `pes`, a whole PES packet, on `pid` unchanged ([`whole_pes_packets`]).
4359	fn write_pes_packet(&mut self, out: &mut Vec<u8>, pid: u16, pes: &[u8]) -> Result<()> {
4360		let flag = self.breaks(pid);
4361		whole_pes_packets(out, pid, pes, flag)
4362	}
4363
4364	/// Packetize a complete PSI or private section verbatim ([`section_packets`]), returning
4365	/// whether it did rather than drop the section as malformed.
4366	fn write_section(&mut self, out: &mut Vec<u8>, pid: u16, section: &[u8]) -> Result<bool> {
4367		// The verbatim track is public; a non-importer producer could publish a frame
4368		// that isn't a complete section. Drop it (with a warning) rather than emit a
4369		// malformed section a downstream demuxer would choke on. One bad section must
4370		// not abort a live export, so this skips instead of erroring.
4371		if !is_complete_section(section) {
4372			tracing::warn!(pid, len = section.len(), "dropping malformed private section on export");
4373			return Ok(false);
4374		}
4375		let flag = self.breaks(pid);
4376		section_packets(out, pid, section, flag)?;
4377		Ok(true)
4378	}
4379}
4380
4381/// Packetize a PES payload into 188-byte TS packets, flagging a break in the first when `flag`.
4382fn pes_packets(out: &mut Vec<u8>, unit: &PesUnit, payload: &[u8], flag: bool) -> Result<()> {
4383	let pts = to_ts_timestamp(unit.timestamp)?;
4384	// A reordered video frame carries DTS alongside PTS; else PTS-only. The decode clock
4385	// is continuous ticks, so wrap into the 33-bit wire field here, like the PTS.
4386	let dts = unit
4387		.dts
4388		.map(|t| TsTimestamp::new(t & TS_TIMESTAMP_MASK).map_err(|err| malformed!("{err}")))
4389		.transpose()?;
4390	let stream_id = match unit.stream_id {
4391		Some(id) => StreamId::new(id),
4392		None if unit.is_video => StreamId::new(StreamId::VIDEO_MIN),
4393		None => StreamId::new(StreamId::AUDIO_MIN),
4394	};
4395	let header = mpeg2ts::pes::PesHeader {
4396		stream_id,
4397		priority: false,
4398		data_alignment_indicator: true,
4399		copyright: false,
4400		original_or_copy: false,
4401		pts: Some(pts),
4402		dts,
4403		escr: None,
4404	};
4405
4406	// The optional PES header grows by 5 bytes when it also carries a DTS.
4407	let optional_len = PES_OPTIONAL_LEN + if dts.is_some() { PES_DTS_LEN } else { 0 };
4408
4409	// `pes_packet_len` counts the optional header plus the payload (not the
4410	// 6-byte fixed prefix). Unbounded for video (0); bounded for audio when
4411	// it fits a u16.
4412	let pes_packet_len = if unit.is_video {
4413		0
4414	} else {
4415		u16::try_from(optional_len + payload.len()).unwrap_or(0)
4416	};
4417
4418	let mut offset = 0;
4419	let mut first = true;
4420	loop {
4421		let flag = first && flag;
4422		let adaptation = ((first && unit.keyframe) || flag).then(|| AdaptationField {
4423			random_access_indicator: first && unit.keyframe,
4424			..flags(flag)
4425		});
4426
4427		let header_len = if first { 6 + optional_len } else { 0 };
4428		let af_len = adaptation.as_ref().map(adaptation_size).unwrap_or(0);
4429		let avail = TsBytes::MAX_SIZE - header_len - af_len;
4430		let take = avail.min(payload.len() - offset);
4431		let chunk = &payload[offset..offset + take];
4432
4433		let ts_payload = if first {
4434			TsPayload::PesStart(Pes {
4435				header: header.clone(),
4436				pes_packet_len,
4437				data: TsBytes::new(chunk).map_err(|err| malformed!("{err}"))?,
4438			})
4439		} else {
4440			TsPayload::PesContinuation(TsBytes::new(chunk).map_err(|err| malformed!("{err}"))?)
4441		};
4442
4443		write_packet(out, unit.pid, adaptation, ts_payload)?;
4444
4445		offset += take;
4446		first = false;
4447		if offset >= payload.len() {
4448			break;
4449		}
4450	}
4451	Ok(())
4452}
4453
4454/// Packetize `pes`, a whole PES packet, into TS packets on `pid` without touching a byte of
4455/// it, flagging a break in the first packet when `flag` and stuffing the last packet's
4456/// adaptation field. The `mpeg2ts` writer would rebuild the PES header instead, so the packets
4457/// are laid out by hand.
4458fn whole_pes_packets(out: &mut Vec<u8>, pid: u16, pes: &[u8], flag: bool) -> Result<()> {
4459	ensure!(pid < 0x1FFF, "PID out of range: {pid}");
4460	let mut offset = 0;
4461	while offset < pes.len() {
4462		let start = offset == 0;
4463		let flag = start && flag;
4464		// The adaptation field: its length byte, then a flags byte for the break.
4465		let field = if flag { 2 } else { 0 };
4466		let take = (TsBytes::MAX_SIZE - field).min(pes.len() - offset);
4467		let field = TsBytes::MAX_SIZE - take;
4468		out.extend_from_slice(&[0x47, u8::from(start) << 6 | (pid >> 8) as u8, pid as u8]);
4469		match field {
4470			0 => out.push(0x10),
4471			_ => {
4472				out.push(0x30);
4473				out.push((field - 1) as u8);
4474				if field > 1 {
4475					out.push(if flag { 0x80 } else { 0 });
4476					out.resize(out.len() + field - 2, 0xff);
4477				}
4478			}
4479		}
4480		out.extend_from_slice(&pes[offset..offset + take]);
4481		offset += take;
4482	}
4483	Ok(())
4484}
4485
4486/// Packetize a complete PSI or private section verbatim, flagging a break in the first packet
4487/// when `flag`. The first packet carries the pointer_field plus the section start as a
4488/// `Section` payload (sets the unit-start bit so the receiver finds the pointer_field);
4489/// continuations are `Raw`. The section bytes are opaque, so this round-trips byte-for-byte.
4490fn section_packets(out: &mut Vec<u8>, pid: u16, section: &[u8], flag: bool) -> Result<()> {
4491	let mut offset = 0;
4492	let mut first = true;
4493	loop {
4494		let flag = (first && flag).then(|| flags(true));
4495		let payload = if first {
4496			// pointer_field (1 byte, written by `Section`) eats one payload byte, and a flag
4497			// for the break its adaptation field.
4498			let room = TsBytes::MAX_SIZE - 1 - flag.as_ref().map_or(0, adaptation_size);
4499			let take = room.min(section.len());
4500			let chunk = &section[..take];
4501			offset = take;
4502			TsPayload::Section(Section {
4503				pointer_field: 0,
4504				data: TsBytes::new(chunk).map_err(|err| malformed!("{err}"))?,
4505			})
4506		} else {
4507			let take = TsBytes::MAX_SIZE.min(section.len() - offset);
4508			let chunk = &section[offset..offset + take];
4509			offset += take;
4510			TsPayload::Raw(TsBytes::new(chunk).map_err(|err| malformed!("{err}"))?)
4511		};
4512
4513		write_packet(out, pid, flag, payload)?;
4514		first = false;
4515		if offset >= section.len() {
4516			break;
4517		}
4518	}
4519	Ok(())
4520}
4521
4522/// Serialize one TS packet into `out`. Its continuity counter is numbered when it goes
4523/// out ([`Export::number`]), since the schedule decides that order.
4524fn write_packet(
4525	out: &mut Vec<u8>,
4526	pid: u16,
4527	adaptation_field: Option<AdaptationField>,
4528	payload: TsPayload,
4529) -> Result<()> {
4530	let continuity_counter = ContinuityCounter::default();
4531
4532	let packet = TsPacket {
4533		header: TsHeader {
4534			transport_error_indicator: false,
4535			transport_priority: false,
4536			pid: Pid::new(pid)?,
4537			transport_scrambling_control: TransportScramblingControl::NotScrambled,
4538			continuity_counter,
4539		},
4540		adaptation_field,
4541		payload: Some(payload),
4542	};
4543
4544	let mut writer = TsPacketWriter::new(out);
4545	writer.write_ts_packet(&packet).map_err(|err| malformed!("{err}"))?;
4546	Ok(())
4547}
4548
4549impl<E: catalog::Catalog> Export<crate::catalog::Consumer<E>> {
4550	pub(super) fn catalog_format(&self) -> crate::catalog::CatalogFormat {
4551		self.selected().catalog.as_ref().expect("selected catalog").format()
4552	}
4553}
4554
4555/// One adaptation-field-only TS packet carrying `ticks` (continuous 90 kHz) as its
4556/// PCR, laid out by hand: the `mpeg2ts` serializer writes the six reserved bits
4557/// between PCR base and extension as zeros where ISO 13818-1 requires ones, and
4558/// strict analyzers flag that.
4559///
4560/// There is no payload, so the field's stuffing fills the packet; its continuity counter
4561/// is numbered when it goes out ([`Export::number`]).
4562fn pcr_packet(pid: u16, pcr: u64) -> Result<Vec<u8>> {
4563	ensure!(pid <= 0x1FFF, "PID out of range: {pid}");
4564	let mut p = Vec::with_capacity(TsPacket::SIZE);
4565	p.push(0x47);
4566	p.push((pid >> 8) as u8);
4567	p.push(pid as u8);
4568	// adaptation_field_control = adaptation field only, no scrambling.
4569	p.push(0x20);
4570	// adaptation_field_length covers the rest of the packet.
4571	p.push(183);
4572	// PCR_flag alone.
4573	p.push(0x10);
4574	p.extend_from_slice(&super::schedule::pcr_field(pcr));
4575	p.resize(TsPacket::SIZE, 0xff);
4576	Ok(p)
4577}
4578
4579/// PES header bytes ahead of the optional region: start code, stream id and packet length.
4580const PES_PREFIX_LEN: usize = 6;
4581/// Optional PES header region carrying PTS only: 2 flag bytes + 1 length byte + 5 PTS bytes.
4582const PES_OPTIONAL_LEN: usize = 3 + 5;
4583/// Extra bytes when the optional region also carries a DTS (5 DTS bytes).
4584const PES_DTS_LEN: usize = 5;
4585
4586/// What the mux reads of a frame holding one whole PES packet ([`Kind::PesPacket`]).
4587struct PesPacket {
4588	/// Its PTS in 90 kHz ticks, as the 33-bit field carries it.
4589	pts: Option<u64>,
4590	/// Its DTS, likewise, where it differs from the PTS.
4591	dts: Option<u64>,
4592	/// Where its payload begins, past the header.
4593	payload: usize,
4594}
4595
4596impl PesPacket {
4597	/// Read `bytes` as exactly one well-formed PES packet of a stream of `stream_type`:
4598	/// the start code, a `PES_packet_length` that matches, and a complete optional header
4599	/// where the `stream_id` has one (ISO 13818-1 2.4.3.6). Only video may leave the
4600	/// length zero, unbounded, as 2.4.3.7 permits.
4601	fn parse(bytes: &[u8], stream_type: u8) -> Result<Self> {
4602		// The importer refuses with this same check, so a PES it published never fails here.
4603		let pes = psi::PesStart::parse(bytes)?;
4604		// The clock fields it refuses ride through unchanged.
4605		pes.whole(stream_type)?;
4606		if let Some(len) = pes.data_len {
4607			ensure!(
4608				len == pes.data.len(),
4609				"PES_packet_length declares {len} payload bytes where the frame holds {}",
4610				pes.data.len()
4611			);
4612		}
4613		Ok(Self {
4614			pts: pes.pts,
4615			dts: pes.dts,
4616			payload: pes.header.len(),
4617		})
4618	}
4619}
4620
4621/// A 33-bit PTS read off a placed PES, on the media timeline in nanoseconds: the value
4622/// nearest its placement `at` that the wrapped field allows, since a PES decodes close to
4623/// where it is placed.
4624fn unwrap_pts(pts: u64, at: Timestamp) -> u128 {
4625	const WRAP: i128 = 1 << 33;
4626	let base = i128::from(to_ticks(at));
4627	let ahead = (i128::from(pts) - base).rem_euclid(WRAP);
4628	let ticks = base + if ahead >= WRAP / 2 { ahead - WRAP } else { ahead };
4629	(ticks.max(0) as u128) * 1_000_000_000 / 90_000
4630}
4631
4632/// When each Dolby access unit that begins in a PES's `payload` leaves the decoder buffer and
4633/// the bytes it takes, counting on from `decode`, the PES's PTS: [`Schedule::push_placed`]'s
4634/// frames. The bytes ahead of the first unit go with it, and a frame the PES leaves
4635/// unfinished keeps its unit's time for the bytes it holds. Empty with fewer than two units,
4636/// where the whole PES leaves at once.
4637fn dolby_removals(codec: Dolby, payload: &[u8], decode: u128) -> Vec<(u128, usize)> {
4638	let Some(mut offset) = dolby_sync(codec, payload) else {
4639		return Vec::new();
4640	};
4641	let mut frames: Vec<(u128, usize)> = Vec::new();
4642	let (mut at, mut lead) = (decode, offset);
4643	while offset < payload.len() {
4644		let rest = &payload[offset..];
4645		let Ok(header) = codec.parse(rest) else {
4646			break;
4647		};
4648		let len = header.len.min(rest.len());
4649		match frames.last_mut() {
4650			// A substream leaves with its access unit, or the first when that began earlier.
4651			Some((_, bytes)) if !codec.begins_unit(rest) => *bytes += len,
4652			None if !codec.begins_unit(rest) => lead += len,
4653			_ => {
4654				frames.push((at, len));
4655				at += 1_000_000_000 * u128::from(header.samples) / u128::from(header.sample_rate.max(1));
4656			}
4657		}
4658		offset += len.max(1);
4659	}
4660	if let Some(head) = frames.first_mut() {
4661		head.1 += lead;
4662	}
4663	if let Some(tail) = frames.last_mut() {
4664		tail.1 += payload.len().saturating_sub(offset);
4665	}
4666	frames
4667}
4668
4669/// Whether `timestamp` has crossed into a later repetition slot than `last`.
4670///
4671/// Slots are absolute on the media timeline (`floor(timestamp / interval)`) rather than
4672/// measured forward from the previous emission, so a table lands on the same frames no
4673/// matter when the exporter started. Two exporters of one broadcast then emit the tables
4674/// at the same points, which a redundant pair compares byte for byte. `None` (nothing
4675/// emitted yet) is always due, so a fresh exporter leads with the tables and a receiver
4676/// can tune in without waiting for the next slot.
4677///
4678/// A *later* slot, not merely a different one: video is emitted in decode order, so a
4679/// reordered (B-frame) PTS steps backwards all the time, and re-emitting on every
4680/// oscillation across a boundary buys nothing and costs a table each way.
4681fn due(timestamp: Timestamp, last: Option<Timestamp>, interval: Duration) -> bool {
4682	// "Every frame", which the slot arithmetic can't express (and would divide by zero on).
4683	if interval.is_zero() {
4684		return true;
4685	}
4686	let Some(last) = last else {
4687		return true;
4688	};
4689	slot(timestamp, interval) > slot(last, interval)
4690}
4691
4692/// Whether a changed SI snapshot may go out: `interval` has elapsed on the media
4693/// timeline since the entry last hit the wire.
4694///
4695/// A floor measured from the entry's own last emission, unlike [`due`]'s absolute
4696/// grid, so a revision goes out promptly (`SiTrack::dirty`, [`SI_REVISION_INTERVAL`])
4697/// while a publisher revising every frame still cannot drive the mux at that rate.
4698/// `None` (never emitted) is always due, so a fresh exporter leads with the tables.
4699fn si_due(timestamp: Timestamp, last: Option<Timestamp>, interval: Duration) -> bool {
4700	let Some(last) = last else {
4701		return true;
4702	};
4703	// Reordered (B-frame) timestamps step backwards; saturate rather than wrap so a
4704	// dip never counts as elapsed time (a zero interval still means "every frame").
4705	nanos(timestamp).saturating_sub(nanos(last)) >= interval.as_nanos()
4706}
4707
4708/// DVB's TDT and TOT: tables whose content is the current time, so a repeat of an
4709/// unchanged snapshot asserts a time already sent (#2934).
4710fn is_clock_table(table_id: u8) -> bool {
4711	matches!(table_id, 0x70 | 0x73)
4712}
4713
4714/// Index of `timestamp`'s repetition slot: how many whole `interval`s fit under it.
4715///
4716/// Nanoseconds, so the divisor is zero only for a genuinely zero `interval`, which [`due`]
4717/// takes before it gets here. Coarser units would floor a sub-unit interval to zero and
4718/// divide by it.
4719fn slot(timestamp: Timestamp, interval: Duration) -> u128 {
4720	nanos(timestamp) / interval.as_nanos()
4721}
4722
4723/// A repetition slot's boundary as a media timestamp.
4724fn slot_stamp(index: u128) -> Result<Timestamp> {
4725	stamp(index * PCR_INTERVAL.as_micros() * 1_000)
4726}
4727
4728/// A nanosecond position on the media timeline as a microsecond [`Timestamp`], the
4729/// scale the exporter stamps its own output in.
4730fn stamp(nanos: u128) -> Result<Timestamp> {
4731	let micros = (nanos / 1_000)
4732		.try_into()
4733		.map_err(|_| malformed!("media timeline out of range"))?;
4734	Ok(Timestamp::from_micros(micros)?)
4735}
4736
4737/// An adaptation field carrying nothing but `discontinuity_indicator`.
4738fn flags(discontinuity: bool) -> AdaptationField {
4739	AdaptationField {
4740		discontinuity_indicator: discontinuity,
4741		random_access_indicator: false,
4742		es_priority_indicator: false,
4743		pcr: None,
4744		opcr: None,
4745		splice_countdown: None,
4746		transport_private_data: Vec::new(),
4747		extension: None,
4748	}
4749}
4750
4751/// External byte size of an adaptation field (manual mirror of the crate's
4752/// private `external_size`); only PCR is ever set.
4753fn adaptation_size(af: &AdaptationField) -> usize {
4754	2 + if af.pcr.is_some() { 6 } else { 0 }
4755}
4756
4757/// Where an audio frame of `samples` at `rate` presented at `timestamp` sits on the media
4758/// timeline, counted in frames. Rounded, since a frame need not last whole microseconds:
4759/// AAC's 1,024 samples at 48 kHz.
4760fn place(timestamp: Timestamp, samples: u64, rate: u32) -> u128 {
4761	let frame = 1_000_000 * u128::from(samples);
4762	(nanos(timestamp) / 1_000 * u128::from(rate) + frame / 2) / frame
4763}
4764
4765/// The 33-bit wire timestamp field (90 kHz). DTS and PTS both wrap into it.
4766const TS_TIMESTAMP_MASK: u64 = (1 << 33) - 1;
4767
4768/// Continuous (unwrapped) 90 kHz tick count for a media timestamp. The decode clock runs in
4769/// this domain so it never wraps mid-stream (the source timestamps are already unwrapped);
4770/// [`to_ts_timestamp`] masks to the 33-bit wire field only at emission.
4771fn to_ticks(timestamp: Timestamp) -> u64 {
4772	(nanos(timestamp) / 1_000 * 90_000 / 1_000_000) as u64
4773}
4774
4775/// A media timestamp in nanoseconds.
4776///
4777/// Every timestamp the exporter holds has a scale: a track refuses an unscaled frame as it reads
4778/// one ([`Track::fill`]), an SI revision keeps none, and the rest are stamped here. Zero stands in
4779/// for one that can't reach here rather than a panic.
4780fn nanos(timestamp: Timestamp) -> u128 {
4781	timestamp.as_nanos().unwrap_or_default()
4782}
4783
4784fn to_ts_timestamp(timestamp: Timestamp) -> Result<TsTimestamp> {
4785	// Continuous 90 kHz ticks, wrapped into the 33-bit field.
4786	TsTimestamp::new(to_ticks(timestamp) & TS_TIMESTAMP_MASK).map_err(|err| malformed!("{err}"))
4787}
4788
4789fn video_kind(config: &VideoConfig, name: &str) -> Result<Kind> {
4790	ensure_raw(&config.container, "video", name)?;
4791	// Both in-band (avc3/hev1) and out-of-band (avc1/hvc1) are accepted:
4792	// ExportSource normalizes both to length-prefixed NALU + avcC/hvcC, and the
4793	// muxer rewrites them to Annex-B.
4794	match &config.codec {
4795		VideoCodec::H264(_) => Ok(Kind::Video(StreamType::H264)),
4796		VideoCodec::H265(_) => Ok(Kind::Video(StreamType::H265)),
4797		other => bail_unsupported!("TS export does not support video codec {other:?} (track '{name}')"),
4798	}
4799}
4800
4801/// The delay a track subscription states for an export running `delay` behind: all of it, as both
4802/// bounds, so a relay resets a group only once it is that old and a replay reaches back that far.
4803/// A live start joins at the edge whatever the min ([`ExportSource::live`]).
4804pub(super) fn subscribed(delay: Duration) -> crate::container::Delay {
4805	crate::container::Delay::default().with_min(delay).with_max(delay)
4806}
4807
4808/// Skip a stalled group once the group after it runs `delay` past it, and wait that long for a
4809/// missing one, so a stall shorter than the delay loses nothing. The reader delivers in order, so a
4810/// group whose tail never arrives holds the next one for the whole delay, and the next group's
4811/// first frames go out late. No min, unlike [`subscribed`], so a live start begins at the newest
4812/// group rather than reach back the delay.
4813pub(super) fn skipping(source: ExportSource, delay: Duration) -> ExportSource {
4814	source.skipping_at(crate::container::Delay::default().with_min(None).with_max(delay))
4815}
4816
4817/// Start a media track's source at the live edge, the newest group, so the export does not
4818/// begin on a group up to a delay old and carry that lag ever after; unless `replay`.
4819/// Verbatim streams are sparse, and anything of theirs ahead of the first keyframe is
4820/// dropped anyway, so they reach back as far as the skip budget allows.
4821fn at_edge(source: ExportSource, replay: bool) -> ExportSource {
4822	match replay {
4823		true => source,
4824		false => source.live(),
4825	}
4826}
4827
4828/// Start an `mpegts` section track's source as [`at_edge`] would, if it is MPEG-1/2 video
4829/// carried whole: video, not sparse, whose groups older than the edge would only be trimmed.
4830fn stream_edge(source: ExportSource, kind: &Kind, replay: bool) -> ExportSource {
4831	match kind.class() {
4832		super::stats::Class::Video => at_edge(source, replay),
4833		_ => source,
4834	}
4835}
4836
4837/// A video level's T-STD limits (H.222.0 2.14.3.1, 2.17.2), in bits per second and bits.
4838#[derive(Clone, Copy, Debug)]
4839struct Level {
4840	/// The leak from MB into EB, Rbx: CpbBrNalFactor * MaxBR.
4841	leak: u64,
4842	/// BitRate without an HRD, which `factor` scales to Rx: 1200 * MaxBR for H.264, the
4843	/// least cpbBrNalFactor of any profile, and CpbBrVclFactor * MaxBR for H.265.
4844	bit_rate: u64,
4845	/// EB without an HRD: CpbBrNalFactor * MaxCPB.
4846	cpb: u64,
4847	/// Rx over an HRD's BitRate, in thousandths: 1.2 for H.264, CpbBrNalFactor /
4848	/// CpbBrVclFactor for H.265.
4849	factor: u64,
4850}
4851
4852/// A video rendition's level limits from its catalog codec (H.264 Table A-1, H.265 Table
4853/// A.8). A level the tables don't list takes the lowest, which only sends its units earlier.
4854fn video_level(config: &VideoConfig, name: &str) -> Level {
4855	let level = match &config.codec {
4856		VideoCodec::H264(h264) => {
4857			// level_idc 11 with constraint_set3_flag is level 1b for Baseline, Main and Extended.
4858			let level_1b = h264.level == 11 && h264.constraints & 0x10 != 0 && matches!(h264.profile, 66 | 77 | 88);
4859			let limits = match h264.level {
4860				_ if level_1b => Some((128, 350)),
4861				9 => Some((128, 350)),
4862				10 => Some((64, 175)),
4863				11 => Some((192, 500)),
4864				12 => Some((384, 1_000)),
4865				13 => Some((768, 2_000)),
4866				20 => Some((2_000, 2_000)),
4867				21 | 22 => Some((4_000, 4_000)),
4868				30 => Some((10_000, 10_000)),
4869				31 => Some((14_000, 14_000)),
4870				32 => Some((20_000, 20_000)),
4871				40 => Some((20_000, 25_000)),
4872				41 | 42 => Some((50_000, 62_500)),
4873				50 => Some((135_000, 135_000)),
4874				51 | 52 | 60 => Some((240_000, 240_000)),
4875				61 => Some((480_000, 480_000)),
4876				62 => Some((800_000, 800_000)),
4877				_ => None,
4878			};
4879			limits.map(|(max_br, max_cpb)| Level {
4880				leak: 1_200 * max_br,
4881				bit_rate: 1_200 * max_br,
4882				cpb: 1_200 * max_cpb,
4883				factor: 1_200,
4884			})
4885		}
4886		VideoCodec::H265(h265) => {
4887			let limits = match (h265.level_idc, h265.tier_flag) {
4888				(30, false) => Some((128, 350)),
4889				(60, false) => Some((1_500, 1_500)),
4890				(63, false) => Some((3_000, 3_000)),
4891				(90, false) => Some((6_000, 6_000)),
4892				(93, false) => Some((10_000, 10_000)),
4893				(120, false) => Some((12_000, 12_000)),
4894				(120, true) => Some((30_000, 30_000)),
4895				(123, false) => Some((20_000, 20_000)),
4896				(123, true) => Some((50_000, 50_000)),
4897				(150, false) => Some((25_000, 25_000)),
4898				(150, true) => Some((100_000, 100_000)),
4899				(153, false) => Some((40_000, 40_000)),
4900				(153, true) => Some((160_000, 160_000)),
4901				(156 | 180, false) => Some((60_000, 60_000)),
4902				(156 | 180, true) => Some((240_000, 240_000)),
4903				(183, false) => Some((120_000, 120_000)),
4904				(183, true) => Some((480_000, 480_000)),
4905				(186, false) => Some((240_000, 240_000)),
4906				(186, true) => Some((800_000, 800_000)),
4907				_ => None,
4908			};
4909			limits.map(|(max_br, max_cpb)| Level {
4910				leak: 1_100 * max_br,
4911				bit_rate: 1_000 * max_br,
4912				cpb: 1_100 * max_cpb,
4913				factor: 1_100,
4914			})
4915		}
4916		_ => None,
4917	};
4918	level.unwrap_or_else(|| {
4919		tracing::warn!(track = %name, codec = %config.codec, "no T-STD limits for this level; sending its units early");
4920		Level {
4921			leak: 1_200 * 64,
4922			bit_rate: 1_200 * 64,
4923			cpb: 1_200 * 175,
4924			factor: 1_200,
4925		}
4926	})
4927}
4928
4929/// How long `bits` take to arrive at `rate` bits per second: how far ahead of its decode
4930/// time a decoder buffer that size, filling at that rate, holds a unit.
4931fn fill(bits: u64, rate: u64) -> Duration {
4932	let nanos = u128::from(bits) * 1_000_000_000 / u128::from(rate.max(1));
4933	Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
4934}
4935
4936/// An audio stream's buffers in a receiver (H.222.0 2.4.2.3): by channel count for ADTS
4937/// AAC (and Opus, which borrows them), 2 Mb/s and the codec's main buffer for the rest. B
4938/// reaches as far ahead as it takes to fill at Rx ([`audio_reach`]).
4939fn audio_buffer(config: &AudioConfig, kind: &Kind) -> Buffer {
4940	let by_channels = || match config.channel_count {
4941		0..=2 => (2_000_000, 3_584),
4942		3..=8 => (5_529_600, 8_976),
4943		9..=12 => (8_294_400, 12_804),
4944		_ => (33_177_600, 51_216),
4945	};
4946	let (rate, size) = match kind {
4947		Kind::Aac { .. } | Kind::Adts { .. } | Kind::Opus { .. } => by_channels(),
4948		Kind::Mp2 { .. } => (2_000_000, 3_584),
4949		// ATSC A/53 Part 5 5.7, and A/52 Annex G 3.6.1 for E-AC-3.
4950		Kind::Ac3 => (2_000_000, 2_592),
4951		Kind::Eac3 => (2_000_000, 12_896),
4952		_ => (2_000_000, 3_584),
4953	};
4954	Buffer {
4955		rate,
4956		leak: None,
4957		size: Some(size),
4958		transport: 512,
4959		reach: fill(size as u64 * 8, rate),
4960	}
4961}
4962
4963/// How far ahead of its decode time audio B holds a unit in a multiplex padded to `mux_rate`: as
4964/// long as B takes to fill at Rx, or at the multiplex rate when that is slower, since nothing
4965/// reaches B faster than the multiplex carries it, within half of `delay` so a frame keeps the
4966/// rest to arrive in, as a packed PES does.
4967///
4968/// A slow multiplex so spreads its audio over the slots before it decodes and carries it near its
4969/// own rate. Sent only in the slot it decodes in, every slot would need room for the most audio
4970/// any one decodes, beside the tables and the clock: about 400 kb/s for 96 kb/s of FFmpeg's AC-3.
4971fn audio_reach(buffer: &Buffer, mux_rate: Option<u64>, delay: Duration) -> Duration {
4972	let Some(size) = buffer.size else {
4973		return buffer.reach;
4974	};
4975	let bits = size as u64 * 8;
4976	let at_rx = fill(bits, buffer.rate);
4977	match mux_rate {
4978		Some(mux_rate) if mux_rate < buffer.rate => fill(bits, mux_rate).min(delay / 2).max(at_rx),
4979		_ => at_rx,
4980	}
4981}
4982
4983/// The DVB AC-3 descriptor's tag (ETSI EN 300 468 6.2.1), marking AC-3 as private data.
4984const AC3_DESCRIPTOR: u8 = 0x6a;
4985
4986/// The DVB Enhanced AC-3 descriptor's tag (ETSI EN 300 468 Annex D).
4987const EAC3_DESCRIPTOR: u8 = 0x7a;
4988
4989/// The DVB teletext descriptor's tag (ETSI EN 300 468 6.2.43).
4990const TELETEXT_DESCRIPTOR: u8 = 0x56;
4991
4992/// A whole-PES stream's buffers, for the kinds its descriptors identify: Dolby audio as DVB
4993/// private data (ETSI TS 101 154 4.1.6.11), and teletext, whose 480-byte transport buffer drains at
4994/// 6.75 Mb/s (ETSI EN 300 472 5). Any other stream has none the schedule knows.
4995fn verbatim_buffer(kind: &Kind, descriptors: &[catalog::Descriptor]) -> Option<Buffer> {
4996	let Kind::PesPacket { stream_type: 0x06 } = kind else {
4997		return None;
4998	};
4999	descriptors.iter().find_map(|descriptor| match descriptor.tag {
5000		// ETSI TS 101 154 V2.9.1 4.1.6.11 recommends 5,696 bytes for both DVB codecs.
5001		AC3_DESCRIPTOR | EAC3_DESCRIPTOR => Some(Buffer {
5002			rate: 2_000_000,
5003			leak: None,
5004			size: Some(5_696),
5005			transport: 512,
5006			reach: fill(5_696 * 8, 2_000_000),
5007		}),
5008		TELETEXT_DESCRIPTOR => Some(Buffer {
5009			rate: 6_750_000,
5010			leak: None,
5011			size: None,
5012			transport: 480,
5013			reach: Duration::ZERO,
5014		}),
5015		_ => None,
5016	})
5017}
5018
5019/// The Dolby audio a track passes through as DVB private data.
5020#[derive(Clone, Copy, PartialEq, Eq)]
5021enum Dolby {
5022	Ac3,
5023	Eac3,
5024}
5025
5026impl Dolby {
5027	/// The Dolby audio a private-data stream's descriptors identify.
5028	fn described(descriptors: &[catalog::Descriptor]) -> Option<Self> {
5029		descriptors.iter().find_map(|descriptor| match descriptor.tag {
5030			AC3_DESCRIPTOR => Some(Self::Ac3),
5031			EAC3_DESCRIPTOR => Some(Self::Eac3),
5032			_ => None,
5033		})
5034	}
5035
5036	/// Bytes needed to attempt a header parse: an E-AC-3 stream's AC-3 core has the longer one.
5037	fn min_header_len(self) -> usize {
5038		let ac3 = crate::codec::ac3::DESCRIPTOR.min_header_len;
5039		match self {
5040			Self::Ac3 => ac3,
5041			Self::Eac3 => ac3.max(crate::codec::eac3::DESCRIPTOR.min_header_len),
5042		}
5043	}
5044
5045	/// Parse the header of the sync frame at the start of `data`, of any substream.
5046	fn parse(self, data: &[u8]) -> crate::codec::legacy::Result<crate::codec::legacy::Header> {
5047		match self {
5048			Self::Eac3 if !ac3_core(data) => crate::codec::eac3::sync_header(data),
5049			_ => crate::codec::ac3::parse_header(data),
5050		}
5051	}
5052
5053	/// Whether the sync frame at the start of `frame`, whose header parses, begins an access
5054	/// unit rather than adding a substream to the one before it.
5055	fn begins_unit(self, frame: &[u8]) -> bool {
5056		match self {
5057			Self::Eac3 if !ac3_core(frame) => crate::codec::eac3::begins_unit(frame),
5058			_ => true,
5059		}
5060	}
5061}
5062
5063/// Whether the sync frame at the start of `data` is AC-3 (bsid 10 or less), which an E-AC-3
5064/// stream may carry as its independent substream 0 (ETSI TS 102 366 E.1.3.1.2).
5065fn ac3_core(data: &[u8]) -> bool {
5066	data.get(5).is_some_and(|byte| byte >> 3 <= 10)
5067}
5068
5069/// Where the first Dolby sync frame in `payload` begins: a sync word whose header parses and
5070/// whose frame ends at the next sync word. Failing that, the first that may still begin one,
5071/// for the next PES to confirm: a frame that runs to the payload's end or past it, or a
5072/// header the payload cuts short. A sync word in the body of a frame begun before the join can
5073/// pass for a header, so it is taken only when nothing confirmed follows.
5074fn dolby_sync(codec: Dolby, payload: &[u8]) -> Option<usize> {
5075	let mut fallback = None;
5076	for (i, _) in payload.iter().enumerate().filter(|&(_, &byte)| byte == 0x0b) {
5077		let rest = &payload[i..];
5078		match codec.parse(rest) {
5079			Ok(header) => match rest.get(header.len..) {
5080				Some([0x0b, 0x77, ..]) => return Some(i),
5081				Some(next) if !ac3_sync_prefix(next) => continue,
5082				_ => {}
5083			},
5084			Err(_) if rest.len() < codec.min_header_len() && ac3_sync_prefix(rest) => {}
5085			Err(_) => continue,
5086		}
5087		fallback.get_or_insert(i);
5088	}
5089	fallback
5090}
5091
5092/// Whether `bytes` could begin a Dolby sync word, for all they show of it.
5093fn ac3_sync_prefix(bytes: &[u8]) -> bool {
5094	bytes.iter().zip([0x0b, 0x77]).all(|(&byte, sync)| byte == sync)
5095}
5096
5097/// Build the elementary-stream payload for a frame of `kind`, repeating an AAC program config
5098/// element when `pce`. Video needs the resolved avcC/hvcC to rewrite length-prefixed NALs as
5099/// Annex-B. Section-framed verbatim streams carry no PES payload, so they have none.
5100fn es_payload(kind: &Kind, description: Option<&Bytes>, frame: &Frame, pce: bool) -> Result<Option<Vec<u8>>> {
5101	Ok(match kind {
5102		Kind::Video(stream_type) => Some(video_es_payload(*stream_type, description, frame)?),
5103		Kind::Aac { config, .. } => {
5104			let pce = match pce {
5105				true => config.program_config.as_deref().unwrap_or_default(),
5106				false => &[],
5107			};
5108			let raw_len = pce.len() + frame.payload.len();
5109			let header = adts::write_header(config.object_type, config.sample_rate, config.channel_config, raw_len)?;
5110			let mut framed = Vec::with_capacity(header.len() + raw_len);
5111			framed.extend_from_slice(&header);
5112			framed.extend_from_slice(pce);
5113			framed.extend_from_slice(&frame.payload);
5114			Some(framed)
5115		}
5116		Kind::Adts { .. } => {
5117			let header = adts::Header::parse(&frame.payload)?;
5118			header.payload(&frame.payload)?;
5119			// ADTS names the core; the catalog may name SBR's output rate and channels.
5120			Some(frame.payload.to_vec())
5121		}
5122		// Each moq Opus frame is one packet; prefix the Opus-in-TS control header.
5123		Kind::Opus { .. } => Some(opus_es_payload(&frame.payload)),
5124		// Legacy audio frames were ingested whole (framing header included), so
5125		// they pass through untouched.
5126		Kind::Mp2 { .. } | Kind::Ac3 | Kind::Eac3 => Some(frame.payload.to_vec()),
5127		// Section-framed verbatim streams carry no PES payload.
5128		Kind::Verbatim { .. } => None,
5129		// The frame is the PES already, written by [`Export::place`].
5130		Kind::PesPacket { .. } => None,
5131	})
5132}
5133
5134/// The PES stream_id a frame of `kind` goes out under, `None` to derive it from whether it is
5135/// video: Opus is private-data PES, carried under private_stream_1 like ffmpeg.
5136fn stream_id(kind: &Kind) -> Option<u8> {
5137	matches!(kind, Kind::Opus { .. }).then_some(StreamId::PRIVATE_STREAM_1)
5138}
5139
5140/// Whether a video frame is an HEVC RADL picture, which leads its keyframe but references only
5141/// it, so it goes out wherever that keyframe does rather than being trimmed as an orphan.
5142fn radl(stream_type: StreamType, description: Option<&Bytes>, frame: &Frame) -> bool {
5143	stream_type == StreamType::H265
5144		&& description
5145			.and_then(|description| crate::codec::h265::hvcc_params(description).ok())
5146			.is_some_and(|(length_size, _)| crate::codec::h265::hvc1_is_radl(&frame.payload, length_size))
5147}
5148
5149/// Build the Annex-B elementary-stream payload for one video frame: rewrite the
5150/// length-prefixed NALs to start-code-delimited NALs, injecting the parameter
5151/// sets (SPS/PPS, plus VPS for H.265) from the avcC/hvcC after a leading AUD on
5152/// keyframes so a receiver can tune in mid-stream.
5153fn video_es_payload(stream_type: StreamType, description: Option<&Bytes>, frame: &Frame) -> Result<Vec<u8>> {
5154	let description = description.context("video codec config (avcC/hvcC) not resolved")?;
5155	let (codec, (length_size, params)) = match stream_type {
5156		StreamType::H264 => (InBandCodec::H264, crate::codec::h264::avcc_params(description)?),
5157		StreamType::H265 => (InBandCodec::H265, crate::codec::h265::hvcc_params(description)?),
5158		other => bail_unsupported!("unsupported TS video stream type {other:?}"),
5159	};
5160
5161	let mut out = Vec::with_capacity(frame.payload.len() + 64);
5162	let mut nals = annexb::length_prefixed_nals(&frame.payload, length_size)?;
5163	if frame.keyframe {
5164		if let Some(aud) = nals.take_delimiter(codec)? {
5165			out.extend_from_slice(&annexb::START_CODE);
5166			out.extend_from_slice(aud);
5167		}
5168		for nal in &params {
5169			out.extend_from_slice(&annexb::START_CODE);
5170			out.extend_from_slice(nal);
5171		}
5172	}
5173	for nal in nals {
5174		out.extend_from_slice(&annexb::START_CODE);
5175		out.extend_from_slice(nal?);
5176	}
5177	Ok(out)
5178}
5179
5180fn audio_kind(config: &AudioConfig, name: &str) -> Result<Kind> {
5181	ensure_raw(&config.container, "audio", name)?;
5182	match &config.codec {
5183		AudioCodec::AAC(codec) => {
5184			let Some(asc) = &config.description else {
5185				return Ok(Kind::Adts {
5186					profile: codec.profile,
5187					sample_rate: config.sample_rate,
5188					channels: config.channel_count,
5189				});
5190			};
5191			// The description names the LC core under explicit SBR or PS.
5192			let in_band = aac::in_band(asc)?;
5193			// A rebuilt kind repeats the element too, so a catalog update between a PAT/PMT and
5194			// this track's next frame cannot drop it.
5195			Ok(Kind::Aac {
5196				config: in_band,
5197				repeat: true,
5198			})
5199		}
5200		AudioCodec::Mp2 => Ok(Kind::Mp2 {
5201			sample_rate: config.sample_rate,
5202		}),
5203		AudioCodec::Opus => Ok(Kind::Opus {
5204			channel_config_code: opus_channel_code(config, name)?,
5205		}),
5206		AudioCodec::Ac3 => Ok(Kind::Ac3),
5207		AudioCodec::Ec3 => Ok(Kind::Eac3),
5208		other => bail_unsupported!("TS export does not support audio codec {other:?} (track '{name}')"),
5209	}
5210}
5211
5212/// The two PMT descriptors for an Opus elementary stream: the `Opus` registration
5213/// descriptor (which sets the codec) and the DVB extension descriptor 0x80 carrying
5214/// the channel configuration. ffmpeg's demuxer requires both to recognize the stream.
5215///
5216/// `channel_config_code` is already a plain code ([`opus_channel_code`]): 1 is mono,
5217/// 2 is stereo, and 3..=8 is the Vorbis family 1 mapping for that many channels.
5218fn opus_descriptors(channel_config_code: u8) -> Vec<catalog::Descriptor> {
5219	vec![
5220		registration(b"Opus"),
5221		catalog::Descriptor {
5222			tag: 0x7f,
5223			// extension_descriptor_tag 0x80, then the plain channel_config_code.
5224			data: Bytes::copy_from_slice(&[0x80, channel_config_code]),
5225		},
5226	]
5227}
5228
5229/// A registration descriptor (tag 0x05) naming the format identifier.
5230fn registration(format: &'static [u8; 4]) -> catalog::Descriptor {
5231	catalog::Descriptor {
5232		tag: 0x05,
5233		data: Bytes::from_static(format),
5234	}
5235}
5236
5237/// Plain `channel_config_code` for an Opus track the extension descriptor can name.
5238///
5239/// Family 0, and family 1 with the Vorbis mapping, use that channel count. A missing
5240/// head is mono or stereo only. Every other layout is refused: the descriptor has no
5241/// code for it, and a clamped count would name a layout the packets do not have.
5242fn opus_channel_code(config: &AudioConfig, name: &str) -> Result<u8> {
5243	let Some(description) = config.description.as_deref() else {
5244		ensure_supported!(
5245			matches!(config.channel_count, 1 | 2),
5246			"TS export cannot label Opus track '{name}' with {} channels and no OpusHead",
5247			config.channel_count
5248		);
5249		return Ok(config.channel_count as u8);
5250	};
5251
5252	let mut buf = description;
5253	let head = opus::Config::parse(&mut buf)
5254		.map_err(|err| malformed!("TS export cannot read the OpusHead on track '{name}': {err}"))?;
5255	ensure!(
5256		head.channel_count == config.channel_count,
5257		"Opus head has {} channels but the catalog declares {} (track '{name}')",
5258		head.channel_count,
5259		config.channel_count
5260	);
5261
5262	if let Some(mapping) = &head.mapping {
5263		let channels = mapping.table().len() as u8;
5264		let vorbis = opus::Mapping::vorbis(channels).ok();
5265		ensure_supported!(
5266			vorbis.as_ref() == Some(mapping),
5267			"TS export cannot label Opus track '{name}': channel mapping family {} is not the Vorbis layout",
5268			mapping.family()
5269		);
5270	}
5271
5272	let code = u8::try_from(head.channel_count).map_err(|_| {
5273		unsupported!(
5274			"TS export cannot label Opus track '{name}' with {} channels",
5275			head.channel_count
5276		)
5277	})?;
5278	ensure_supported!(
5279		(1..=8).contains(&code),
5280		"TS export cannot label Opus track '{name}' with {code} channels"
5281	);
5282	Ok(code)
5283}
5284
5285/// Wrap a raw Opus packet in the Opus-in-TS access-unit control header, producing one
5286/// PES access unit. Emits the 11-bit `0x3FF` sync (no trim, no control extension), then
5287/// the `0xFF`-run `au_size`, then the packet.
5288fn opus_es_payload(packet: &[u8]) -> Vec<u8> {
5289	let mut out = Vec::with_capacity(packet.len() + 4);
5290	// Sync 0x3FF over 11 bits: all of byte 0 (0x7F) plus the top 3 bits of byte 1. The
5291	// low 5 bits of byte 1 are the start-trim/end-trim/control-extension flags, all clear.
5292	out.push(0x7f);
5293	out.push(0xe0);
5294	// au_size: a run of 0xFF bytes summing toward the size, then a final byte < 0xFF. A
5295	// size that is an exact multiple of 255 still emits a terminating 0x00 byte.
5296	let mut n = packet.len();
5297	loop {
5298		out.push(n.min(255) as u8);
5299		if n < 255 {
5300			break;
5301		}
5302		n -= 255;
5303	}
5304	out.extend_from_slice(packet);
5305	out
5306}
5307
5308/// Refuse an SI PID that would share a packet stream with PAT, PMT, null, or an ES.
5309fn reject_colliding_si_pids(mpegts: &catalog::Mpegts, pmt_pid: u16, es_pids: &[u16]) -> Result<()> {
5310	for pid in mpegts.si.keys() {
5311		ensure!(
5312			(1..0x1FFF).contains(pid) && *pid != pmt_pid && !es_pids.contains(pid),
5313			"mpegts.si PID {pid} collides with PAT, PMT, null, or an elementary stream"
5314		);
5315	}
5316	Ok(())
5317}
5318
5319/// Refuse an `mpegts.tracks` entry that names both carriages, or carries a track the
5320/// catalog also describes as a media rendition: either leaves two ways to write one PID.
5321fn reject_ambiguous_tracks<E: catalog::Catalog>(catalog: &Catalog<E>, mpegts: &catalog::Mpegts) -> Result<()> {
5322	for (name, track) in &mpegts.tracks {
5323		ensure!(
5324			track.verbatim.is_none() || track.pes_packet.is_none(),
5325			"mpegts track '{name}' names both verbatim and pesPacket carriage"
5326		);
5327		ensure!(
5328			(track.verbatim.is_none() && track.pes_packet.is_none())
5329				|| !(catalog.video.renditions.contains_key(name) || catalog.audio.renditions.contains_key(name)),
5330			"mpegts track '{name}' is carried undecoded but also described as a media rendition"
5331		);
5332	}
5333	Ok(())
5334}
5335
5336/// The PMT descriptors recorded for `name` in the `mpegts` section, if any.
5337fn track_descriptors(mpegts: &catalog::Mpegts, name: &str) -> Vec<catalog::Descriptor> {
5338	mpegts
5339		.tracks
5340		.get(name)
5341		.map(|t| t.descriptors.clone())
5342		.unwrap_or_default()
5343}
5344
5345/// One section-framed verbatim frame must be exactly one section: at least the
5346/// 3-byte header and a total length matching the declared section_length.
5347/// Structural only (no table semantics); the bytes are still carried verbatim.
5348fn is_complete_section(section: &[u8]) -> bool {
5349	section.len() >= 3 && section.len() == 3 + ((((section[1] & 0x0f) as usize) << 8) | section[2] as usize)
5350}
5351
5352fn ensure_raw(container: &Container, kind: &str, name: &str) -> Result<()> {
5353	match container {
5354		// TS carries raw codec payloads, like Legacy, LOC, Raw, and CTS formats.
5355		Container::Legacy | Container::Loc | Container::Raw | Container::Cts => Ok(()),
5356		Container::Cmaf { .. } => bail_unsupported!("TS export does not support CMAF {kind} track '{name}'"),
5357		Container::Unknown(unknown) => bail_unsupported!(
5358			"TS export does not support container '{}' on {kind} track '{name}'",
5359			unknown.kind()
5360		),
5361	}
5362}
5363
5364/// The HRD declared by the first (base-layer) SPS in a video rendition's avcC/hvcC.
5365fn declared_hrd(stream_type: StreamType, description: &[u8]) -> Option<Hrd> {
5366	match stream_type {
5367		StreamType::H264 => {
5368			crate::codec::h264::sps_hrd(crate::codec::h264::Avcc::parse(description).ok()?.sps.first()?)
5369		}
5370		StreamType::H265 => crate::codec::h265::sps_hrd(
5371			crate::codec::h265::base_sps(&crate::codec::h265::Hvcc::parse(description).ok()?.sps).ok()??,
5372		),
5373		_ => None,
5374	}
5375}
5376
5377/// The reordering declared by the first (base-layer) SPS in a video rendition's avcC/hvcC.
5378fn declared_reorder(stream_type: StreamType, description: &[u8]) -> Option<Reorder> {
5379	match stream_type {
5380		StreamType::H264 => {
5381			crate::codec::h264::sps_reorder(crate::codec::h264::Avcc::parse(description).ok()?.sps.first()?)
5382		}
5383		StreamType::H265 => crate::codec::h265::sps_reorder(
5384			crate::codec::h265::base_sps(&crate::codec::h265::Hvcc::parse(description).ok()?.sps).ok()??,
5385		),
5386		_ => None,
5387	}
5388}
5389
5390#[cfg(test)]
5391mod tests {
5392	use std::time::Duration;
5393
5394	use moq_net::Timestamp;
5395
5396	use super::{
5397		Buffer, DecodeClock, Dolby, Kind, Laid, PSI_INTERVAL, PesPacket, Psi, Settle, dolby_removals, due,
5398		is_complete_section, si_due, slot, unwrap_pts, verbatim_buffer,
5399	};
5400
5401	/// The tables as they stand take the version after the last laid, whatever was set on the
5402	/// schedule meanwhile, and the last laid's own when they come back to it. The PAT keeps its
5403	/// own version until its network entry or PMT PID changes.
5404	#[test]
5405	fn a_revision_takes_the_version_after_the_last_laid() {
5406		use mpeg2ts::ts::{Pid, VersionNumber};
5407
5408		let pmt = |pids: &[u16]| super::psi::Pmt {
5409			program_number: 1,
5410			pcr_pid: Pid::new(0x100).ok(),
5411			program_info: Vec::new(),
5412			streams: pids
5413				.iter()
5414				.map(|&pid| super::psi::Es {
5415					stream_type: 0x0f,
5416					pid: Pid::new(pid).unwrap(),
5417					descriptors: Vec::new(),
5418				})
5419				.collect(),
5420		};
5421		let mut psi = Psi {
5422			transport_stream_id: 1,
5423			pmt: pmt(&[0x100]),
5424			pmt_pid: 0x20,
5425			moving: None,
5426			left: Vec::new(),
5427			led: None,
5428			stated: None,
5429			laid: None,
5430			sending: Default::default(),
5431			out: None,
5432		};
5433		let version = |version| VersionNumber::from_u8(version).unwrap();
5434		let first = (version(3), version(7));
5435		let versions = |laid: &Laid| (laid.version.as_u8(), laid.pat_version.as_u8());
5436		let laid = psi.current(false, first).unwrap();
5437		assert_eq!(versions(&laid), (3, 7));
5438		psi.laid = Some(laid.clone());
5439
5440		psi.pmt = pmt(&[0x100, 0x101]);
5441		let revised = psi.current(false, first).unwrap();
5442		assert_eq!(versions(&revised), (4, 7));
5443		assert_eq!(revised.pat, laid.pat);
5444
5445		psi.pmt = pmt(&[0x100]);
5446		assert_eq!(versions(&psi.current(false, first).unwrap()), (3, 7));
5447
5448		let network = psi.current(true, first).unwrap();
5449		assert_eq!(versions(&network), (3, 8));
5450		assert_ne!(network.pat, laid.pat);
5451
5452		// A moved PMT re-encodes the PAT at its own next version, naming the new PID: after 31
5453		// PMT revisions, the PMT's next is the PAT's last.
5454		psi.laid = Some(Laid {
5455			version: version(31),
5456			pat_version: version(0),
5457			..laid
5458		});
5459		psi.pmt_pid = 0x30;
5460		let moved = psi.current(false, first).unwrap();
5461		assert_eq!(versions(&moved), (31, 1));
5462		let pat = super::psi::PatAssembler::default().section(&moved.pat).unwrap();
5463		assert_eq!(pat.programs[0].pmt_pid.as_u16(), 0x30);
5464	}
5465
5466	/// How many unmarked steps back [`super::Track::steps_back`] counts on video read in decode
5467	/// order, each frame presented at `(ms, keyframe)`, clocked as [`super::Track::queue`] clocks
5468	/// it: on a clock per group at the catalog `reorder` depth, or inferred when it declares none.
5469	async fn video_steps(reorder: Option<usize>, frames: &[(u64, bool)]) -> u64 {
5470		use crate::catalog::hang::Wire;
5471		use crate::container::{Kind as MediaKind, Producer};
5472
5473		let broadcast = moq_net::broadcast::Info::new().produce();
5474		let publisher = broadcast.create_track("video", hang::container::track_info(0)).unwrap();
5475		let _publisher = Producer::new(publisher, Wire::legacy(MediaKind::Video));
5476		let source = crate::source::announced(&broadcast.consume()).await;
5477		let source = super::ExportSource::for_stream(
5478			&source,
5479			"video",
5480			crate::container::Delay::default().with_max(Duration::from_secs(2)),
5481		)
5482		.unwrap();
5483		let mut track = super::Track::new(source, Kind::Video(mpeg2ts::es::StreamType::H264));
5484		let arrived = kio::clock::now();
5485		for &(at, keyframe) in frames {
5486			let mut pending = super::Pending {
5487				frame: super::Frame {
5488					timestamp: ms(at),
5489					decode: None,
5490					duration: None,
5491					payload: bytes::Bytes::new(),
5492					keyframe,
5493				},
5494				restart: track.steps,
5495				skip: track.steps,
5496				cut: 0,
5497				arrived,
5498				read: arrived,
5499			};
5500			track.steps_back(&mut pending);
5501			if pending.restart != track.restart {
5502				track.restart = pending.restart;
5503				track.clock = DecodeClock::default();
5504				track.declared = track.declared.take().map(super::DeclaredClock::restart);
5505			}
5506			if keyframe {
5507				track.declared = reorder.map(super::DeclaredClock::new);
5508			}
5509			let pts = super::to_ticks(ms(at));
5510			match &mut track.declared {
5511				Some(clock) => {
5512					clock.push(Some((pending, None)), pts, ms(at)).unwrap();
5513					while clock.pop(false).unwrap().is_some() {}
5514				}
5515				None => track.clock.push((pending, None), pts, arrived, 0),
5516			}
5517		}
5518		track.steps
5519	}
5520
5521	/// Two groups of a B-pyramid two frames deep, 40 ms a frame, in decode order from `at` ms, its
5522	/// second group stepped back `step` ms after its first `before` frames.
5523	fn pyramid(at: u64, step: u64, before: usize) -> Vec<(u64, bool)> {
5524		const ORDER: [u64; 9] = [0, 4, 2, 1, 3, 8, 6, 5, 7];
5525		(0..2)
5526			.flat_map(|group| ORDER.map(move |place| (group, place)))
5527			.enumerate()
5528			.map(|(index, (group, place))| {
5529				let pts = at + (group * 9 + place) * 40;
5530				let pts = if index >= 9 + before { pts - step } else { pts };
5531				(pts, place == 0)
5532			})
5533			.collect()
5534	}
5535
5536	/// A rendition that declares its `reorder` proves a frame following more frames than that in
5537	/// presentation order stepped back, while its own reordering is left as it is.
5538	#[tokio::test(start_paused = true)]
5539	async fn a_declared_reorder_bounds_a_step_back() {
5540		assert_eq!(
5541			video_steps(Some(2), &pyramid(10_000, 0, 0)).await,
5542			0,
5543			"in-bound reordering"
5544		);
5545		for step in [300, 560] {
5546			assert_eq!(
5547				video_steps(Some(2), &pyramid(10_000, step, 4)).await,
5548				1,
5549				"a {step} ms step within a group"
5550			);
5551			assert_eq!(
5552				video_steps(Some(2), &pyramid(10_000, step, 0)).await,
5553				1,
5554				"a group stepped whole by {step} ms"
5555			);
5556		}
5557		// Two frames back is within the declared depth, however far back they are presented.
5558		let deep = [(10_000, true), (11_000, false), (11_040, false), (10_040, false)];
5559		assert_eq!(
5560			video_steps(Some(2), &deep).await,
5561			0,
5562			"in-bound reordering past the delay"
5563		);
5564	}
5565
5566	/// Video that declares no `reorder` is left as it is: neither a deep reorder nor a step back
5567	/// can be told apart from the timestamps, so neither restarts the timeline.
5568	#[tokio::test(start_paused = true)]
5569	async fn undeclared_reordering_never_steps_back() {
5570		let slow = [(0, true), (1_600, false), (800, false)];
5571		assert_eq!(video_steps(None, &slow).await, 0, "reordering past the delay");
5572		assert_eq!(
5573			video_steps(None, &pyramid(10_000, 560, 4)).await,
5574			0,
5575			"a step past the delay"
5576		);
5577	}
5578
5579	/// The same available video/audio backlog must choose the same start in either fill order.
5580	#[tokio::test(start_paused = true)]
5581	async fn track_fill_observes_every_available_track_before_acquisition() {
5582		use crate::catalog::hang::Wire;
5583		use crate::container::{Kind as MediaKind, Producer};
5584
5585		for order in [[0, 1], [1, 0]] {
5586			let broadcast = moq_net::broadcast::Info::new().produce();
5587			let mut publishers = Vec::new();
5588			for name in ["video", "audio"] {
5589				let track = broadcast.create_track(name, hang::container::track_info(0)).unwrap();
5590				publishers.push(Producer::new(track, Wire::legacy(MediaKind::Data)));
5591			}
5592			let source = crate::source::announced(&broadcast.consume()).await;
5593			let mut tracks = Vec::new();
5594			for (pid, name, kind) in [
5595				(1, "video", Kind::Video(mpeg2ts::es::StreamType::H264)),
5596				(2, "audio", Kind::Mp2 { sample_rate: 48_000 }),
5597			] {
5598				let source = super::ExportSource::for_stream(
5599					&source,
5600					name,
5601					crate::container::Delay::default().with_max(Duration::from_secs(2)),
5602				)
5603				.unwrap();
5604				let mut track = super::Track::new(source, kind);
5605				track.pid = pid;
5606				tracks.push(track);
5607			}
5608			let frame = |at| super::Frame {
5609				timestamp: ms(at),
5610				decode: None,
5611				duration: None,
5612				payload: bytes::Bytes::from_static(b"frame"),
5613				keyframe: at % 600 == 0,
5614			};
5615			let start = kio::clock::now();
5616			let mut jitter = super::jitter::Buffer::new(Duration::from_millis(500));
5617			jitter.expect([super::TrackKey::new(0, "video"), super::TrackKey::new(0, "audio")]);
5618			let mut trimmed = 0;
5619			for publisher in &mut publishers {
5620				publisher.write(frame(0)).unwrap();
5621			}
5622			// As in Export::poll_next, the first held frame of each track arrives first.
5623			kio::wait(|waiter| {
5624				for (track, name) in tracks.iter_mut().zip(["video", "audio"]) {
5625					track
5626						.fill(
5627							name,
5628							waiter,
5629							&mut super::Input {
5630								waiting_for_header: false,
5631								video_start: None,
5632								jitter: &mut jitter,
5633								trimmed: &mut trimmed,
5634							},
5635						)
5636						.unwrap();
5637				}
5638				if jitter.len() == 2 {
5639					std::task::Poll::Ready(())
5640				} else {
5641					std::task::Poll::Pending
5642				}
5643			})
5644			.await;
5645			for (index, publisher) in publishers.iter_mut().enumerate() {
5646				let end = if index == 0 { 1_200 } else { 800 };
5647				for at in (40..=end).step_by(40) {
5648					publisher.write(frame(at)).unwrap();
5649				}
5650				publisher.end_with(None).unwrap();
5651			}
5652			let waiter = kio::Waiter::noop();
5653			for index in order {
5654				tracks[index]
5655					.fill(
5656						["video", "audio"][index],
5657						&waiter,
5658						&mut super::Input {
5659							waiting_for_header: false,
5660							video_start: None,
5661							jitter: &mut jitter,
5662							trimmed: &mut trimmed,
5663						},
5664					)
5665					.unwrap();
5666			}
5667			assert!(jitter.poll_next(&waiter).is_pending());
5668			// The last available audio frame, including its scheduling lead, anchors both orders.
5669			let (decode, key, _) = tracks[1].released.unwrap();
5670			assert_eq!(decode.as_micros().unwrap(), 800_000);
5671			assert_eq!(
5672				jitter.at(0, key.try_into().unwrap()),
5673				Some(start.saturating_add(Duration::from_millis(500))),
5674				"{order:?}"
5675			);
5676			tokio::time::advance(Duration::from_millis(500)).await;
5677			let video = std::iter::from_fn(|| match jitter.poll_next(&waiter) {
5678				std::task::Poll::Ready(ready) => Some(ready),
5679				std::task::Poll::Pending => None,
5680			})
5681			.find(|ready| ready.track.name == "video")
5682			.expect("a video start");
5683			assert_eq!(video.item.frame.timestamp.as_micros().unwrap(), 600_000, "{order:?}");
5684		}
5685	}
5686
5687	fn ms(value: u64) -> Timestamp {
5688		Timestamp::from_millis(value).unwrap()
5689	}
5690
5691	#[test]
5692	fn aac_without_a_description_preserves_adts() {
5693		let config = hang::catalog::AudioConfig::new(hang::catalog::AAC { profile: 2 }, 44_100, 1);
5694		let kind = super::audio_kind(&config, "audio").unwrap();
5695		let mut packet = super::adts::write_header(2, 44_100, 1, 3).unwrap().to_vec();
5696		packet.extend_from_slice(&[0x01, 0x52, 0xf2]);
5697		let frame = super::Frame {
5698			timestamp: ms(0),
5699			decode: None,
5700			payload: packet.clone().into(),
5701			keyframe: true,
5702			duration: None,
5703		};
5704		assert_eq!(super::es_payload(&kind, None, &frame, true).unwrap().unwrap(), packet);
5705	}
5706
5707	#[test]
5708	fn video_es_payload_keeps_aud_first() {
5709		for (stream_type, params, aud, slice) in [
5710			(
5711				super::StreamType::H264,
5712				vec![vec![0x67, 0x42, 0, 0x1f], vec![0x68, 0xce]],
5713				vec![0x09, 0x10],
5714				vec![0x65, 0x88],
5715			),
5716			(
5717				super::StreamType::H265,
5718				vec![vec![0x40, 1], vec![0x42, 1], vec![0x44, 1]],
5719				vec![0x46, 1, 0x10],
5720				vec![0x26, 1, 0x88],
5721			),
5722		] {
5723			let params: Vec<bytes::Bytes> = params.into_iter().map(bytes::Bytes::from).collect();
5724			let description = if stream_type == super::StreamType::H264 {
5725				crate::codec::h264::build_avcc(&params[..1], &params[1..]).unwrap()
5726			} else {
5727				let mut hvcc = vec![0; 23];
5728				hvcc[21] = 3;
5729				hvcc[22] = 3;
5730				for (kind, nal) in (32..=34).zip(&params) {
5731					hvcc.extend_from_slice(&[kind, 0, 1]);
5732					hvcc.extend_from_slice(&(nal.len() as u16).to_be_bytes());
5733					hvcc.extend_from_slice(nal);
5734				}
5735				hvcc.into()
5736			};
5737			for keyframe in [false, true] {
5738				for leading in [None, Some(aud.as_slice())] {
5739					let mut payload = Vec::new();
5740					for nal in leading.into_iter().chain([slice.as_slice()]) {
5741						payload.extend_from_slice(&(nal.len() as u32).to_be_bytes());
5742						payload.extend_from_slice(nal);
5743					}
5744					let frame = super::Frame {
5745						timestamp: ms(0),
5746						decode: None,
5747						payload: payload.into(),
5748						keyframe,
5749						duration: None,
5750					};
5751					let mut expected = Vec::new();
5752					if let Some(aud) = leading {
5753						expected.extend_from_slice(&super::annexb::START_CODE);
5754						expected.extend_from_slice(aud);
5755					}
5756					if keyframe {
5757						expected.extend_from_slice(&super::annexb::build_prefix(&params));
5758					}
5759					expected.extend_from_slice(&super::annexb::START_CODE);
5760					expected.extend_from_slice(&slice);
5761					assert_eq!(
5762						super::video_es_payload(stream_type, Some(&description), &frame).unwrap(),
5763						expected
5764					);
5765				}
5766			}
5767		}
5768	}
5769
5770	/// A six-block E-AC-3 sync frame of 512 bytes: `stream` is byte 2's top bits (strmtyp,
5771	/// substreamid) and `rate` byte 4 (fscod, numblkscod, acmod, lfeon).
5772	fn eac3(stream: u8, rate: u8) -> Vec<u8> {
5773		let mut frame = vec![0x0b, 0x77, stream, 0xff, rate, 0x80];
5774		frame.resize(512, 0xaa);
5775		frame
5776	}
5777
5778	/// Teletext passed through as DVB private data takes its transport buffer's rate from
5779	/// EN 300 472, so the schedule spreads it no faster than a receiver passes it on; private
5780	/// data nothing identifies has no buffers.
5781	#[test]
5782	fn teletext_drains_at_its_own_rate() {
5783		let kind = Kind::PesPacket { stream_type: 0x06 };
5784		let descriptor = |tag| super::catalog::Descriptor {
5785			tag,
5786			data: bytes::Bytes::from_static(b"eng\x09\x00"),
5787		};
5788		assert_eq!(
5789			verbatim_buffer(&kind, &[descriptor(0x56)]),
5790			Some(Buffer {
5791				rate: 6_750_000,
5792				leak: None,
5793				size: None,
5794				transport: 480,
5795				reach: Duration::ZERO,
5796			})
5797		);
5798		assert_eq!(verbatim_buffer(&kind, &[descriptor(0x0a)]), None);
5799	}
5800
5801	/// Push a decode-order PTS stream (90 kHz) through the decode clock under a catalog
5802	/// `jitter` and a declared reorder `floor`, flushing at the end, and return the DTS per
5803	/// frame.
5804	fn run_clock(pts: &[u64], jitter: u64, floor: u64) -> Vec<u64> {
5805		let mut clock = DecodeClock::default();
5806		let mut dts = vec![0; pts.len()];
5807		for (i, &p) in pts.iter().enumerate() {
5808			clock.push(i, p, kio::clock::Instant::ZERO, 0);
5809			while let Some((i, d)) = clock.pop(jitter, floor, Settle::Due) {
5810				dts[i] = d;
5811			}
5812		}
5813		while let Some((i, d)) = clock.pop(jitter, floor, Settle::All) {
5814			dts[i] = d;
5815		}
5816		dts
5817	}
5818
5819	/// A burst sharing one PTS, read at once, never settles by time or by a later PTS, so the
5820	/// byte budget settles it.
5821	#[test]
5822	fn a_decode_clock_burst_sharing_a_pts_settles_at_the_byte_budget() {
5823		const MAX_BYTES: usize = 10_000;
5824		let start = kio::clock::Instant::ZERO;
5825		let delay = Duration::from_millis(500);
5826		let mut clock = DecodeClock::default();
5827		let (mut held, mut most) = (0, 0);
5828		for index in 0..1_000u32 {
5829			clock.push(index, 0, start, 1_000);
5830			held += 1;
5831			while clock
5832				.pop(90_000, 0, clock.settle(90_000, start, delay, MAX_BYTES))
5833				.is_some()
5834			{
5835				held -= 1;
5836			}
5837			most = most.max(held);
5838		}
5839		assert!(
5840			most <= 17,
5841			"held {most} frames of 1,000 bytes past a {MAX_BYTES} byte budget"
5842		);
5843	}
5844
5845	/// One frame alone filling the byte budget does not settle the B-frames reordered around it:
5846	/// fewer frames are held than any codec reorders.
5847	#[test]
5848	fn a_frame_filling_the_byte_budget_keeps_the_reorder() {
5849		const MAX_BYTES: usize = 1_000_000;
5850		let start = kio::clock::Instant::ZERO;
5851		let delay = Duration::from_millis(500);
5852		let mut clock = DecodeClock::default();
5853		let mut dts = vec![0; 5];
5854		let frames = [(0, 16), (4, MAX_BYTES - 8), (2, 8), (1, 8), (3, 8)];
5855		for (i, (rank, bytes)) in frames.into_iter().enumerate() {
5856			clock.push(i, 900_000 + rank * 18_000, start, bytes);
5857			while let Some((i, d)) = clock.pop(90_000, 36_000, clock.settle(90_000, start, delay, MAX_BYTES)) {
5858				dts[i] = d;
5859			}
5860		}
5861		while let Some((i, d)) = clock.pop(90_000, 36_000, Settle::All) {
5862			dts[i] = d;
5863		}
5864		assert_eq!(dts, [864_000, 882_000, 900_000, 918_000, 936_000]);
5865	}
5866
5867	/// A budget filled by one frame and the reordered frames around it still counts the B-frames
5868	/// already read in the reorder delay, so none decodes after it is presented.
5869	#[test]
5870	fn a_budget_filled_past_the_reorder_depth_keeps_the_delay() {
5871		const MAX_BYTES: usize = 1_000_000;
5872		let start = kio::clock::Instant::ZERO;
5873		let delay = Duration::from_millis(500);
5874		let ranks = [0, 4, 2, 1, 3].into_iter().chain(5..=40);
5875		let mut clock = DecodeClock::default();
5876		let mut dts = Vec::new();
5877		for (i, rank) in ranks.enumerate() {
5878			let bytes = if i == 1 { MAX_BYTES - 512 } else { 16 };
5879			clock.push(i, 900_000 + rank * 3_000, start, bytes);
5880			while let Some((i, d)) = clock.pop(90_000, 0, clock.settle(90_000, start, delay, MAX_BYTES)) {
5881				dts.push((i, d));
5882			}
5883		}
5884		assert_eq!(
5885			dts[..5],
5886			[(0, 894_000), (1, 897_000), (2, 900_000), (3, 903_000), (4, 906_000)]
5887		);
5888	}
5889
5890	/// Decode-order PTS for a constant-frame-rate display timeline with `b` B-frames between
5891	/// each pair of reference frames (the common broadcast structure: references pulled ahead
5892	/// of the B-frames they predict). `base` keeps the timeline off zero, like a real feed's
5893	/// initial PTS offset.
5894	fn decode_order(refs: usize, b: usize, dur: u64, base: u64) -> Vec<u64> {
5895		let pts = |display: usize| base + display as u64 * dur;
5896		let span = b + 1;
5897		let mut out = vec![pts(0)]; // first reference (keyframe) at display 0
5898		for g in 1..refs {
5899			let reference = g * span;
5900			out.push(pts(reference)); // reference, decoded before its B-frames
5901			for j in 1..=b {
5902				out.push(pts(reference - span + j)); // the B-frames between the two references
5903			}
5904		}
5905		out
5906	}
5907
5908	/// How an encoder times `pts`: the n-th frame decodes at the n-th presentation time, a
5909	/// fixed `delay` early. Returns the DTS and the catalog `jitter` an importer would publish.
5910	fn source_dts(pts: &[u64], delay: u64) -> (Vec<u64>, u64) {
5911		let mut slots = pts.to_vec();
5912		slots.sort();
5913		let dts: Vec<u64> = slots.iter().map(|slot| slot - delay).collect();
5914		let jitter = pts.iter().zip(&dts).map(|(p, d)| p - d).max().unwrap();
5915		(dts, jitter)
5916	}
5917
5918	#[test]
5919	fn dts_is_monotonic_across_reorder() {
5920		// 25 fps, 10 s offset. Even with nothing declared, the decode timeline is strictly
5921		// increasing (the `+igndts` fix), and past the first reordered frames it stays at or
5922		// before the PTS.
5923		for b in [1, 3, 5] {
5924			let pts = decode_order(40, b, 3_600, 10_000_000);
5925			assert!(pts.windows(2).any(|w| w[1] < w[0]), "b={b}: stream must reorder PTS");
5926			let dts = run_clock(&pts, 0, 0);
5927			for (i, win) in dts.windows(2).enumerate() {
5928				assert!(win[1] > win[0], "b={b}: DTS not strictly increasing at {i}: {win:?}");
5929			}
5930			let settled = 2 * (b + 1);
5931			for (i, (&d, &p)) in dts.iter().zip(pts.iter()).enumerate().skip(settled) {
5932				assert!(d <= p, "b={b}: DTS {d} after PTS {p} at {i}");
5933			}
5934		}
5935	}
5936
5937	#[test]
5938	fn dts_clock_survives_33bit_wrap() {
5939		// The decode clock runs in continuous ticks, so it stays strictly increasing even as
5940		// the source timeline crosses the 33-bit wire boundary (~26.5 h). The wrap is applied
5941		// only at emission, so here the authored DTS keeps climbing past 1 << 33.
5942		let wrap = 1u64 << 33;
5943		let pts = decode_order(40, 3, 3_600, wrap - 20 * 3_600);
5944		let dts = run_clock(&pts, 0, 0);
5945
5946		assert!(pts.iter().any(|&p| p >= wrap), "test must cross the wrap boundary");
5947		for (i, win) in dts.windows(2).enumerate() {
5948			assert!(
5949				win[1] > win[0],
5950				"DTS not strictly increasing across wrap at {i}: {win:?}"
5951			);
5952		}
5953	}
5954
5955	#[test]
5956	fn dts_without_reorder_is_the_pts() {
5957		let pts: Vec<u64> = (0..40).map(|i| 10_000_000 + i * 3_600).collect();
5958		assert_eq!(run_clock(&pts, 0, 0), pts);
5959	}
5960
5961	/// Given the catalog `jitter` and the SPS's reorder depth, a reordered stream decodes
5962	/// exactly as its encoder timed it, a frame period apart.
5963	#[test]
5964	fn reordered_dts_is_the_encoders() {
5965		let dur = 3_600;
5966		for b in [1, 2, 3] {
5967			let pts = decode_order(40, b, dur, 10_000_000);
5968			let (source, jitter) = source_dts(&pts, dur);
5969			assert_eq!(run_clock(&pts, jitter, dur), source, "b={b}");
5970		}
5971	}
5972
5973	/// A field-coded passage decodes a field apart and a frame-coded one a frame apart: the
5974	/// reorder delay is a time, so a switch between them does not squeeze the timeline.
5975	#[test]
5976	fn a_switch_to_field_coding_keeps_the_encoders_spacing() {
5977		let frame = 3_600;
5978		let mut pts = decode_order(10, 2, frame, 10_000_000);
5979		// Then each picture is two fields, a reference pair ahead of the B pairs it predicts.
5980		let start = pts.iter().max().unwrap() + frame;
5981		for g in 0..10u64 {
5982			let reference = start + (g * 3 + 2) * frame;
5983			let pair = |at: u64| [at, at + frame / 2];
5984			pts.extend(pair(reference));
5985			pts.extend(pair(reference - 2 * frame));
5986			pts.extend(pair(reference - frame));
5987		}
5988		let (source, jitter) = source_dts(&pts, frame);
5989		assert_eq!(run_clock(&pts, jitter, frame), source);
5990	}
5991
5992	/// An open GOP's leading pictures, read after the keyframe they precede in presentation,
5993	/// decode a slot apart rather than one tick behind it.
5994	#[test]
5995	fn leading_pictures_decode_a_slot_apart() {
5996		let frame = 3_600;
5997		let base = 10_000_000;
5998		// The keyframe is presented after three leading B-frames.
5999		let mut pts = vec![base + 3 * frame, base, base + frame, base + 2 * frame];
6000		pts.extend(decode_order(10, 2, frame, base + 3 * frame).into_iter().skip(1));
6001		let (source, jitter) = source_dts(&pts, frame);
6002		let dts = run_clock(&pts, jitter, frame);
6003		assert_eq!(dts, source);
6004		for (i, win) in dts.windows(2).enumerate() {
6005			assert!(win[1] - win[0] >= frame, "DTS less than a frame apart at {i}: {dts:?}");
6006		}
6007	}
6008
6009	#[test]
6010	fn dts_is_join_independent_at_a_peak() {
6011		// An exporter that has been running and one that just joined author the same decode
6012		// timeline from any frame whose PTS leads everything decoded before it. A keyframe is
6013		// exactly that (export only ever tunes in on one).
6014		for b in [1, 3, 5] {
6015			let pts = decode_order(40, b, 3_600, 10_000_000);
6016			let (_, jitter) = source_dts(&pts, 3_600);
6017			let running = run_clock(&pts, jitter, 3_600);
6018
6019			let mut peaks = 0;
6020			for k in 1..pts.len() {
6021				if pts[..k].iter().any(|&p| p >= pts[k]) {
6022					continue;
6023				}
6024				peaks += 1;
6025				let fresh = run_clock(&pts[k..], jitter, 3_600);
6026				assert_eq!(
6027					&running[k..],
6028					&fresh[..],
6029					"b={b}: joining at {k} authored a different clock"
6030				);
6031			}
6032			assert!(peaks > 10, "b={b}: fixture must have peaks to join at, got {peaks}");
6033		}
6034	}
6035
6036	#[test]
6037	fn due_crosses_an_absolute_slot() {
6038		assert!(due(ms(1_000), None, PSI_INTERVAL));
6039		assert!(!due(ms(1_250), Some(ms(1_000)), PSI_INTERVAL));
6040		assert!(due(ms(1_500), Some(ms(1_000)), PSI_INTERVAL));
6041
6042		// A backwards timestamp is a slot already served, not a new one. Emitting there would
6043		// fire on every B-frame that steps back across a boundary (see `due_ignores_reorder`).
6044		assert!(!due(ms(750), Some(ms(1_000)), PSI_INTERVAL));
6045
6046		// The slot grid honors whatever interval it is given, not just the PSI's own.
6047		let coarse = Duration::from_millis(2_000);
6048		assert!(!due(ms(1_500), Some(ms(1_000)), coarse));
6049		assert!(due(ms(3_000), Some(ms(1_000)), coarse));
6050	}
6051
6052	#[test]
6053	fn si_due_floors_repeats_from_the_last_emission() {
6054		// Never emitted: always due, so a fresh exporter leads with the tables.
6055		assert!(si_due(ms(1_000), None, PSI_INTERVAL));
6056
6057		// The interval is measured from the entry's own last emission, not an absolute
6058		// grid: an emission at 1.4s holds the next repeat to 3.4s, where the grid
6059		// would have re-sent at 2s.
6060		let interval = Duration::from_millis(2_000);
6061		assert!(!si_due(ms(2_000), Some(ms(1_400)), interval));
6062		assert!(!si_due(ms(3_399), Some(ms(1_400)), interval));
6063		assert!(si_due(ms(3_400), Some(ms(1_400)), interval));
6064
6065		// A reordered (B-frame) timestamp behind the last emission is not elapsed time.
6066		assert!(!si_due(ms(1_000), Some(ms(1_400)), interval));
6067		// A zero interval means every frame, even one sharing the last timestamp.
6068		assert!(si_due(ms(1_400), Some(ms(1_400)), Duration::ZERO));
6069	}
6070
6071	/// Drive a run of timestamps through the slot cadence, advancing the stored emission
6072	/// only when one fires, and return how many tables it emitted. PSI additionally emits
6073	/// (and re-anchors) at every video keyframe; SI repeats use the same grid.
6074	fn run_cadence(stamps: &[Timestamp], interval: Duration) -> usize {
6075		let mut last = None;
6076		let mut emissions = 0;
6077		for &ts in stamps {
6078			if due(ts, last, interval) {
6079				emissions += 1;
6080				last = Some(ts);
6081			}
6082		}
6083		emissions
6084	}
6085
6086	#[test]
6087	fn due_ignores_reorder() {
6088		// Video is emitted in decode order, so a B-frame stream steps its PTS backwards
6089		// constantly (measured at 39% of frames on real contribution content). The cadence has
6090		// to follow the slots the stream has *reached*, not fire on every crossing of one, or
6091		// each oscillation across a boundary re-sends the tables both ways.
6092		let ticks = decode_order(40, 3, 3_600, 10_000_000);
6093		let stamps: Vec<Timestamp> = ticks
6094			.iter()
6095			.map(|&t| Timestamp::from_micros(t * 1_000_000 / 90_000).unwrap())
6096			.collect();
6097		assert!(stamps.windows(2).any(|w| w[1] < w[0]), "fixture must reorder its PTS");
6098
6099		// One table per slot the stream covers, however often the reorder revisits a boundary.
6100		let first = slot(stamps[0], PSI_INTERVAL);
6101		let last = slot(
6102			stamps.iter().copied().reduce(crate::container::later).unwrap(),
6103			PSI_INTERVAL,
6104		);
6105		assert_eq!(run_cadence(&stamps, PSI_INTERVAL), (last - first + 1) as usize);
6106	}
6107
6108	#[test]
6109	fn due_zero_interval_emits_every_frame() {
6110		// A catalog is free to ask for a table on every frame. Slot arithmetic can't express
6111		// that (and would divide by zero), so it is handled before the division. Repeated
6112		// timestamps are the case a slot count gets wrong: two tracks can share one.
6113		let stamps: Vec<Timestamp> = [0, 0, 40, 40, 80].iter().map(|&t| ms(t)).collect();
6114		assert_eq!(run_cadence(&stamps, Duration::ZERO), stamps.len());
6115	}
6116
6117	#[test]
6118	fn due_survives_a_sub_microsecond_interval() {
6119		// Only an exactly-zero interval short-circuits, so the slot divisor has to stay
6120		// non-zero for every other duration. Nanoseconds do; anything coarser floors a
6121		// sub-unit interval to zero and panics on the division.
6122		let interval = Duration::from_nanos(500);
6123		assert!(
6124			!interval.is_zero() && interval.as_micros() == 0,
6125			"fixture must be sub-microsecond"
6126		);
6127		assert!(due(ms(1), Some(ms(0)), interval));
6128		assert!(!due(ms(0), Some(ms(0)), interval));
6129	}
6130
6131	#[test]
6132	fn due_ignores_when_the_last_emission_landed_in_its_slot() {
6133		// The whole point of the absolute grid: two exporters that emitted at different
6134		// points *within* the same slot agree on every later frame, so the emission points
6135		// belong to the broadcast rather than to whoever started when.
6136		for last in [1_000, 1_100, 1_499] {
6137			assert!(!due(ms(1_499), Some(ms(last)), PSI_INTERVAL), "last={last}");
6138			assert!(due(ms(1_500), Some(ms(last)), PSI_INTERVAL), "last={last}");
6139		}
6140	}
6141
6142	#[test]
6143	fn section_validation() {
6144		// section_length 27 (0x1b) -> 30 bytes total.
6145		let mut ok = vec![0xfc, 0x30, 0x1b];
6146		ok.resize(30, 0x00);
6147		assert!(is_complete_section(&ok));
6148		// minimal: section_length 0 -> exactly the 3-byte header.
6149		assert!(is_complete_section(&[0xfc, 0x00, 0x00]));
6150		// any table_id is accepted (verbatim carriage isn't SCTE-specific).
6151		assert!(is_complete_section(&[0x00, 0x00, 0x00]));
6152
6153		// shorter than the 3-byte header.
6154		assert!(!is_complete_section(&[0xfc, 0x00]));
6155		// declared section_length (27) does not match the actual length (3).
6156		assert!(!is_complete_section(&[0xfc, 0x30, 0x1b]));
6157	}
6158
6159	/// A PES of `stream_id` with an optional header of `flags` and `fields`, its length right.
6160	fn pes(stream_id: u8, flags: u8, fields: &[u8], payload: &[u8]) -> Vec<u8> {
6161		let mut pes = vec![0, 0, 1, stream_id];
6162		pes.extend_from_slice(&((3 + fields.len() + payload.len()) as u16).to_be_bytes());
6163		pes.extend_from_slice(&[0x84, flags, fields.len() as u8]);
6164		pes.extend_from_slice(fields);
6165		pes.extend_from_slice(payload);
6166		pes
6167	}
6168
6169	#[test]
6170	fn pes_packet_validation() {
6171		// A PTS of 0x1_2345_6789 behind the '0010' prefix, read back as written.
6172		let pts = [0x29, 0x8d, 0x15, 0xcf, 0x13];
6173		let parsed = PesPacket::parse(&pes(0xbd, 0x80, &pts, b"data"), 0x06).unwrap();
6174		assert_eq!(parsed.pts, Some(0x1_2345_6789));
6175		assert_eq!(parsed.payload, 14);
6176		assert_eq!(
6177			PesPacket::parse(&pes(0xbd, 0x00, &[], b"data"), 0x06).unwrap().pts,
6178			None
6179		);
6180		// private_stream_2 and padding carry no optional header.
6181		let bare = [0, 0, 1, 0xbf, 0, 2, 0xaa, 0xbb];
6182		assert_eq!(PesPacket::parse(&bare, 0x06).unwrap().payload, 6);
6183
6184		// No start code, a length that disagrees, or a header that runs past the packet.
6185		assert!(PesPacket::parse(&[0, 0, 2, 0xbd, 0, 0], 0x06).is_err());
6186		let mut long = pes(0xbd, 0x00, &[], b"data");
6187		long.push(0);
6188		assert!(PesPacket::parse(&long, 0x06).is_err());
6189		let mut truncated = pes(0xbd, 0x00, &[], &[]);
6190		truncated[8] = 4;
6191		assert!(PesPacket::parse(&truncated, 0x06).is_err());
6192		// The marker bits, the forbidden PTS_DTS_flags, and fields past the header length.
6193		let mut marker = pes(0xbd, 0x00, &[], b"data");
6194		marker[6] = 0x44;
6195		assert!(PesPacket::parse(&marker, 0x06).is_err());
6196		assert!(PesPacket::parse(&pes(0xbd, 0x40, &pts, b""), 0x06).is_err());
6197		assert!(PesPacket::parse(&pes(0xbd, 0xc0, &pts, b""), 0x06).is_err());
6198		assert!(PesPacket::parse(&pes(0xbd, 0x01, &[0x80, 0, 0], b""), 0x06).is_err());
6199		// A clock field with the wrong prefix, or a marker bit cleared, PTS and DTS alike.
6200		let mut prefix = pts;
6201		prefix[0] = 0x39;
6202		assert!(PesPacket::parse(&pes(0xbd, 0x80, &prefix, b""), 0x06).is_err());
6203		let mut marker = pts;
6204		marker[2] &= !1;
6205		assert!(PesPacket::parse(&pes(0xbd, 0x80, &marker, b""), 0x06).is_err());
6206		let mut both = [pts, pts].concat();
6207		both[0] = 0x39;
6208		both[5] = 0x19;
6209		assert!(PesPacket::parse(&pes(0xbd, 0xc0, &both, b""), 0x06).is_ok());
6210		both[9] &= !1;
6211		assert!(PesPacket::parse(&pes(0xbd, 0xc0, &both, b""), 0x06).is_err());
6212
6213		// Only video may leave the length unbounded: its stream IDs, or 0xFD under a video type.
6214		let unbounded = |stream_id: u8| {
6215			let mut pes = pes(stream_id, 0x00, &[], b"picture");
6216			pes[4..6].fill(0);
6217			pes
6218		};
6219		assert!(PesPacket::parse(&unbounded(0xe0), 0x06).is_ok());
6220		assert!(PesPacket::parse(&unbounded(0xfd), 0xea).is_ok());
6221		assert!(PesPacket::parse(&unbounded(0xfd), 0x06).is_err());
6222		assert!(PesPacket::parse(&unbounded(0xbd), 0x06).is_err());
6223	}
6224
6225	#[test]
6226	fn placed_pts_unwraps_near_its_placement() {
6227		// A PTS just past the 33-bit wrap belongs after a placement just before it.
6228		let at = Timestamp::from_micros(((1u64 << 33) - 900) * 1_000_000 / 90_000).unwrap();
6229		assert_eq!(unwrap_pts(900, at), ((1u128 << 33) + 900) * 1_000_000_000 / 90_000);
6230		// A PTS a little ahead, and one a little behind, stay where they are.
6231		let at = ms(10_000);
6232		assert_eq!(unwrap_pts(90 * 10_100, at), 10_100_000_000);
6233		assert_eq!(unwrap_pts(90 * 9_900, at), 9_900_000_000);
6234	}
6235
6236	#[test]
6237	fn dolby_removals_count_on_from_the_pts() {
6238		// 32 kb/s 48 kHz sync frames: 128 bytes, 32 ms each.
6239		let mut sync = vec![0x0b, 0x77, 0x00, 0x00, 0x00, 0x40, 0x40];
6240		sync.resize(128, 0);
6241		let mut payload = vec![0xee; 10];
6242		payload.extend(sync.repeat(2));
6243		payload.extend_from_slice(&sync[..50]);
6244		let removals = dolby_removals(Dolby::Ac3, &payload, 1_000_000_000);
6245		// The tail of an earlier frame goes with the first, and the cut frame keeps its time.
6246		assert_eq!(
6247			removals,
6248			vec![(1_000_000_000, 138), (1_032_000_000, 128), (1_064_000_000, 50)]
6249		);
6250		assert!(
6251			dolby_removals(Dolby::Ac3, &[0xee; 20], 0).is_empty(),
6252			"no sync frame begins"
6253		);
6254	}
6255
6256	/// E-AC-3 substreams leave with their access unit, so a PES's units leave a 32 ms interval
6257	/// apart whatever substreams each carries.
6258	#[test]
6259	fn dolby_removals_keep_eac3_substreams_with_their_unit() {
6260		let (independent, dependent) = (eac3(0x00, 0x3f), eac3(0x40, 0x3f));
6261		let payload = [
6262			&dependent[..],
6263			&independent,
6264			&dependent,
6265			&independent,
6266			&dependent[..100],
6267		]
6268		.concat();
6269		let removals = dolby_removals(Dolby::Eac3, &payload, 1_000_000_000);
6270		// The substream ending an earlier unit goes with the first, the cut one with the last.
6271		assert_eq!(removals, vec![(1_000_000_000, 1_536), (1_032_000_000, 612)]);
6272	}
6273}