forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ps.rs1572 lines, 52.5 KiBHistoryRawDownload
1//! MPEG-1 system streams, MPEG-2 program streams (`.mpg`, `.mpeg`, `.vob`, `.m2p`)
2//! and raw MPEG-1/2 video elementary streams (`.m2v`, `.mpv`).
3//!
4//! # Joins (byte-concatenated programs)
5//!
6//! A pack clock (SCR) that steps back by more than 0.5 s, or forward by more than 1 s,
7//! between two consecutive packs starts a new *epoch* (33-bit wraps are removed first).
8//! The SCR only places an epoch on its own clock; at open, each epoch after the first is
9//! shifted so that its first picture is presented where the previous epoch's last
10//! picture ends (latest presentation time plus one frame), measured on the video track.
11//! Audio takes the same shift, so its offset to the video stays the muxer's. The
12//! timeline is therefore continuous: the duration is the sum of the segments and a seek
13//! past a join is as exact as one before it. Without a video picture on either side of a
14//! join the SCR-continuous shift is kept. A restart of the PTS without one of the SCR
15//! is not detected.
16
17use std::collections::{HashMap, VecDeque};
18use std::io::{Read, Seek};
19
20use ec_core::registry::{Demuxer, SeekMode, StreamInfo};
21use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};
22
23use crate::codec::{StreamKind, annexb_to_length_prefixed};
24use crate::demux::{Stats, TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33};
25use crate::psi::{EsEntry, descriptors};
26use crate::track::{PesIn, Queued, TICKS, Track};
27use crate::window::Window;
28
29const MAX_TRACKS: usize = 128;
30const PROBE_BYTES: u64 = 32 << 20;
31/// Files up to this size are walked completely at open to find SCR discontinuities.
32const FULL_WALK: u64 = 96 << 20;
33/// Samples taken to look for a backwards SCR in a larger file.
34const SAMPLES: u64 = 256;
35const BISECT_STOP: u64 = 64 << 10;
36/// A pack clock stepping back by more than this (0.5 s) starts a new timeline epoch.
37const BACK: i64 = TICKS / 2;
38/// A pack clock stepping forward by more than this (1 s) between two consecutive packs
39/// also starts a new epoch (a join of two programs that began at different clocks).
40const FWD: i64 = TICKS;
41/// How far before a join the end of the old segment is measured.
42const JOIN_WINDOW: u64 = 4 << 20;
43/// How far after a join the start of the new segment is measured.
44const JOIN_HEAD: u64 = 1 << 20;
45/// Bytes of a raw elementary stream handed to the picture cutter at a time.
46const ES_CHUNK: usize = 64 << 10;
47/// Pictures indexed in a raw elementary stream.
48const MAX_PICS: usize = 4 << 20;
49/// Largest element: a 16-bit PES length plus its 6-byte header.
50const MAX_EL: usize = 6 + 65535;
51
52/// What the file is.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum PsKind {
55 /// MPEG-1 system stream (`0x2` marker in the pack header).
56 Mpeg1System,
57 /// MPEG-2 program stream (`0x44` marker), VOB included.
58 Mpeg2Program,
59 /// A bare MPEG-1/2 video elementary stream; timestamps are made from the frame rate.
60 VideoElementary,
61}
62
63// ---------------------------------------------------------------------------
64// Pack and element parsing
65// ---------------------------------------------------------------------------
66
67/// A pack header at `b[0..]`: `(length, scr in 90 kHz ticks, mpeg2)`.
68fn parse_pack(b: &[u8]) -> Option<(usize, u64, bool)> {
69 if b.get(..4)? != [0, 0, 1, 0xBA] {
70 return None;
71 }
72 let h = b.get(4..)?;
73 if h.first()? >> 6 == 1 {
74 let h = h.get(..10)?;
75 if h[0] & 0xC4 != 0x44 || h[2] & 4 == 0 || h[4] & 4 == 0 || h[5] & 1 == 0 {
76 return None;
77 }
78 let scr = (u64::from((h[0] >> 3) & 7) << 30)
79 | (u64::from(h[0] & 3) << 28)
80 | (u64::from(h[1]) << 20)
81 | (u64::from(h[2] >> 3) << 15)
82 | (u64::from(h[2] & 3) << 13)
83 | (u64::from(h[3]) << 5)
84 | u64::from(h[4] >> 3);
85 let stuff = usize::from(*b.get(13)? & 7);
86 Some((14 + stuff, scr, true))
87 } else if h.first()? >> 4 == 2 {
88 let scr = read_ts(h)?;
89 Some((12, scr, false))
90 } else {
91 None
92 }
93}
94
95/// True when `b` starts with a system-level start code: pack, system header, PES or end code.
96fn system_code(b: &[u8]) -> bool {
97 b.len() >= 4 && b[..3] == [0, 0, 1] && b[3] >= 0xB9
98}
99
100#[derive(Debug, Clone, Copy)]
101enum El {
102 /// End of file.
103 Eof,
104 /// Not a valid element: resynchronise.
105 Bad,
106 Pack {
107 len: usize,
108 scr: u64,
109 },
110 /// Anything with a 16-bit length (system header, PSM, PES, padding), or the end code.
111 Pes {
112 id: u8,
113 len: usize,
114 /// The file ends inside this element.
115 cut: bool,
116 },
117}
118
119/// Finds the first confirmed pack header in `buf` (a valid pack followed by a system
120/// start code, and the elements after it as far as `buf` shows them).
121fn find_pack(buf: &[u8], from: usize) -> Option<usize> {
122 let mut i = from;
123 while i + 4 <= buf.len() {
124 if buf[i + 2] > 1 {
125 i += 3;
126 continue;
127 }
128 if buf[i..i + 4] == [0, 0, 1, 0xBA]
129 && let Some((len, _, _)) = parse_pack(&buf[i..])
130 {
131 let rest = buf.get(i + len..).unwrap_or(&[]);
132 if rest.len() < 4 || system_code(rest) {
133 return Some(i);
134 }
135 }
136 i += 1;
137 }
138 None
139}
140
141/// True when `head` (the first few KiB of a file) starts an MPEG-1 system or MPEG-2
142/// program stream (a pack header, after at most a few bytes of padding).
143pub fn is_mpegps(head: &[u8]) -> bool {
144 find_pack(head, 0).is_some_and(|at| at < 4096)
145}
146
147/// True when `head` starts a raw MPEG-1/2 video elementary stream (a sequence header,
148/// after at most a few zero bytes).
149pub fn is_mpeg_video_es(head: &[u8]) -> bool {
150 es_start(head).is_some()
151}
152
153fn es_start(head: &[u8]) -> Option<usize> {
154 let z = head.iter().take(16).take_while(|&&b| b == 0).count();
155 let at = z.saturating_sub(2);
156 let h = head.get(at..at + 11)?;
157 let ok = h[..4] == [0, 0, 1, 0xB3]
158 && (u16::from(h[4]) << 4 | u16::from(h[5] >> 4)) != 0
159 && (u16::from(h[5] & 15) << 8 | u16::from(h[6])) != 0
160 && h[10] & 0x20 != 0;
161 ok.then_some(at)
162}
163
164// ---------------------------------------------------------------------------
165// Clock and epochs
166// ---------------------------------------------------------------------------
167
168/// A PSM entry: stream type and its descriptors (tag, body).
169type PsmEntry = (u8, Vec<(u8, Vec<u8>)>);
170
171/// The pack clock unwrapped into a continuous `u` (33-bit wraps removed) and the shift
172/// that keeps the presented timeline monotonic over SCR resets: `T = u + shift`.
173#[derive(Debug, Clone, Copy)]
174struct Clock {
175 last_raw: Option<u64>,
176 cur_u: i64,
177 shift: i64,
178}
179
180impl Clock {
181 /// Feeds a pack's SCR. `true` when it stepped back far enough to start a new epoch.
182 fn feed(&mut self, raw: u64) -> bool {
183 const M: i64 = 1 << 33;
184 let Some(last) = self.last_raw.replace(raw) else {
185 self.cur_u = unwrap33(raw, Some(self.cur_u));
186 return false;
187 };
188 let mut d = (raw as i64 - last as i64).rem_euclid(M);
189 if d >= M / 2 {
190 d -= M;
191 }
192 if !(-BACK..=FWD).contains(&d) {
193 let last_t = self.cur_u + self.shift;
194 self.cur_u = raw as i64;
195 self.shift = last_t - self.cur_u;
196 true
197 } else {
198 self.cur_u += d;
199 false
200 }
201 }
202}
203
204/// A stretch of the file with one SCR timeline.
205#[derive(Debug, Clone, Copy)]
206struct Epoch {
207 off: u64,
208 shift: i64,
209 /// `u` of the first pack.
210 base: i64,
211}
212
213// ---------------------------------------------------------------------------
214// Raw video elementary streams: the picture index
215// ---------------------------------------------------------------------------
216
217struct Pic {
218 off: u64,
219 key: bool,
220 pts: i64,
221 dts: i64,
222}
223
224/// Every picture of a raw stream with timestamps made from the frame rate: pictures are
225/// grouped (a GOP or sequence header, or an anchor whose temporal reference does not
226/// advance, starts a group), the display index is the group's frame count so far plus
227/// the temporal reference, `pts` is that index and `dts` the decode index less the
228/// reordering depth, both in frame durations.
229struct EsIndex {
230 pics: Vec<Pic>,
231 start: i64,
232 end: i64,
233}
234
235// ---------------------------------------------------------------------------
236// The demuxer
237// ---------------------------------------------------------------------------
238
239/// MPEG-1 system / MPEG-2 program stream demuxer (and raw MPEG video elementary
240/// streams).
241pub struct PsDemuxer<R> {
242 win: Window<R>,
243 file_len: u64,
244 kind: PsKind,
245 first_off: u64,
246 pos: u64,
247 psm: HashMap<u8, PsmEntry>,
248 tracks: Vec<Track>,
249 key_map: HashMap<u16, usize>,
250 streams: Vec<StreamInfo>,
251 queue: VecDeque<Queued>,
252 eof: bool,
253 stats: Stats,
254 framing: VideoFraming,
255 last_off: u64,
256 duration: Option<i64>,
257 frozen: bool,
258 clock: Clock,
259 epochs: Vec<Epoch>,
260 first_scr: Option<i64>,
261 es: Option<EsIndex>,
262 scratch: Vec<u8>,
263 /// A damaged element was skipped since the last PES; flags the next one.
264 bad_next: bool,
265 /// After a seek: drop this many pictures of the reference video track that start
266 /// in the PES at the landing offset ahead of the keyframe.
267 skip: Option<(usize, u64, u32)>,
268 /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every
269 /// packet that starts before this offset.
270 pre_drop: Option<u64>,
271 walk_limit: u64,
272}
273
274impl<R: Read + Seek> PsDemuxer<R> {
275 /// Opens `reader` as a program stream, a system stream or a raw video stream.
276 pub fn new(reader: R) -> Result<PsDemuxer<R>> {
277 Self::open(reader, FULL_WALK)
278 }
279
280 /// As [`PsDemuxer::new`], with files larger than `walk_limit` bytes checked for SCR
281 /// resets by sampling instead of a full walk (tests exercise that path on small files).
282 #[doc(hidden)]
283 pub fn with_walk_limit(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
284 Self::open(reader, walk_limit)
285 }
286
287 fn open(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
288 let mut win = Window::new(reader);
289 let file_len = win.len()?;
290 let head = win.get(0, 64 * 1024)?;
291 let (kind, first_off) = if let Some(at) = find_pack(head, 0) {
292 let mpeg2 = parse_pack(&head[at..]).is_some_and(|p| p.2);
293 (
294 if mpeg2 {
295 PsKind::Mpeg2Program
296 } else {
297 PsKind::Mpeg1System
298 },
299 at as u64,
300 )
301 } else if let Some(at) = es_start(head) {
302 (PsKind::VideoElementary, at as u64)
303 } else {
304 return Err(Error::corrupt("mpegps: no pack header or sequence header"));
305 };
306 let mut d = PsDemuxer {
307 win,
308 file_len,
309 kind,
310 first_off,
311 pos: first_off,
312 psm: HashMap::new(),
313 tracks: Vec::new(),
314 key_map: HashMap::new(),
315 streams: Vec::new(),
316 queue: VecDeque::new(),
317 eof: false,
318 stats: Stats::default(),
319 framing: VideoFraming::AnnexB,
320 last_off: first_off,
321 duration: None,
322 frozen: false,
323 clock: Clock {
324 last_raw: None,
325 cur_u: 0,
326 shift: 0,
327 },
328 epochs: Vec::new(),
329 first_scr: None,
330 es: None,
331 scratch: Vec::new(),
332 bad_next: false,
333 skip: None,
334 pre_drop: None,
335 walk_limit,
336 };
337 if kind == PsKind::VideoElementary {
338 d.open_es()?;
339 } else {
340 d.open_ps()?;
341 }
342 Ok(d)
343 }
344
345 // ----- public queries -----------------------------------------------------
346
347 /// What the file is: system stream, program stream or raw video.
348 pub fn kind(&self) -> PsKind {
349 self.kind
350 }
351
352 /// Every elementary stream seen (including refused ones), in order of appearance.
353 /// `pid` is the `stream_id` in the high byte and, for private_stream_1, the
354 /// substream id in the low byte; `stream_type` is the program stream map's value
355 /// when there is one, else the MPEG-TS type of what the stream is.
356 pub fn tracks(&self) -> Vec<TrackInfo> {
357 self.tracks
358 .iter()
359 .map(|t| TrackInfo {
360 pid: t.es.pid,
361 stream_type: t.es.stream_type,
362 kind: t.kind.clone(),
363 stream: t.stream,
364 refusal: t.refusal.clone(),
365 language: None,
366 })
367 .collect()
368 }
369
370 /// `stream_id` of stream `stream`.
371 pub fn stream_id(&self, stream: u32) -> Option<u8> {
372 self.stream_key(stream).map(|k| (k >> 8) as u8)
373 }
374
375 /// `(stream_id << 8) | substream_id` of stream `stream` (substream 0 outside private_stream_1).
376 pub fn stream_key(&self, stream: u32) -> Option<u16> {
377 self.tracks
378 .iter()
379 .find(|t| t.stream == Some(stream))
380 .map(|t| t.es.pid)
381 }
382
383 /// The 90 kHz time base of every packet.
384 pub fn time_base(&self) -> TimeBase {
385 TimeBase::new(1, TICKS)
386 }
387
388 /// Length in seconds, from the first and last timestamps.
389 pub fn duration_secs(&self) -> Option<f64> {
390 self.duration.map(|d| d as f64 / TICKS as f64)
391 }
392
393 /// Counters of what was repaired or skipped (`resyncs`, `discontinuities` = SCR
394 /// resets, `bad_pes`); the transport-only counters stay 0.
395 pub fn stats(&self) -> Stats {
396 self.stats
397 }
398
399 /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps
400 /// after each are shifted to continue the timeline.
401 pub fn epoch_count(&self) -> usize {
402 self.epochs.len().max(1)
403 }
404
405 /// File offset of the PES (or raw picture) that began the last packet returned;
406 /// after [`Demuxer::seek`] it is where the read resumes.
407 pub fn last_packet_offset(&self) -> u64 {
408 self.last_off
409 }
410
411 /// Sets how H.264 and HEVC packets are framed (default Annex B).
412 pub fn set_video_framing(&mut self, framing: VideoFraming) {
413 self.framing = framing;
414 }
415
416 // ----- elements ---------------------------------------------------------------
417
418 fn el_at(&mut self, pos: u64) -> Result<El> {
419 let avail = self.file_len.saturating_sub(pos);
420 if avail == 0 {
421 return Ok(El::Eof);
422 }
423 let b = self.win.get(pos, 32)?;
424 if b.len() < 4 {
425 return Ok(El::Bad);
426 }
427 if !system_code(b) {
428 return Ok(El::Bad);
429 }
430 let code = b[3];
431 let (total, pack) = if code == 0xBA {
432 match parse_pack(b) {
433 Some((len, scr, _)) => (len, Some(scr)),
434 None => return Ok(El::Bad),
435 }
436 } else if code == 0xB9 {
437 (4, None)
438 } else {
439 if b.len() < 6 {
440 return Ok(El::Bad);
441 }
442 (6 + ((usize::from(b[4]) << 8) | usize::from(b[5])), None)
443 };
444 let cut = (total as u64) > avail;
445 if !cut {
446 // What follows must be another element (or the end of the file).
447 let after = self.win.get(pos + total as u64, 4)?;
448 if !after.is_empty() && !system_code(after) && after.len() >= 4 {
449 return Ok(El::Bad);
450 }
451 }
452 Ok(match pack {
453 Some(scr) if !cut => El::Pack { len: total, scr },
454 Some(_) => El::Bad,
455 None => El::Pes {
456 id: code,
457 len: total,
458 cut,
459 },
460 })
461 }
462
463 /// The next confirmed pack header at or after `from`.
464 fn next_pack(&mut self, from: u64) -> Result<Option<u64>> {
465 let mut at = from;
466 loop {
467 let buf = self.win.get(at, 64 * 1024)?;
468 if buf.len() < 4 {
469 return Ok(None);
470 }
471 let full = buf.len() == 64 * 1024;
472 let limit = if full { buf.len() - 32 } else { buf.len() };
473 if let Some(i) = find_pack(buf, 0).filter(|&i| i < limit) {
474 return Ok(Some(at + i as u64));
475 }
476 if !full {
477 return Ok(None);
478 }
479 at += limit as u64;
480 }
481 }
482
483 // ----- engine -------------------------------------------------------------------
484
485 fn mark_bad(&mut self) {
486 self.bad_next = true;
487 }
488
489 /// Processes one element. `Ok(false)` once the end was reached and everything
490 /// buffered was flushed.
491 fn step(&mut self) -> Result<bool> {
492 if self.eof {
493 return Ok(false);
494 }
495 if self.kind == PsKind::VideoElementary {
496 return self.step_es();
497 }
498 let pos = self.pos;
499 match self.el_at(pos)? {
500 El::Eof => {
501 self.finish();
502 Ok(false)
503 }
504 El::Bad => {
505 self.stats.resyncs += 1;
506 self.mark_bad();
507 match self.next_pack(pos + 1)? {
508 Some(p) => {
509 self.pos = p;
510 Ok(true)
511 }
512 None => {
513 self.finish();
514 Ok(false)
515 }
516 }
517 }
518 El::Pack { len, scr } => {
519 self.pos += len as u64;
520 self.on_pack(scr, pos);
521 Ok(true)
522 }
523 El::Pes { id, len, cut } => {
524 let avail = (self.file_len - pos) as usize;
525 let take = len.min(avail).min(MAX_EL);
526 let mut buf = std::mem::take(&mut self.scratch);
527 buf.clear();
528 buf.extend_from_slice(self.win.get(pos, take)?);
529 self.pos += take as u64;
530 if cut {
531 self.mark_bad();
532 }
533 match id {
534 0xBC => self.on_psm(&buf),
535 0xBD | 0xC0..=0xEF | 0xFD..=0xFE | 0xFA | 0xFB | 0xFC => {
536 self.on_pes(pos, &buf);
537 }
538 _ => {}
539 }
540 self.scratch = buf;
541 if cut {
542 self.finish();
543 return Ok(false);
544 }
545 Ok(true)
546 }
547 }
548 }
549
550 fn on_pack(&mut self, scr: u64, at: u64) {
551 if self.first_scr.is_none() {
552 self.first_scr = Some(scr as i64);
553 }
554 if self.clock.feed(scr) {
555 self.stats.discontinuities += 1;
556 // The table made at open knows this join with its aligned shift.
557 if let Some(e) = self.epochs.iter().find(|e| e.off == at) {
558 self.clock.shift = e.shift;
559 }
560 // Whatever is half-read belongs to the old timeline.
561 for ti in 0..self.tracks.len() {
562 self.tracks[ti].flush(ti, &mut self.queue);
563 self.tracks[ti].reset(None);
564 }
565 }
566 }
567
568 fn finish(&mut self) {
569 for ti in 0..self.tracks.len() {
570 self.tracks[ti].flush(ti, &mut self.queue);
571 }
572 self.eof = true;
573 }
574
575 fn on_psm(&mut self, b: &[u8]) {
576 if self.frozen || b.len() < 16 || b[6] & 0x80 == 0 {
577 return;
578 }
579 let info = (usize::from(b[8]) << 8) | usize::from(b[9]);
580 let at = 10 + info;
581 let Some(map_len) = b
582 .get(at..at + 2)
583 .map(|m| (usize::from(m[0]) << 8) | usize::from(m[1]))
584 else {
585 return;
586 };
587 let end = (at + 2 + map_len).min(b.len().saturating_sub(4));
588 let mut i = at + 2;
589 while i + 4 <= end && self.psm.len() < 256 {
590 let (ty, id) = (b[i], b[i + 1]);
591 let dl = (usize::from(b[i + 2]) << 8) | usize::from(b[i + 3]);
592 let d = b.get(i + 4..(i + 4 + dl).min(end)).unwrap_or(&[]);
593 self.psm.insert(id, (ty, descriptors(d)));
594 i += 4 + dl;
595 }
596 }
597
598 /// Timestamps of a PES header on the presented timeline.
599 fn stamp(&self, pts: Option<u64>, dts: Option<u64>) -> (Option<i64>, Option<i64>) {
600 const M: i64 = 1 << 33;
601 let t = |raw: u64| unwrap33(raw, Some(self.clock.cur_u)) + self.clock.shift;
602 let p = pts.map(t);
603 let d = match (dts, pts, p) {
604 (Some(d), Some(rp), Some(p)) => {
605 let mut delta = (d as i64 - rp as i64).rem_euclid(M);
606 if delta >= M / 2 {
607 delta -= M;
608 }
609 Some(p + delta)
610 }
611 _ => None,
612 };
613 (p, d)
614 }
615
616 fn on_pes(&mut self, off: u64, b: &[u8]) {
617 let id = b[3];
618 let (pts, dts, mut payload) = if b.get(6).is_some_and(|&x| x & 0xC0 == 0x80) {
619 match parse_pes(b) {
620 Some(h) => (h.pts, h.dts, h.payload),
621 None => {
622 self.stats.bad_pes += 1;
623 return;
624 }
625 }
626 } else {
627 match parse_pes1(b) {
628 Some(h) => h,
629 None => {
630 self.stats.bad_pes += 1;
631 return;
632 }
633 }
634 };
635 let mut sub = 0u8;
636 if id == 0xBD {
637 let Some(&s) = b.get(payload) else {
638 return;
639 };
640 sub = s;
641 payload += match s {
642 0x20..=0x3F => 1,
643 0x80..=0xAF => 4,
644 _ => 0,
645 };
646 if payload > b.len() {
647 return;
648 }
649 }
650 let key = (u16::from(id) << 8) | u16::from(sub);
651 let ti = match self.key_map.get(&key) {
652 Some(&ti) => ti,
653 None => {
654 if self.frozen || self.tracks.len() >= MAX_TRACKS {
655 return;
656 }
657 let Some(t) = self.make_track(id, sub, &b[payload..]) else {
658 return;
659 };
660 self.tracks.push(t);
661 self.key_map.insert(key, self.tracks.len() - 1);
662 self.tracks.len() - 1
663 }
664 };
665 if !self.tracks[ti].wanted() {
666 return;
667 }
668 let (pts, dts) = self.stamp(pts, dts);
669 let input = PesIn {
670 payload: &b[payload..],
671 pts,
672 dts,
673 off,
674 rai: false,
675 bad: std::mem::take(&mut self.bad_next),
676 };
677 let t = &mut self.tracks[ti];
678 if t.psv.on {
679 t.ps_video_push(ti, &input, &mut self.queue);
680 } else {
681 t.push_pes(ti, &input, &mut self.queue);
682 }
683 }
684
685 fn make_track(&self, id: u8, sub: u8, payload: &[u8]) -> Option<Track> {
686 let key = (u16::from(id) << 8) | u16::from(sub);
687 let entry = |stream_type: u8, descriptors: Vec<(u8, Vec<u8>)>| EsEntry {
688 stream_type,
689 pid: key,
690 descriptors,
691 };
692 let mapped = self.psm.get(&id).cloned();
693 let mut t = match id {
694 0xBD => match sub {
695 0x80..=0x87 => Track::new(entry(0x81, Vec::new())),
696 0xA0..=0xA7 => {
697 let mut t = Track::new(entry(0x80, Vec::new()));
698 t.kind = StreamKind::DvdLpcm;
699 t.refusal = None;
700 t
701 }
702 0x20..=0x3F => {
703 let mut t = Track::new(entry(0x06, Vec::new()));
704 t.kind = StreamKind::DvdSub;
705 t.refusal = None;
706 t
707 }
708 0x88..=0x8F | 0x98..=0x9F => {
709 let mut t = Track::new(entry(0x82, Vec::new()));
710 t.refusal = Some(format!(
711 "dts (private_stream_1 substream 0x{sub:02x}): DTS has no decoder in the family"
712 ));
713 t
714 }
715 s => {
716 let mut t = Track::new(entry(0x06, Vec::new()));
717 t.kind = StreamKind::Other(format!("private_stream_1_0x{s:02x}"));
718 t.refusal = Some(format!(
719 "private_stream_1 substream 0x{s:02x}: no demux path for this substream"
720 ));
721 t
722 }
723 },
724 0xE0..=0xEF => {
725 let (ty, d) = match mapped {
726 Some(m) => m,
727 None => (sniff_video(payload)?, Vec::new()),
728 };
729 Track::new(entry(ty, d))
730 }
731 0xC0..=0xDF => {
732 let (ty, d) = match mapped {
733 Some(m) => m,
734 None => (sniff_audio(payload)?, Vec::new()),
735 };
736 Track::new(entry(ty, d))
737 }
738 _ => {
739 let (ty, d) = mapped?;
740 Track::new(entry(ty, d))
741 }
742 };
743 t.psv.ps = true;
744 t.psv.on = t.kind.is_video();
745 Some(t)
746 }
747
748 // ----- open (program streams) -----------------------------------------------------
749
750 fn open_ps(&mut self) -> Result<()> {
751 let first = match self.el_at(self.first_off)? {
752 El::Pack { scr, .. } => scr as i64,
753 _ => return Err(Error::corrupt("mpegps: no pack header")),
754 };
755 self.epochs = vec![Epoch {
756 off: self.first_off,
757 shift: 0,
758 base: first,
759 }];
760 self.reset_at(self.first_off);
761 self.probe()?;
762 if self.tracks.is_empty() {
763 return Err(Error::corrupt("mpegps: no elementary streams found"));
764 }
765 self.build_epochs()?;
766 self.finish_open()
767 }
768
769 fn probe_complete(&self, read: u64) -> bool {
770 let wanted: Vec<&Track> = self.tracks.iter().filter(|t| t.wanted()).collect();
771 if wanted.is_empty() {
772 return false;
773 }
774 let ready = wanted.iter().all(|t| t.ready());
775 let timed = wanted.iter().all(|t| {
776 if t.kind.is_video() {
777 t.dts_seen.len() >= 12
778 } else {
779 t.packets >= 3
780 }
781 });
782 let span = self
783 .first_scr
784 .is_some_and(|f| self.clock.cur_u - f >= TICKS);
785 ready && timed && (span || read >= 4 << 20)
786 }
787
788 fn probe(&mut self) -> Result<()> {
789 let start = self.pos;
790 loop {
791 self.queue.clear();
792 if self.eof {
793 break;
794 }
795 let read = self.pos - start;
796 if read >= PROBE_BYTES || self.probe_complete(read) {
797 break;
798 }
799 self.step()?;
800 }
801 self.queue.clear();
802 Ok(())
803 }
804
805 /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack
806 /// headers decides whether a full walk is needed.
807 fn build_epochs(&mut self) -> Result<()> {
808 let full = if self.file_len <= self.walk_limit {
809 true
810 } else {
811 let mut last: Option<u64> = None;
812 let mut back = false;
813 for k in 0..SAMPLES {
814 let off = self.first_off + (self.file_len - self.first_off) * k / SAMPLES;
815 let Some(p) = self.next_pack(off)? else {
816 break;
817 };
818 if let El::Pack { scr, .. } = self.el_at(p)? {
819 if let Some(l) = last {
820 let d = (scr as i64 - l as i64).rem_euclid(1 << 33);
821 if d >= 1 << 32 {
822 back = true;
823 break;
824 }
825 }
826 last = Some(scr);
827 }
828 }
829 back
830 };
831 if !full {
832 return Ok(());
833 }
834 let first = self.epochs[0];
835 let mut clock = Clock {
836 last_raw: None,
837 cur_u: first.base,
838 shift: 0,
839 };
840 let mut epochs = vec![first];
841 let mut pos = self.first_off;
842 loop {
843 match self.el_at(pos)? {
844 El::Eof => break,
845 El::Bad => match self.next_pack(pos + 1)? {
846 Some(p) => pos = p,
847 None => break,
848 },
849 El::Pack { len, scr } => {
850 if clock.feed(scr) && epochs.len() < 1 << 16 {
851 epochs.push(Epoch {
852 off: pos,
853 shift: clock.shift,
854 base: clock.cur_u,
855 });
856 }
857 pos += len as u64;
858 }
859 El::Pes { len, .. } => pos += len as u64,
860 }
861 }
862 self.epochs = epochs;
863 self.align_epochs()
864 }
865
866 /// Makes the timeline continuous over joins. The SCR says where a segment sits on its
867 /// own clock only; the presentation times (what players and `duration` use) are
868 /// aligned instead: segment `k` is shifted so that its first picture is shown where
869 /// segment `k-1`'s last picture ends (latest presentation time plus one frame).
870 /// Audio takes the segment's shift too, so its offset to the video is the muxer's.
871 /// Without a video picture on either side the SCR-continuous shift is kept.
872 fn align_epochs(&mut self) -> Result<()> {
873 if self.epochs.len() < 2 {
874 return Ok(());
875 }
876 let Some(rt) = self
877 .tracks
878 .iter()
879 .position(|t| t.wanted() && t.kind.is_video())
880 else {
881 return Ok(());
882 };
883 let ft = self.tracks[rt].frame_ticks().unwrap_or(0);
884 let snapshot: Vec<_> = self
885 .tracks
886 .iter()
887 .map(|t| (t.min_pts, t.max_end, t.packets, t.dts_seen.clone()))
888 .collect();
889 let was_frozen = std::mem::replace(&mut self.frozen, true);
890 let prov: Vec<i64> = self.epochs.iter().map(|e| e.shift).collect();
891 let mut result = Ok(());
892 for k in 1..self.epochs.len() {
893 let (prev, cur) = (self.epochs[k - 1], self.epochs[k]);
894 let next_off = self.epochs.get(k + 1).map_or(self.file_len, |e| e.off);
895 // End of the segment before the join, on its final timeline.
896 let from = prev.off.max(cur.off.saturating_sub(JOIN_WINDOW));
897 let end = match self.scan_segment(from, cur.off, rt) {
898 Ok((_, e)) => e.map(|e| e + ft),
899 Err(e) => {
900 result = Err(e);
901 break;
902 }
903 };
904 // Start of the new segment on its own clock (shift 0).
905 self.epochs[k].shift = 0;
906 let start = match self.scan_segment(cur.off, next_off.min(cur.off + JOIN_HEAD), rt) {
907 Ok((s, _)) => s,
908 Err(e) => {
909 result = Err(e);
910 break;
911 }
912 };
913 self.epochs[k].shift = match (end, start) {
914 (Some(end), Some(start)) => end - start,
915 _ => prov[k] - prov[k - 1] + prev.shift,
916 };
917 }
918 self.frozen = was_frozen;
919 for (t, (min, max, packets, seen)) in self.tracks.iter_mut().zip(snapshot) {
920 t.min_pts = min;
921 t.max_end = max;
922 t.packets = packets;
923 t.dts_seen = seen;
924 }
925 self.reset_at(self.first_off);
926 result
927 }
928
929 /// Reads `[from, to)` and returns the video track `rt`'s earliest presentation time
930 /// and latest end seen there.
931 fn scan_segment(
932 &mut self,
933 from: u64,
934 to: u64,
935 rt: usize,
936 ) -> Result<(Option<i64>, Option<i64>)> {
937 self.reset_at(from);
938 self.tracks[rt].min_pts = None;
939 self.tracks[rt].max_end = None;
940 while self.pos < to {
941 let more = self.step()?;
942 self.queue.clear();
943 if !more {
944 break;
945 }
946 }
947 for ti in 0..self.tracks.len() {
948 self.tracks[ti].flush(ti, &mut self.queue);
949 }
950 self.queue.clear();
951 Ok((self.tracks[rt].min_pts, self.tracks[rt].max_end))
952 }
953
954 fn epoch_at(&self, off: u64) -> Epoch {
955 let i = self.epochs.partition_point(|e| e.off <= off);
956 self.epochs[i.saturating_sub(1)]
957 }
958
959 fn reset_at(&mut self, off: u64) {
960 self.queue.clear();
961 self.eof = false;
962 self.pos = off;
963 self.bad_next = false;
964 self.skip = None;
965 self.pre_drop = None;
966 for t in &mut self.tracks {
967 t.reset(None);
968 }
969 if self.kind != PsKind::VideoElementary {
970 let e = self.epoch_at(off);
971 self.clock = Clock {
972 last_raw: None,
973 cur_u: e.base,
974 shift: e.shift,
975 };
976 }
977 }
978
979 fn finish_open(&mut self) -> Result<()> {
980 for t in &mut self.tracks {
981 t.start_time = t.min_pts;
982 }
983 self.assign_streams();
984 self.frozen = true;
985 let tail = self.scan_tail();
986 self.frozen = false;
987 tail?;
988 self.reset_at(self.first_off);
989 self.stats = Stats::default();
990 Ok(())
991 }
992
993 fn assign_streams(&mut self) {
994 for ti in 0..self.tracks.len() {
995 self.make_stream(ti);
996 }
997 }
998
999 fn make_stream(&mut self, ti: usize) -> Option<u32> {
1000 if let Some(s) = self.tracks[ti].stream {
1001 return Some(s);
1002 }
1003 let index = self.streams.len() as u32;
1004 let mut info = self.tracks[ti].stream_info(index)?;
1005 if !self
1006 .streams
1007 .iter()
1008 .any(|s| s.params.codec.media_type() == info.params.codec.media_type() && s.default)
1009 {
1010 info.default = true;
1011 }
1012 self.tracks[ti].stream = Some(index);
1013 self.streams.push(info);
1014 Some(index)
1015 }
1016
1017 fn scan_tail(&mut self) -> Result<()> {
1018 let mut win: u64 = 4 << 20;
1019 loop {
1020 for t in &mut self.tracks {
1021 t.max_end = None;
1022 }
1023 let from = self.file_len.saturating_sub(win);
1024 let off = from.max(self.first_off);
1025 self.reset_at(off);
1026 // The timestamps are unwrapped against the epoch's base, so a clock that
1027 // wrapped 33 bits since the start of the file still lands near it.
1028 while self.step()? {
1029 self.queue.clear();
1030 }
1031 self.queue.clear();
1032 let timed = self
1033 .tracks
1034 .iter()
1035 .filter(|t| t.stream.is_some() && !t.kind.is_bitmap_sub())
1036 .all(|t| t.max_end.is_some());
1037 if timed || off == self.first_off {
1038 break;
1039 }
1040 win = win.saturating_mul(4);
1041 }
1042 let mut longest: Option<i64> = None;
1043 for t in &self.tracks {
1044 // Subtitles do not define the programme's length: its duration is the audio
1045 // and video's, whatever the subtitle cues span.
1046 if t.kind.is_bitmap_sub() {
1047 continue;
1048 }
1049 let (Some(si), Some(end), Some(start)) = (t.stream, t.max_end, t.start_time) else {
1050 continue;
1051 };
1052 let end = end
1053 + if t.kind.is_video() {
1054 t.frame_ticks().unwrap_or(0)
1055 } else {
1056 0
1057 };
1058 let d = end - start;
1059 if d > 0
1060 && let Some(s) = self.streams.get_mut(si as usize)
1061 {
1062 s.duration = Some(d);
1063 longest = Some(longest.map_or(d, |l| l.max(d)));
1064 }
1065 }
1066 self.duration = longest;
1067 Ok(())
1068 }
1069
1070 // ----- reading -------------------------------------------------------------------------
1071
1072 fn pump(&mut self) -> Result<Option<Queued>> {
1073 loop {
1074 if let Some(mut q) = self.queue.pop_front() {
1075 if self.pre_drop.is_some_and(|o| q.off < o) {
1076 continue;
1077 }
1078 if let Some((ti, off, n)) = &mut self.skip
1079 && q.track == *ti
1080 && q.off == *off
1081 && *n > 0
1082 {
1083 *n -= 1;
1084 continue;
1085 }
1086 if let Some(ix) = &self.es
1087 && let Ok(i) = ix.pics.binary_search_by_key(&q.off, |p| p.off)
1088 {
1089 q.pts = Some(ix.pics[i].pts);
1090 q.dts = Some(ix.pics[i].dts);
1091 }
1092 return Ok(Some(q));
1093 }
1094 if !self.step()? {
1095 if self.queue.is_empty() {
1096 return Ok(None);
1097 }
1098 continue;
1099 }
1100 }
1101 }
1102
1103 fn make_packet(&mut self, q: Queued) -> Option<Packet> {
1104 let ti = q.track;
1105 let stream = match self.tracks[ti].stream {
1106 Some(s) => s,
1107 None => {
1108 if self.tracks[ti].start_time.is_none() {
1109 self.tracks[ti].start_time = self.tracks[ti].min_pts;
1110 }
1111 self.make_stream(ti)?
1112 }
1113 };
1114 let kind = &self.tracks[ti].kind;
1115 let data = if self.framing == VideoFraming::LengthPrefixed && kind.is_annexb_video() {
1116 annexb_to_length_prefixed(&q.data, 4)
1117 } else {
1118 q.data
1119 };
1120 let mut p = Packet::new(stream, self.time_base(), data);
1121 p.pts = q.pts;
1122 p.dts = q.dts;
1123 p.duration = q.dur;
1124 p.flags = PacketFlags {
1125 keyframe: q.key,
1126 corrupt: q.corrupt,
1127 ..PacketFlags::default()
1128 };
1129 self.last_off = q.off;
1130 Some(p)
1131 }
1132
1133 // ----- seeking ------------------------------------------------------------------------------
1134
1135 fn time_at(&mut self, off: u64, ti: usize) -> Result<Option<i64>> {
1136 self.reset_at(off);
1137 while let Some(q) = self.pump()? {
1138 if q.track == ti
1139 && let Some(t) = q.dts.or(q.pts)
1140 {
1141 return Ok(Some(t));
1142 }
1143 }
1144 Ok(None)
1145 }
1146
1147 fn scan_for(
1148 &mut self,
1149 from: u64,
1150 ti: usize,
1151 target: i64,
1152 mode: SeekMode,
1153 all_sync: bool,
1154 ) -> Result<Option<(u64, u32, u64)>> {
1155 self.reset_at(from);
1156 let mut best = None;
1157 // Offsets of the two latest keyframes of the track, for [`PsDemuxer::land`].
1158 let (mut key_cur, mut key_prev): (Option<u64>, Option<u64>) = (None, None);
1159 // Pictures of the track seen so far that start in the same packet.
1160 let (mut run_off, mut run_n) = (u64::MAX, 0u32);
1161 while let Some(q) = self.pump()? {
1162 if q.track != ti {
1163 continue;
1164 }
1165 if q.off != run_off {
1166 (run_off, run_n) = (q.off, 0);
1167 }
1168 let idx = run_n;
1169 run_n += 1;
1170 if q.key && key_cur != Some(q.off) {
1171 (key_prev, key_cur) = (key_cur, Some(q.off));
1172 }
1173 let pre = key_prev.or(key_cur).unwrap_or(q.off).min(q.off);
1174 // A picture whose timestamps were derived from its neighbours cannot start a read.
1175 // (A keyframe whose time follows from the display order is trusted once the
1176 // scan has seen the GOP before it.)
1177 let trusted = !q.derived || (q.key && q.pts.is_some() && key_prev.is_some());
1178 let Some(pts) = q.pts.or(q.dts).filter(|_| trusted) else {
1179 continue;
1180 };
1181 let dts = q.dts.unwrap_or(pts);
1182 let key = all_sync || q.key;
1183 match mode {
1184 SeekMode::SyncAfter => {
1185 if key && pts >= target {
1186 return Ok(Some((q.off, idx, pre)));
1187 }
1188 }
1189 SeekMode::Exact => {
1190 if dts > target {
1191 break;
1192 }
1193 best = Some((q.off, idx, pre));
1194 }
1195 SeekMode::SyncBefore => {
1196 if dts > target {
1197 break;
1198 }
1199 if key && pts <= target {
1200 best = Some((q.off, idx, pre));
1201 }
1202 }
1203 }
1204 }
1205 Ok(best)
1206 }
1207
1208 fn seek_scan(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1209 let Some(ti) = self.tracks.iter().position(|t| t.stream == Some(stream)) else {
1210 return Err(Error::corrupt(format!(
1211 "mpegps: no stream {stream} to seek"
1212 )));
1213 };
1214 let target = to.rescale(self.time_base(), Rounding::Nearest).ticks;
1215 if self.es.is_some() {
1216 return self.seek_es(target, mode);
1217 }
1218 let ref_ti = self
1219 .tracks
1220 .iter()
1221 .position(|t| t.stream.is_some() && t.kind.is_video())
1222 .unwrap_or(ti);
1223 let all_sync = !self.tracks[ref_ti].kind.is_video();
1224 let start = self.tracks[ref_ti].start_time.unwrap_or(0);
1225 let landing = if target <= start && mode != SeekMode::Exact {
1226 None
1227 } else {
1228 let mut lo = self.first_off;
1229 let mut hi = self.file_len;
1230 while hi - lo > BISECT_STOP {
1231 let mid = lo + (hi - lo) / 2;
1232 match self.time_at(mid, ref_ti)? {
1233 Some(t) if t <= target => lo = mid,
1234 _ => hi = mid,
1235 }
1236 }
1237 let mut back: u64 = 256 << 10;
1238 loop {
1239 let from = lo.saturating_sub(back).max(self.first_off);
1240 if let Some(found) = self.scan_for(from, ref_ti, target, mode, all_sync)? {
1241 break Some(found);
1242 }
1243 if from <= self.first_off {
1244 break None;
1245 }
1246 back = back.saturating_mul(4);
1247 }
1248 };
1249 self.land(landing, mode, Some(ref_ti))
1250 }
1251
1252 fn land(
1253 &mut self,
1254 landing: Option<(u64, u32, u64)>,
1255 mode: SeekMode,
1256 ref_ti: Option<usize>,
1257 ) -> Result<()> {
1258 match landing {
1259 Some((off, n, pre)) => {
1260 // MPEG-1/2 pictures without a stamp take their time from the display order
1261 // so far, which needs the whole GOP before the landing one: reading starts
1262 // at the keyframe before the landing keyframe (`pre`) and drops what starts
1263 // ahead of the landing offset, so the packets equal the sequential read's.
1264 let pre = if ref_ti.is_some_and(|ti| self.tracks[ti].kind.is_mpeg_video()) {
1265 pre.min(off)
1266 } else {
1267 off
1268 };
1269 self.reset_at(pre);
1270 self.last_off = off;
1271 if pre < off {
1272 self.pre_drop = Some(off);
1273 }
1274 if n > 0 {
1275 self.skip = ref_ti.map(|ti| (ti, off, n));
1276 }
1277 }
1278 None if mode == SeekMode::SyncAfter => {
1279 self.reset_at(self.file_len);
1280 self.last_off = self.file_len;
1281 return Err(Error::Eof);
1282 }
1283 None => {
1284 self.reset_at(self.first_off);
1285 self.last_off = self.first_off;
1286 }
1287 }
1288 Ok(())
1289 }
1290
1291 // ----- raw video elementary streams ------------------------------------------------------------
1292
1293 fn open_es(&mut self) -> Result<()> {
1294 let mut t = Track::new(EsEntry {
1295 stream_type: 0x02,
1296 pid: 0xE000,
1297 descriptors: Vec::new(),
1298 });
1299 t.psv.on = true;
1300 t.psv.buf.exact = true;
1301 self.tracks.push(t);
1302 self.key_map.insert(0xE000, 0);
1303 self.reset_at(self.first_off);
1304 while !self.eof && !self.tracks[0].ready() && self.pos - self.first_off < PROBE_BYTES {
1305 self.step()?;
1306 self.queue.clear();
1307 }
1308 self.queue.clear();
1309 let Some(f) = self.tracks[0].cfg.mpeg2.clone() else {
1310 return Err(Error::corrupt("mpegps: no decodable sequence header"));
1311 };
1312 let ix = self.index_es(f.rate)?;
1313 self.tracks[0].start_time = Some(ix.start);
1314 self.duration = Some(ix.end - ix.start);
1315 self.es = Some(ix);
1316 self.assign_streams();
1317 if let Some(s) = self.streams.first_mut() {
1318 s.duration = self.duration;
1319 }
1320 self.reset_at(self.first_off);
1321 Ok(())
1322 }
1323
1324 fn step_es(&mut self) -> Result<bool> {
1325 let pos = self.pos;
1326 let b = self.win.get(pos, ES_CHUNK)?;
1327 if b.is_empty() {
1328 self.finish();
1329 return Ok(false);
1330 }
1331 let mut chunk = std::mem::take(&mut self.scratch);
1332 chunk.clear();
1333 chunk.extend_from_slice(b);
1334 self.pos += chunk.len() as u64;
1335 let input = PesIn {
1336 payload: &chunk,
1337 pts: None,
1338 dts: None,
1339 off: pos,
1340 rai: false,
1341 bad: false,
1342 };
1343 self.tracks[0].ps_video_push(0, &input, &mut self.queue);
1344 self.scratch = chunk;
1345 Ok(true)
1346 }
1347
1348 /// Reads the whole stream once for its pictures.
1349 fn index_es(&mut self, rate: (u32, u32)) -> Result<EsIndex> {
1350 const CH: usize = 1 << 20;
1351 struct Raw {
1352 off: u64,
1353 tr: i32,
1354 ty: u8,
1355 key: bool,
1356 group: bool,
1357 }
1358 let mut raw: Vec<Raw> = Vec::new();
1359 let mut off = self.first_off;
1360 // The chain of header codes in front of the next picture header.
1361 let mut chain: Option<(u64, bool, bool)> = None; // (start, has B3, has B3 or B8)
1362 loop {
1363 let buf = self.win.get(off, CH + 8)?;
1364 let at_end = buf.len() < CH + 8;
1365 let limit = if at_end { buf.len() } else { CH };
1366 let mut i = 0usize;
1367 while i < limit && i + 4 <= buf.len() {
1368 if buf[i + 2] > 1 {
1369 i += 3;
1370 continue;
1371 }
1372 if !(buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1) {
1373 i += 1;
1374 continue;
1375 }
1376 let code = buf[i + 3];
1377 let here = off + i as u64;
1378 match code {
1379 0xB2 | 0xB5 => {
1380 chain.get_or_insert((here, false, false));
1381 }
1382 0xB3 | 0xB8 => {
1383 let c = chain.get_or_insert((here, false, false));
1384 c.2 = true;
1385 if code == 0xB3 {
1386 c.1 = true;
1387 }
1388 }
1389 0x00 => {
1390 let (start, seq, grp) = chain.take().unwrap_or((here, false, false));
1391 if raw.len() >= MAX_PICS {
1392 return Err(Error::corrupt("mpegps: too many pictures to index"));
1393 }
1394 let (b4, b5) = (buf.get(i + 4).copied(), buf.get(i + 5).copied());
1395 if let (Some(b4), Some(b5)) = (b4, b5) {
1396 let ty = (b5 >> 3) & 7;
1397 raw.push(Raw {
1398 off: start,
1399 tr: (i32::from(b4) << 2) | i32::from(b5 >> 6),
1400 ty,
1401 key: ty == 1 || seq,
1402 group: grp,
1403 });
1404 }
1405 }
1406 _ => chain = None,
1407 }
1408 i += 4;
1409 }
1410 if at_end {
1411 break;
1412 }
1413 off += i as u64;
1414 }
1415 if raw.is_empty() {
1416 return Err(Error::corrupt("mpegps: no pictures"));
1417 }
1418 let (num, den) = (i128::from(rate.0.max(1)), i128::from(rate.1.max(1)));
1419 let ticks =
1420 |n: i64| -> i64 { (i128::from(n) * i128::from(TICKS) * den).div_euclid(num) as i64 };
1421 // Groups and display indices.
1422 let mut disp: Vec<i64> = Vec::with_capacity(raw.len());
1423 let (mut base, mut gmax, mut anchor) = (0i64, -1i64, None::<i32>);
1424 for (i, r) in raw.iter().enumerate() {
1425 let new_group = r.group || (r.ty != 3 && anchor.is_some_and(|a| r.tr < a));
1426 if new_group && i > 0 {
1427 base += gmax + 1;
1428 gmax = -1;
1429 anchor = None;
1430 }
1431 disp.push(base + i64::from(r.tr));
1432 gmax = gmax.max(i64::from(r.tr));
1433 if r.ty != 3 {
1434 anchor = Some(r.tr);
1435 }
1436 }
1437 let min_disp = disp.iter().copied().min().unwrap_or(0);
1438 // How far a picture is displayed behind its decode position, over the first
1439 // dozens of pictures.
1440 let delay = disp
1441 .iter()
1442 .take(96)
1443 .enumerate()
1444 .map(|(i, d)| i as i64 - (d - min_disp))
1445 .max()
1446 .unwrap_or(0)
1447 .max(0);
1448 let mut pics = Vec::with_capacity(raw.len());
1449 let mut start = i64::MAX;
1450 let mut end = i64::MIN;
1451 for (i, r) in raw.iter().enumerate() {
1452 let pts = ticks(disp[i] - min_disp);
1453 let dts = ticks(i as i64 - delay).min(pts);
1454 start = start.min(pts);
1455 end = end.max(pts);
1456 pics.push(Pic {
1457 off: r.off,
1458 key: r.key,
1459 pts,
1460 dts,
1461 });
1462 }
1463 let one = ticks(1);
1464 Ok(EsIndex {
1465 pics,
1466 start,
1467 end: end + one,
1468 })
1469 }
1470
1471 fn seek_es(&mut self, target: i64, mode: SeekMode) -> Result<()> {
1472 let Some(ix) = &self.es else {
1473 return Ok(());
1474 };
1475 let pics = &ix.pics;
1476 let upto = pics.partition_point(|p| p.dts <= target);
1477 let landing = match mode {
1478 SeekMode::Exact => upto.checked_sub(1).map(|i| (pics[i].off, 0, pics[i].off)),
1479 SeekMode::SyncBefore => pics[..upto]
1480 .iter()
1481 .rev()
1482 .find(|p| p.key && p.pts <= target)
1483 .map(|p| (p.off, 0, p.off)),
1484 SeekMode::SyncAfter => pics
1485 .iter()
1486 .find(|p| p.key && p.pts >= target)
1487 .map(|p| (p.off, 0, p.off)),
1488 };
1489 self.land(landing, mode, None)
1490 }
1491}
1492
1493/// The codec of a video stream with no program stream map entry, from the first start
1494/// code of its first packet that tells: 0x02 MPEG video, 0x1B H.264, 0x24 HEVC.
1495fn sniff_video(p: &[u8]) -> Option<u8> {
1496 let mut i = 0;
1497 for _ in 0..64 {
1498 while i + 4 <= p.len() && p[i..i + 3] != [0, 0, 1] {
1499 i += 1;
1500 }
1501 let b = *p.get(i + 3)?;
1502 match b {
1503 0x00 | 0xB2 | 0xB3 | 0xB5 | 0xB8 => return Some(0x02),
1504 0x40 | 0x42 | 0x44 | 0x46 | 0x4E | 0x26 | 0x28 => return Some(0x24),
1505 // SPS / PPS with a non-zero nal_ref_idc; slice-like bytes are MPEG-2 slice codes.
1506 0x47 | 0x48 | 0x67 | 0x68 => return Some(0x1B),
1507 _ => {}
1508 }
1509 i += 4;
1510 }
1511 None
1512}
1513
1514/// MPEG audio (0x03) or AAC in ADTS (0x0F) from the first sync pattern of the payload.
1515fn sniff_audio(p: &[u8]) -> Option<u8> {
1516 p.windows(2)
1517 .find(|w| w[0] == 0xFF && w[1] & 0xF0 == 0xF0)
1518 .map(|w| if w[1] & 0x06 == 0 { 0x0F } else { 0x03 })
1519}
1520
1521/// MPEG-1 PES header: `(pts, dts, payload offset)`.
1522fn parse_pes1(b: &[u8]) -> Option<(Option<u64>, Option<u64>, usize)> {
1523 let mut i = 6usize;
1524 let mut stuff = 0;
1525 while *b.get(i)? == 0xFF {
1526 i += 1;
1527 stuff += 1;
1528 if stuff > 16 {
1529 return None;
1530 }
1531 }
1532 if b[i] & 0xC0 == 0x40 {
1533 i += 2;
1534 }
1535 let f = *b.get(i)?;
1536 match f >> 4 {
1537 2 => Some((Some(read_ts(b.get(i..)?)?), None, i + 5)),
1538 3 => Some((
1539 Some(read_ts(b.get(i..)?)?),
1540 Some(read_ts(b.get(i + 5..)?)?),
1541 i + 10,
1542 )),
1543 _ if f == 0x0F => Some((None, None, i + 1)),
1544 _ => None,
1545 }
1546}
1547
1548impl<R: Read + Seek + Send> Demuxer for PsDemuxer<R> {
1549 fn streams(&self) -> &[StreamInfo] {
1550 &self.streams
1551 }
1552
1553 fn next_packet(&mut self) -> Result<Packet> {
1554 loop {
1555 let Some(q) = self.pump()? else {
1556 return Err(Error::Eof);
1557 };
1558 if let Some(p) = self.make_packet(q) {
1559 return Ok(p);
1560 }
1561 }
1562 }
1563
1564 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1565 let saved = self.stats;
1566 self.frozen = true;
1567 let r = self.seek_scan(stream, to, mode);
1568 self.frozen = false;
1569 self.stats = saved;
1570 r
1571 }
1572}