forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

demux.rs1060 lines, 32.2 KiBHistoryRawDownload
1//! The transport stream demuxer.
2
3use std::collections::{HashMap, VecDeque};
4use std::io::{Read, Seek};
5
6use ec_core::registry::{Demuxer, SeekMode, StreamInfo};
7use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};
8
9use crate::codec::{StreamKind, annexb_to_length_prefixed};
10use crate::psi::{self, EsEntry, PatEntry, Pmt, SectionBuf};
11use crate::track::{MAX_PES, PesIn, Queued, TICKS, Track};
12use crate::ts::{self, Layout, SYNC, TS_LEN};
13use crate::window::Window;
14
15/// Most programs listed, tracks kept (across PMT changes) and bytes probed.
16const MAX_PROGRAMS: usize = 64;
17const MAX_TRACKS: usize = 128;
18const PROBE_BYTES: u64 = 32 << 20;
19/// Bisection stops when the interval is this small; the rest is a forward scan.
20const BISECT_STOP: u64 = 64 << 10;
21
22/// How video access units are delivered.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum VideoFraming {
25 /// Annex B start codes, parameter sets in band (what the bytes of the stream are).
26 #[default]
27 AnnexB,
28 /// Every NAL unit preceded by a 4-byte big-endian length, as `avc1`/`hvc1` samples
29 /// are. The `extradata` of the stream is the matching `avcC`/`hvcC` record.
30 LengthPrefixed,
31}
32
33/// A program of the PAT, with what its PMT says once that was seen.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ProgramInfo {
36 /// `program_number`.
37 pub number: u16,
38 /// PID of the PMT.
39 pub pmt_pid: u16,
40 /// PID that carries the PCR, once the PMT was seen.
41 pub pcr_pid: Option<u16>,
42 /// The PMT's elementary streams (empty until the PMT was seen).
43 pub streams: Vec<EsEntry>,
44}
45
46/// One elementary stream of the selected program, whether or not it is exposed.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct TrackInfo {
49 /// Elementary PID.
50 pub pid: u16,
51 /// PMT `stream_type`.
52 pub stream_type: u8,
53 /// What the stream carries.
54 pub kind: StreamKind,
55 /// Index in [`Demuxer::streams`] when the stream is exposed.
56 pub stream: Option<u32>,
57 /// Why the stream is not exposed, naming the codec.
58 pub refusal: Option<String>,
59 /// ISO 639 language, when the PMT gives one.
60 pub language: Option<String>,
61}
62
63/// Counters of what the demuxer had to put up with.
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65pub struct Stats {
66 /// Times the sync byte was lost and found again.
67 pub resyncs: u64,
68 /// Continuity-counter gaps on tracked PIDs.
69 pub cc_errors: u64,
70 /// Duplicate packets dropped.
71 pub duplicates: u64,
72 /// PSI sections with a bad CRC.
73 pub crc_errors: u64,
74 /// Packets with the transport error indicator set.
75 pub tei: u64,
76 /// `discontinuity_indicator` seen.
77 pub discontinuities: u64,
78 /// PMT changes after the first (of the selected program).
79 pub pmt_changes: u64,
80 /// PES packets dropped (bad start code, oversize).
81 pub bad_pes: u64,
82}
83
84enum Cc {
85 Ok,
86 Dup,
87 Gap,
88}
89
90pub(crate) fn unwrap33(raw: u64, last: Option<i64>) -> i64 {
91 const M: i64 = 1 << 33;
92 let raw = raw as i64;
93 match last {
94 None => raw,
95 Some(l) => {
96 let mut d = (raw - l).rem_euclid(M);
97 if d >= M / 2 {
98 d -= M;
99 }
100 l + d
101 }
102 }
103}
104
105pub(crate) fn read_ts(b: &[u8]) -> Option<u64> {
106 let b = b.get(..5)?;
107 if b[0] & 1 == 0 || b[2] & 1 == 0 || b[4] & 1 == 0 {
108 return None;
109 }
110 Some(
111 (u64::from((b[0] >> 1) & 7) << 30)
112 | (u64::from(b[1]) << 22)
113 | (u64::from(b[2] >> 1) << 15)
114 | (u64::from(b[3]) << 7)
115 | u64::from(b[4] >> 1),
116 )
117}
118
119/// PES header facts.
120pub(crate) struct PesHead {
121 pub pts: Option<u64>,
122 pub dts: Option<u64>,
123 pub payload: usize,
124}
125
126pub(crate) fn parse_pes(buf: &[u8]) -> Option<PesHead> {
127 if buf.get(..3)? != [0, 0, 1] {
128 return None;
129 }
130 let id = *buf.get(3)?;
131 if matches!(id, 0xBC | 0xBE | 0xBF | 0xF0 | 0xF1 | 0xF2 | 0xF8 | 0xFF) {
132 return Some(PesHead {
133 pts: None,
134 dts: None,
135 payload: 6,
136 });
137 }
138 let h = buf.get(..9)?;
139 if h[6] & 0xC0 != 0x80 {
140 return None;
141 }
142 let flags = h[7] >> 6;
143 let payload = 9 + usize::from(h[8]);
144 if payload > buf.len() {
145 return None;
146 }
147 let pts = if flags & 2 != 0 {
148 read_ts(buf.get(9..)?)
149 } else {
150 None
151 };
152 let dts = if flags == 3 {
153 read_ts(buf.get(14..)?)
154 } else {
155 None
156 };
157 Some(PesHead { pts, dts, payload })
158}
159
160/// MPEG-2 transport stream demuxer.
161///
162/// Opens `.ts` (188-byte), BDAV `.m2ts`/`.mts` (192-byte, 4-byte `TP_extra_header`)
163/// and 204-byte (Reed-Solomon) streams, detected by sync-byte stride. The first
164/// program is exposed unless [`TsDemuxer::with_program`] names another.
165pub struct TsDemuxer<R> {
166 win: Window<R>,
167 file_len: u64,
168 layout: Layout,
169 first_off: u64,
170 pos: u64,
171 programs: Vec<ProgramInfo>,
172 sel: Option<u16>,
173 pmt_seen: bool,
174 pcr_pid: Option<u16>,
175 first_pcr: Option<u64>,
176 sections: HashMap<u16, SectionBuf>,
177 /// Last continuity counter per PID, with the packet that carried it.
178 cc: HashMap<u16, (u8, Box<[u8; TS_LEN]>)>,
179 tracks: Vec<Track>,
180 pid_map: HashMap<u16, usize>,
181 streams: Vec<StreamInfo>,
182 queue: VecDeque<Queued>,
183 eof: bool,
184 stats: Stats,
185 framing: VideoFraming,
186 last_off: u64,
187 duration: Option<i64>,
188 /// While scanning (tail, bisection) PSI is read but not acted on.
189 frozen: bool,
190}
191
192impl<R: Read + Seek> TsDemuxer<R> {
193 /// Opens `reader`, exposing the first program.
194 pub fn new(reader: R) -> Result<TsDemuxer<R>> {
195 Self::open(reader, None)
196 }
197
198 /// Opens `reader`, exposing the program with this `program_number`.
199 pub fn with_program(reader: R, program_number: u16) -> Result<TsDemuxer<R>> {
200 Self::open(reader, Some(program_number))
201 }
202
203 fn open(reader: R, program: Option<u16>) -> Result<TsDemuxer<R>> {
204 let mut win = Window::new(reader);
205 let file_len = win.len()?;
206 let head = win.get(0, 64 * 1024)?;
207 let Some((layout, first)) = ts::detect(head) else {
208 return Err(Error::corrupt("mpegts: no transport packet sync found"));
209 };
210 let first_off = first as u64;
211 let mut d = TsDemuxer {
212 win,
213 file_len,
214 layout,
215 first_off,
216 pos: first_off,
217 programs: Vec::new(),
218 sel: program,
219 pmt_seen: false,
220 pcr_pid: None,
221 first_pcr: None,
222 sections: HashMap::new(),
223 cc: HashMap::new(),
224 tracks: Vec::new(),
225 pid_map: HashMap::new(),
226 streams: Vec::new(),
227 queue: VecDeque::new(),
228 eof: false,
229 stats: Stats::default(),
230 framing: VideoFraming::AnnexB,
231 last_off: first_off,
232 duration: None,
233 frozen: false,
234 };
235 d.probe()?;
236 if !d.pmt_seen {
237 return Err(Error::corrupt(match (d.programs.is_empty(), program) {
238 (true, _) => "mpegts: no PAT found".to_string(),
239 (false, Some(n)) => format!("mpegts: program {n} has no PMT"),
240 (false, None) => "mpegts: no PMT found".to_string(),
241 }));
242 }
243 d.finish_open()?;
244 Ok(d)
245 }
246
247 // ----- public queries ---------------------------------------------------
248
249 /// Bytes per transport packet in the file: 188, 192 or 204.
250 pub fn packet_size(&self) -> usize {
251 self.layout.size
252 }
253
254 /// True for BDAV (`.m2ts`/`.mts`) packets with a 4-byte `TP_extra_header`.
255 pub fn is_bdav(&self) -> bool {
256 self.layout.sync_off == 4
257 }
258
259 /// Every program of the PAT with its PMT streams.
260 pub fn programs(&self) -> &[ProgramInfo] {
261 &self.programs
262 }
263
264 /// `program_number` of the program being read.
265 pub fn program_number(&self) -> Option<u16> {
266 self.sel
267 }
268
269 /// Every elementary stream of the selected program (including refused ones), in
270 /// PMT order, with later PMT additions after.
271 pub fn tracks(&self) -> Vec<TrackInfo> {
272 self.tracks
273 .iter()
274 .map(|t| TrackInfo {
275 pid: t.es.pid,
276 stream_type: t.es.stream_type,
277 kind: t.kind.clone(),
278 stream: t.stream,
279 refusal: t.refusal.clone(),
280 language: t.es.language(),
281 })
282 .collect()
283 }
284
285 /// PID of stream `stream`.
286 pub fn stream_pid(&self, stream: u32) -> Option<u16> {
287 self.tracks
288 .iter()
289 .find(|t| t.stream == Some(stream))
290 .map(|t| t.es.pid)
291 }
292
293 /// The 90 kHz time base of every packet.
294 pub fn time_base(&self) -> TimeBase {
295 TimeBase::new(1, TICKS)
296 }
297
298 /// Length of the file in seconds, from the first and last timestamps.
299 pub fn duration_secs(&self) -> Option<f64> {
300 self.duration.map(|d| d as f64 / TICKS as f64)
301 }
302
303 /// Counters of what the demuxer repaired or skipped so far.
304 pub fn stats(&self) -> Stats {
305 self.stats
306 }
307
308 /// First PCR (27 MHz) seen on the program's PCR PID.
309 pub fn first_pcr(&self) -> Option<u64> {
310 self.first_pcr
311 }
312
313 /// PCR PID of the selected program.
314 pub fn pcr_pid(&self) -> Option<u16> {
315 self.pcr_pid
316 }
317
318 /// File offset of the transport packet that began the last packet returned by
319 /// [`Demuxer::next_packet`]; after [`Demuxer::seek`] it is where the read resumes.
320 pub fn last_packet_offset(&self) -> u64 {
321 self.last_off
322 }
323
324 /// Sets how H.264 and HEVC packets are framed (default Annex B).
325 pub fn set_video_framing(&mut self, framing: VideoFraming) {
326 self.framing = framing;
327 }
328
329 /// The video framing in effect.
330 pub fn video_framing(&self) -> VideoFraming {
331 self.framing
332 }
333
334 // ----- engine -------------------------------------------------------------
335
336 fn cc_check(&mut self, h: &ts::Header, pkt: &[u8; TS_LEN]) -> Cc {
337 if !h.has_payload {
338 return Cc::Ok;
339 }
340 let prev = self.cc.insert(h.pid, (h.cc, Box::new(*pkt)));
341 match prev {
342 None => Cc::Ok,
343 // A repeat of the packet before it is the one repeat the standard allows.
344 Some((p, last)) if p == h.cc && *last == *pkt => Cc::Dup,
345 Some((p, _)) if (p + 1) & 15 == h.cc => Cc::Ok,
346 Some(_) if h.discontinuity => Cc::Ok,
347 Some(_) => Cc::Gap,
348 }
349 }
350
351 fn mark_bad(&mut self) {
352 for t in &mut self.tracks {
353 if t.pes_on {
354 t.pes_bad = true;
355 }
356 }
357 }
358
359 /// Looks for the next confirmed packet start after `from`. `None` at end of file.
360 fn resync(&mut self, from: u64) -> Result<Option<u64>> {
361 let mut at = from;
362 let step = 64 * 1024usize;
363 let overlap = (self.layout.size * 5) as u64;
364 loop {
365 let buf = self.win.get(at, step)?;
366 if buf.is_empty() {
367 return Ok(None);
368 }
369 let full = buf.len() == step;
370 if let Some(i) = ts::find_sync(buf, 0, self.layout) {
371 return Ok(Some(at + i as u64));
372 }
373 if !full {
374 return Ok(None);
375 }
376 at += step as u64 - overlap;
377 }
378 }
379
380 /// Processes one transport packet. `Ok(false)` once the end was reached and
381 /// everything buffered was flushed.
382 fn step(&mut self) -> Result<bool> {
383 if self.eof {
384 return Ok(false);
385 }
386 let size = self.layout.size;
387 let so = self.layout.sync_off;
388 let mut pkt = [0u8; TS_LEN];
389 let ok = {
390 let b = self.win.get(self.pos, size + so + 1)?;
391 if b.len() < so + TS_LEN {
392 if !b.is_empty() {
393 // A packet cut short: whatever PES was open is cut short with it.
394 self.mark_bad();
395 }
396 self.finish();
397 return Ok(false);
398 }
399 let next_ok = b.get(size + so).is_none_or(|&n| n == SYNC);
400 if b[so] == SYNC && next_ok {
401 pkt.copy_from_slice(&b[so..so + TS_LEN]);
402 true
403 } else {
404 false
405 }
406 };
407 if !ok {
408 self.stats.resyncs += 1;
409 self.mark_bad();
410 self.cc.clear();
411 for s in self.sections.values_mut() {
412 s.reset();
413 }
414 match self.resync(self.pos + 1)? {
415 Some(p) => self.pos = p,
416 None => {
417 self.finish();
418 return Ok(false);
419 }
420 }
421 return Ok(true);
422 }
423 let off = self.pos;
424 self.pos += size as u64;
425 let Some(h) = ts::parse(&pkt) else {
426 self.mark_bad();
427 return Ok(true);
428 };
429 if h.pid == 0x1FFF {
430 return Ok(true);
431 }
432 if h.tei {
433 self.stats.tei += 1;
434 if let Some(&ti) = self.pid_map.get(&h.pid) {
435 self.tracks[ti].pes_bad = true;
436 }
437 return Ok(true);
438 }
439 if Some(h.pid) == self.pcr_pid
440 && let Some(pcr) = h.pcr
441 {
442 self.first_pcr.get_or_insert(pcr);
443 }
444 if h.discontinuity {
445 self.stats.discontinuities += 1;
446 }
447 let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid);
448 let tracked = self.pid_map.get(&h.pid).copied();
449 if !is_psi && tracked.is_none() {
450 return Ok(true);
451 }
452 let cc = self.cc_check(&h, &pkt);
453 match cc {
454 Cc::Dup => {
455 self.stats.duplicates += 1;
456 return Ok(true);
457 }
458 Cc::Gap => {
459 self.stats.cc_errors += 1;
460 if let Some(ti) = tracked {
461 self.tracks[ti].pes_bad = true;
462 }
463 if let Some(s) = self.sections.get_mut(&h.pid) {
464 s.reset();
465 }
466 }
467 Cc::Ok => {}
468 }
469 if !h.has_payload {
470 return Ok(true);
471 }
472 let payload = &pkt[h.payload.0..h.payload.1];
473 if is_psi {
474 let mut out = Vec::new();
475 let bad = self
476 .sections
477 .entry(h.pid)
478 .or_default()
479 .push(h.pusi, payload, &mut out);
480 self.stats.crc_errors += u64::from(bad);
481 for s in out {
482 self.on_section(h.pid, &s);
483 }
484 return Ok(true);
485 }
486 if let Some(ti) = tracked {
487 self.on_es_payload(ti, &h, payload, off);
488 }
489 Ok(true)
490 }
491
492 fn on_es_payload(&mut self, ti: usize, h: &ts::Header, payload: &[u8], off: u64) {
493 if !self.tracks[ti].wanted() {
494 return;
495 }
496 if h.pusi {
497 self.finish_pes(ti);
498 let t = &mut self.tracks[ti];
499 t.pes.clear();
500 t.pes_on = true;
501 t.pes_off = off;
502 t.pes_rai = h.random_access;
503 t.pes_bad = false;
504 t.pes_expect = None;
505 if payload.len() >= 3 && payload[..3] != [0, 0, 1] {
506 t.pes_on = false;
507 self.stats.bad_pes += 1;
508 return;
509 }
510 } else if !self.tracks[ti].pes_on {
511 return;
512 }
513 let t = &mut self.tracks[ti];
514 t.pes.extend_from_slice(payload);
515 if t.pes_expect.is_none() && t.pes.len() >= 6 {
516 let len = (usize::from(t.pes[4]) << 8) | usize::from(t.pes[5]);
517 if len > 0 {
518 t.pes_expect = Some(6 + len);
519 }
520 }
521 if t.pes.len() > MAX_PES {
522 t.pes_on = false;
523 t.pes.clear();
524 self.stats.bad_pes += 1;
525 return;
526 }
527 if let Some(n) = t.pes_expect
528 && t.pes.len() >= n
529 {
530 t.pes.truncate(n);
531 self.finish_pes(ti);
532 }
533 }
534
535 fn finish_pes(&mut self, ti: usize) {
536 let t = &mut self.tracks[ti];
537 if !t.pes_on {
538 return;
539 }
540 t.pes_on = false;
541 let buf = std::mem::take(&mut t.pes);
542 let Some(head) = parse_pes(&buf) else {
543 self.stats.bad_pes += 1;
544 t.pes = buf;
545 t.pes.clear();
546 return;
547 };
548 let pts = head.pts.map(|raw| unwrap33(raw, t.last_pts));
549 if let Some(p) = pts {
550 t.last_pts = Some(p);
551 }
552 let dts = match (head.dts, head.pts, pts) {
553 (Some(d), Some(rp), Some(p)) => {
554 const M: i64 = 1 << 33;
555 let mut delta = (d as i64 - rp as i64).rem_euclid(M);
556 if delta >= M / 2 {
557 delta -= M;
558 }
559 Some(p + delta)
560 }
561 _ => None,
562 };
563 let input = PesIn {
564 payload: &buf[head.payload..],
565 pts,
566 dts,
567 off: t.pes_off,
568 rai: t.pes_rai,
569 bad: t.pes_bad,
570 };
571 t.push_pes(ti, &input, &mut self.queue);
572 t.pes_bad = false;
573 t.pes = buf;
574 t.pes.clear();
575 }
576
577 fn finish(&mut self) {
578 for ti in 0..self.tracks.len() {
579 let t = &mut self.tracks[ti];
580 if t.pes_on && t.pes_expect.is_some_and(|n| t.pes.len() < n) {
581 t.pes_bad = true;
582 }
583 self.finish_pes(ti);
584 self.tracks[ti].flush(ti, &mut self.queue);
585 }
586 self.eof = true;
587 }
588
589 // ----- PSI --------------------------------------------------------------
590
591 fn on_section(&mut self, pid: u16, sec: &[u8]) {
592 if self.frozen {
593 return;
594 }
595 if pid == 0 {
596 if let Some((_, entries)) = psi::parse_pat(sec) {
597 self.apply_pat(entries);
598 }
599 } else if let Some(pmt) = psi::parse_pmt(sec)
600 && self
601 .programs
602 .iter()
603 .any(|p| p.pmt_pid == pid && p.number == pmt.program_number)
604 {
605 self.apply_pmt(pmt);
606 }
607 }
608
609 fn apply_pat(&mut self, entries: Vec<PatEntry>) {
610 let mut next: Vec<ProgramInfo> = Vec::new();
611 for e in entries.into_iter().take(MAX_PROGRAMS) {
612 if next.iter().any(|p| p.number == e.program_number) {
613 continue;
614 }
615 let old = self.programs.iter().find(|p| p.number == e.program_number);
616 next.push(ProgramInfo {
617 number: e.program_number,
618 pmt_pid: e.pmt_pid,
619 pcr_pid: old.and_then(|o| o.pcr_pid),
620 streams: old.map(|o| o.streams.clone()).unwrap_or_default(),
621 });
622 }
623 if self.sel.is_none() {
624 self.sel = next.first().map(|p| p.number);
625 }
626 self.programs = next;
627 }
628
629 fn apply_pmt(&mut self, pmt: Pmt) {
630 if let Some(p) = self
631 .programs
632 .iter_mut()
633 .find(|p| p.number == pmt.program_number)
634 {
635 p.pcr_pid = Some(pmt.pcr_pid);
636 p.streams = pmt.streams.clone();
637 }
638 if Some(pmt.program_number) != self.sel {
639 return;
640 }
641 self.pcr_pid = Some(pmt.pcr_pid);
642 let same = self.pmt_seen
643 && self
644 .tracks
645 .iter()
646 .filter(|t| t.active)
647 .map(|t| &t.es)
648 .eq(pmt.streams.iter());
649 if same {
650 return;
651 }
652 if self.pmt_seen {
653 self.stats.pmt_changes += 1;
654 }
655 self.pmt_seen = true;
656 for ti in 0..self.tracks.len() {
657 let t = &self.tracks[ti];
658 let kept = pmt
659 .streams
660 .iter()
661 .any(|e| e.pid == t.es.pid && e.stream_type == t.es.stream_type);
662 if t.active && !kept {
663 self.finish_pes(ti);
664 self.tracks[ti].flush(ti, &mut self.queue);
665 self.tracks[ti].active = false;
666 }
667 }
668 for e in &pmt.streams {
669 if let Some(t) = self
670 .tracks
671 .iter_mut()
672 .find(|t| t.es.pid == e.pid && t.es.stream_type == e.stream_type)
673 {
674 t.es = e.clone();
675 if !t.active {
676 t.active = true;
677 t.reset(None);
678 }
679 } else if self.tracks.len() < MAX_TRACKS {
680 self.tracks.push(Track::new(e.clone()));
681 }
682 }
683 self.pid_map.clear();
684 for (i, t) in self.tracks.iter().enumerate() {
685 if t.active {
686 self.pid_map.insert(t.es.pid, i);
687 }
688 }
689 }
690
691 // ----- open ---------------------------------------------------------------
692
693 fn probe_complete(&self) -> bool {
694 if !self.pmt_seen {
695 return false;
696 }
697 let all_ready = self.tracks.iter().filter(|t| t.wanted()).all(|t| t.ready());
698 // A dozen pictures to read a frame rate from, a few frames of everything else.
699 let timed = self.tracks.iter().filter(|t| t.wanted()).all(|t| {
700 if t.kind.is_video() {
701 t.dts_seen.len() >= 12
702 } else {
703 t.packets >= 3 || t.kind.is_bitmap_sub()
704 }
705 });
706 all_ready && timed
707 }
708
709 fn probe(&mut self) -> Result<()> {
710 let start = self.pos;
711 loop {
712 self.queue.clear();
713 if self.eof {
714 break;
715 }
716 let read = self.pos - start;
717 if read >= PROBE_BYTES || self.probe_complete() {
718 break;
719 }
720 self.step()?;
721 }
722 self.queue.clear();
723 Ok(())
724 }
725
726 fn reset_at(&mut self, off: u64, seed: Option<i64>) {
727 self.queue.clear();
728 self.eof = false;
729 self.pos = off;
730 self.cc.clear();
731 for s in self.sections.values_mut() {
732 s.reset();
733 }
734 for t in &mut self.tracks {
735 let s = seed.or(t.start_time);
736 t.reset(s);
737 }
738 }
739
740 fn finish_open(&mut self) -> Result<()> {
741 for t in &mut self.tracks {
742 t.start_time = t.min_pts;
743 }
744 self.assign_streams();
745 self.frozen = true;
746 let tail = self.scan_tail();
747 self.frozen = false;
748 tail?;
749 self.reset_at(self.first_off, None);
750 self.stats = Stats::default();
751 Ok(())
752 }
753
754 fn assign_streams(&mut self) {
755 for ti in 0..self.tracks.len() {
756 self.make_stream(ti);
757 }
758 }
759
760 /// Gives track `ti` a stream index when it can be described. Returns it.
761 fn make_stream(&mut self, ti: usize) -> Option<u32> {
762 if let Some(s) = self.tracks[ti].stream {
763 return Some(s);
764 }
765 let index = self.streams.len() as u32;
766 let mut info = self.tracks[ti].stream_info(index)?;
767 if !self
768 .streams
769 .iter()
770 .any(|s| s.params.codec.media_type() == info.params.codec.media_type() && s.default)
771 {
772 info.default = true;
773 }
774 self.tracks[ti].stream = Some(index);
775 self.streams.push(info);
776 Some(index)
777 }
778
779 fn scan_tail(&mut self) -> Result<()> {
780 let size = self.layout.size as u64;
781 let mut win: u64 = 4 << 20;
782 loop {
783 for t in &mut self.tracks {
784 t.max_end = None;
785 }
786 let from = self.file_len.saturating_sub(win);
787 let off = if from <= self.first_off {
788 self.first_off
789 } else {
790 self.first_off + (from - self.first_off) / size * size
791 };
792 self.reset_at(off, None);
793 while self.step()? {
794 self.queue.clear();
795 }
796 self.queue.clear();
797 let timed = self
798 .tracks
799 .iter()
800 .filter(|t| t.stream.is_some() && !t.kind.is_bitmap_sub())
801 .all(|t| t.max_end.is_some());
802 if timed || off == self.first_off {
803 break;
804 }
805 win = win.saturating_mul(4);
806 }
807 let mut longest: Option<i64> = None;
808 for t in &self.tracks {
809 let (Some(si), Some(end), Some(start)) = (t.stream, t.max_end, t.start_time) else {
810 continue;
811 };
812 let end = end
813 + if t.kind.is_video() {
814 t.frame_ticks().unwrap_or(0)
815 } else {
816 0
817 };
818 let d = end - start;
819 if d > 0
820 && let Some(s) = self.streams.get_mut(si as usize)
821 {
822 s.duration = Some(d);
823 longest = Some(longest.map_or(d, |l| l.max(d)));
824 }
825 }
826 self.duration = longest;
827 Ok(())
828 }
829
830 // ----- reading --------------------------------------------------------------
831
832 fn pump(&mut self) -> Result<Option<Queued>> {
833 loop {
834 if let Some(q) = self.queue.pop_front() {
835 return Ok(Some(q));
836 }
837 if !self.step()? {
838 return Ok(self.queue.pop_front());
839 }
840 }
841 }
842
843 fn make_packet(&mut self, q: Queued) -> Option<Packet> {
844 let ti = q.track;
845 let stream = match self.tracks[ti].stream {
846 Some(s) => s,
847 None => {
848 if self.tracks[ti].start_time.is_none() {
849 self.tracks[ti].start_time = self.tracks[ti].min_pts;
850 }
851 self.make_stream(ti)?
852 }
853 };
854 let kind = &self.tracks[ti].kind;
855 let data = if self.framing == VideoFraming::LengthPrefixed && kind.is_annexb_video() {
856 annexb_to_length_prefixed(&q.data, 4)
857 } else {
858 q.data
859 };
860 let mut p = Packet::new(stream, self.time_base(), data);
861 p.pts = q.pts;
862 p.dts = q.dts;
863 p.duration = q.dur;
864 p.flags = PacketFlags {
865 keyframe: q.key,
866 corrupt: q.corrupt,
867 ..PacketFlags::default()
868 };
869 self.last_off = q.off;
870 Some(p)
871 }
872
873 // ----- seeking ----------------------------------------------------------------
874
875 fn align(&self, off: u64) -> u64 {
876 let size = self.layout.size as u64;
877 if off <= self.first_off {
878 self.first_off
879 } else {
880 self.first_off + (off - self.first_off) / size * size
881 }
882 }
883
884 /// Decode (or presentation) time of the first packet of track `ti` at or after `off`.
885 fn time_at(&mut self, off: u64, ti: usize) -> Result<Option<i64>> {
886 self.reset_at(off, None);
887 while let Some(q) = self.pump()? {
888 if q.track == ti
889 && let Some(t) = q.dts.or(q.pts)
890 {
891 return Ok(Some(t));
892 }
893 }
894 Ok(None)
895 }
896
897 /// Scans forward from `from` for the landing packet of a seek to `target`.
898 fn scan_for(
899 &mut self,
900 from: u64,
901 ti: usize,
902 target: i64,
903 mode: SeekMode,
904 all_sync: bool,
905 ) -> Result<Option<(u64, i64)>> {
906 self.reset_at(from, None);
907 let mut best = None;
908 while let Some(q) = self.pump()? {
909 if q.track != ti {
910 continue;
911 }
912 let Some(pts) = q.pts.or(q.dts) else {
913 continue;
914 };
915 let dts = q.dts.unwrap_or(pts);
916 let key = all_sync || q.key;
917 match mode {
918 SeekMode::SyncAfter => {
919 if key && pts >= target {
920 return Ok(Some((q.off, pts)));
921 }
922 }
923 SeekMode::Exact => {
924 if dts > target {
925 break;
926 }
927 best = Some((q.off, pts));
928 }
929 SeekMode::SyncBefore => {
930 if dts > target {
931 break;
932 }
933 if key && pts <= target {
934 best = Some((q.off, pts));
935 }
936 }
937 }
938 }
939 Ok(best)
940 }
941}
942
943impl<R: Read + Seek + Send> Demuxer for TsDemuxer<R> {
944 fn streams(&self) -> &[StreamInfo] {
945 &self.streams
946 }
947
948 fn next_packet(&mut self) -> Result<Packet> {
949 loop {
950 let Some(q) = self.pump()? else {
951 return Err(Error::Eof);
952 };
953 if let Some(p) = self.make_packet(q) {
954 return Ok(p);
955 }
956 }
957 }
958
959 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
960 let saved = self.stats;
961 self.frozen = true;
962 let r = self.seek_scan(stream, to, mode);
963 self.frozen = false;
964 self.stats = saved;
965 // The landing re-read starts with the PSI of the stream again.
966 r
967 }
968}
969
970impl<R: Read + Seek> TsDemuxer<R> {
971 fn seek_scan(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
972 let Some(ti) = self.tracks.iter().position(|t| t.stream == Some(stream)) else {
973 return Err(Error::corrupt(format!(
974 "mpegts: no stream {stream} to seek"
975 )));
976 };
977 // The picture decides where to land; without one, the stream itself.
978 let ref_ti = self
979 .tracks
980 .iter()
981 .position(|t| t.stream.is_some() && t.kind.is_video())
982 .unwrap_or(ti);
983 let all_sync = !self.tracks[ref_ti].kind.is_video();
984 let target = to.rescale(self.time_base(), Rounding::Nearest).ticks;
985 let start = self.tracks[ref_ti].start_time.unwrap_or(0);
986 let landing = if target <= start && mode != SeekMode::Exact {
987 None
988 } else {
989 let mut lo = self.first_off;
990 let mut hi = self.file_len;
991 while hi - lo > BISECT_STOP {
992 let mid = self.align(lo + (hi - lo) / 2);
993 if mid <= lo {
994 break;
995 }
996 match self.time_at(mid, ref_ti)? {
997 Some(t) if t <= target => lo = mid,
998 _ => hi = mid,
999 }
1000 }
1001 let mut back: u64 = 256 << 10;
1002 loop {
1003 let from = self.align(lo.saturating_sub(back));
1004 if let Some(found) = self.scan_for(from, ref_ti, target, mode, all_sync)? {
1005 break Some(found);
1006 }
1007 if from <= self.first_off {
1008 break None;
1009 }
1010 back = back.saturating_mul(4);
1011 }
1012 };
1013 match landing {
1014 Some((off, pts)) => {
1015 self.reset_at(off, Some(pts));
1016 self.last_off = off;
1017 }
1018 None if mode == SeekMode::SyncAfter => {
1019 self.reset_at(self.file_len, None);
1020 self.last_off = self.file_len;
1021 return Err(Error::Eof);
1022 }
1023 None => {
1024 self.reset_at(self.first_off, None);
1025 self.last_off = self.first_off;
1026 }
1027 }
1028 Ok(())
1029 }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034 use super::*;
1035
1036 #[test]
1037 fn unwrap_follows_the_clock_across_2_pow_33() {
1038 let m = 1i64 << 33;
1039 assert_eq!(unwrap33(5, None), 5);
1040 assert_eq!(unwrap33(10, Some(5)), 10);
1041 // Forward over the wrap.
1042 assert_eq!(unwrap33(100, Some(m - 100)), m + 100);
1043 // A little backwards (B-frame pts) across the wrap stays put.
1044 assert_eq!(unwrap33(m as u64 - 50, Some(m + 20)), m - 50);
1045 // Far later: still the nearest candidate.
1046 assert_eq!(unwrap33(7, Some(3 * m + 1)), 3 * m + 7);
1047 }
1048
1049 #[test]
1050 fn pes_header_timestamps() {
1051 let mut p = vec![0, 0, 1, 0xE0, 0, 0, 0x80, 0xC0, 10];
1052 p.extend_from_slice(&[0x31, 0, 1, 0, 3]); // pts 1
1053 p.extend_from_slice(&[0x11, 0, 1, 0, 1]); // dts 0
1054 p.extend_from_slice(&[9, 9]);
1055 let h = parse_pes(&p).unwrap();
1056 assert_eq!((h.pts, h.dts, h.payload), (Some(1), Some(0), 19));
1057 assert!(parse_pes(&p[..12]).is_none());
1058 assert!(parse_pes(&[1, 2, 3]).is_none());
1059 }
1060}