Skip to main content

moq_mux/container/ts/
programs.rs

1//! Every program of a multiplex, each imported as its own broadcast.
2
3use std::collections::{BTreeMap, HashMap, HashSet};
4
5use mpeg2ts::ts::Pid;
6
7use super::demux::{Demux, Packet};
8use super::error::{Error, Result, ensure_supported};
9use super::health::{Checks, Health, PmtPacket};
10use super::import::SectionReassembler;
11use super::unclaimed::Unclaimed;
12use super::{Ext, Import, catalog::SI_PIDS, health, psi, stats};
13use crate::catalog;
14
15/// Imports every program the PAT lists, each as its own broadcast on `origin`, with its own
16/// clock and catalog.
17///
18/// Program `n` of `event.hang` publishes on `event/n.hang`, keeping the catalog suffix last so
19/// format detection still sees it; a name without one gains a plain `/n`. A program starts once
20/// its PMT lists an elementary stream; until then it publishes nothing. One whose PMT has not
21/// arrived 0.5 s of program clock after the PAT listed it, the bound TR 101 290 sets for
22/// `PMT_error_2`, is late: each 0.5 s its PMT PID carries no PMT section counts in
23/// [`stats::Snapshot::pmt_error`], its PIDs count as unclaimed, and the other programs carry on.
24/// It starts whenever its PMT arrives. The clock is a running program's, so nothing is late
25/// before one runs, and one whose PMT arrived listing no stream yet is not late. Input ahead of
26/// that PMT is dropped, as a single [`Import`] drops media ahead of its PSI; its SI arrives with
27/// the next repetition, as for an import joining mid-stream.
28///
29/// The PAT is followed as it changes. A program a later PAT adds waits for its PMT as the first
30/// PAT's do, and each program follows its PMT to the PID the latest PAT names. One a later PAT
31/// drops is retired: its tracks finish and its broadcast is unannounced, while the other
32/// programs carry on. A program that returns publishes a new stream, under a new identity.
33///
34/// The multiplex is parsed once: framing, continuity, the PAT and the SI sections are shared,
35/// and each program reads only the packets on the PIDs its PAT entry and PMT claim. A packet on a
36/// PID no program reads, the PAT's PMT PIDs, the SI PIDs and the null PID aside, is counted once
37/// for the multiplex (see [`stats::Snapshot::streams`]). Counting waits until every program the
38/// PAT lists has its PMT or is late, since until then a PID may be a program's still to come.
39///
40/// Each PID is counted once, so a PID several programs read has one continuous set of
41/// counters while they start and retire. The PMT sections are reassembled here, once per PMT
42/// PID, so a bad CRC counts once however many programs read the PID. Every other count of a PID
43/// is taken from one program at a time for each way it is read: its row and PTS
44/// cadence from a program carrying it, or else one reading it, its PCR checks from one taking
45/// its clock there, and its PMT interval from one reading its PMT there. When that program stops
46/// reading it so, the earliest running one that does takes over the intervals it was timing,
47/// and counts on from the total it leaves.
48pub struct Programs {
49	origin: moq_net::origin::Producer,
50	name: moq_net::Path,
51	config: catalog::Config,
52	demux: Demux,
53	/// The latest whole PAT, from the first that lists a program, which seeds every program.
54	pat: Option<psi::Pat>,
55	/// The programs the latest PAT lists and no PMT has started yet, by the PMT PID it names
56	/// for them.
57	waiting: HashMap<u16, HashMap<u16, Wait>>,
58	/// `PMT_error_2` on the PMT PIDs only waiting programs read.
59	pmt_errors: health::Errors,
60	/// Each PMT PID the latest PAT lists.
61	pmts: HashMap<u16, PmtPid>,
62	/// Whether each PID, by index, is one of [`Self::pmts`], read without hashing every packet.
63	pmt_pids: Vec<bool>,
64	/// PMT sections dropped for a bad CRC, by PID.
65	crc_errors: BTreeMap<u16, u64>,
66	/// Each PID's counts, but for its PMT sections' CRC, by the way it is read.
67	tallies: BTreeMap<(u16, Checks), Tally>,
68	/// Empty until a PMT starts a program, and again once a PAT retires every one.
69	programs: Vec<Program>,
70	/// The programs reading each PID they claim, indexed by PID, in program order. The PAT and
71	/// the SI PIDs go to every program instead.
72	readers: Vec<Vec<usize>>,
73	/// The programs the current [`decode`](Self::decode) call routed a packet to.
74	touched: Vec<usize>,
75	/// Whether a retired program had announced.
76	announced: bool,
77	/// Times the programs waiting for their PMT.
78	clock: Clock,
79	/// The [`Clock`] reading past which a waiting program is late or a PMT PID it waits on is
80	/// overdue, while one waits. A PMT only moves it later, so one may leave it early: passing
81	/// it then times the waits again and finds nothing due.
82	deadline: Option<u64>,
83	/// How many waiting programs are not late yet: while one is, a PID no program claims may
84	/// be its. Counted as each one's PMT arrives, so that costs no pass over every program.
85	joining: usize,
86	/// Where the input can next expire a program's health check, so a program that reads no
87	/// packet is advanced without a scan of every program per packet. Kept early when a routed
88	/// packet moves its check later.
89	due: health::Due,
90	/// The packets on PIDs no program reads.
91	unclaimed: Unclaimed,
92}
93
94/// `PMT_error_2`: a PMT recurs at least every 0.5 s of program clock.
95const PMT_LIMIT: u64 = super::passthrough::PCR_HZ / 2;
96
97/// Whether a running program reads its PMT on `pid`, so its health times `PMT_error_2` there.
98fn timed(tallies: &BTreeMap<(u16, Checks), Tally>, pid: u16) -> bool {
99	tallies
100		.get(&(pid, Checks::Table))
101		.is_some_and(|tally| tally.owner.is_some())
102}
103
104/// A PMT PID the latest PAT lists.
105struct PmtPid {
106	/// Its PMT sections, reassembled once for every program.
107	sections: SectionReassembler,
108	/// The [`Clock`] reading from which its next `PMT_error_2` is timed: that of the packet
109	/// starting its last PMT section, or of the PAT that named it, moved on 0.5 s for each
110	/// interval already past. Kept whichever programs read the PID, so a waiting program times
111	/// it on from where a running one left it.
112	section: u64,
113}
114
115impl PmtPid {
116	fn new(now: u64) -> Self {
117		Self {
118			sections: SectionReassembler::default(),
119			section: now,
120		}
121	}
122
123	/// Move [`Self::section`] past each 0.5 s interval without a PMT section through `now`,
124	/// returning how many it passed.
125	fn overdue(&mut self, now: u64) -> u64 {
126		let silent = now.saturating_sub(self.section);
127		if silent <= PMT_LIMIT {
128			return 0;
129		}
130		let count = (silent - 1) / PMT_LIMIT;
131		self.section += count * PMT_LIMIT;
132		count
133	}
134}
135
136/// How long a listed program has waited for its PMT, on the [`Clock`].
137#[derive(Clone, Copy)]
138enum Wait {
139	/// Since this many ticks.
140	Since(u64),
141	/// Past the bound: its PIDs count as unclaimed, and it starts whenever its PMT arrives.
142	Late,
143	/// Its PMT arrived listing no stream yet, so it is not late.
144	Described,
145}
146
147/// A program clock for the programs that have none yet: the ticks a running program's clock
148/// has advanced while it was the reference, which passes to another when it retires. It stands
149/// still while no running program has a clock, so nothing is late before one runs.
150#[derive(Default)]
151struct Clock {
152	ticks: u64,
153	/// The reference program's index, and its clock when last read.
154	reference: Option<(usize, u64)>,
155}
156
157impl Clock {
158	/// Take program `index` as the reference if there is none and its clock runs.
159	fn offer(&mut self, index: usize, import: &Import<Ext>) {
160		if self.reference.is_none() {
161			self.reference = import.now().map(|now| (index, now));
162		}
163	}
164
165	/// Advance by what the reference program's clock moved since the last read.
166	fn advance(&mut self, programs: &[Program]) {
167		if let Some((index, last)) = &mut self.reference
168			&& let Some(now) = programs[*index].import.now()
169		{
170			self.ticks += now.saturating_sub(*last);
171			*last = now;
172		}
173	}
174}
175
176/// One program's broadcast.
177struct Program {
178	/// The PAT's program number.
179	number: u16,
180	/// The program's route, created hidden: dropping it retracts the broadcast the importer
181	/// fills.
182	route: moq_net::origin::Route,
183	import: Import<Ext>,
184	catalog: catalog::Producer<Ext>,
185	/// The catalog track until the catalog first names a servable track: announced any sooner,
186	/// a relay would ask for tracks it cannot serve yet.
187	pending: Option<moq_net::track::Consumer>,
188	/// The PIDs this program is listed under in [`Programs::readers`], sorted.
189	claims: Vec<u16>,
190	/// The ways it reads each PID, sorted, but for the PAT and the SI PIDs every program reads.
191	reads: Vec<(u16, Checks)>,
192	/// Whether the current [`Programs::decode`] call routed it a packet.
193	touched: bool,
194}
195
196impl Program {
197	/// Announce the broadcast once its catalog has gone out.
198	fn announce_if_listed(&mut self) -> Result<bool> {
199		super::republish::listed(&mut self.pending, &self.route)
200	}
201}
202
203/// What one program counted on one PID in one way: for [`Checks::Stream`] its row too.
204#[derive(Clone, Default)]
205struct Count {
206	row: Option<stats::Stream>,
207	errors: health::Errors,
208}
209
210impl Count {
211	/// `pid`'s `checks` in a program's `stats` and `errors`.
212	fn read(stats: &stats::Snapshot, errors: &health::Errors, (pid, checks): (u16, Checks)) -> Self {
213		Self {
214			row: (checks == Checks::Stream)
215				.then(|| stats.streams.get(&pid).cloned())
216				.flatten(),
217			errors: errors.only(pid, checks),
218		}
219	}
220
221	/// What these counts gained since `from`, an earlier reading of the same program.
222	fn since(mut self, from: &Self) -> Self {
223		if let (Some(row), Some(from)) = (&mut self.row, &from.row) {
224			row.combine(from, u64::saturating_sub);
225		}
226		self.errors.combine(&from.errors, u64::saturating_sub);
227		self
228	}
229
230	/// Add what `earlier` counted, keeping this row's track, class and quiet.
231	fn after(mut self, earlier: &Self) -> Self {
232		match (&mut self.row, &earlier.row) {
233			(Some(row), Some(earlier)) => row.combine(earlier, u64::saturating_add),
234			(None, Some(earlier)) => self.row = Some(earlier.clone()),
235			_ => {}
236		}
237		self.errors.combine(&earlier.errors, u64::saturating_add);
238		self
239	}
240}
241
242/// A program's counts and timers just before it read a packet on its PMT PID, which may move
243/// its counts to another program.
244struct Before {
245	stats: stats::Snapshot,
246	errors: health::Errors,
247	health: Health,
248}
249
250impl Before {
251	fn of(import: &Import<Ext>) -> Self {
252		let health = import.timing();
253		Self {
254			stats: import.stats(),
255			errors: import.errors().clone(),
256			health: health.clone(),
257		}
258	}
259}
260
261/// One PID's counts in one way for the multiplex.
262#[derive(Default)]
263struct Tally {
264	/// What the programs that counted it before the current one counted.
265	kept: Count,
266	/// The program counting it now, by index, with its reading when it took over.
267	owner: Option<(usize, Count)>,
268}
269
270impl Tally {
271	/// The counts, given the owner's reading now.
272	fn total(&self, now: Option<Count>) -> Count {
273		match (&self.owner, now) {
274			(Some((_, from)), Some(now)) => now.since(from).after(&self.kept),
275			_ => self.kept.clone(),
276		}
277	}
278
279	/// The owner stops counting, its reading at the end `ended`.
280	fn release(&mut self, ended: Count) {
281		self.kept = self.total(Some(ended));
282		self.owner = None;
283		// Nothing is expected on a PID no program counts, so it is not quiet.
284		if let Some(row) = &mut self.kept.row {
285			row.quiet = None;
286		}
287	}
288}
289
290/// Whether every program reads `pid`: the PAT, and the SI PIDs.
291fn everyone(pid: u16) -> bool {
292	pid == Pid::PAT || SI_PIDS.contains(&pid)
293}
294
295/// The ways `import` reads the PIDs it `claims`, sorted.
296fn reads(import: &Import<Ext>, claims: &[u16]) -> Vec<(u16, Checks)> {
297	let mut reads: Vec<_> = (claims.iter().map(|&pid| (pid, Checks::Stream)))
298		.chain(import.pcr_pid().map(|pid| (pid, Checks::Clock)))
299		.chain(import.pmt_pid().map(|pid| (pid, Checks::Table)))
300		.collect();
301	reads.sort_unstable();
302	reads
303}
304
305/// The `reads` of sorted `ours` not in sorted `theirs`.
306fn difference(ours: &[(u16, Checks)], theirs: &[(u16, Checks)]) -> Vec<(u16, Checks)> {
307	(ours.iter())
308		.filter(|read| theirs.binary_search(read).is_err())
309		.copied()
310		.collect()
311}
312
313/// Which running program counts `pid` in the way `checks`, given the one that does now: one
314/// carrying an elementary stream there counts its row before one only reading the PID, and
315/// otherwise the current one carries on while it reads the PID so, then the earliest that does.
316fn counter(
317	programs: &[Program],
318	readers: &[Vec<usize>],
319	(pid, checks): (u16, Checks),
320	current: Option<usize>,
321) -> Option<usize> {
322	let everyone = everyone(pid);
323	let reads = |index: usize| everyone || programs[index].reads.binary_search(&(pid, checks)).is_ok();
324	let candidates = || -> Box<dyn Iterator<Item = usize> + '_> {
325		match everyone {
326			true => Box::new(0..programs.len()),
327			false => Box::new(readers[usize::from(pid)].iter().copied()),
328		}
329	};
330	let current = current.filter(|&index| reads(index));
331	if checks == Checks::Stream && !everyone {
332		let carries = |index: usize| programs[index].import.carries(pid);
333		if !current.is_some_and(carries)
334			&& let Some(carrier) = candidates().find(|&index| carries(index))
335		{
336			return Some(carrier);
337		}
338	}
339	current.or_else(|| candidates().find(|&index| reads(index)))
340}
341
342impl Programs {
343	/// Split the multiplex into broadcasts named after `name`, each catalog built from `config`.
344	pub fn new(origin: moq_net::origin::Producer, name: impl Into<moq_net::Path>, config: catalog::Config) -> Self {
345		Self {
346			origin,
347			name: name.into(),
348			config,
349			demux: Demux::new(true),
350			pat: None,
351			waiting: HashMap::new(),
352			pmt_errors: health::Errors::default(),
353			pmts: HashMap::new(),
354			pmt_pids: vec![false; 1 << 13],
355			crc_errors: BTreeMap::new(),
356			tallies: BTreeMap::new(),
357			programs: Vec::new(),
358			readers: vec![Vec::new(); 1 << 13],
359			touched: Vec::new(),
360			announced: false,
361			clock: Clock::default(),
362			deadline: None,
363			joining: 0,
364			due: health::Due::default(),
365			unclaimed: Unclaimed::default(),
366		}
367	}
368
369	/// Demux a chunk of the multiplex. A trailing partial packet is retained for the next call.
370	pub fn decode(&mut self, data: &[u8]) -> Result<()> {
371		let mut demux = std::mem::take(&mut self.demux);
372		let result = self.decode_with(&mut demux, data);
373		self.demux = demux;
374		result
375	}
376
377	fn decode_with(&mut self, demux: &mut Demux, data: &[u8]) -> Result<()> {
378		demux.push(data);
379		let mut read = None;
380		while let Some(packet) = demux.next() {
381			let at = health::At {
382				count: packet.count,
383				arrival: packet.arrival,
384			};
385			read = Some(at.arrival);
386			if self.due.count.is_some_and(|due| at.count >= due) {
387				self.due = health::Due::default();
388				for program in &mut self.programs {
389					program.import.timing_mut().advance(at);
390					self.due = self.due.min(program.import.timing().due());
391				}
392			}
393			if let Some(pat) = &packet.pat {
394				self.follow(pat)?;
395			} else if self.pmt_pids[usize::from(packet.pid)] {
396				self.describe(&packet)?;
397			}
398			// Every program reads the PAT, and the SI sections the parser reassembled.
399			let everyone = packet.pid == Pid::PAT || (SI_PIDS.contains(&packet.pid) && !packet.sections.is_empty());
400			if !everyone && self.readers[usize::from(packet.pid)].is_empty() {
401				self.unclaimed(&packet);
402			}
403			let readers = (!everyone).then(|| self.readers[usize::from(packet.pid)].as_slice());
404			let mut changed = Vec::new();
405			for at in 0..readers.map_or(self.programs.len(), <[usize]>::len) {
406				let index = readers.map_or(at, |readers| readers[at]);
407				let program = &mut self.programs[index];
408				if !std::mem::replace(&mut program.touched, true) {
409					self.touched.push(index);
410				}
411				let import = &mut program.import;
412				// A PMT moves counts between programs as it stood before the PMT, so a tail its
413				// end flushes or a refusal on the way to a PID counts once, and an interval the
414				// PMT stops timing carries on.
415				let before = (self.pmt_pids[usize::from(packet.pid)] && import.pmt_pid() == Some(packet.pid))
416					.then(|| Before::of(import));
417				import.packet(&packet)?;
418				self.due = self.due.min(import.timing().due());
419				self.clock.offer(index, import);
420				if import.claims_changed() {
421					changed.push((index, before));
422				}
423			}
424			drop(packet);
425			// Only a PAT or PMT moves claims or restarts a route.
426			for (index, before) in changed {
427				for pid in self.programs[index].import.restarts() {
428					// Another program still reading the PID judges its partial bytes against
429					// this chain, so only the PID's sole reader restarts it.
430					if self.readers[usize::from(pid)].iter().all(|&reader| reader == index) {
431						demux.restart(pid);
432					}
433				}
434				self.reclaim(index, before.as_ref());
435			}
436			// The waiting programs have no clock of their own until their PMT names one.
437			self.clock.advance(&self.programs);
438			if self.deadline.is_some_and(|deadline| self.clock.ticks > deadline) {
439				self.expire();
440			}
441		}
442		demux.drain();
443		// Every packet this chunk completed is read: grade the input through its arrival.
444		if let Some(arrival) = read
445			&& self.due.arrival.is_some_and(|due| arrival >= due)
446		{
447			self.due = health::Due::default();
448			for program in &mut self.programs {
449				program.import.timing_mut().settle(arrival);
450				self.due = self.due.min(program.import.timing().due());
451			}
452		}
453		// Only a program that read something has anything to flush or announce, so a call
454		// costs what it carried rather than one pass over every program.
455		for index in self.touched.drain(..) {
456			let program = &mut self.programs[index];
457			program.touched = false;
458			program.import.flush_batch()?;
459			program.announce_if_listed()?;
460		}
461		Ok(())
462	}
463
464	/// Follow a whole PAT, from the first that lists a program: retire each started program it
465	/// no longer lists, move each waiting one to the PMT PID it names or drop it, and wait for
466	/// the PMT of each it adds. A started program follows its own PMT PID.
467	///
468	/// Fails on a PAT naming another transport stream while a program runs, as each program's
469	/// importer would, and when a retired program cannot finish.
470	fn follow(&mut self, pat: &psi::Pat) -> Result<()> {
471		// The PAT repeats several times a second, mostly unchanged.
472		if self.pat.as_ref() == Some(pat) {
473			return Ok(());
474		}
475		if let Some(running) = self.pat.as_ref().filter(|_| !self.programs.is_empty()) {
476			ensure_supported!(
477				running.transport_stream_id == pat.transport_stream_id,
478				"the PAT changed transport_stream_id from {} to {} while its programs run, which their carried service information does not describe",
479				running.transport_stream_id,
480				pat.transport_stream_id
481			);
482		}
483		let mut listed = HashMap::new();
484		for entry in &pat.programs {
485			// An importer takes a program's first entry, so a repeated number waits there alone.
486			if entry.program_number != 0 {
487				listed.entry(entry.program_number).or_insert(entry.pmt_pid.as_u16());
488			}
489		}
490		if self.pat.is_none() && listed.is_empty() {
491			return Ok(());
492		}
493		// A running program's health counted the intervals its PMT PID has already gone
494		// without a PMT, so a program left waiting on the PID once it retires counts on from
495		// there.
496		let ticks = self.clock.ticks;
497		for pmt in self.pmts.values_mut() {
498			pmt.overdue(ticks);
499		}
500		self.retire(&listed)?;
501		let mut moved = Vec::new();
502		self.waiting.retain(|pid, waiting| {
503			waiting.retain(|number, _| match listed.get(number) {
504				Some(listed) if listed == pid => true,
505				Some(&listed) => {
506					moved.push((*number, listed));
507					false
508				}
509				None => false,
510			});
511			!waiting.is_empty()
512		});
513		// A PMT on a new PID is due 0.5 s from the PAT that names it.
514		let now = Wait::Since(ticks);
515		for (number, pid) in moved {
516			self.waiting.entry(pid).or_default().insert(number, now);
517		}
518		let known: HashSet<u16> = self
519			.programs
520			.iter()
521			.map(|program| program.number)
522			.chain(self.waiting.values().flat_map(|waiting| waiting.keys().copied()))
523			.collect();
524		for (&number, &pid) in &listed {
525			if known.contains(&number) {
526				continue;
527			}
528			if self.pat.is_some() {
529				tracing::info!(program = number, pmt_pid = pid, "TS program joined the PAT");
530			}
531			self.waiting.entry(pid).or_default().insert(number, now);
532		}
533		// A PMT PID the PAT now names starts reassembling at its next section.
534		let named: HashSet<u16> = listed.values().copied().collect();
535		for &pid in self.pmts.keys() {
536			self.pmt_pids[usize::from(pid)] = false;
537		}
538		self.pmts.retain(|pid, _| named.contains(pid));
539		for pid in named {
540			self.pmts.entry(pid).or_insert_with(|| PmtPid::new(ticks));
541			self.pmt_pids[usize::from(pid)] = true;
542		}
543		self.pat = Some(pat.clone());
544		self.time_waits();
545		Ok(())
546	}
547
548	/// Time the next wait for a PMT to run out, and count the programs not late yet, once a
549	/// PAT or an expiry changed which programs wait.
550	fn time_waits(&mut self) {
551		self.joining = 0;
552		self.deadline = None;
553		for (pid, waiting) in &self.waiting {
554			let overdue = self.pmts.get(pid).map(|pmt| pmt.section + PMT_LIMIT);
555			for wait in waiting.values() {
556				if let Wait::Since(since) = wait {
557					self.joining += 1;
558					let late = since + PMT_LIMIT;
559					self.deadline = Some(self.deadline.map_or(late, |deadline| deadline.min(late)));
560				}
561			}
562			self.deadline = self.deadline.into_iter().chain(overdue).min();
563		}
564	}
565
566	/// Mark each program waiting more than 0.5 s of program clock for its PMT late, and count
567	/// `PMT_error_2` for each 0.5 s a PMT PID only waiting programs read carries no PMT section.
568	/// A running program reading its PMT on the PID counts it instead.
569	fn expire(&mut self) {
570		let now = self.clock.ticks;
571		for (&pid, waiting) in &mut self.waiting {
572			for (&number, wait) in waiting.iter_mut() {
573				if matches!(*wait, Wait::Since(since) if now > since + PMT_LIMIT) {
574					tracing::warn!(
575						program = number,
576						pmt_pid = pid,
577						"TS program the PAT lists sent no PMT within 0.5 s of program clock (PMT_error_2); the others carry on"
578					);
579					*wait = Wait::Late;
580				}
581			}
582			let count = self.pmts.get_mut(&pid).map_or(0, |pmt| pmt.overdue(now));
583			if count > 0 && !timed(&self.tallies, pid) {
584				self.pmt_errors.pmt_error(pid, count);
585			}
586		}
587		self.time_waits();
588	}
589
590	/// End every started program `listed` no longer names: finish its tracks, announcing it
591	/// as the end of the input would, then its catalog, and close its broadcast, so it is
592	/// unannounced now rather than lingering. Subscribers already reading a track read it to
593	/// its end, and the other programs carry on. Each PID a retired program counted stays
594	/// counted, and its next reader counts on from there.
595	///
596	/// The programs and the PIDs they read are rebuilt once, so a PAT costs what the programs
597	/// claim however many it drops. Fails when a program cannot finish, as an import does at
598	/// the end of its input.
599	fn retire(&mut self, listed: &HashMap<u16, u16>) -> Result<()> {
600		let leaving = |program: &Program| !listed.contains_key(&program.number);
601		if !self.programs.iter().any(leaving) {
602			return Ok(());
603		}
604		// What each leaver had counted before its finish, by index.
605		let before: HashMap<usize, (stats::Snapshot, health::Errors)> = (self.programs.iter().enumerate())
606			.filter(|(_, program)| leaving(program))
607			.map(|(index, program)| (index, (program.import.stats(), program.import.errors().clone())))
608			.collect();
609		// A refusal leaves every program listed, so the caller's abort reaches them all.
610		for program in self.programs.iter_mut().filter(|program| leaving(program)) {
611			tracing::info!(
612				program = program.number,
613				"TS program left the PAT; retiring its broadcast"
614			);
615			program.import.finish_in_place()?;
616			self.announced |= program.announce_if_listed()?;
617			program.catalog.finish()?;
618		}
619		let mut kept = 0;
620		let moved: Vec<Option<usize>> = self
621			.programs
622			.iter()
623			.map(|program| {
624				(!leaving(program)).then(|| {
625					kept += 1;
626					kept - 1
627				})
628			})
629			.collect();
630		for program in &self.programs {
631			for &pid in &program.claims {
632				self.readers[usize::from(pid)].clear();
633			}
634		}
635		let mut gone = HashMap::new();
636		for (index, program) in std::mem::take(&mut self.programs).into_iter().enumerate() {
637			match moved[index] {
638				Some(_) => self.programs.push(program),
639				None => {
640					gone.insert(index, (program, None));
641				}
642			}
643		}
644		for (index, program) in self.programs.iter().enumerate() {
645			for &pid in &program.claims {
646				self.readers[usize::from(pid)].push(index);
647			}
648		}
649		self.touched.retain_mut(|index| match moved[*index] {
650			Some(to) => {
651				*index = to;
652				true
653			}
654			None => false,
655		});
656		// A clock that leaves stops here; the next running one carries on from this reading.
657		self.clock.reference = self
658			.clock
659			.reference
660			.and_then(|(index, last)| Some((moved[index]?, last)));
661		// Each count a leaver kept passes to the next program reading the PID so. One a running
662		// program carrying the PID takes ends at the leaver's count before its finish: that
663		// program holds the tail the finish flushed, and counts it when it delivers it.
664		let mut readings = HashMap::new();
665		for (&read, tally) in &mut self.tallies {
666			let Some((owner, _)) = &mut tally.owner else {
667				continue;
668			};
669			if let Some(to) = moved[*owner] {
670				*owner = to;
671				continue;
672			}
673			let (program, after) = gone.get_mut(owner).expect("a leaver counted it");
674			let next = counter(&self.programs, &self.readers, read, None);
675			let holds_tail =
676				read.1 == Checks::Stream && next.is_some_and(|next| self.programs[next].import.carries(read.0));
677			let ended = match holds_tail {
678				true => {
679					let (stats, errors) = &before[owner];
680					Count::read(stats, errors, read)
681				}
682				false => {
683					let stats = after.get_or_insert_with(|| program.import.stats());
684					Count::read(stats, program.import.errors(), read)
685				}
686			};
687			tally.release(ended);
688			if let Some(next) = next {
689				let to = &mut self.programs[next].import;
690				to.take_over(read.0, program.import.timing());
691				let reading = readings.entry(next).or_insert_with(|| to.stats());
692				tally.owner = Some((next, Count::read(reading, to.errors(), read)));
693			}
694		}
695		for (program, _) in gone.values() {
696			program.route.broadcast().close();
697		}
698		Ok(())
699	}
700
701	/// Count a packet on a PID no program reads, unless the PAT claims it or a waiting program's
702	/// PMT may still claim it.
703	fn unclaimed(&mut self, packet: &Packet) {
704		// A packet flagged corrupt may carry another PID's number.
705		if packet.pkt[1] & 0x80 != 0 || Unclaimed::fixed(packet.pid, true) || self.pmt_pids[usize::from(packet.pid)] {
706			return;
707		}
708		// A program still waiting for its PMT may claim it, until it is late.
709		if self.pat.is_some() && self.joining == 0 {
710			self.unclaimed.packet(packet.pid);
711		}
712	}
713
714	/// Reassemble a packet on a PMT PID, count the PMT sections it completes with a bad CRC, and
715	/// start each waiting program whose PMT it completes with a stream listed.
716	///
717	/// A started program reads this packet itself, from the reassembler as it stood before it,
718	/// so its own PMT path applies the PMT and starts its clock from the PCR already seen. Of
719	/// several revisions in the packet, the last decides.
720	fn describe(&mut self, packet: &Packet) -> Result<()> {
721		let Some(pmt) = self.pmts.get_mut(&packet.pid) else {
722			return Ok(());
723		};
724		let mut waiting = self.waiting.get_mut(&packet.pid);
725		// Timed as a running program's health times its PMT PID, before any CRC check.
726		match PmtPacket::of(packet.pkt, packet.continuation) {
727			PmtPacket::Section => pmt.section = self.clock.ticks,
728			PmtPacket::Scrambled if waiting.is_some() && !timed(&self.tallies, packet.pid) => {
729				self.pmt_errors.pmt_error(packet.pid, 1);
730			}
731			PmtPacket::Scrambled | PmtPacket::Other => {}
732		}
733		let sections = &mut pmt.sections;
734		let before = waiting.is_some().then(|| sections.clone());
735		let mut completed = Vec::new();
736		sections.push(packet.pkt, &mut completed);
737		let mut corrupt = 0;
738		let mut latest: Vec<psi::Pmt> = Vec::new();
739		for section in completed {
740			// Other tables may share the PID.
741			if section.first() != Some(&psi::PMT_TABLE_ID) {
742				continue;
743			}
744			if !psi::crc_ok(&section) {
745				corrupt += 1;
746				continue;
747			}
748			if let Some(waiting) = &waiting
749				&& let Some(pmt) = psi::Pmt::parse(&section)
750				&& waiting.contains_key(&pmt.program_number)
751			{
752				latest.retain(|seen| seen.program_number != pmt.program_number);
753				latest.push(pmt);
754			}
755		}
756		if corrupt > 0 {
757			*self.crc_errors.entry(packet.pid).or_default() += corrupt;
758			tracing::warn!(pid = packet.pid, "dropped a PSI section with a bad CRC");
759		}
760		let (Some(waiting), Some(before)) = (waiting.as_mut(), before) else {
761			return Ok(());
762		};
763		// A program no longer waiting only moves the deadline later, so it stays as it is.
764		let mut joined = 0;
765		for pmt in latest.iter().filter(|pmt| pmt.streams.is_empty()) {
766			let wait = waiting.insert(pmt.program_number, Wait::Described);
767			joined += usize::from(matches!(wait, Some(Wait::Since(_))));
768		}
769		latest.retain(|pmt| !pmt.streams.is_empty());
770		for pmt in &latest {
771			let wait = waiting.remove(&pmt.program_number);
772			joined += usize::from(matches!(wait, Some(Wait::Since(_))));
773		}
774		if waiting.is_empty() {
775			self.waiting.remove(&packet.pid);
776		}
777		self.joining -= joined;
778		for pmt in latest {
779			self.start(pmt.program_number, packet.pid, before.clone())?;
780		}
781		Ok(())
782	}
783
784	/// Create the broadcast of program `number`, its importer seeded with the PAT and carrying
785	/// on the PMT `sections` began on `pmt_pid`.
786	fn start(&mut self, number: u16, pmt_pid: u16, sections: SectionReassembler) -> Result<()> {
787		let pat = self.pat.as_ref().expect("a program waits on its PAT");
788		let name = program_broadcast(self.name.as_str(), number);
789		// Each program is its own publisher identity for this run, minted by its route, so a
790		// restart replaces it rather than resuming into it.
791		let route = self.origin.route(&name, moq_net::origin::RouteOptions::hidden())?;
792		// TS carries undecoded elementary streams verbatim, so each catalog carries the
793		// `mpegts` extension, and owns its broadcast's catalog tracks.
794		let config = self
795			.config
796			.clone()
797			.with_catalog(catalog::hang::Catalog::<Ext>::default());
798		let catalog = catalog::Producer::new(&mut route.broadcast().clone(), config)?;
799		let pmt_pid = Pid::new(pmt_pid).expect("a packet's PID fits 13 bits");
800		let mut import = Import::new(route.broadcast().clone(), catalog.reserve())
801			.with_program(number)
802			.with_pmt(pmt_pid, sections);
803		import.handle_pat(pat)?;
804		let listed = route.broadcast().consume().track(hang::Catalog::DEFAULT_NAME)?;
805		self.programs.push(Program {
806			number,
807			route,
808			import,
809			catalog,
810			pending: Some(listed),
811			claims: Vec::new(),
812			reads: Vec::new(),
813			touched: false,
814		});
815		let index = self.programs.len() - 1;
816		self.reclaim(index, None);
817		let mut readings = HashMap::new();
818		for pid in std::iter::once(Pid::PAT).chain(SI_PIDS.iter().copied()) {
819			self.settle((pid, Checks::Stream), index, None, &mut readings);
820		}
821		Ok(())
822	}
823
824	/// Move program `index` in [`Self::readers`] to the PIDs it claims now, and settle who
825	/// counts each PID in each way it reads it now or did, given its counts `before` the packet
826	/// that moved them, if that was a PMT.
827	fn reclaim(&mut self, index: usize, before: Option<&Before>) {
828		// A handover may bring an older interval into another program's health checks.
829		self.due = health::Due::NOW;
830		let program = &mut self.programs[index];
831		let claims = program.import.claims();
832		for &pid in program.claims.iter().filter(|pid| claims.binary_search(pid).is_err()) {
833			self.readers[usize::from(pid)].retain(|&reader| reader != index);
834		}
835		for &pid in claims.iter().filter(|pid| program.claims.binary_search(pid).is_err()) {
836			let readers = &mut self.readers[usize::from(pid)];
837			let at = readers.partition_point(|&reader| reader < index);
838			readers.insert(at, index);
839		}
840		let reads = reads(&program.import, &claims);
841		program.claims = claims;
842		let mut settled = difference(&program.reads, &reads);
843		settled.extend_from_slice(&reads);
844		program.reads = reads;
845		let mut readings = HashMap::new();
846		for read in settled {
847			self.settle(read, index, before, &mut readings);
848		}
849	}
850
851	/// Move `read`'s count to the program [`counter`] picks, if not the one counting it now. The
852	/// next counts on from its reading now, and the last counts up to its reading now, but for
853	/// program `index`, which read the packet that moved the count: its reading `before` it
854	/// stands where it starts counting, so what that packet counted on the way to the PID counts,
855	/// and where it stops in favour of a program carrying the PID, which holds the tail its
856	/// route's end flushed. `readings` caches the programs' stats.
857	fn settle(
858		&mut self,
859		read: (u16, Checks),
860		index: usize,
861		before: Option<&Before>,
862		readings: &mut HashMap<usize, stats::Snapshot>,
863	) {
864		let tally = self.tallies.entry(read).or_default();
865		let current = tally.owner.as_ref().map(|&(owner, _)| owner);
866		let next = counter(&self.programs, &self.readers, read, current);
867		if next == current {
868			return;
869		}
870		let programs = &self.programs;
871		let mut reading = |at: usize, earlier: bool| match before.filter(|_| earlier && at == index) {
872			Some(before) => Count::read(&before.stats, &before.errors, read),
873			None => {
874				let import = &programs[at].import;
875				let stats = readings.entry(at).or_insert_with(|| import.stats());
876				Count::read(stats, import.errors(), read)
877			}
878		};
879		if let Some(current) = current {
880			let holds_tail = read.1 == Checks::Stream && next.is_some_and(|next| programs[next].import.carries(read.0));
881			tally.release(reading(current, holds_tail));
882		}
883		let Some(next) = next else {
884			return;
885		};
886		tally.owner = Some((next, reading(next, true)));
887		let Some(current) = current else {
888			return;
889		};
890		match before.filter(|_| current == index) {
891			Some(before) => (self.programs[next].import).take_over(read.0, &before.health),
892			None => {
893				let [from, to] = self
894					.programs
895					.get_disjoint_mut([current, next])
896					.expect("a count moves to another program");
897				to.import.take_over(read.0, from.import.timing());
898			}
899		}
900	}
901
902	/// Every program's counters in one map, each PID counted once.
903	///
904	/// The multiplex is graded once. Programs sharing a PMT PID read the same PMT sections, so
905	/// a dropped section counts once however many read it, and a PID several programs read is
906	/// counted by one of them at a time. What a retired program counted stays in the totals, so
907	/// no total goes back when a program leaves or returns. So are the packets on PIDs no
908	/// program reads, in the row of the program that reads the PID whenever one does.
909	pub fn stats(&self) -> stats::Snapshot {
910		let mut readings: Vec<Option<stats::Snapshot>> = (0..self.programs.len()).map(|_| None).collect();
911		let mut errors = self.demux.errors().clone();
912		let mut stats = stats::Snapshot::default();
913		for (&read, tally) in &self.tallies {
914			let now = tally.owner.as_ref().map(|&(index, _)| {
915				let import = &self.programs[index].import;
916				let reading = readings[index].get_or_insert_with(|| import.stats());
917				Count::read(reading, import.errors(), read)
918			});
919			let count = tally.total(now);
920			if let Some(row) = count.row {
921				stats.streams.insert(read.0, row);
922			}
923			errors.combine(&count.errors, u64::saturating_add);
924		}
925		self.unclaimed.report(&mut stats.streams, |pid| {
926			Unclaimed::fixed(pid, true) || self.pmt_pids[usize::from(pid)] || !self.readers[usize::from(pid)].is_empty()
927		});
928		errors.combine(&self.pmt_errors, u64::saturating_add);
929		stats.crc_error = self.crc_errors.values().sum::<u64>() + self.demux.pat_crc_error();
930		errors.report(&mut stats);
931		stats
932	}
933
934	/// Finish each program's tracks, then its catalog while it still lists them, and return the
935	/// [`Finished`] programs.
936	///
937	/// The finished tracks stay servable while the [`Finished`] programs are held, so hand them and
938	/// their [`broadcasts`](Finished::broadcasts) to a [`Linger`](crate::Linger) to keep them up for
939	/// late subscribers. Fails when the input ended before its PAT listed a program or any program
940	/// declared a track. A finish that fails aborts every program with the cause, so it can't be
941	/// retried.
942	pub fn finish(mut self) -> Result<Finished> {
943		if let Err(err) = self.end() {
944			self.fail(err.clone().into());
945			return Err(err);
946		}
947		Ok(Finished { programs: self })
948	}
949
950	/// Finish every program, stopping at the first failure.
951	fn end(&mut self) -> Result<()> {
952		self.demux.finish();
953		if self.pat.is_none() {
954			return Err(Error::Empty("its PAT listed a program"));
955		}
956		let mut announced = self.announced;
957		for program in &mut self.programs {
958			program.import.finish_in_place()?;
959			announced |= program.announce_if_listed()?;
960			program.catalog.finish()?;
961		}
962		if !announced {
963			return Err(Error::Empty("any program declared a track"));
964		}
965		Ok(())
966	}
967
968	/// Each running program's broadcast.
969	fn broadcasts(&self) -> Vec<moq_net::broadcast::Producer> {
970		self.programs
971			.iter()
972			.map(|program| program.route.broadcast().clone())
973			.collect()
974	}
975
976	/// Abort every program's catalog and media tracks with `err`. Consumes the importer.
977	pub fn abort(mut self, err: moq_net::Error) {
978		self.fail(err.into());
979	}
980
981	/// Abort every program's catalog and media tracks with `cause`.
982	fn fail(&mut self, cause: crate::Error) {
983		for program in &mut self.programs {
984			program.catalog.clone().abort(cause.reason());
985			program.import.fail(cause.clone());
986		}
987	}
988}
989
990/// Every program of a multiplex [finished](Programs::finish): every track has ended, and they can
991/// still be read or aborted, but it takes no more input.
992///
993/// Dropping it releases every program's tracks, which leave their broadcasts' listings.
994///
995/// ```compile_fail,E0599
996/// # fn cannot_decode(mut programs: moq_mux::container::ts::programs::Finished) {
997/// programs.decode(b"").unwrap();
998/// # }
999/// ```
1000#[must_use = "dropping it releases every program's tracks"]
1001pub struct Finished {
1002	programs: Programs,
1003}
1004
1005impl Finished {
1006	/// Each running program's broadcast; a retired one has already closed.
1007	pub fn broadcasts(&self) -> Vec<moq_net::broadcast::Producer> {
1008		self.programs.broadcasts()
1009	}
1010
1011	/// Every program's counters in one map; see [`Programs::stats`].
1012	pub fn stats(&self) -> stats::Snapshot {
1013		self.programs.stats()
1014	}
1015
1016	/// Abort every program's catalog and media tracks with `err`; see [`Programs::abort`].
1017	pub fn abort(self, err: moq_net::Error) {
1018		self.programs.abort(err);
1019	}
1020}
1021
1022/// The broadcast one program of `name` publishes on: `event.hang` becomes `event/2.hang`.
1023fn program_broadcast(name: &str, program: u16) -> String {
1024	let (stem, extension) = match catalog::CatalogFormat::detect(name) {
1025		Some(format) => (&name[..name.len() - format.extension().len()], format.extension()),
1026		None => (name, ""),
1027	};
1028	// A final segment that is only the extension (`room/.hang`) leaves the stem's separator behind.
1029	match stem.strip_suffix('/').unwrap_or(stem) {
1030		"" => format!("{program}{extension}"),
1031		stem => format!("{stem}/{program}{extension}"),
1032	}
1033}
1034
1035#[cfg(test)]
1036mod test {
1037	use std::time::Duration;
1038
1039	use super::*;
1040	use crate::catalog::hang::Wire;
1041	use crate::container::Consumer;
1042	use crate::container::ts::fixture::{Flags, MS, Mux};
1043	use crate::container::ts::import::test::{
1044		CUE, MP2, annexb_au, corrupt, fifty_programs, mp2_pes, pat_section, pmt_section, psi_packets, two_programs,
1045		two_section_pat, video_pes,
1046	};
1047
1048	/// The identity each running program publishes under, announced yet or not.
1049	fn identities(programs: &Programs) -> Vec<(u16, moq_net::Identity)> {
1050		programs
1051			.programs
1052			.iter()
1053			.map(|program| (program.number, program.route.identity()))
1054			.collect()
1055	}
1056
1057	/// Steps of a two-program multiplex: each a PAT listing `listed`, both programs' PMTs, and a
1058	/// PCR and an MP2 PES of two frames on each program, whether or not the PAT lists it.
1059	struct Steps {
1060		mux: Mux,
1061		cc: [u8; 2],
1062		pts: u64,
1063	}
1064
1065	impl Steps {
1066		fn new() -> Self {
1067			Self {
1068				mux: Mux::default(),
1069				cc: [0; 2],
1070				pts: 90_000,
1071			}
1072		}
1073
1074		fn step(&mut self, programs: &mut Programs, listed: &[(u16, u16)]) {
1075			self.mux
1076				.pat(listed)
1077				.pmt(0x100, 1, 0x1f1, &[(MP2, 0x61)], 0)
1078				.pmt(0x200, 2, 0x1f2, &[(MP2, 0x71)], 0);
1079			for (cc, (pid, clock)) in self.cc.iter_mut().zip([(0x61, 0x1f1), (0x71, 0x1f2)]) {
1080				self.mux.packet(clock, Flags::pcr(self.pts * 300));
1081				self.mux.out.extend(mp2_pes(pid, *cc, self.pts, [pid as u8; 2]));
1082				*cc = (*cc + 1) & 0x0f;
1083			}
1084			// Past both 72 ms frames.
1085			self.pts += 18_000;
1086			programs.decode(&std::mem::take(&mut self.mux.out)).unwrap();
1087		}
1088	}
1089
1090	/// A program a later PAT adds publishes, one it drops retires alone, its catalog finished and
1091	/// its broadcast closed, and one it restores publishes a new identity that counts on from the
1092	/// retired one, while the program no PAT touched runs throughout.
1093	#[tokio::test]
1094	async fn programs_follow_the_pat() {
1095		let origin = crate::source::produce_origin();
1096		let mut programs = Programs::new(
1097			origin,
1098			moq_net::Path::from_static("event.hang"),
1099			catalog::Config::default(),
1100		);
1101		let mut steps = Steps::new();
1102
1103		steps.step(&mut programs, &[(1, 0x100)]);
1104		let one = identities(&programs);
1105		assert_eq!(one.len(), 1);
1106
1107		steps.step(&mut programs, &[(1, 0x100), (2, 0x200)]);
1108		let both = identities(&programs);
1109		assert_eq!(both[0], one[0], "program 1 carries on");
1110		assert_eq!(both[1].0, 2, "the added program publishes");
1111		let two = programs.programs[1].route.broadcast().consume();
1112		let mut catalog = hang::catalog::Catalog::<()>::subscribe(&two).await.unwrap();
1113
1114		steps.step(&mut programs, &[(1, 0x100)]);
1115		assert_eq!(identities(&programs), one, "program 1 carries on");
1116		assert!(two.is_closed(), "the dropped program is unannounced");
1117		while catalog.next().await.unwrap().is_some() {}
1118		let retired = &programs.stats().streams[&0x71];
1119		assert_eq!(retired.units, 2, "the retired program's frames stay counted");
1120		assert_eq!(retired.quiet, None, "nothing is expected on a retired PID");
1121
1122		steps.step(&mut programs, &[(1, 0x100), (2, 0x200)]);
1123		let back = identities(&programs);
1124		assert_eq!(back[0], one[0], "program 1 carries on");
1125		assert_eq!(back[1].0, 2);
1126		assert_ne!(back[1].1, both[1].1, "the returning program is a new identity");
1127
1128		let finished = programs.finish().unwrap();
1129
1130		let programs = &finished.programs;
1131		let stats = programs.stats();
1132		assert_eq!(stats.streams[&0x61].units, 8, "program 1 delivered every frame");
1133		assert_eq!(stats.streams[&0x71].units, 4, "the returning program counts on");
1134	}
1135
1136	/// A PAT that drops a program reaches no importer of it, so the multiplex carries on rather
1137	/// than ending on that program's refusal, and the program after it keeps reading its PIDs.
1138	#[test]
1139	fn a_dropped_program_does_not_end_the_multiplex() {
1140		let origin = crate::source::produce_origin();
1141		let mut programs = Programs::new(
1142			origin,
1143			moq_net::Path::from_static("event.hang"),
1144			catalog::Config::default(),
1145		);
1146		let mut steps = Steps::new();
1147		steps.step(&mut programs, &[(1, 0x100), (2, 0x200)]);
1148		// Fed a packet at a time, so the PAT that drops program 1 completes in a call of its own.
1149		steps.mux.pat(&[(2, 0x200)]);
1150		steps.mux.out.extend(mp2_pes(0x71, 1, 108_000, [0x71; 2]));
1151		for packet in std::mem::take(&mut steps.mux.out).chunks(188) {
1152			programs.decode(packet).unwrap();
1153		}
1154		let running: Vec<_> = identities(&programs).into_iter().map(|(number, _)| number).collect();
1155		assert_eq!(running, [2]);
1156		let finished = programs.finish().unwrap();
1157		let programs = &finished.programs;
1158		assert_eq!(programs.stats().streams[&0x71].units, 4, "program 2 read on");
1159	}
1160
1161	/// A program the PAT lists whose PMT does not arrive is late at the first packet past 0.5 s
1162	/// of program clock, timed on the program that runs: its PMT PID counts `PMT_error_2` each
1163	/// 0.5 s, its PIDs count as unclaimed, and the running program carries on. It starts once its
1164	/// PMT arrives. One whose PMT arrives listing no stream is not late.
1165	#[test]
1166	fn a_late_pmt_ends_only_its_own_program() {
1167		let origin = crate::source::produce_origin();
1168		let mut programs = Programs::new(
1169			origin,
1170			moq_net::Path::from_static("event.hang"),
1171			catalog::Config::default(),
1172		);
1173		let mut mux = Mux::default();
1174		mux.pat(&[(1, 0x100), (3, 0x300), (4, 0x400)]);
1175		let step = |programs: &mut Programs, mux: &mut Mux, ms: u64| {
1176			mux.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0)
1177				.pmt(0x400, 4, 0x1ff, &[], 0)
1178				.packet(0x73, Flags::default())
1179				.packet(0x1ff, Flags::pcr(27_000_000 + ms * MS));
1180			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1181			let stats = programs.stats();
1182			let refused = stats.streams.get(&0x73).map_or(0, |row| row.refused);
1183			(stats.pmt_error, refused)
1184		};
1185		// Program 1's clock starts at its first PCR, and the wait with it.
1186		for ms in (0..=500).step_by(100) {
1187			assert_eq!(step(&mut programs, &mut mux, ms), (0, 0), "{ms} ms");
1188		}
1189		assert_eq!(
1190			step(&mut programs, &mut mux, 501),
1191			(1, 0),
1192			"late at the packet past 0.5 s"
1193		);
1194		assert_eq!(
1195			step(&mut programs, &mut mux, 1000),
1196			(1, 1),
1197			"its PIDs count as unclaimed"
1198		);
1199		assert_eq!(step(&mut programs, &mut mux, 1001), (2, 2), "each 0.5 s counts");
1200		let running: Vec<_> = identities(&programs).into_iter().map(|(number, _)| number).collect();
1201		assert_eq!(running, [1], "the running program carries on");
1202
1203		mux.pmt(0x300, 3, 0x1ff, &[(MP2, 0x73)], 0);
1204		assert_eq!(
1205			step(&mut programs, &mut mux, 1100),
1206			(2, 2),
1207			"the late program claims its PID"
1208		);
1209		let running: Vec<_> = identities(&programs).into_iter().map(|(number, _)| number).collect();
1210		assert_eq!(running, [1, 3], "the late program starts once its PMT arrives");
1211	}
1212
1213	/// A PMT PID a running program reads counts its `PMT_error_2` once, however many programs
1214	/// still wait on it.
1215	#[test]
1216	fn a_late_pmt_on_a_running_programs_pid_counts_once() {
1217		let pmt_error = |listed: &[(u16, u16)]| {
1218			let origin = crate::source::produce_origin();
1219			let mut programs = Programs::new(
1220				origin,
1221				moq_net::Path::from_static("event.hang"),
1222				catalog::Config::default(),
1223			);
1224			let mut mux = Mux::default();
1225			mux.pat(listed);
1226			for ms in (0..=2000).step_by(100) {
1227				if ms <= 400 {
1228					mux.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0);
1229				}
1230				mux.packet(0x1ff, Flags::pcr(27_000_000 + ms * MS));
1231				programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1232			}
1233			programs.stats().pmt_error
1234		};
1235		let alone = pmt_error(&[(1, 0x100)]);
1236		assert!(alone > 0);
1237		assert_eq!(pmt_error(&[(1, 0x100), (3, 0x100)]), alone);
1238	}
1239
1240	/// A waiting program's PMT PID is timed as a running program's health times its own: a PMT
1241	/// section with a bad CRC still restarts the interval, so it counts as a CRC error alone.
1242	#[test]
1243	fn a_late_pmt_with_a_bad_crc_counts_only_its_crc() {
1244		let origin = crate::source::produce_origin();
1245		let mut programs = Programs::new(
1246			origin,
1247			moq_net::Path::from_static("event.hang"),
1248			catalog::Config::default(),
1249		);
1250		let mut mux = Mux::default();
1251		mux.pat(&[(1, 0x100), (3, 0x300)]);
1252		for ms in (0..=2000).step_by(100) {
1253			mux.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0)
1254				.section(0x300, &corrupt(pmt_section(3, 0, &[(MP2, 0x73, &[])])))
1255				.packet(0x1ff, Flags::pcr(27_000_000 + ms * MS));
1256			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1257		}
1258		let stats = programs.stats();
1259		assert_eq!(stats.crc_error, 21, "each PMT section counts its bad CRC");
1260		assert_eq!(stats.pmt_error, 0, "and no PMT_error_2");
1261	}
1262
1263	/// A PMT PID a running program leaves to a waiting one keeps its interval: the waiting
1264	/// program counts `PMT_error_2` 0.5 s after the PID's last PMT section, not after the PAT
1265	/// that added it.
1266	#[test]
1267	fn a_late_pmt_times_on_from_a_retired_programs_pid() {
1268		let origin = crate::source::produce_origin();
1269		let mut programs = Programs::new(
1270			origin,
1271			moq_net::Path::from_static("event.hang"),
1272			catalog::Config::default(),
1273		);
1274		let mut mux = Mux::default();
1275		let mut pmt_error = Vec::new();
1276		for ms in (0..=1000).step_by(50) {
1277			match ms {
1278				0..400 => mux.pat(&[(1, 0x100), (5, 0x500)]),
1279				400..450 => mux.pat(&[(1, 0x100), (2, 0x100), (5, 0x500)]),
1280				_ => mux.pat(&[(2, 0x100), (5, 0x500)]),
1281			};
1282			match ms {
1283				0 => mux.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0),
1284				800 => mux.pmt(0x100, 2, 0x1ff, &[(MP2, 0x62)], 0),
1285				_ => &mut mux,
1286			};
1287			mux.pmt(0x500, 5, 0x1ff, &[(MP2, 0x65)], 0)
1288				.packet(0x1ff, Flags::pcr(27_000_000 + ms * MS));
1289			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1290			pmt_error.push((ms, programs.stats().pmt_error));
1291		}
1292		let at = |ms: u64| pmt_error.iter().find(|&&(at, _)| at == ms).unwrap().1;
1293		assert_eq!(at(500), 0, "program 1 retired before its PMT was due");
1294		assert_eq!(at(550), 1, "due 0.5 s after program 1's last PMT");
1295		assert_eq!(at(1000), 1, "program 2's PMT ends the wait");
1296		let running: Vec<_> = identities(&programs).into_iter().map(|(number, _)| number).collect();
1297		assert_eq!(running, [5, 2], "program 2 starts once its PMT arrives");
1298	}
1299
1300	/// A program leaving the PAT flushes the picture it shares with a program still running,
1301	/// which that program delivers itself at the next picture, so the picture counts once.
1302	#[test]
1303	fn a_picture_a_retired_program_flushed_counts_once() {
1304		const H264: u8 = 0x1b;
1305		let origin = crate::source::produce_origin();
1306		let mut programs = Programs::new(
1307			origin,
1308			moq_net::Path::from_static("event.hang"),
1309			catalog::Config::default(),
1310		);
1311		let mut mux = Mux::default();
1312		let both = [(1, 0x100), (2, 0x200)];
1313		mux.pat(&both)
1314			.pmt(0x100, 1, 0x50, &[(H264, 0x50)], 0)
1315			.pmt(0x200, 2, 0x50, &[(H264, 0x50)], 0);
1316		let mut pictures =
1317			(0..).map(|n: u8| video_pes(0x50, n & 0x0f, 90_000 + u64::from(n) * 3_000, None, &annexb_au(n == 0)));
1318		mux.out.extend(pictures.next().unwrap());
1319		mux.out.extend(pictures.next().unwrap());
1320		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1321		let units = |programs: &Programs| programs.stats().streams[&0x50].units;
1322		assert_eq!(units(&programs), 1, "the second picture ends at the third");
1323
1324		mux.pat(&both[1..]);
1325		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1326		assert_eq!(programs.programs.len(), 1);
1327		assert_eq!(units(&programs), 1, "program 2 still holds the second picture");
1328		programs.decode(&pictures.next().unwrap()).unwrap();
1329		assert_eq!(units(&programs), 2, "the second picture counts once");
1330		let finished = programs.finish().unwrap();
1331		let programs = &finished.programs;
1332		assert_eq!(units(programs), 3);
1333	}
1334
1335	/// A program leaving the PAT counts the picture its finish flushes on a PID the programs
1336	/// still running no longer carry, though one keeps its clock and its row there.
1337	#[test]
1338	fn a_picture_a_retired_program_flushed_alone_counts() {
1339		const H264: u8 = 0x1b;
1340		let origin = crate::source::produce_origin();
1341		let mut programs = Programs::new(
1342			origin,
1343			moq_net::Path::from_static("event.hang"),
1344			catalog::Config::default(),
1345		);
1346		let mut mux = Mux::default();
1347		let both = [(1, 0x100), (2, 0x200)];
1348		mux.pat(&both)
1349			.pmt(0x100, 1, 0x50, &[(H264, 0x50)], 0)
1350			.pmt(0x200, 2, 0x50, &[(H264, 0x50)], 0);
1351		let mut pictures =
1352			(0..).map(|n: u8| video_pes(0x50, n & 0x0f, 90_000 + u64::from(n) * 3_000, None, &annexb_au(n == 0)));
1353		mux.out.extend(pictures.next().unwrap());
1354		mux.out.extend(pictures.next().unwrap());
1355		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1356		let units = |programs: &Programs| programs.stats().streams[&0x50].units;
1357		assert_eq!(units(&programs), 1, "the second picture ends at the third");
1358
1359		// Program 2 stops carrying the video, and flushes the second picture as it does.
1360		mux.pmt_at(1, 0x200, 2, 0x50, &[(MP2, 0x61, &[])], 0);
1361		mux.out.extend(pictures.next().unwrap());
1362		mux.out.extend(pictures.next().unwrap());
1363		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1364		assert_eq!(units(&programs), 3, "program 1 delivers the second and third");
1365
1366		mux.pat(&both[1..]);
1367		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1368		assert_eq!(programs.programs.len(), 1);
1369		assert_eq!(units(&programs), 4, "program 1's finish delivers the fourth");
1370	}
1371
1372	/// A PMT section a program began on a PID the PAT then moves it from ends there unread by
1373	/// any program, so a bad CRC on it counts for the programs still waiting on that PID.
1374	#[test]
1375	fn a_section_a_moved_program_left_unfinished_counts() {
1376		let origin = crate::source::produce_origin();
1377		let mut programs = Programs::new(
1378			origin,
1379			moq_net::Path::from_static("event.hang"),
1380			catalog::Config::default(),
1381		);
1382		let mut cc = [0; 2];
1383		let mut data = psi_packets(0, &mut cc[0], &[], &pat_section(&[(1, 0x0100), (2, 0x0100)]));
1384		data.extend(psi_packets(
1385			0x0100,
1386			&mut cc[1],
1387			&[],
1388			&pmt_section(1, 0, &[(MP2, 0x0061, &[])]),
1389		));
1390		let long = corrupt(pmt_section(2, 0, &[(MP2, 0x0062, &[0x80; 200])]));
1391		let long = psi_packets(0x0100, &mut cc[1], &[], &long);
1392		assert_eq!(long.len(), 2 * 188);
1393		data.extend(&long[..188]);
1394		programs.decode(&data).unwrap();
1395		assert_eq!(programs.programs.len(), 1);
1396
1397		let mut data = psi_packets(0, &mut cc[0], &[], &pat_section(&[(1, 0x0200), (2, 0x0100)]));
1398		data.extend(&long[188..]);
1399		programs.decode(&data).unwrap();
1400		assert_eq!(programs.stats().crc_error, 1);
1401	}
1402
1403	/// A retired program's counts stay in the totals, once: a PMT PID it shared with a program
1404	/// still running is that program's to count, and its own PMT PID keeps its count.
1405	#[test]
1406	fn a_retired_program_keeps_what_it_alone_counted() {
1407		let origin = crate::source::produce_origin();
1408		let mut programs = Programs::new(
1409			origin,
1410			moq_net::Path::from_static("event.hang"),
1411			catalog::Config::default(),
1412		);
1413		let pmt = |program: u16| pmt_section(program, 0, &[(MP2, 0x0060 + program, &[])]);
1414		let mut cc = [0; 3];
1415		let listed = pat_section(&[(1, 0x0100), (2, 0x0100), (3, 0x0300)]);
1416		let mut data = psi_packets(0, &mut cc[0], &[], &listed);
1417		let mut shared = pmt(1);
1418		shared.extend(pmt(2));
1419		data.extend(psi_packets(0x0100, &mut cc[1], &[], &shared));
1420		data.extend(psi_packets(0x0300, &mut cc[2], &[], &pmt(3)));
1421		data.extend(psi_packets(0x0100, &mut cc[1], &[], &corrupt(pmt(2))));
1422		data.extend(psi_packets(0x0300, &mut cc[2], &[], &corrupt(pmt(3))));
1423		programs.decode(&data).unwrap();
1424		assert_eq!(programs.programs.len(), 3);
1425		assert_eq!(programs.stats().crc_error, 2);
1426
1427		programs
1428			.decode(&psi_packets(0, &mut cc[0], &[], &pat_section(&[(1, 0x0100)])))
1429			.unwrap();
1430		assert_eq!(programs.programs.len(), 1);
1431		assert_eq!(programs.stats().crc_error, 2, "each dropped section still counts once");
1432	}
1433
1434	/// Programs sharing an elementary PID count its units once, each from its own start, so the
1435	/// earliest reader's count stands, while they all run and as they leave.
1436	#[test]
1437	fn programs_sharing_a_stream_count_it_once() {
1438		let origin = crate::source::produce_origin();
1439		let mut programs = Programs::new(
1440			origin,
1441			moq_net::Path::from_static("event.hang"),
1442			catalog::Config::default(),
1443		);
1444		let all = [(1, 0x100), (2, 0x200), (3, 0x300)];
1445		let mut mux = Mux::default();
1446		// Each PMT arrives a PES after the one before, so each program counts less.
1447		for (cc, &(program, pid)) in (0..).zip(&all) {
1448			mux.pat(&all).pmt(pid, program, 0x61, &[(MP2, 0x61)], 0);
1449			mux.out
1450				.extend(mp2_pes(0x61, cc, 90_000 + u64::from(cc) * 18_000, [0x61; 2]));
1451			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1452		}
1453		assert_eq!(programs.programs.len(), 3);
1454		assert_eq!(programs.stats().streams[&0x61].units, 6);
1455		for listed in [&all[1..], &all[2..]] {
1456			mux.pat(listed);
1457			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1458			assert_eq!(programs.programs.len(), listed.len());
1459			assert_eq!(programs.stats().streams[&0x61].units, 6, "{} running", listed.len());
1460		}
1461	}
1462
1463	/// A PTS outage on a shared PID counts the same whether or not the program timing it retires
1464	/// or drops the PID partway: the program reading on takes over the interval running since
1465	/// the last PTS, which it never saw and which began before its own clock started, rather
1466	/// than timing the PID only from its own next PTS.
1467	#[test]
1468	fn a_pts_outage_counts_on_across_a_handover() {
1469		#[derive(PartialEq)]
1470		enum Leave {
1471			Stay,
1472			Retire,
1473			Drop,
1474		}
1475		let outage = |leave: Leave| {
1476			let origin = crate::source::produce_origin();
1477			let mut programs = Programs::new(
1478				origin,
1479				moq_net::Path::from_static("event.hang"),
1480				catalog::Config::default(),
1481			);
1482			let both = [(1, 0x100), (2, 0x200)];
1483			let mut mux = Mux::default();
1484			mux.pat(&both)
1485				.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0)
1486				.packet(0x1ff, Flags::pcr(27_000_000));
1487			mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1488			// Program 2 starts 0.5 s after the last PTS on the PID they share, and program 1
1489			// leaves before that PTS is late.
1490			for ms in (100..=1_500).step_by(100) {
1491				let left = ms >= 700;
1492				let listed = if left && leave == Leave::Retire {
1493					&both[1..]
1494				} else {
1495					&both[..]
1496				};
1497				mux.pat(listed);
1498				match left && leave == Leave::Drop {
1499					true => mux.pmt_at(1, 0x100, 1, 0x1ff, &[(MP2, 0x62, &[])], 0),
1500					false => mux.pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0),
1501				};
1502				if ms >= 500 {
1503					mux.pmt(0x200, 2, 0x1ff, &[(MP2, 0x61)], 0);
1504				}
1505				mux.packet(0x1ff, Flags::pcr(27_000_000 + ms * MS));
1506				programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1507			}
1508			assert_eq!(programs.programs.len(), if leave == Leave::Retire { 1 } else { 2 });
1509			programs.stats().streams[&0x61].pts_error
1510		};
1511		assert_eq!(outage(Leave::Stay), 2, "the 1.5 s since the PTS");
1512		assert_eq!(outage(Leave::Retire), 2, "counted on by the program left");
1513		assert_eq!(outage(Leave::Drop), 2, "counted on by the program still carrying it");
1514	}
1515
1516	#[tokio::test(start_paused = true)]
1517	async fn a_shared_pts_timer_keeps_its_age_when_clocks_are_sampled_apart() {
1518		let mut programs = Programs::new(
1519			crate::source::produce_origin(),
1520			moq_net::Path::from_static("event.hang"),
1521			catalog::Config::default(),
1522		);
1523		let mut mux = Mux::default();
1524		let both = [(1, 0x100), (2, 0x200)];
1525		mux.pat(&both[..1]).pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0);
1526		mux.packet(0x1ff, Flags::pcr(27_000_000));
1527		mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1528		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1529		tokio::time::advance(std::time::Duration::from_millis(200)).await;
1530		mux.pat(&both).pmt(0x200, 2, 0x1f2, &[(MP2, 0x61)], 0);
1531		mux.packet(0x1f2, Flags::pcr(27_000_000));
1532		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1533		tokio::time::advance(std::time::Duration::from_millis(1)).await;
1534		mux.packet(0x1fff, Flags::default());
1535		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1536		tokio::time::advance(std::time::Duration::from_millis(19)).await;
1537		mux.packet(0x1f2, Flags::pcr(27_000_000 + 20 * MS));
1538		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1539		tokio::time::advance(std::time::Duration::from_millis(30)).await;
1540		mux.pmt_at(1, 0x100, 1, 0x1ff, &[(MP2, 0x62, &[])], 0);
1541		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1542		tokio::time::advance(std::time::Duration::from_millis(450)).await;
1543		mux.packet(0x1fff, Flags::default());
1544		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1545		assert_eq!(programs.stats().pts_error, 0, "exactly 700 ms is on time");
1546		tokio::time::advance(std::time::Duration::from_millis(1)).await;
1547		mux.packet(0x1fff, Flags::default());
1548		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1549		assert_eq!(
1550			programs.stats().pts_error,
1551			1,
1552			"701 ms since the PTS, across the handover"
1553		);
1554	}
1555
1556	#[tokio::test(start_paused = true)]
1557	async fn a_missing_shared_pcr_counts_once_across_a_late_handover() {
1558		let mut programs = Programs::new(
1559			crate::source::produce_origin(),
1560			moq_net::Path::from_static("event.hang"),
1561			catalog::Config::default(),
1562		);
1563		let mut mux = Mux::default();
1564		let both = [(1, 0x100), (2, 0x200)];
1565		mux.pat(&both[..1]).pmt(0x100, 1, 0x1ff, &[(MP2, 0x61)], 0);
1566		mux.packet(0x1ff, Flags::pcr(27_000_000));
1567		mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1568		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1569		tokio::time::advance(std::time::Duration::from_millis(200)).await;
1570		mux.pat(&both).pmt(0x200, 2, 0x1ff, &[(MP2, 0x61)], 0);
1571		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1572		assert_eq!(programs.stats().pcr_repetition_error, 1);
1573		tokio::time::advance(std::time::Duration::from_millis(50)).await;
1574		mux.pat(&both[1..]);
1575		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1576		for _ in 0..3 {
1577			tokio::time::advance(std::time::Duration::from_millis(100)).await;
1578			mux.packet(0x1fff, Flags::default());
1579			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1580			assert_eq!(programs.stats().pcr_repetition_error, 1, "the same outage still runs");
1581		}
1582		// The PTS was seen at t=0. Rebasing against a stale destination clock must
1583		// not turn its exact 700 ms boundary into an early PTS error.
1584		tokio::time::advance(std::time::Duration::from_millis(150)).await;
1585		mux.packet(0x1fff, Flags::default());
1586		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1587		assert_eq!(programs.stats().pts_error, 0);
1588		tokio::time::advance(std::time::Duration::from_millis(1)).await;
1589		mux.packet(0x1fff, Flags::default());
1590		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1591		assert_eq!(programs.stats().pts_error, 1);
1592		let _finished = programs.finish().unwrap();
1593	}
1594
1595	#[tokio::test(start_paused = true)]
1596	async fn a_stalled_owner_cannot_hide_a_shared_pids_outage() {
1597		for shared_clock in [false, true] {
1598			for continuing in [false, true] {
1599				let mut programs = Programs::new(
1600					crate::source::produce_origin(),
1601					moq_net::Path::from_static("event.hang"),
1602					catalog::Config::default(),
1603				);
1604				let mut mux = Mux::default();
1605				let both = [(1, 0x100), (2, 0x200)];
1606				let clocks = [0x1f1, if shared_clock { 0x1f1 } else { 0x1f2 }];
1607				mux.pat(&both);
1608				for ((number, pid), clock) in both.into_iter().zip(clocks) {
1609					mux.pmt(pid, number, clock, &[(MP2, 0x61)], 0);
1610					mux.packet(clock, Flags::pcr(27_000_000));
1611				}
1612				mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1613				programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1614				for i in 1..=10 {
1615					tokio::time::advance(std::time::Duration::from_millis(100)).await;
1616					if continuing {
1617						mux.pat(&both);
1618						for ((number, pid), clock) in both.into_iter().zip(clocks) {
1619							mux.pmt(pid, number, clock, &[(MP2, 0x61)], 0);
1620						}
1621						mux.out
1622							.extend(mp2_pes(0x61, i, 90_000 + u64::from(i) * 9_000, [0x61; 2]));
1623					}
1624					if !shared_clock {
1625						mux.packet(clocks[1], Flags::pcr(27_000_000 + u64::from(i) * 100 * MS));
1626					}
1627					// No program reads this packet: it must still advance every health check.
1628					mux.packet(0x1fff, Flags::default());
1629					programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1630				}
1631				let stats = programs.stats();
1632				assert_eq!(stats.pcr_repetition_error, 1, "{shared_clock} {continuing}: {stats:?}");
1633				assert_eq!(stats.pat_error, u64::from(!continuing), "{stats:?}");
1634				assert_eq!(stats.pmt_error, 2 * u64::from(!continuing), "{stats:?}");
1635				assert_eq!(stats.pts_error, u64::from(!continuing), "{stats:?}");
1636				assert_eq!(stats.streams[&0x61].pts_error, stats.pts_error);
1637				let _finished = programs.finish().unwrap();
1638			}
1639		}
1640	}
1641
1642	/// A section stream refused for want of a PCR keeps its refusal in the totals once, though
1643	/// the PMT that adds it counts it before its program reads the PID, while the programs
1644	/// listing it run and as one leaves.
1645	#[test]
1646	fn a_stream_refused_without_a_pcr_counts_once() {
1647		const SECTIONS: u8 = 0x05;
1648		let origin = crate::source::produce_origin();
1649		let mut programs = Programs::new(
1650			origin,
1651			moq_net::Path::from_static("event.hang"),
1652			catalog::Config::default(),
1653		);
1654		let both = [(1, 0x100), (2, 0x200)];
1655		let mut mux = Mux::default();
1656		for listed in [&both[..], &both[1..]] {
1657			mux.pat(listed);
1658			for (program, pid) in both {
1659				mux.pmt(pid, program, 0x1fff, &[(MP2, 0x61), (SECTIONS, 0x72)], 0);
1660			}
1661			programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1662			assert_eq!(programs.programs.len(), listed.len());
1663			assert_eq!(programs.stats().streams[&0x72].refused, 1, "{} running", listed.len());
1664		}
1665	}
1666
1667	/// A PID one program takes its clock from and a later one carries counts the carrier's
1668	/// units and the clock's PCR checks, each from the program reading it that way.
1669	#[test]
1670	fn a_pid_read_as_a_clock_and_a_stream_counts_both() {
1671		let origin = crate::source::produce_origin();
1672		let mut programs = Programs::new(
1673			origin,
1674			moq_net::Path::from_static("event.hang"),
1675			catalog::Config::default(),
1676		);
1677		let mut mux = Mux::default();
1678		let both = [(1, 0x100), (2, 0x200)];
1679		mux.pat(&both).pmt(0x100, 1, 0x61, &[(MP2, 0x62)], 0);
1680		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1681		mux.pat(&both).pmt(0x200, 2, 0x1f2, &[(MP2, 0x61)], 0);
1682		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1683		assert_eq!(programs.programs.len(), 2);
1684		// PCRs every 50 ms but for a 150 ms gap on 0x61, which breaks the 100 ms bound once, and
1685		// a PES of two frames on each stream every 150 ms.
1686		let mut cc = 0;
1687		for ms in (0..=450).step_by(50) {
1688			let pcr = Flags::pcr(27_000_000 + ms * MS);
1689			if !(200..=250).contains(&ms) {
1690				mux.packet(0x61, pcr);
1691			}
1692			mux.packet(0x1f2, pcr);
1693			if ms % 150 == 0 {
1694				for pid in [0x61, 0x62] {
1695					mux.out.extend(mp2_pes(pid, cc, 90_000 + ms * 90, [pid as u8; 2]));
1696				}
1697				cc += 1;
1698			}
1699		}
1700		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1701		let finished = programs.finish().unwrap();
1702		let programs = &finished.programs;
1703		let stats = programs.stats();
1704		assert_eq!(stats.streams[&0x61].units, 8, "program 2 delivers every frame");
1705		assert_eq!(stats.pcr_repetition_error, 1, "program 1 grades its clock");
1706	}
1707
1708	/// A PMT that drops a shared H.264 PID from the program counting it flushes the picture it
1709	/// held, which the program still carrying the PID delivers itself at the next picture, so
1710	/// the picture counts once.
1711	#[test]
1712	fn a_picture_a_dropped_route_flushed_counts_once() {
1713		const H264: u8 = 0x1b;
1714		let origin = crate::source::produce_origin();
1715		let mut programs = Programs::new(
1716			origin,
1717			moq_net::Path::from_static("event.hang"),
1718			catalog::Config::default(),
1719		);
1720		let mut mux = Mux::default();
1721		mux.pat(&[(1, 0x100), (2, 0x200)])
1722			.pmt(0x100, 1, 0x1f1, &[(H264, 0x50)], 0)
1723			.pmt(0x200, 2, 0x1f2, &[(H264, 0x50)], 0)
1724			.packet(0x1f1, Flags::pcr(27_000_000))
1725			.packet(0x1f2, Flags::pcr(27_000_000));
1726		let mut pictures =
1727			(0..).map(|n: u8| video_pes(0x50, n & 0x0f, 90_000 + u64::from(n) * 3_000, None, &annexb_au(n == 0)));
1728		mux.out.extend(pictures.next().unwrap());
1729		mux.out.extend(pictures.next().unwrap());
1730		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1731		let units = |programs: &Programs| programs.stats().streams[&0x50].units;
1732		assert_eq!(units(&programs), 1, "the second picture ends at the third");
1733
1734		mux.pmt_at(1, 0x100, 1, 0x1f1, &[(MP2, 0x61, &[])], 0);
1735		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1736		assert_eq!(units(&programs), 1, "program 2 still holds the second picture");
1737		programs.decode(&pictures.next().unwrap()).unwrap();
1738		assert_eq!(units(&programs), 2, "the second picture counts once");
1739		let finished = programs.finish().unwrap();
1740		let programs = &finished.programs;
1741		assert_eq!(units(programs), 3);
1742	}
1743
1744	/// One PAT dropping programs on either side of those it keeps rebuilds who reads each PID
1745	/// at once: the programs left read on, their own PIDs and the shared ones alike.
1746	#[test]
1747	fn a_pat_dropping_several_programs_keeps_the_rest_reading() {
1748		let origin = crate::source::produce_origin();
1749		let mut programs = Programs::new(
1750			origin,
1751			moq_net::Path::from_static("event.hang"),
1752			catalog::Config::default(),
1753		);
1754		let mut mux = Mux::default();
1755		let step = |mux: &mut Mux, listed: &[(u16, u16)], cc: u8| {
1756			mux.pat(listed);
1757			for (program, pid) in [(1, 0x100), (2, 0x100), (3, 0x300), (4, 0x100)] {
1758				mux.pmt(pid, program, 0x61, &[(MP2, 0x61), (MP2, 0x70 + program)], 0);
1759			}
1760			for pid in [0x61, 0x71, 0x72, 0x73, 0x74] {
1761				mux.out
1762					.extend(mp2_pes(pid, cc, 90_000 + u64::from(cc) * 18_000, [pid as u8; 2]));
1763			}
1764		};
1765		step(&mut mux, &[(1, 0x100), (2, 0x100), (3, 0x300), (4, 0x100)], 0);
1766		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1767		assert_eq!(programs.programs.len(), 4);
1768		step(&mut mux, &[(2, 0x100), (4, 0x100)], 1);
1769		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1770		let finished = programs.finish().unwrap();
1771		let programs = &finished.programs;
1772		let running: Vec<_> = identities(programs).into_iter().map(|(number, _)| number).collect();
1773		assert_eq!(running, [2, 4]);
1774		let units = |pid| programs.stats().streams[&pid].units;
1775		assert_eq!([0x61, 0x72, 0x74].map(units), [4; 3], "the programs kept read on");
1776		assert_eq!(
1777			[0x71, 0x73].map(units),
1778			[2; 2],
1779			"the dropped programs' frames stay counted"
1780		);
1781	}
1782
1783	/// A program that starts and leaves within one call is announced as it retires, as the
1784	/// same bytes fed in two calls announce it, so the input declared a track.
1785	#[test]
1786	fn a_program_that_starts_and_leaves_in_one_call_is_announced() {
1787		let origin = crate::source::produce_origin();
1788		let mut programs = Programs::new(
1789			origin,
1790			moq_net::Path::from_static("event.hang"),
1791			catalog::Config::default(),
1792		);
1793		let mut mux = Mux::default();
1794		mux.pat(&[(1, 0x100)]).pmt(0x100, 1, 0x61, &[(MP2, 0x61)], 0);
1795		mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1796		mux.pat(&[]);
1797		programs.decode(&mux.out).unwrap();
1798		assert!(programs.programs.is_empty());
1799		let _finished = programs.finish().unwrap();
1800	}
1801
1802	/// A PAT naming another transport stream is refused while a program runs, before it retires
1803	/// one, even when it lists none of them.
1804	#[test]
1805	fn a_pat_naming_another_transport_stream_is_refused() {
1806		let origin = crate::source::produce_origin();
1807		let mut programs = Programs::new(
1808			origin,
1809			moq_net::Path::from_static("event.hang"),
1810			catalog::Config::default(),
1811		);
1812		let mut steps = Steps::new();
1813		steps.step(&mut programs, &[(1, 0x100)]);
1814		steps.mux.pat_in(2, &[(2, 0x200)]);
1815		let err = programs.decode(&std::mem::take(&mut steps.mux.out)).unwrap_err();
1816		assert!(
1817			matches!(&err, Error::Unsupported(msg) if msg.contains("transport_stream_id")),
1818			"{err}"
1819		);
1820		assert_eq!(programs.programs.len(), 1, "a refused PAT retires nothing");
1821	}
1822
1823	/// A dropped program that cannot finish refuses the multiplex, as at the end of the input,
1824	/// and stays listed for the abort that follows, so its subscribers see the cause.
1825	#[tokio::test(start_paused = true)]
1826	async fn a_retired_program_that_cannot_finish_refuses_the_multiplex() {
1827		let origin = crate::source::produce_origin();
1828		let mut programs = Programs::new(
1829			origin,
1830			moq_net::Path::from_static("event.hang"),
1831			catalog::Config::default(),
1832		);
1833		// Program 2 carries a clock on 0x71 and SCTE-35 on 0x72, and no PTS to place a cue by.
1834		let mut cuei = vec![0xe0, 0x71, 0xf0, 6, 0x05, 4];
1835		cuei.extend_from_slice(b"CUEI");
1836		cuei.extend_from_slice(&[0x02, 0xe0, 0x71, 0xf0, 0, 0x86, 0xe0, 0x72, 0xf0, 0]);
1837		let mut mux = Mux::default();
1838		mux.pat(&[(1, 0x100), (2, 0x200)])
1839			.pmt(0x100, 1, 0x61, &[(MP2, 0x61)], 0)
1840			.section(0x200, &psi::section(psi::PMT_TABLE_ID, 2, 0, 0, 0, &cuei))
1841			.packet(0x71, Flags::pcr(27_000_000))
1842			.section(0x72, &CUE);
1843		mux.out.extend(mp2_pes(0x61, 0, 90_000, [0x61; 2]));
1844		programs.decode(&std::mem::take(&mut mux.out)).unwrap();
1845		assert_eq!(programs.programs.len(), 2);
1846		let mut catalog = programs.programs[1].catalog.consume().unwrap();
1847
1848		mux.pat(&[(1, 0x100)]);
1849		let err = programs.decode(&std::mem::take(&mut mux.out)).unwrap_err();
1850		assert!(
1851			matches!(&err, Error::Malformed(msg) if msg.contains("without a media timestamp")),
1852			"{err}"
1853		);
1854		programs.abort(moq_net::Error::Transport("decode failed".into()));
1855		let err = loop {
1856			match catalog.next().await {
1857				Ok(Some(_)) => {}
1858				other => break other.unwrap_err(),
1859			}
1860		};
1861		assert!(matches!(err, crate::Error::Moq(moq_net::Error::Transport(ref reason)) if reason == "decode failed"));
1862	}
1863
1864	#[tokio::test(start_paused = true)]
1865	async fn internal_program_abort_preserves_the_catalog_error() {
1866		let origin = crate::source::produce_origin();
1867		let mut programs = Programs::new(
1868			origin,
1869			moq_net::Path::from_static("event.hang"),
1870			catalog::Config::default(),
1871		);
1872		programs.decode(&two_programs()).unwrap();
1873		let mut consumers: Vec<_> = programs.programs.iter().map(|p| p.catalog.consume().unwrap()).collect();
1874		programs.abort(moq_net::Error::Transport("decode failed".into()));
1875		for consumer in &mut consumers {
1876			let err = loop {
1877				match consumer.next().await {
1878					Ok(Some(_)) => {}
1879					other => break other.unwrap_err(),
1880				}
1881			};
1882			assert!(
1883				matches!(err, crate::Error::Moq(moq_net::Error::Transport(ref reason)) if reason == "decode failed")
1884			);
1885		}
1886	}
1887
1888	#[test]
1889	fn program_broadcasts_keep_the_catalog_suffix_last() {
1890		assert_eq!(program_broadcast("event.hang", 2), "event/2.hang");
1891		assert_eq!(program_broadcast("demo/event.msf", 7), "demo/event/7.msf");
1892		assert_eq!(program_broadcast("event", 1), "event/1");
1893		assert_eq!(program_broadcast("", 1), "1");
1894		assert_eq!(program_broadcast(".hang", 2), "2.hang");
1895		assert_eq!(program_broadcast("room/.msf", 2), "room/2.msf");
1896	}
1897
1898	/// The first whole PAT in a buffer, as the parser reads it.
1899	fn pat_programs(data: &[u8]) -> Option<Vec<u16>> {
1900		let mut demux = Demux::new(false);
1901		demux.push(data);
1902		while let Some(packet) = demux.next() {
1903			if let Some(pat) = packet.pat {
1904				return Some(pat.programs.iter().map(|entry| entry.program_number).collect());
1905			}
1906		}
1907		None
1908	}
1909
1910	#[test]
1911	fn pat_programs_reads_the_first_whole_pat() {
1912		let data = two_programs();
1913		assert_eq!(pat_programs(&data), Some(vec![1, 2]));
1914		// A sync byte in leading junk is skipped; a truncated PAT is not a PAT yet.
1915		let mut shifted = vec![0x47, 0x40, 0x00, 0x10];
1916		shifted.extend_from_slice(&data);
1917		assert_eq!(pat_programs(&shifted), Some(vec![1, 2]));
1918		assert_eq!(pat_programs(&data[..100]), None);
1919	}
1920
1921	/// A PAT too big for one packet is read whole, so the program listed in its second packet
1922	/// publishes, and the forty-nine without a PMT start nothing.
1923	#[tokio::test]
1924	async fn a_pat_spanning_two_packets_is_read_whole() {
1925		let origin = crate::source::produce_origin();
1926		let mut programs = Programs::new(
1927			origin.clone(),
1928			moq_net::Path::from_static("event.hang"),
1929			catalog::Config::default(),
1930		);
1931		let input = fifty_programs();
1932		for chunk in input.chunks(100) {
1933			programs.decode(chunk).unwrap();
1934		}
1935		let finished = programs.finish().unwrap();
1936		let programs = &finished.programs;
1937		assert_eq!(programs.programs.len(), 1, "only program 50 has a PMT");
1938
1939		let consumer = origin.consume().request("event/50.hang", None).await.unwrap();
1940		let catalog = hang::catalog::Catalog::<()>::subscribe(&consumer)
1941			.await
1942			.unwrap()
1943			.next()
1944			.await
1945			.unwrap()
1946			.expect("a catalog")
1947			.value;
1948		assert_eq!(catalog.audio.renditions.len(), 1, "program 50 publishes its stream");
1949	}
1950
1951	/// A corrupt PAT is counted and ignored; the good repetition after it is read without
1952	/// counting again.
1953	#[test]
1954	fn a_corrupt_pat_starts_no_program() {
1955		let origin = crate::source::produce_origin();
1956		let mut programs = Programs::new(
1957			origin,
1958			moq_net::Path::from_static("event.hang"),
1959			catalog::Config::default(),
1960		);
1961		// A null packet after each PAT confirms its sync byte.
1962		let mut null = vec![0x47, 0x1f, 0xff, 0x10];
1963		null.resize(188, 0xff);
1964		let mut cc = 0;
1965		let mut data = psi_packets(0, &mut cc, &[], &corrupt(pat_section(&[(1, 0x0100)])));
1966		data.extend_from_slice(&null);
1967		programs.decode(&data).unwrap();
1968		assert!(programs.pat.is_none());
1969		assert_eq!(programs.stats().crc_error, 1);
1970
1971		let mut data = psi_packets(0, &mut cc, &[], &pat_section(&[(1, 0x0100)]));
1972		data.extend_from_slice(&null);
1973		programs.decode(&data).unwrap();
1974		assert!(programs.pat.is_some());
1975		assert_eq!(programs.stats().crc_error, 1);
1976	}
1977
1978	/// How many audio renditions the catalog `path` publishes lists.
1979	async fn renditions(origin: &moq_net::origin::Producer, path: &str) -> usize {
1980		let consumer = origin.consume().request(path, None).await.unwrap();
1981		let catalog = hang::catalog::Catalog::<()>::subscribe(&consumer)
1982			.await
1983			.unwrap()
1984			.next()
1985			.await
1986			.unwrap()
1987			.expect("a catalog")
1988			.value;
1989		catalog.audio.renditions.len()
1990	}
1991
1992	/// A PAT in two sections starts both programs, each handed the whole table
1993	/// rather than only the section that completed it.
1994	#[tokio::test]
1995	async fn a_pat_in_two_sections_starts_every_program() {
1996		let origin = crate::source::produce_origin();
1997		let mut programs = Programs::new(
1998			origin.clone(),
1999			moq_net::Path::from_static("event.hang"),
2000			catalog::Config::default(),
2001		);
2002		programs.decode(&two_section_pat()).unwrap();
2003		let finished = programs.finish().unwrap();
2004		let programs = &finished.programs;
2005		assert_eq!(programs.programs.len(), 2);
2006		assert_eq!(renditions(&origin, "event/1.hang").await, 1);
2007		assert_eq!(renditions(&origin, "event/2.hang").await, 1);
2008	}
2009
2010	/// A PAT naming a thousand programs starts only the two whose PMTs the input carries, even
2011	/// where an undescribed program shares a described one's PMT PID.
2012	#[tokio::test]
2013	async fn only_programs_a_pmt_describes_publish() {
2014		let origin = crate::source::produce_origin();
2015		let mut programs = Programs::new(
2016			origin.clone(),
2017			moq_net::Path::from_static("event.hang"),
2018			catalog::Config::default(),
2019		);
2020		// Pairs of programs share a PMT PID, so 6 waits on the PID that starts 7.
2021		let pmt_pid = |program: u16| 0x0100 + program / 2;
2022		let mut cc = 0;
2023		let mut data = Vec::new();
2024		for section in 0..4u8 {
2025			let entries: Vec<u8> = (1..=250)
2026				.map(|n| u16::from(section) * 250 + n)
2027				.flat_map(|n| {
2028					let pid = pmt_pid(n);
2029					[(n >> 8) as u8, n as u8, 0xe0 | (pid >> 8) as u8, pid as u8]
2030				})
2031				.collect();
2032			data.extend(psi_packets(
2033				0,
2034				&mut cc,
2035				&[],
2036				&psi::section(0x00, 1, 0, section, 3, &entries),
2037			));
2038		}
2039		for (program, pid, fills) in [(7u16, 0x0061, [0xAA, 0xBB]), (900, 0x0071, [0xCC, 0xDD])] {
2040			let pmt = pmt_section(program, 0, &[(MP2, pid, &[])]);
2041			data.extend(psi_packets(pmt_pid(program), &mut 0, &[], &pmt));
2042			data.extend(mp2_pes(pid, 0, 90_000, fills));
2043		}
2044		programs.decode(&data).unwrap();
2045		let finished = programs.finish().unwrap();
2046		let programs = &finished.programs;
2047
2048		let started: Vec<_> = programs.programs.iter().map(|program| program.number).collect();
2049		assert_eq!(started, [7, 900]);
2050		assert_eq!(renditions(&origin, "event/7.hang").await, 1);
2051		assert_eq!(renditions(&origin, "event/900.hang").await, 1);
2052	}
2053
2054	/// A later PAT moves a waiting program to its new PMT PID and drops one it no longer lists,
2055	/// so neither the stale PMT nor the dropped program's PMT starts anything.
2056	#[tokio::test]
2057	async fn a_later_pat_revises_the_waiting_programs() {
2058		let origin = crate::source::produce_origin();
2059		let mut programs = Programs::new(
2060			origin.clone(),
2061			moq_net::Path::from_static("event.hang"),
2062			catalog::Config::default(),
2063		);
2064		let mut cc = 0;
2065		let mut data = psi_packets(0, &mut cc, &[], &pat_section(&[(1, 0x0100), (2, 0x0101)]));
2066		let revised = psi::section(0x00, 1, 1, 0, 0, &[0x00, 0x01, 0xe2, 0x00]);
2067		data.extend(psi_packets(0, &mut cc, &[], &revised));
2068		for (pid, program, version, es) in [(0x0100, 1, 0, 0x0062), (0x0101, 2, 0, 0x0071), (0x0200, 1, 1, 0x0061)] {
2069			data.extend(psi_packets(
2070				pid,
2071				&mut 0,
2072				&[],
2073				&pmt_section(program, version, &[(MP2, es, &[])]),
2074			));
2075		}
2076		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
2077		programs.decode(&data).unwrap();
2078		let finished = programs.finish().unwrap();
2079		let programs = &finished.programs;
2080
2081		let started: Vec<_> = programs.programs.iter().map(|program| program.number).collect();
2082		assert_eq!(started, [1]);
2083		assert_eq!(renditions(&origin, "event/1.hang").await, 1);
2084	}
2085
2086	/// Of two revisions of a PMT in one packet, the program starts on the later.
2087	#[tokio::test]
2088	async fn a_program_starts_on_the_last_pmt_in_its_packet() {
2089		let origin = crate::source::produce_origin();
2090		let mut programs = Programs::new(
2091			origin.clone(),
2092			moq_net::Path::from_static("event.hang"),
2093			catalog::Config::default(),
2094		);
2095		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100)]));
2096		let mut sections = pmt_section(1, 0, &[(MP2, 0x0062, &[])]);
2097		sections.extend(pmt_section(1, 1, &[(MP2, 0x0061, &[])]));
2098		data.extend(psi_packets(0x0100, &mut 0, &[], &sections));
2099		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
2100		programs.decode(&data).unwrap();
2101		let _finished = programs.finish().unwrap();
2102		assert_eq!(renditions(&origin, "event/1.hang").await, 1);
2103	}
2104
2105	/// A PMT spanning two packets starts its program, which carries on from the first packet
2106	/// rather than reading the second alone.
2107	#[tokio::test]
2108	async fn a_pmt_spanning_two_packets_starts_its_program() {
2109		let origin = crate::source::produce_origin();
2110		let mut programs = Programs::new(
2111			origin.clone(),
2112			moq_net::Path::from_static("event.hang"),
2113			catalog::Config::default(),
2114		);
2115		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100)]));
2116		let mut private = vec![0x80, 200];
2117		private.resize(202, 0);
2118		let packets = psi_packets(0x0100, &mut 0, &[], &pmt_section(1, 0, &[(MP2, 0x0061, &private)]));
2119		assert_eq!(packets.len(), 2 * 188, "the PMT spans two packets");
2120		data.extend(packets);
2121		data.extend(mp2_pes(0x0061, 0, 90_000, [0xAA, 0xBB]));
2122		programs.decode(&data).unwrap();
2123		let _finished = programs.finish().unwrap();
2124		assert_eq!(renditions(&origin, "event/1.hang").await, 1);
2125	}
2126
2127	/// A corrupt PMT counts once whether it arrives before any program reads its PID, in the
2128	/// packet that starts one, while one program reads it beside a waiting one, or while both
2129	/// do, including after a PAT moves a started program onto a waiting one's PID.
2130	#[test]
2131	fn a_corrupt_pmt_counts_once_whoever_reads_it() {
2132		let origin = crate::source::produce_origin();
2133		let mut programs = Programs::new(
2134			origin,
2135			moq_net::Path::from_static("event.hang"),
2136			catalog::Config::default(),
2137		);
2138		let mut null = vec![0x47, 0x1f, 0xff, 0x10];
2139		null.resize(188, 0xff);
2140		let pmt = |program| pmt_section(program, 0, &[(MP2, 0x0060 + program, &[])]);
2141		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100), (2, 0x0100)]));
2142		let mut cc = 0;
2143		let mut starting = corrupt(pmt(1));
2144		starting.extend(pmt(1));
2145		for section in [corrupt(pmt(1)), starting, corrupt(pmt(2)), pmt(2), corrupt(pmt(1))] {
2146			data.extend(psi_packets(0x0100, &mut cc, &[], &section));
2147		}
2148		data.extend_from_slice(&null);
2149		programs.decode(&data).unwrap();
2150		assert_eq!(programs.programs.len(), 2);
2151		assert_eq!(programs.stats().crc_error, 4);
2152
2153		let origin = crate::source::produce_origin();
2154		let mut programs = Programs::new(
2155			origin,
2156			moq_net::Path::from_static("event.hang"),
2157			catalog::Config::default(),
2158		);
2159		let mut cc = 0;
2160		let mut data = psi_packets(0, &mut cc, &[], &pat_section(&[(1, 0x0100), (2, 0x0200)]));
2161		data.extend(psi_packets(0x0100, &mut 0, &[], &pmt(1)));
2162		let moved = [0x00, 0x01, 0xe2, 0x00, 0x00, 0x02, 0xe2, 0x00];
2163		data.extend(psi_packets(0, &mut cc, &[], &psi::section(0x00, 1, 1, 0, 0, &moved)));
2164		data.extend(psi_packets(0x0200, &mut 0, &[], &corrupt(pmt(2))));
2165		programs.decode(&data).unwrap();
2166		assert_eq!(programs.programs.len(), 1);
2167		assert_eq!(programs.stats().crc_error, 1);
2168
2169		// The same move landing while the corrupt section is partway in: the program it moved
2170		// never saw that section begin, so the scan counts it.
2171		let origin = crate::source::produce_origin();
2172		let mut programs = Programs::new(
2173			origin,
2174			moq_net::Path::from_static("event.hang"),
2175			catalog::Config::default(),
2176		);
2177		let mut cc = 0;
2178		let mut data = psi_packets(0, &mut cc, &[], &pat_section(&[(1, 0x0100), (2, 0x0200)]));
2179		data.extend(psi_packets(0x0100, &mut 0, &[], &pmt(1)));
2180		let mut private = vec![0x80, 200];
2181		private.resize(202, 0);
2182		let split = psi_packets(
2183			0x0200,
2184			&mut 0,
2185			&[],
2186			&corrupt(pmt_section(2, 0, &[(MP2, 0x0071, &private)])),
2187		);
2188		assert_eq!(split.len(), 2 * 188, "the corrupt PMT spans two packets");
2189		data.extend_from_slice(&split[..188]);
2190		data.extend(psi_packets(0, &mut cc, &[], &psi::section(0x00, 1, 1, 0, 0, &moved)));
2191		data.extend_from_slice(&split[188..]);
2192		programs.decode(&data).unwrap();
2193		assert_eq!(programs.stats().crc_error, 1);
2194
2195		// After that move, a section start abandons the partial for another split corrupt
2196		// section, which the moved program reads from its start, so it alone counts it.
2197		let origin = crate::source::produce_origin();
2198		let mut programs = Programs::new(
2199			origin,
2200			moq_net::Path::from_static("event.hang"),
2201			catalog::Config::default(),
2202		);
2203		let mut cc = 0;
2204		let mut data = psi_packets(0, &mut cc, &[], &pat_section(&[(1, 0x0100), (2, 0x0200)]));
2205		data.extend(psi_packets(0x0100, &mut 0, &[], &pmt(1)));
2206		data.extend_from_slice(&split[..188]);
2207		data.extend(psi_packets(0, &mut cc, &[], &psi::section(0x00, 1, 1, 0, 0, &moved)));
2208		data.extend(psi_packets(
2209			0x0200,
2210			&mut 1,
2211			&[],
2212			&corrupt(pmt_section(2, 0, &[(MP2, 0x0071, &private)])),
2213		));
2214		programs.decode(&data).unwrap();
2215		assert_eq!(programs.stats().crc_error, 1);
2216
2217		// A corrupt section begun in the packet that starts a program sharing the PID: the new
2218		// program reads that packet, so it alone counts the section.
2219		let origin = crate::source::produce_origin();
2220		let mut programs = Programs::new(
2221			origin,
2222			moq_net::Path::from_static("event.hang"),
2223			catalog::Config::default(),
2224		);
2225		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100), (2, 0x0100)]));
2226		let mut sections = pmt(1);
2227		sections.extend(corrupt(pmt_section(2, 0, &[(MP2, 0x0071, &private)])));
2228		data.extend(psi_packets(0x0100, &mut 0, &[], &sections));
2229		programs.decode(&data).unwrap();
2230		assert_eq!(programs.programs.len(), 1);
2231		assert_eq!(programs.stats().crc_error, 1);
2232
2233		// A waiting program's PMT PID that a started program reads only as media: no program
2234		// reassembles PMTs there, so the scan counts the corrupt section, before the started
2235		// program ends on reading a section as a PES header.
2236		let origin = crate::source::produce_origin();
2237		let mut programs = Programs::new(
2238			origin,
2239			moq_net::Path::from_static("event.hang"),
2240			catalog::Config::default(),
2241		);
2242		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100), (2, 0x0061)]));
2243		data.extend(psi_packets(0x0100, &mut 0, &[], &pmt(1)));
2244		data.extend(psi_packets(0x0061, &mut 0, &[], &corrupt(pmt(2))));
2245		let err = programs.decode(&data).expect_err("a section is no PES");
2246		assert!(err.to_string().contains("PES header on PID 97"), "{err}");
2247		assert_eq!(programs.programs.len(), 1);
2248		assert_eq!(programs.stats().crc_error, 1);
2249	}
2250
2251	/// Each program announces as its own publisher identity for the run, so a restart
2252	/// replaces it rather than resuming into it.
2253	#[test]
2254	fn every_program_names_its_own_identity() {
2255		let origin = crate::source::produce_origin();
2256		let mut programs = Programs::new(
2257			origin,
2258			moq_net::Path::from_static("event.hang"),
2259			catalog::Config::default(),
2260		);
2261		programs.decode(&two_section_pat()).unwrap();
2262		let finished = programs.finish().unwrap();
2263		let programs = &finished.programs;
2264		assert!(
2265			programs.programs.iter().all(|program| program.route.is_announced()),
2266			"every program announces"
2267		);
2268		let identities: Vec<_> = programs
2269			.programs
2270			.iter()
2271			.map(|program| program.route.identity())
2272			.collect();
2273		assert_eq!(identities.len(), 2);
2274		assert_ne!(identities[0], identities[1]);
2275	}
2276
2277	/// A program is announced only once its catalog lists its tracks, never on the PAT alone,
2278	/// so a relay that queries it the moment it is announced finds them.
2279	#[test]
2280	fn a_program_announces_once_it_declares_its_tracks() {
2281		let origin = crate::source::produce_origin();
2282		let mut programs = Programs::new(
2283			origin,
2284			moq_net::Path::from_static("event.hang"),
2285			catalog::Config::default(),
2286		);
2287		let input = two_programs();
2288		let mut packets = input.chunks(188);
2289		while programs.programs.is_empty() {
2290			programs
2291				.decode(packets.next().expect("a PMT starts a program"))
2292				.unwrap();
2293		}
2294		assert!(
2295			programs.programs.iter().all(|program| !program.route.is_announced()),
2296			"announced on the PSI alone"
2297		);
2298		for packet in packets {
2299			programs.decode(packet).unwrap();
2300		}
2301		let finished = programs.finish().unwrap();
2302		let programs = &finished.programs;
2303		assert!(
2304			programs.programs.iter().all(|program| program.route.is_announced()),
2305			"every program is announced once it has declared its tracks"
2306		);
2307	}
2308
2309	/// Input that ends before any PAT fails rather than exiting cleanly with nothing announced.
2310	#[test]
2311	fn input_ending_before_a_pat_fails() {
2312		let origin = crate::source::produce_origin();
2313		let mut programs = Programs::new(
2314			origin,
2315			moq_net::Path::from_static("event.hang"),
2316			catalog::Config::default(),
2317		);
2318		let mut null = vec![0x47, 0x1f, 0xff, 0x10];
2319		null.resize(188, 0xff);
2320		programs.decode(&null).unwrap();
2321		let Err(err) = programs.finish() else { panic!("no PAT") };
2322		assert!(matches!(err, Error::Empty("its PAT listed a program")), "{err}");
2323	}
2324
2325	/// PAT and PMT metadata can name elementary streams before their codec config is known. EOF
2326	/// there must fail without making an empty program discoverable.
2327	#[test]
2328	fn input_ending_after_pmts_but_before_media_fails_unannounced() {
2329		let origin = crate::source::produce_origin();
2330		let mut programs = Programs::new(
2331			origin,
2332			moq_net::Path::from_static("event.hang"),
2333			catalog::Config::default(),
2334		);
2335		let input = two_programs();
2336		programs.decode(&input[..3 * 188]).unwrap();
2337
2338		// The finish's own steps, so the programs can be inspected after the failure.
2339		let Err(err) = programs.end() else {
2340			panic!("the PMTs have no configured media")
2341		};
2342		assert!(matches!(err, Error::Empty("any program declared a track")), "{err}");
2343		assert!(
2344			programs.programs.iter().all(|program| !program.route.is_announced()),
2345			"no empty program is announced"
2346		);
2347	}
2348
2349	/// A partial PAT holds only itself, not the multiplex that follows it.
2350	#[test]
2351	fn a_partial_pat_does_not_hold_the_multiplex() {
2352		let origin = crate::source::produce_origin();
2353		let mut programs = Programs::new(
2354			origin,
2355			moq_net::Path::from_static("event.hang"),
2356			catalog::Config::default(),
2357		);
2358		programs.decode(&fifty_programs()[..188]).unwrap();
2359		let mut null = vec![0x47, 0x1f, 0xff, 0x10];
2360		null.resize(188, 0xff);
2361		for _ in 0..1000 {
2362			programs.decode(&null).unwrap();
2363		}
2364		assert!(programs.programs.is_empty());
2365		assert!(programs.demux.held() < 188, "held {} bytes", programs.demux.held());
2366	}
2367
2368	/// A corrupt PAT section sharing a packet with the good one that starts the programs is
2369	/// counted once.
2370	#[test]
2371	fn a_corrupt_pat_beside_a_good_one_counts_once() {
2372		let origin = crate::source::produce_origin();
2373		let mut programs = Programs::new(
2374			origin,
2375			moq_net::Path::from_static("event.hang"),
2376			catalog::Config::default(),
2377		);
2378		let mut sections = corrupt(pat_section(&[(1, 0x0100)]));
2379		sections.extend(pat_section(&[(1, 0x0100)]));
2380		let mut data = psi_packets(0, &mut 0, &[], &sections);
2381		let mut null = vec![0x47, 0x1f, 0xff, 0x10];
2382		null.resize(188, 0xff);
2383		data.extend_from_slice(&null);
2384		programs.decode(&data).unwrap();
2385		assert!(programs.pat.is_some());
2386		assert_eq!(programs.stats().crc_error, 1);
2387	}
2388
2389	/// A second program claiming an elementary PID another already reads keeps the PID's
2390	/// continuity chain, so a counter gap right after its PMT still counts.
2391	#[test]
2392	fn a_shared_pid_keeps_its_chain_when_another_program_claims_it() {
2393		const MP2: u8 = 0x03;
2394		let es = |cc: u8| {
2395			let mut pkt = vec![0x47, 0x00, 0x61, 0x10 | cc];
2396			pkt.resize(188, 0xff);
2397			pkt
2398		};
2399		let origin = crate::source::produce_origin();
2400		let mut programs = Programs::new(
2401			origin,
2402			moq_net::Path::from_static("event.hang"),
2403			catalog::Config::default(),
2404		);
2405		let pmt = |program: u16| {
2406			psi_packets(
2407				program << 8,
2408				&mut 0,
2409				&[],
2410				&pmt_section(program, 0, &[(MP2, 0x0061, &[])]),
2411			)
2412		};
2413		let mut data = psi_packets(0, &mut 0, &[], &pat_section(&[(1, 0x0100), (2, 0x0200)]));
2414		data.extend(pmt(1));
2415		data.extend(es(0));
2416		data.extend(pmt(2));
2417		data.extend(es(2));
2418		programs.decode(&data).unwrap();
2419		assert_eq!(programs.stats().continuity_count_error, 1);
2420	}
2421
2422	/// The input is held until the PAT is whole, then each program publishes as its own
2423	/// broadcast carrying only that program, its catalog clock anchored on its own first frame
2424	/// apart on one shared clock.
2425	#[tokio::test]
2426	async fn every_program_publishes_its_own_broadcast() {
2427		let origin = crate::source::produce_origin();
2428		let mut programs = Programs::new(
2429			origin.clone(),
2430			moq_net::Path::from_static("event.hang"),
2431			catalog::Config::default(),
2432		);
2433
2434		let input = two_programs();
2435		let before = kio::clock::wall();
2436		programs.decode(&input[..100]).unwrap();
2437		assert!(
2438			programs.programs.is_empty(),
2439			"no program is known before the PAT is whole"
2440		);
2441		programs.decode(&input[100..]).unwrap();
2442		let _finished = programs.finish().unwrap();
2443		let after = kio::clock::wall();
2444
2445		for (path, fills) in [("event/1.hang", [0xAA, 0xBB]), ("event/2.hang", [0xCC, 0xDD])] {
2446			let consumer = origin.consume().request(path, None).await.unwrap();
2447			let catalog = hang::catalog::Catalog::<()>::subscribe(&consumer)
2448				.await
2449				.unwrap()
2450				.next()
2451				.await
2452				.unwrap()
2453				.expect("a catalog")
2454				.value;
2455			let renditions: Vec<_> = catalog.audio.renditions.iter().collect();
2456			assert_eq!(renditions.len(), 1, "{path} carries its own program's one stream");
2457			let (name, config) = renditions[0];
2458			let track = consumer.track(name).unwrap().subscribe(None).await.unwrap();
2459			let container = Wire::try_from(config).unwrap();
2460			let frame = Consumer::new(track, container)
2461				.read_frame()
2462				.await
2463				.unwrap()
2464				.expect("a frame");
2465			assert!(fills.contains(&frame.payload[4]), "{path} carries only its own program");
2466			let skew = Duration::from_secs(2);
2467			let wall = catalog
2468				.sync
2469				.clock
2470				.expect("the catalog advertises a clock")
2471				.wall_clock(frame.timestamp)
2472				.unwrap();
2473			assert!(
2474				before - skew <= wall && wall <= after + skew,
2475				"{path} is live on arrival: {wall:?} not in {before:?}..={after:?}"
2476			);
2477		}
2478	}
2479}