1use 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
35pub(super) const LEAP: Duration = Duration::from_secs(10);
37const PTS_HZ: u64 = 90_000;
38const PTS_WRAP: u64 = 1 << 33;
39
40#[derive(Clone, Debug)]
46pub(super) struct Restart {
47 pub step: Step,
49 pub remainder: Bytes,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum Step {
57 Rewind {
59 by: Duration,
61 flagged: bool,
63 },
64 Leap {
66 by: Duration,
68 },
69 Identity {
71 transport_stream_id: u16,
73 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
97pub(super) struct Routes<'a> {
99 pub pcr_pid: Option<u16>,
101 pub timed: &'a dyn Fn(u16) -> bool,
103 pub now: Option<u64>,
105 pub switched: &'a dyn Fn(&Pat) -> Option<Step>,
107}
108
109pub(super) enum Verdict {
111 Route,
113 Hold,
115 Restart(Step),
117}
118
119#[derive(Default)]
121pub(super) struct Steps {
122 clock: Option<(u16, Option<u64>)>,
124 pids: HashMap<u16, Seen>,
126 cleared: u64,
128 ahead: Option<Ahead>,
130 headers: Headers,
132}
133
134#[derive(Clone, Copy)]
136struct Seen {
137 ticks: u64,
139 at: Option<u64>,
141}
142
143#[derive(Clone, Copy, PartialEq, Eq)]
145enum Way {
146 Back,
147 Leap,
148}
149
150#[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#[derive(Default)]
179struct Marks {
180 flagged: bool,
182 pcr: Option<u64>,
184 pes: Option<u64>,
186 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 if (routes.timed)(pid) {
196 (marks.chain, marks.pes) = headers.read(pid, pkt);
197 }
198 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#[derive(Clone, Default)]
213struct Chain {
214 continuity: Continuity,
215 begun: Option<Vec<u8>>,
216}
217
218#[derive(Clone, Default)]
223struct Headers(HashMap<u16, Chain>);
224
225impl Headers {
226 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 Continuation::Duplicate => return (None, None),
233 Continuation::Contiguous => {}
234 Continuation::Broken => chain.begun = None,
236 Continuation::Corrupt => {
237 chain.begun = None;
238 return (Some(chain), None);
239 }
240 }
241 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 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 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 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
284struct Ahead {
286 at: u64,
288 stepped: Option<(Way, Duration)>,
291 pcr: bool,
293 pids: HashSet<u16>,
295 heard: HashSet<u16>,
297 headers: Headers,
299 back: Option<Duration>,
301 since: Option<u64>,
303 scan: u64,
305 framer: Framer,
306 confirmed: Option<Step>,
308}
309
310impl Steps {
311 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 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 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 pub(super) fn forget(&mut self, pid: u16) {
367 self.pids.remove(&pid);
368 self.headers.0.remove(&pid);
369 }
370
371 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 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 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 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 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 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 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 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 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 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 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 const FRAME: u64 = PCR_HZ / 25;
530 const SWITCH: u64 = 16_844 * PCR_HZ + PCR_HZ / 2;
532
533 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 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 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 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 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 #[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 #[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 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 #[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 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 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 #[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 #[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}