Skip to main content

moq_mux/container/ts/
step.rs

1//! Whether the source's clock stepped onto another timeline, or its PAT named another
2//! program, either of which ends the import's identity.
3//!
4//! A contribution switched between two encoders whose clocks were never locked steps every
5//! timestamp at once without `discontinuity_indicator`. Splicing the two would put two sources
6//! on one timeline, and a step back would break the rule that group starts never go
7//! backwards within an identity, so the import ends its identity at the step and hands the
8//! input from there to a caller that republishes it under a new identity.
9//!
10//! The step is judged the way ffmpeg infers an unflagged one: the program clock and every
11//! elementary stream that keeps a timestamp cadence step together, forward by more than
12//! [`LEAP`] or back by any amount short of the 33-bit wrap. TR 101 290's 100 ms bound would
13//! read SRT loss as a step. One clock stepping alone, such as a corrupt PCR or a stream whose
14//! PTS jumps, is not a new source and is left to the import. After a flagged break, the
15//! streams stepping back is a rewind; one stepping forward splices as before.
16//!
17//! A PAT naming another `transport_stream_id` or program number is another source too, even
18//! when it arrives before the new source's first clock reading. The new identity reads from
19//! the packet that completes that PAT, so one spanning packets is read at its next repetition.
20
21use std::collections::{HashMap, HashSet};
22use std::time::Duration;
23
24use bytes::Bytes;
25use mpeg2ts::ts::{Pid, TsPacket};
26
27use super::demux::Demux;
28use super::error::Result;
29use super::health::{Continuation, Continuity, Delta, PTS_LIMIT};
30use super::import::{Framer, Payload, STAGING_BYTES_MAX, adaptation_valid, discontinuity_indicator, payload, pcr};
31use super::mux_rate::PCR_WRAP;
32use super::passthrough::PCR_HZ;
33use super::psi::{Pat, PesStart};
34
35/// A forward step beyond this is another timeline: ffmpeg's `dts_delta_threshold`.
36pub(super) const LEAP: Duration = Duration::from_secs(10);
37const PTS_HZ: u64 = 90_000;
38const PTS_WRAP: u64 = 1 << 33;
39
40/// The source's clock stepped onto another timeline, or its PAT named another program, so the
41/// [`Import`](super::Import) ended its identity there.
42///
43/// Only [`Republish`](super::Republish) sees it, and reads [`remainder`](Self::remainder) into a
44/// new identity on the same path; a raw import fails with [`Error::Restarted`](super::Error::Restarted).
45#[derive(Clone, Debug)]
46pub(super) struct Restart {
47	/// How the source changed.
48	pub step: Step,
49	/// The input from the step on, which this import did not read.
50	pub remainder: Bytes,
51}
52
53/// How the source changed, ending an import's identity.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum Step {
57	/// Back by `by`, after a `discontinuity_indicator` when `flagged`.
58	Rewind {
59		/// How far back.
60		by: Duration,
61		/// Whether the clock PID flagged the break.
62		flagged: bool,
63	},
64	/// Forward by `by`, more than 10 s, without a `discontinuity_indicator`.
65	Leap {
66		/// How far forward.
67		by: Duration,
68	},
69	/// The PAT named another `transport_stream_id` or program number for the imported program.
70	Identity {
71		/// The new `transport_stream_id`.
72		transport_stream_id: u16,
73		/// The new program number.
74		program_number: u16,
75	},
76}
77
78impl std::fmt::Display for Step {
79	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80		match self {
81			Self::Rewind { by, flagged: true } => write!(f, "clock went back {by:?} after a flagged break"),
82			Self::Rewind { by, flagged: false } => {
83				write!(f, "clock went back {by:?} without a discontinuity_indicator")
84			}
85			Self::Leap { by } => write!(f, "clock jumped forward {by:?} without a discontinuity_indicator"),
86			Self::Identity {
87				transport_stream_id,
88				program_number,
89			} => write!(
90				f,
91				"PAT named transport_stream_id {transport_stream_id} program {program_number}"
92			),
93		}
94	}
95}
96
97/// What the import routes: which packets carry the clocks being watched.
98pub(super) struct Routes<'a> {
99	/// The PID the PMT names for the program clock.
100	pub pcr_pid: Option<u16>,
101	/// Whether a PID routes to an elementary stream whose PES are timestamped.
102	pub timed: &'a dyn Fn(u16) -> bool,
103	/// The program clock: PCR ticks summed since the first, as [`Import::now`](super::Import::now).
104	pub now: Option<u64>,
105	/// The identity a whole PAT names for the program, when it is not the one being read.
106	pub switched: &'a dyn Fn(&Pat) -> Option<Step>,
107}
108
109/// What to do with the next packet.
110pub(super) enum Verdict {
111	/// Route it.
112	Route,
113	/// Route nothing yet: a step is being judged on input still to come.
114	Hold,
115	/// The clock stepped at it: end the identity there.
116	Restart(Step),
117}
118
119/// Watches the program clock and each timed PID, holding the input while a step is judged.
120#[derive(Default)]
121pub(super) struct Steps {
122	/// The clock PID, and the last PCR routed on it.
123	clock: Option<(u16, Option<u64>)>,
124	/// Each timed PID's last DTS, or PTS without one, as routed.
125	pids: HashMap<u16, Seen>,
126	/// Packets before this input offset were judged already, so they route without a lookahead.
127	cleared: u64,
128	/// The step being judged, from the next packet to route on.
129	ahead: Option<Ahead>,
130	/// The PES headers begun on the timed PIDs, as routed.
131	headers: Headers,
132}
133
134/// A PID's last timestamp.
135#[derive(Clone, Copy)]
136struct Seen {
137	/// Raw 90 kHz.
138	ticks: u64,
139	/// The program clock when it was routed.
140	at: Option<u64>,
141}
142
143/// Which way a clock stepped.
144#[derive(Clone, Copy, PartialEq, Eq)]
145enum Way {
146	Back,
147	Leap,
148}
149
150/// One clock reading against the last.
151#[derive(Clone, Copy)]
152enum Reading {
153	Inline,
154	Stepped(Way, Duration),
155}
156
157impl Reading {
158	fn new(last: u64, value: u64, wrap: u64, hz: u64) -> Self {
159		let duration = |ticks: u64| {
160			Duration::from_nanos(u64::try_from(u128::from(ticks) * 1_000_000_000 / u128::from(hz)).unwrap_or(u64::MAX))
161		};
162		match Delta::between(last, value, wrap) {
163			Delta::Back(ticks) => Self::Stepped(Way::Back, duration(ticks)),
164			Delta::Forward(ticks) if duration(ticks) > LEAP => Self::Stepped(Way::Leap, duration(ticks)),
165			Delta::Forward(_) => Self::Inline,
166		}
167	}
168
169	fn way(self) -> Option<Way> {
170		match self {
171			Self::Inline => None,
172			Self::Stepped(way, _) => Some(way),
173		}
174	}
175}
176
177/// The clock readings one packet carries.
178#[derive(Default)]
179struct Marks {
180	/// A `discontinuity_indicator` on the clock PID.
181	flagged: bool,
182	/// A PCR on the clock PID.
183	pcr: Option<u64>,
184	/// The DTS, or PTS without one, of a PES header this packet completes on a timed PID.
185	pes: Option<u64>,
186	/// Its timed PID's chain after it, or `None` when it leaves the chain as it was.
187	chain: Option<Chain>,
188}
189
190impl Marks {
191	fn read(pkt: &[u8; TsPacket::SIZE], routes: &Routes, headers: &Headers) -> Self {
192		let mut marks = Self::default();
193		let pid = (u16::from(pkt[1] & 0x1f) << 8) | u16::from(pkt[2]);
194		// A timed PID's chain follows every packet the import's does, the damaged ones too.
195		if (routes.timed)(pid) {
196			(marks.chain, marks.pes) = headers.read(pid, pkt);
197		}
198		// A packet the demodulator flagged corrupt, or whose adaptation field overruns itself,
199		// says nothing the import trusts.
200		if pkt[1] & 0x80 != 0 || !adaptation_valid(pkt) {
201			return marks;
202		}
203		if routes.pcr_pid == Some(pid) {
204			marks.flagged = discontinuity_indicator(pkt);
205			marks.pcr = pcr(pkt);
206		}
207		marks
208	}
209}
210
211/// One timed PID's packets so far: whether they still chain, and the PES header begun on it.
212#[derive(Clone, Default)]
213struct Chain {
214	continuity: Continuity,
215	begun: Option<Vec<u8>>,
216}
217
218/// The PES headers begun on each timed PID, so one split across packets still reads.
219///
220/// Packets join under the import's continuity rules, so a retransmission or a loss cannot
221/// splice a timestamp out of bytes the import never joins.
222#[derive(Clone, Default)]
223struct Headers(HashMap<u16, Chain>);
224
225impl Headers {
226	/// What `pkt` does on `pid` without retaining it: the chain after it, `None` when unchanged,
227	/// and the DTS, or PTS without one, of a header it completes.
228	fn read(&self, pid: u16, pkt: &[u8; TsPacket::SIZE]) -> (Option<Chain>, Option<u64>) {
229		let mut chain = self.0.get(&pid).cloned().unwrap_or_default();
230		match chain.continuity.observe(pkt) {
231			// The import ignores a retransmission entirely.
232			Continuation::Duplicate => return (None, None),
233			Continuation::Contiguous => {}
234			// The bytes joined so far are lost, as the import's partial PES is.
235			Continuation::Broken => chain.begun = None,
236			Continuation::Corrupt => {
237				chain.begun = None;
238				return (Some(chain), None);
239			}
240		}
241		// The import ends on a malformed adaptation field and cannot read a scrambled payload.
242		if !adaptation_valid(pkt) || pkt[3] & 0xc0 != 0 {
243			chain.begun = None;
244			return (Some(chain), None);
245		}
246		let Payload::Bytes(payload) = payload(pkt) else {
247			return (Some(chain), None);
248		};
249		// A PES start abandons whatever header was begun before it, where the import ends.
250		let begun = chain.begun.take();
251		let header = if pkt[1] & 0x40 != 0 {
252			payload.to_vec()
253		} else if let Some(mut begun) = begun {
254			begun.extend_from_slice(payload);
255			begun
256		} else {
257			return (Some(chain), None);
258		};
259		// The optional fields are at most 255 bytes, so a held header stays small.
260		let ticks = match PesStart::header_len(&header) {
261			Ok(len) if header.len() >= len => match PesStart::parse(&header) {
262				Ok(PesStart {
263					pts: Some(pts), dts, ..
264				}) => Some(dts.unwrap_or(pts)),
265				_ => None,
266			},
267			Ok(_) => {
268				chain.begun = Some(header);
269				None
270			}
271			Err(_) => None,
272		};
273		(Some(chain), ticks)
274	}
275
276	/// Retain the chain a packet left on `pid`.
277	fn apply(&mut self, pid: u16, chain: Option<Chain>) {
278		if let Some(chain) = chain {
279			self.0.insert(pid, chain);
280		}
281	}
282}
283
284/// A step being judged, from the packet that showed it on.
285struct Ahead {
286	/// The input offset of that packet, where a new identity starts.
287	at: u64,
288	/// The way it stepped and by how much, or `None` for the clock PID's flagged break, which
289	/// ends the identity only if the streams step back.
290	stepped: Option<(Way, Duration)>,
291	/// Whether the PCR still has to step with it.
292	pcr: bool,
293	/// The PIDs that still have to step with it.
294	pids: HashSet<u16>,
295	/// The PIDs whose first PES since was judged.
296	heard: HashSet<u16>,
297	/// The PES headers begun on the timed PIDs, as read ahead.
298	headers: Headers,
299	/// How far back the first PID to step back went, which a flagged rewind reports.
300	back: Option<Duration>,
301	/// The first PCR read since, which times how long the silent streams are waited for.
302	since: Option<u64>,
303	/// The next input offset to read, never before `at`, and the framer's state there.
304	scan: u64,
305	framer: Framer,
306	/// The step, once every clock confirmed it.
307	confirmed: Option<Step>,
308}
309
310impl Steps {
311	/// Judge the next packet the import would route on `demux`.
312	pub(super) fn judge(&mut self, demux: &Demux, routes: &Routes) -> Verdict {
313		if self.clock.map(|(pid, _)| pid) != routes.pcr_pid {
314			self.clock = routes.pcr_pid.map(|pid| (pid, None));
315		}
316		let (mut cursor, mut framer) = demux.cursor();
317		let Some((at, pkt)) = demux.peek(&mut cursor, &mut framer) else {
318			return Verdict::Route;
319		};
320		let pid = (u16::from(pkt[1] & 0x1f) << 8) | u16::from(pkt[2]);
321		// The PAT never routes, so every later call peeks it again and repeats the restart.
322		if pid == Pid::PAT
323			&& let Some(step) = demux.pat_after(pkt).as_ref().and_then(routes.switched)
324		{
325			return Verdict::Restart(step);
326		}
327		let marks = Marks::read(pkt, routes, &self.headers);
328
329		if self.ahead.is_none() && at >= self.cleared {
330			self.ahead = self.trigger(at, pid, &marks, routes, framer);
331		}
332		let Some(ahead) = &mut self.ahead else {
333			self.observe(pid, marks, routes);
334			return Verdict::Route;
335		};
336		if let Some(step) = ahead.confirmed {
337			return Verdict::Restart(step);
338		}
339		match ahead.scan(demux, routes, &self.clock, &self.pids) {
340			Some(Ok(step)) => {
341				ahead.confirmed = Some(step);
342				Verdict::Restart(step)
343			}
344			Some(Err(cleared)) => {
345				self.cleared = cleared;
346				self.ahead = None;
347				self.observe(pid, marks, routes);
348				Verdict::Route
349			}
350			None => Verdict::Hold,
351		}
352	}
353
354	/// No input follows. A step still being judged never completed, so its input routes as
355	/// read; returns whether there is any.
356	pub(super) fn settle(&mut self) -> bool {
357		if self.ahead.as_ref().is_some_and(|ahead| ahead.confirmed.is_none()) {
358			self.ahead = None;
359			self.cleared = u64::MAX;
360			return true;
361		}
362		false
363	}
364
365	/// `pid` changed route: its timestamps no longer continue the last.
366	pub(super) fn forget(&mut self, pid: u16) {
367		self.pids.remove(&pid);
368		self.headers.0.remove(&pid);
369	}
370
371	/// Start judging a step at the packet at `at` if it shows one, with the clocks expected to
372	/// step with it. `framer` is locked onto that packet, so the scan reads it again from `at`
373	/// rather than from the junk a resync skipped before it.
374	fn trigger(&self, at: u64, pid: u16, marks: &Marks, routes: &Routes, framer: Framer) -> Option<Ahead> {
375		let last_pcr = self.clock.and_then(|(_, last)| last);
376		let stepped = if marks.flagged {
377			None
378		} else {
379			// Without a clock to step with them, the streams alone say nothing of the source.
380			last_pcr?;
381			let pcr = marks
382				.pcr
383				.zip(last_pcr)
384				.map(|(value, last)| Reading::new(last, value, PCR_WRAP, PCR_HZ));
385			let pes = marks
386				.pes
387				.zip(self.pids.get(&pid))
388				.map(|(value, last)| Reading::new(last.ticks, value, PTS_WRAP, PTS_HZ));
389			let stepped = [pcr, pes].into_iter().flatten().find_map(|reading| match reading {
390				Reading::Stepped(way, by) => Some((way, by)),
391				Reading::Inline => None,
392			});
393			Some(stepped?)
394		};
395		// A PID that kept TR 101 290's PTS cadence up to here is expected to step too.
396		let mut pids: HashSet<u16> = self
397			.pids
398			.iter()
399			.filter(|(pid, seen)| {
400				(routes.timed)(**pid)
401					&& match (seen.at, routes.now) {
402						(_, None) => true,
403						(Some(at), Some(now)) => now.saturating_sub(at) <= PTS_LIMIT,
404						(None, Some(_)) => false,
405					}
406			})
407			.map(|(pid, _)| *pid)
408			.collect();
409		if marks.pes.is_some() && self.pids.contains_key(&pid) {
410			pids.insert(pid);
411		}
412		Some(Ahead {
413			at,
414			stepped,
415			pcr: !marks.flagged && last_pcr.is_some(),
416			pids,
417			heard: HashSet::new(),
418			headers: self.headers.clone(),
419			back: None,
420			since: None,
421			scan: at,
422			framer,
423			confirmed: None,
424		})
425	}
426
427	/// Record the readings of a packet routed.
428	fn observe(&mut self, pid: u16, marks: Marks, routes: &Routes) {
429		if let (Some(value), Some((_, last))) = (marks.pcr, &mut self.clock) {
430			*last = Some(value);
431		}
432		if let Some(ticks) = marks.pes {
433			self.pids.insert(pid, Seen { ticks, at: routes.now });
434		}
435		self.headers.apply(pid, marks.chain);
436	}
437}
438
439impl Ahead {
440	/// Read on until every clock expected to step has, `Some(Ok)`, or one did not, `Some(Err)`
441	/// with the offset judged through. `None` waits for more input.
442	fn scan(
443		&mut self,
444		demux: &Demux,
445		routes: &Routes,
446		clock: &Option<(u16, Option<u64>)>,
447		pids: &HashMap<u16, Seen>,
448	) -> Option<Result<Step, u64>> {
449		let last_pcr = clock.and_then(|(_, last)| last);
450		loop {
451			// Held no longer than the import stages bytes awaiting a timestamp.
452			if self.scan - self.at > STAGING_BYTES_MAX as u64 {
453				return Some(Err(self.scan));
454			}
455			let (at, pkt) = demux.peek(&mut self.scan, &mut self.framer)?;
456			let end = at + TsPacket::SIZE as u64;
457			let pid = (u16::from(pkt[1] & 0x1f) << 8) | u16::from(pkt[2]);
458			let marks = Marks::read(pkt, routes, &self.headers);
459
460			if self.pcr
461				&& let (Some(value), Some(last)) = (marks.pcr, last_pcr)
462			{
463				let reading = Reading::new(last, value, PCR_WRAP, PCR_HZ);
464				if reading.way() != self.stepped.map(|(way, _)| way) {
465					return Some(Err(end));
466				}
467				self.pcr = false;
468			}
469			// A cadenced stream speaks within TR 101 290's PTS interval, so one still silent
470			// that long after the step dropped out with the old source: those that spoke decide.
471			if let Some(value) = marks.pcr {
472				let since = *self.since.get_or_insert(value);
473				if let Delta::Forward(elapsed) = Delta::between(since, value, PCR_WRAP)
474					&& elapsed >= PTS_LIMIT
475					&& !self.pcr
476				{
477					return Some(self.verdict(end, !self.heard.is_empty()));
478				}
479			}
480			// Every PID with a timestamp to step from has its say, once: a sparse one too, which
481			// only the cadenced ones are waited for.
482			if let (Some(value), Some(last)) = (marks.pes, pids.get(&pid))
483				&& self.heard.insert(pid)
484			{
485				self.pids.remove(&pid);
486				let reading = Reading::new(last.ticks, value, PTS_WRAP, PTS_HZ);
487				let wanted = match self.stepped {
488					Some((way, _)) => way,
489					None => Way::Back,
490				};
491				let Reading::Stepped(way, by) = reading else {
492					return Some(Err(end));
493				};
494				if way != wanted {
495					return Some(Err(end));
496				}
497				self.back.get_or_insert(by);
498			}
499			self.headers.apply(pid, marks.chain);
500
501			// A clock alone, such as one corrupt PCR, needs a stream to step with it.
502			if !self.pcr && self.pids.is_empty() && (self.stepped.is_none() || !self.heard.is_empty()) {
503				return Some(self.verdict(end, true));
504			}
505		}
506	}
507
508	/// The step every clock heard from agreed on, `stepped` when that is enough to end the
509	/// identity, or the offset judged through when it is not.
510	fn verdict(&self, end: u64, stepped: bool) -> Result<Step, u64> {
511		match self.stepped {
512			Some((Way::Back, by)) if stepped => Ok(Step::Rewind { by, flagged: false }),
513			Some((Way::Leap, by)) if stepped => Ok(Step::Leap { by }),
514			Some(_) => Err(end),
515			// A flagged break no PID has stepped back from is a splice.
516			None => self.back.map(|by| Step::Rewind { by, flagged: true }).ok_or(end),
517		}
518	}
519}
520
521#[cfg(test)]
522mod tests {
523	use super::super::fixture::{Flags, Mux};
524	use super::*;
525
526	const CLOCK: u16 = 0x1ff;
527	const VIDEO: u16 = 0x100;
528	/// 40 ms of program clock, in 27 MHz ticks.
529	const FRAME: u64 = PCR_HZ / 25;
530	/// The step the issue's contribution took, in 27 MHz ticks.
531	const SWITCH: u64 = 16_844 * PCR_HZ + PCR_HZ / 2;
532
533	/// Judge each packet of `ts` and route it, as an import does, with `timed` the PIDs that
534	/// carry timestamped PES. Returns the first restart.
535	fn judge(ts: &[u8], timed: &[u16]) -> Option<Step> {
536		let mut demux = Demux::default();
537		demux.push(ts);
538		let mut steps = Steps::default();
539		let timed = |pid| timed.contains(&pid);
540		let routes = Routes {
541			pcr_pid: Some(CLOCK),
542			timed: &timed,
543			now: None,
544			switched: &|_| None,
545		};
546		loop {
547			match steps.judge(&demux, &routes) {
548				Verdict::Restart(step) => return Some(step),
549				Verdict::Hold => return None,
550				Verdict::Route => demux.next()?,
551			};
552		}
553	}
554
555	/// A video PES at `pts` (90 kHz), with a short body.
556	fn pes_bytes(pts: u64) -> Vec<u8> {
557		let mut pes = vec![0, 0, 1, 0xe0, 0, 0, 0x80, 0x80, 5];
558		pes.extend_from_slice(&[
559			0x21 | ((pts >> 29) & 0x0e) as u8,
560			(pts >> 22) as u8,
561			0x01 | ((pts >> 14) & 0xfe) as u8,
562			(pts >> 7) as u8,
563			0x01 | ((pts << 1) & 0xfe) as u8,
564		]);
565		pes.extend_from_slice(&[0xaa; 32]);
566		pes
567	}
568
569	/// One packet on `pid` carrying `payload`, padded with adaptation stuffing as a muxer does.
570	fn ts(cc: &mut u8, pid: u16, start: bool, payload: &[u8]) -> [u8; 188] {
571		let mut pkt = [0xff; 188];
572		pkt[..3].copy_from_slice(&[0x47, u8::from(start) << 6 | (pid >> 8) as u8, pid as u8]);
573		pkt[3] = 0x30 | *cc;
574		pkt[4] = (183 - payload.len()) as u8;
575		pkt[5] = 0x00;
576		pkt[188 - payload.len()..].copy_from_slice(payload);
577		*cc = (*cc + 1) & 0x0f;
578		pkt
579	}
580
581	/// One PES start on `pid` with `pts` (90 kHz), its header split at each of `splits` across
582	/// packets. The packet holding fragment `repeat` is sent twice, as ISO 13818-1 allows a
583	/// retransmission.
584	fn pes(cc: &mut u8, pid: u16, pts: u64, splits: &[usize], repeat: Option<usize>) -> Vec<u8> {
585		let pes = pes_bytes(pts);
586		let bounds: Vec<usize> = std::iter::once(0)
587			.chain(splits.iter().copied())
588			.chain(std::iter::once(pes.len()))
589			.collect();
590		let mut out = Vec::new();
591		for (i, range) in bounds.windows(2).enumerate() {
592			let pkt = ts(cc, pid, i == 0, &pes[range[0]..range[1]]);
593			out.extend_from_slice(&pkt);
594			if repeat == Some(i) {
595				out.extend_from_slice(&pkt);
596			}
597		}
598		out
599	}
600
601	/// A second of the clock and the video on it, from `start` (27 MHz).
602	fn second(mux: &mut Mux, cc: &mut u8, start: u64, video: bool) {
603		for frame in 0..25 {
604			let clock = (start + frame * FRAME) % PCR_WRAP;
605			mux.packet(CLOCK, Flags::pcr(clock));
606			if video {
607				mux.out
608					.extend(pes(cc, VIDEO, (clock / 300 + 9_000) % PTS_WRAP, &[7], None));
609			}
610		}
611	}
612
613	/// A program clock stepping with no stream to step with it, such as one corrupt PCR in a
614	/// program whose streams are idle, is not another source.
615	#[test]
616	fn a_clock_alone_does_not_restart() {
617		let (mut mux, mut cc) = (Mux::default(), 0);
618		second(&mut mux, &mut cc, PCR_HZ, false);
619		second(&mut mux, &mut cc, PCR_WRAP + 2 * PCR_HZ - SWITCH, false);
620		assert_eq!(judge(&mux.out, &[VIDEO]), None);
621	}
622
623	/// A retransmitted fragment of a split PES header is ignored, as the import ignores it, so
624	/// it cannot read as the stream stepping with a lone PCR glitch.
625	#[test]
626	fn a_repeated_header_fragment_does_not_step() {
627		let (mut mux, mut cc) = (Mux::default(), 0);
628		mux.packet(CLOCK, Flags::pcr(PCR_HZ));
629		mux.out.extend(pes(&mut cc, VIDEO, 90_000, &[7], None));
630		// One corrupt PCR, then the next frame on time, its PTS 93,600 split after its first byte
631		// and the next two. Joining the repeat would read `21 00 05 00 05`, PTS 65,538: back.
632		mux.packet(CLOCK, Flags::pcr(PCR_WRAP + PCR_HZ + FRAME - SWITCH));
633		mux.out.extend(pes(&mut cc, VIDEO, 93_600, &[10, 12], Some(1)));
634		second(&mut mux, &mut cc, PCR_HZ + 2 * FRAME, true);
635		assert_eq!(judge(&mux.out, &[VIDEO]), None);
636	}
637
638	/// A PES start abandons the header begun before it, as the import's does, so the new PES's
639	/// body cannot complete the old header and read as a stream stepping with a lone PCR glitch.
640	#[test]
641	fn a_pes_start_abandons_the_header_begun() {
642		let (mut mux, mut cc) = (Mux::default(), 0);
643		mux.packet(CLOCK, Flags::pcr(PCR_HZ));
644		mux.out.extend(pes(&mut cc, VIDEO, 90_000, &[7], None));
645		// A PES start cut short after nine bytes, then a whole one at PTS 93,600.
646		mux.out.extend(ts(&mut cc, VIDEO, true, &pes_bytes(90_000)[..9]));
647		mux.out.extend(ts(&mut cc, VIDEO, true, &pes_bytes(93_600)));
648		// One corrupt PCR, then a body that, joined to the cut-short header, reads PTS 65,538: back.
649		mux.packet(CLOCK, Flags::pcr(PCR_WRAP + PCR_HZ + FRAME - SWITCH));
650		mux.out
651			.extend(ts(&mut cc, VIDEO, false, &[0x21, 0x00, 0x05, 0x00, 0x05]));
652		second(&mut mux, &mut cc, PCR_HZ + 2 * FRAME, true);
653		assert_eq!(judge(&mux.out, &[VIDEO]), None);
654	}
655
656	/// Junk before the switch, such as a torn packet at the splice, makes the framer resync onto
657	/// the packet that shows the step, past the cursor. The look-ahead reads on from that
658	/// packet, not from the junk, so the switch is still judged whole.
659	#[test]
660	fn a_resync_before_the_step_reads_on_from_it() {
661		let (mut mux, mut cc) = (Mux::default(), 0);
662		second(&mut mux, &mut cc, PCR_HZ, true);
663		mux.out.extend_from_slice(&[0x00; 5]);
664		second(&mut mux, &mut cc, PCR_WRAP + 2 * PCR_HZ - SWITCH, true);
665		let Some(Step::Rewind { by, flagged: false }) = judge(&mux.out, &[VIDEO]) else {
666			panic!("the switch was missed");
667		};
668		assert!(
669			by.abs_diff(Duration::from_millis(16_844_460)) < Duration::from_millis(100),
670			"{by:?}"
671		);
672	}
673
674	/// A PES header split across packets still times its stream, so the switch is seen.
675	#[test]
676	fn a_split_pes_header_steps_with_the_clock() {
677		let (mut mux, mut cc) = (Mux::default(), 0);
678		second(&mut mux, &mut cc, PCR_HZ, true);
679		second(&mut mux, &mut cc, PCR_WRAP + 2 * PCR_HZ - SWITCH, true);
680		let Some(Step::Rewind { by, flagged: false }) = judge(&mux.out, &[VIDEO]) else {
681			panic!("the switch was missed");
682		};
683		assert!(
684			by.abs_diff(Duration::from_millis(16_844_460)) < Duration::from_millis(100),
685			"{by:?}"
686		);
687	}
688}