FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M9.15: MPEG-2 Systems demuxer crate (TS 188/192/204, PS/VOB, PSI, PES, access-unit index)
Brandon Thomas104dff1e82b8
diff --git a/crates/mpegts/src/es.rs b/crates/mpegts/src/es.rsnew file mode 100644index 000000000..901db0b31--- /dev/null+++ b/crates/mpegts/src/es.rs@@ -0,0 +1,580 @@+//! Splitting elementary streams into access units while the file is scanned.+//!+//! The scanners feed each stream's payload bytes chunk by chunk (a TS packet's payload, a PS+//! packet's payload). A chunk is identified by the position the reader restarts from (`pos`) and+//! the elementary-stream offset of its first byte. Splitting needs only a few bytes beyond a+//! boundary, so only the most recent chunks are remembered.++use std::collections::VecDeque;++use crate::{Codec, PictureInfo, Unit};++/// How a stream is cut into units.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Mode {+ /// MPEG-1/2 video: one coded frame (a frame picture or two field pictures) per unit.+ MpegVideo,+ /// H.264 / HEVC: one PES packet (with a timestamp) per unit; NAL types give the flags.+ Nal { hevc: bool },+ /// Framed audio with self-describing frame headers.+ Audio(AudioSync),+ /// One PES packet per unit.+ Pes,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum AudioSync {+ Mpa,+ Adts,+ Loas,+ Ac3,+}++impl Mode {+ fn of(codec: &Codec) -> Mode {+ match codec {+ Codec::Mpeg1Video | Codec::Mpeg2Video => Mode::MpegVideo,+ Codec::H264 => Mode::Nal { hevc: false },+ Codec::Hevc => Mode::Nal { hevc: true },+ Codec::MpegAudio => Mode::Audio(AudioSync::Mpa),+ Codec::AacAdts => Mode::Audio(AudioSync::Adts),+ Codec::AacLatm => Mode::Audio(AudioSync::Loas),+ Codec::Ac3 | Codec::Eac3 => Mode::Audio(AudioSync::Ac3),+ _ => Mode::Pes,+ }+ }+}++#[derive(Clone, Copy)]+struct PesMark {+ es_start: u64,+ pts: Option<i64>,+ dts: Option<i64>,+ used: bool,+}++/// A unit whose end is not known yet.+#[derive(Clone, Copy)]+struct Open {+ start: u64,+ pos: u64,+ offset: u32,+ pts: Option<i64>,+ dts: Option<i64>,+ key: bool,+ disposable: bool,+ /// A coded slice has been seen (H.264 / HEVC).+ vcl: bool,+ picture: Option<PictureInfo>,+}++/// MPEG video picture waiting for its coding extension (to tell fields from frames).+#[derive(Clone, Copy)]+struct PendingPicture {+ /// Start of the unit if the picture begins one (its first sequence / GOP header).+ unit_start: u64,+ /// The picture start code (timestamps belong to the unit whose picture starts in the PES).+ at: u64,+ info: PictureInfo,+}++pub(crate) struct Splitter {+ mode: Mode,+ /// Elementary-stream bytes fed so far.+ es_pos: u64,+ /// Recent chunks: (reader position, ES offset of the first byte).+ chunks: VecDeque<(u64, u64)>,+ pes: VecDeque<PesMark>,+ /// Unconsumed bytes (start codes / frame headers spanning chunks), starting at `buf_start`.+ buf: Vec<u8>,+ buf_start: u64,+ open: Option<Open>,+ pub units: Vec<Unit>,+ pub skipped: u64,+ // MPEG video state+ header_start: Option<u64>,+ seq_in_unit: bool,+ gop: Option<(bool, bool)>,+ pending: Option<PendingPicture>,+ open_field: Option<u8>,+ // audio state+ next_frame: Option<u64>,+}++/// AC-3 frame sizes in 16-bit words for 48 / 44.1 / 32 kHz (A/52 Table 5.18), by+/// frmsizecod / 2; 44.1 kHz adds a word for odd frmsizecod.+const AC3_KBPS: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640];++pub(crate) fn ac3_frame_bytes(fscod: u8, frmsizecod: u8) -> Option<usize> {+ let kbps = *AC3_KBPS.get((frmsizecod / 2) as usize)?;+ let words = match fscod {+ 0 => kbps * 2,+ 1 => kbps * 96_000 / 44_100 + (frmsizecod & 1) as u32,+ 2 => kbps * 3,+ _ => return None,+ };+ Some(words as usize * 2)+}++const MPA_KBPS: [[u16; 15]; 5] = [+ [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448], // MPEG-1 layer I+ [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384], // MPEG-1 layer II+ [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320], // MPEG-1 layer III+ [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256], // MPEG-2/2.5 layer I+ [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], // MPEG-2/2.5 layers II, III+];++/// MPEG audio frame header (ISO/IEC 11172-3 §2.4.2.3, 13818-3 LSF): (frame bytes, sample rate,+/// samples per frame).+pub(crate) fn mpa_header(b: &[u8]) -> Option<(usize, u32, u32)> {+ if b.len() < 4 || b[0] != 0xFF || b[1] & 0xE0 != 0xE0 {+ return None;+ }+ let version = (b[1] >> 3) & 3; // 0: 2.5, 2: MPEG-2, 3: MPEG-1+ let layer = (b[1] >> 1) & 3; // 3: I, 2: II, 1: III+ let br = (b[2] >> 4) as usize;+ let sr = (b[2] >> 2) & 3;+ let pad = ((b[2] >> 1) & 1) as usize;+ if version == 1 || layer == 0 || br == 0 || br == 15 || sr == 3 {+ return None;+ }+ let rate = [44_100u32, 48_000, 32_000][sr as usize]+ >> match version {+ 3 => 0,+ 2 => 1,+ _ => 2,+ };+ let table = match (version == 3, layer) {+ (true, 3) => 0,+ (true, 2) => 1,+ (true, _) => 2,+ (false, 3) => 3,+ (false, _) => 4,+ };+ let kbps = MPA_KBPS[table][br] as usize;+ let (bytes, samples) = match layer {+ 3 => ((12 * kbps * 1000 / rate as usize + pad) * 4, 384),+ 2 => (144 * kbps * 1000 / rate as usize + pad, 1152),+ _ if version == 3 => (144 * kbps * 1000 / rate as usize + pad, 1152),+ _ => (72 * kbps * 1000 / rate as usize + pad, 576),+ };+ (bytes >= 4).then_some((bytes, rate, samples))+}++/// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)`+/// is never returned).+fn frame_len(sync: AudioSync, b: &[u8]) -> Option<usize> {+ match sync {+ AudioSync::Mpa => mpa_header(b).map(|h| h.0),+ AudioSync::Adts => {+ if b.len() < 7 || b[0] != 0xFF || b[1] & 0xF6 != 0xF0 {+ return None;+ }+ let len = ((b[3] as usize & 3) << 11) | (b[4] as usize) << 3 | (b[5] as usize) >> 5;+ (len >= 7).then_some(len)+ }+ AudioSync::Loas => {+ if b.len() < 3 || b[0] != 0x56 || b[1] & 0xE0 != 0xE0 {+ return None;+ }+ let len = ((b[1] as usize & 0x1F) << 8) | b[2] as usize;+ (len > 0).then_some(len + 3)+ }+ AudioSync::Ac3 => {+ if b.len() < 6 || b[0] != 0x0B || b[1] != 0x77 {+ return None;+ }+ let bsid = b[5] >> 3;+ if bsid <= 10 {+ ac3_frame_bytes(b[4] >> 6, b[4] & 0x3F)+ } else if bsid <= 16 {+ // E-AC-3: frmsiz+ Some(((((b[2] & 7) as usize) << 8) | b[3] as usize) * 2 + 2)+ } else {+ None+ }+ }+ }+}++impl Splitter {+ pub fn new(codec: &Codec) -> Splitter {+ Splitter {+ mode: Mode::of(codec),+ es_pos: 0,+ chunks: VecDeque::new(),+ pes: VecDeque::new(),+ buf: Vec::new(),+ buf_start: 0,+ open: None,+ units: Vec::new(),+ skipped: 0,+ header_start: None,+ seq_in_unit: false,+ gop: None,+ pending: None,+ open_field: None,+ next_frame: None,+ }+ }++ /// A PES packet starts (its payload follows in the next chunks).+ pub fn pes_start(&mut self, pts: Option<i64>, dts: Option<i64>) {+ self.pes.push_back(PesMark { es_start: self.es_pos, pts, dts, used: false });+ while self.pes.len() > 64 {+ self.pes.pop_front();+ }+ match self.mode {+ Mode::Pes => self.begin_pes_unit(true),+ Mode::Nal { .. } => self.begin_pes_unit(pts.is_some() || dts.is_some()),+ _ => {}+ }+ }++ /// PES-delimited units: a packet with a timestamp (or any packet in plain PES mode) starts a+ /// new unit; one without continues the previous unit.+ fn begin_pes_unit(&mut self, new: bool) {+ if !new && self.open.is_some() {+ return;+ }+ let at = self.es_pos;+ self.close(at);+ // the chunk of this position arrives with the next feed: resolved there+ self.open = Some(Open { start: at, pos: u64::MAX, offset: 0, pts: None, dts: None, key: false, disposable: false, vcl: false, picture: None });+ if let Some((pts, dts)) = self.timestamps_at(at) {+ let o = self.open.as_mut().expect("open");+ o.pts = pts;+ o.dts = dts;+ }+ if self.mode == Mode::Pes {+ self.open.as_mut().expect("open").key = true;+ }+ }++ /// The unused timestamps of the PES packet holding `at` (consumed).+ fn timestamps_at(&mut self, at: u64) -> Option<(Option<i64>, Option<i64>)> {+ let m = self.pes.iter_mut().rev().find(|m| m.es_start <= at)?;+ if m.used || (m.pts.is_none() && m.dts.is_none()) {+ return None;+ }+ m.used = true;+ Some((m.pts, m.dts))+ }++ /// Reader position and offset of elementary-stream byte `at`.+ fn locate(&self, at: u64) -> Option<(u64, u32)> {+ let c = self.chunks.iter().rev().find(|c| c.1 <= at)?;+ Some((c.0, (at - c.1) as u32))+ }++ /// End the open unit at `end`.+ fn close(&mut self, end: u64) {+ let Some(o) = self.open.take() else { return };+ if end <= o.start || o.pos == u64::MAX {+ return;+ }+ let size = (end - o.start).min(u32::MAX as u64) as u32;+ self.units.push(Unit { pts: o.pts, dts: o.dts, key: o.key, disposable: o.disposable, size, pos: o.pos, offset: o.offset, picture: o.picture });+ }++ /// Payload bytes of one chunk (`pos`: where the reader restarts to find them).+ pub fn feed(&mut self, pos: u64, data: &[u8]) {+ if data.is_empty() {+ return;+ }+ self.chunks.push_back((pos, self.es_pos));+ if let Some(o) = self.open.as_mut()+ && o.pos == u64::MAX+ && o.start == self.es_pos+ {+ o.pos = pos;+ o.offset = 0;+ }+ let start = self.es_pos;+ self.es_pos += data.len() as u64;+ match self.mode {+ Mode::Pes => {}+ Mode::Nal { hevc } => self.scan_nal(start, data, hevc),+ Mode::MpegVideo => self.scan_mpeg(start, data),+ Mode::Audio(sync) => self.scan_audio(start, data, sync),+ }+ // forget chunks no pending position can refer to+ let keep_from = self.buf_start.min(self.pending.map_or(u64::MAX, |p| p.unit_start.min(p.at))).min(self.header_start.unwrap_or(u64::MAX));+ while self.chunks.len() > 2 && self.chunks[1].1 <= keep_from {+ self.chunks.pop_front();+ }+ }++ /// Append to the window and return it with its start.+ fn window(&mut self, start: u64, data: &[u8]) {+ if self.buf.is_empty() || self.buf_start + self.buf.len() as u64 != start {+ self.buf.clear();+ self.buf_start = start;+ }+ self.buf.extend_from_slice(data);+ }++ /// Keep only the last `keep` bytes of the window.+ fn trim(&mut self, keep: usize) {+ if self.buf.len() > keep {+ let drop = self.buf.len() - keep;+ self.buf.drain(..drop);+ self.buf_start += drop as u64;+ }+ }++ /// Start codes in the window from index `from`: (window index of `00 00 01`, code).+ fn next_start_code(&self, from: usize) -> Option<usize> {+ let b = &self.buf;+ let mut i = from;+ while i + 3 <= b.len() {+ match b[i + 2] {+ 1 if b[i] == 0 && b[i + 1] == 0 => return Some(i),+ 0 => i += 1,+ _ => i += 3,+ }+ }+ None+ }++ fn scan_nal(&mut self, start: u64, data: &[u8], hevc: bool) {+ self.window(start, data);+ let mut i = 0;+ let mut blocked = None;+ while let Some(k) = self.next_start_code(i) {+ // NAL header byte(s) needed+ if k + 5 > self.buf.len() {+ blocked = Some(k);+ break;+ }+ let h = self.buf[k + 3];+ let (key, vcl, non_ref) = if hevc {+ let t = (h >> 1) & 0x3F;+ (+ (16..=23).contains(&t),+ t < 32,+ // sub-layer non-reference pictures (TRAIL_N, TSA_N, STSA_N, RADL_N, RASL_N)+ t < 16 && t.is_multiple_of(2),+ )+ } else {+ let t = h & 0x1F;+ (t == 5, (1..=5).contains(&t), h & 0x60 == 0)+ };+ if let Some(o) = self.open.as_mut()+ && vcl+ {+ o.key |= key;+ // disposable while every slice is non-reference+ o.disposable = if o.vcl { o.disposable && non_ref } else { non_ref };+ o.vcl = true;+ }+ i = k + 3;+ }+ self.keep_tail(i, blocked);+ }++ /// Drop the scanned part of the window: keep from a start code waiting for more bytes, or+ /// the last bytes a split start code may begin in.+ fn keep_tail(&mut self, i: usize, blocked: Option<usize>) {+ let len = self.buf.len();+ let resume = blocked.unwrap_or_else(|| i.max(len.saturating_sub(3)));+ self.trim(len - resume.min(len));+ }++ fn scan_mpeg(&mut self, start: u64, data: &[u8]) {+ self.window(start, data);+ let mut i = 0;+ let mut blocked = None;+ while let Some(k) = self.next_start_code(i) {+ // up to 5 bytes after the code are inspected+ if k + 9 > self.buf.len() {+ blocked = Some(k);+ break;+ }+ let at = self.buf_start + k as u64;+ let code = self.buf[k + 3];+ let p = [self.buf[k + 4], self.buf[k + 5], self.buf[k + 6], self.buf[k + 7], self.buf[k + 8]];+ match code {+ 0xB3 => {+ self.settle_pending();+ self.header_start.get_or_insert(at);+ self.seq_in_unit = true;+ }+ 0xB8 => {+ self.settle_pending();+ self.header_start.get_or_insert(at);+ self.gop = Some((p[3] & 0x40 != 0, p[3] & 0x20 != 0));+ }+ 0x00 => {+ self.settle_pending();+ let info = PictureInfo {+ coding_type: (p[1] >> 3) & 7,+ temporal_reference: ((p[0] as u16) << 2) | (p[1] >> 6) as u16,+ structure: 3,+ progressive_frame: true,+ sequence_header: self.seq_in_unit,+ gop: self.gop.is_some(),+ closed_gop: self.gop.is_some_and(|g| g.0),+ broken_link: self.gop.is_some_and(|g| g.1),+ ..Default::default()+ };+ let unit_start = self.header_start.take().unwrap_or(at);+ self.seq_in_unit = false;+ self.gop = None;+ self.pending = Some(PendingPicture { unit_start, at, info });+ }+ 0xB5 if p[0] >> 4 == 8 => {+ if let Some(pp) = self.pending.as_mut() {+ pp.info.structure = p[2] & 3;+ pp.info.top_field_first = p[3] & 0x80 != 0;+ pp.info.repeat_first_field = p[3] & 0x02 != 0;+ pp.info.progressive_frame = p[4] & 0x80 != 0;+ }+ self.settle_pending();+ }+ 0xB5 | 0xB2 => {}+ _ => self.settle_pending(),+ }+ i = k + 3;+ }+ self.keep_tail(i, blocked);+ }++ /// A picture's structure is known: start a unit, or join a first field.+ fn settle_pending(&mut self) {+ let Some(pp) = self.pending.take() else { return };+ let s = pp.info.structure;+ if let Some(first) = self.open_field+ && s != 3+ && first != s+ && s != 0+ {+ self.open_field = None;+ return;+ }+ self.close(pp.unit_start);+ let (pos, offset) = self.locate(pp.unit_start).unwrap_or((u64::MAX, 0));+ let mut o = Open {+ start: pp.unit_start,+ pos,+ offset,+ pts: None,+ dts: None,+ key: matches!(pp.info.coding_type, 1 | 4),+ disposable: pp.info.coding_type == 3,+ vcl: true,+ picture: Some(pp.info),+ };+ if let Some((pts, dts)) = self.timestamps_at(pp.at) {+ o.pts = pts;+ o.dts = dts;+ }+ self.open = Some(o);+ self.open_field = (s == 1 || s == 2).then_some(s);+ }++ fn scan_audio(&mut self, start: u64, data: &[u8], sync: AudioSync) {+ let end = start + data.len() as u64;+ // skip whole chunks inside the current frame+ if let Some(n) = self.next_frame+ && n >= end+ {+ return;+ }+ self.window(start, data);+ loop {+ let at = match self.next_frame {+ Some(n) if n >= self.buf_start => n,+ _ => self.buf_start,+ };+ let i = (at - self.buf_start) as usize;+ if i + 8 > self.buf.len() {+ // not enough bytes for a header yet+ self.trim(self.buf.len().saturating_sub(i));+ return;+ }+ match frame_len(sync, &self.buf[i..]) {+ Some(len) if self.next_frame == Some(at) || self.confirmed(sync, i, len) => {+ self.close(at);+ let (pos, offset) = self.locate(at).unwrap_or((u64::MAX, 0));+ let mut o = Open { start: at, pos, offset, pts: None, dts: None, key: true, disposable: false, vcl: false, picture: None };+ if let Some((pts, dts)) = self.timestamps_at(at) {+ o.pts = pts;+ o.dts = dts;+ }+ self.open = Some(o);+ self.next_frame = Some(at + len as u64);+ if at + len as u64 >= self.buf_start + self.buf.len() as u64 {+ self.buf.clear();+ self.buf_start = at + len as u64;+ return;+ }+ }+ _ => {+ // lost sync: look for the next header from the following byte+ self.next_frame = None;+ self.skipped += 1;+ let next = self.buf[i + 1..]+ .iter()+ .position(|&b| matches!((sync, b), (AudioSync::Ac3, 0x0B) | (AudioSync::Loas, 0x56) | (AudioSync::Mpa | AudioSync::Adts, 0xFF)));+ match next {+ Some(d) => {+ self.skipped += d as u64;+ self.trim(self.buf.len() - (i + 1 + d));+ }+ None => {+ self.skipped += (self.buf.len() - i - 1) as u64;+ self.trim(0);+ return;+ }+ }+ }+ }+ }+ }++ /// A header found while hunting for sync is accepted when the next frame's header follows+ /// it (or the data ends before it).+ fn confirmed(&self, sync: AudioSync, i: usize, len: usize) -> bool {+ let j = i + len;+ if j + 8 > self.buf.len() {+ return true;+ }+ frame_len(sync, &self.buf[j..]).is_some()+ }++ /// End of stream: close the open unit.+ pub fn finish(&mut self) {+ self.settle_pending();+ let end = match (self.mode, self.next_frame) {+ (Mode::Audio(_), Some(n)) => n.min(self.es_pos),+ _ => self.es_pos,+ };+ if let (Mode::Audio(_), Some(o)) = (self.mode, self.open) {+ // a truncated last frame is dropped+ if self.next_frame.is_some_and(|n| n > self.es_pos) {+ self.skipped += self.es_pos - o.start;+ self.open = None;+ }+ }+ self.close(end);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn audio_frame_sizes() {+ // MPEG-1 layer II 48 kHz 192 kb/s: 576 bytes; layer III 44.1 kHz 128 kb/s with padding: 418+ assert_eq!(mpa_header(&[0xFF, 0xFD, 0xA4, 0x00]), Some((576, 48_000, 1152)));+ assert_eq!(mpa_header(&[0xFF, 0xFB, 0x92, 0x00]), Some((418, 44_100, 1152)));+ // MPEG-2 layer III 24 kHz 64 kb/s: 192 bytes, 576 samples+ assert_eq!(mpa_header(&[0xFF, 0xF3, 0x84, 0x00]), Some((192, 24_000, 576)));+ // AC-3 448 kb/s at 48 kHz = 1792 bytes; 44.1 kHz 192 kb/s odd code = 836 bytes+ assert_eq!(ac3_frame_bytes(0, 30), Some(1792));+ assert_eq!(ac3_frame_bytes(1, 21), Some(836));+ assert_eq!(ac3_frame_bytes(2, 0), Some(192));+ }+}diff --git a/crates/mpegts/src/lib.rs b/crates/mpegts/src/lib.rsindex 69fb707ab..3a3c41431 100644--- a/crates/mpegts/src/lib.rs+++ b/crates/mpegts/src/lib.rs@@ -1 +1,344 @@-//! MPEG-2 Systems demuxer (work in progress).+//! Clean-room MPEG-2 Systems demuxer (ITU-T H.222.0 | ISO/IEC 13818-1).+//!+//! - **Transport Stream**: 188-byte packets, 192-byte BDAV / AVCHD packets (`.m2ts`, `.mts`:+//! a 4-byte arrival timestamp before each packet) and 204-byte packets (Reed-Solomon parity).+//! PAT / PMT (sections reassembled across packets, CRC checked), PES reassembly, PCR, PTS/DTS+//! (33-bit wrap-around unwrapped), discontinuity indicators.+//! - **Program Stream** (`.mpg`, `.vob`, `.mod`, `.tod`): MPEG-2 and ISO/IEC 11172-1 (MPEG-1)+//! packs, system headers, program stream maps, DVD private stream 1 sub-streams (AC-3, DTS,+//! LPCM).+//! - **Elementary streams** are split into access units on open — coded frames for MPEG-1/2+//! video (picture start codes, field pairs), H.264 and HEVC (access unit delimiters / first+//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, PES+//! packets for LPCM — each with its PTS/DTS (a PES timestamp belongs to the first access unit+//! that starts in the packet), random-access flag and, for MPEG video, picture type, temporal+//! reference and field structure. That index is the seeking table.+//! - Units are read back on demand by re-reading the file from the unit's first packet, so the+//! index costs a few dozen bytes per access unit.+//!+//! The crate does no decoding; `filmcraft-codecs` pairs the streams with decoders.++mod es;+mod pes;+mod ps;+mod ts;++use std::io;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("not an MPEG transport or program stream")]+ NotMpeg,+ #[error("I/O: {0}")]+ Io(#[from] io::Error),+ #[error("invalid stream: {0}")]+ Invalid(String),+}++pub type Result<T> = std::result::Result<T, Error>;++/// Random-access bytes (a file, a memory buffer).+pub trait ByteSource {+ fn len(&self) -> u64;+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;+ fn is_empty(&self) -> bool {+ self.len() == 0+ }+}++impl ByteSource for [u8] {+ fn len(&self) -> u64 {+ <[u8]>::len(self) as u64+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ let o = usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::UnexpectedEof))?;+ let src = self.get(o..o + buf.len()).ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;+ buf.copy_from_slice(src);+ Ok(())+ }+}++impl ByteSource for Vec<u8> {+ fn len(&self) -> u64 {+ self.as_slice().len() as u64+ }+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {+ self.as_slice().read_at(offset, buf)+ }+}++/// Read as much as is available at `offset` (up to `buf.len()`); returns the count.+pub(crate) fn read_some<S: ByteSource + ?Sized>(src: &S, offset: u64, buf: &mut [u8]) -> io::Result<usize> {+ let len = src.len();+ if offset >= len {+ return Ok(0);+ }+ let n = ((len - offset) as usize).min(buf.len());+ src.read_at(offset, &mut buf[..n])?;+ Ok(n)+}++/// The container layout.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Format {+ /// Transport stream with `packet_size`-byte packets whose 0x47 sync byte is at `sync_offset`+ /// (4 for 192-byte BDAV packets).+ Ts { packet_size: usize, sync_offset: usize },+ /// Program stream (`mpeg1`: ISO/IEC 11172-1 packs).+ Ps { mpeg1: bool },+}++impl Format {+ pub fn name(&self) -> &'static str {+ match self {+ Format::Ts { packet_size: 192, .. } => "MPEG-2 TS (BDAV/AVCHD)",+ Format::Ts { .. } => "MPEG-2 TS",+ Format::Ps { mpeg1: true } => "MPEG-1 System",+ Format::Ps { mpeg1: false } => "MPEG-2 PS",+ }+ }+}++/// Recognise a transport stream (five consecutive sync bytes at one of the packet sizes, within+/// the first packets) or a program stream (a pack header).+pub fn sniff(head: &[u8]) -> Option<Format> {+ for (size, off) in [(188usize, 0usize), (192, 4), (204, 0)] {+ for start in 0..size.min(head.len()) {+ let ok = (0..5).all(|k| head.get(start + off + k * size) == Some(&0x47));+ if ok {+ return Some(Format::Ts { packet_size: size, sync_offset: off });+ }+ }+ }+ // a pack header, possibly after a few zero bytes+ let z = head.iter().take(64).take_while(|&&b| b == 0).count();+ let p = z.saturating_sub(2);+ if head.len() >= p + 5 && head[p..p + 4] == [0, 0, 1, 0xBA] {+ return Some(Format::Ps { mpeg1: head[p + 4] >> 6 != 1 });+ }+ None+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kind {+ Video,+ Audio,+ Subtitle,+ Other,+}++/// What an elementary stream carries.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Codec {+ Mpeg1Video,+ Mpeg2Video,+ H264,+ Hevc,+ /// MPEG-1/2 audio (layers I-III; the layer is in each frame header).+ MpegAudio,+ /// AAC in ADTS frames.+ AacAdts,+ /// AAC in LATM/LOAS frames.+ AacLatm,+ Ac3,+ Eac3,+ Dts,+ TrueHd,+ /// Blu-ray / AVCHD LPCM (a 4-byte header per PES packet, big-endian samples).+ LpcmBluray,+ /// DVD LPCM (program stream private stream 1; format in [`Stream::lpcm`]).+ LpcmDvd,+ Subtitle(&'static str),+ /// Anything else: the stream type.+ Unknown(u8),+}++impl Codec {+ pub fn name(&self) -> String {+ match self {+ Codec::Mpeg1Video => "MPEG-1 Video".into(),+ Codec::Mpeg2Video => "MPEG-2 Video".into(),+ Codec::H264 => "H.264".into(),+ Codec::Hevc => "HEVC".into(),+ Codec::MpegAudio => "MPEG Audio".into(),+ Codec::AacAdts => "AAC (ADTS)".into(),+ Codec::AacLatm => "AAC (LATM)".into(),+ Codec::Ac3 => "AC-3".into(),+ Codec::Eac3 => "E-AC-3".into(),+ Codec::Dts => "DTS".into(),+ Codec::TrueHd => "Dolby TrueHD".into(),+ Codec::LpcmBluray => "LPCM (Blu-ray)".into(),+ Codec::LpcmDvd => "LPCM (DVD)".into(),+ Codec::Subtitle(s) => (*s).into(),+ Codec::Unknown(t) => format!("stream type 0x{t:02x}"),+ }+ }+ pub fn kind(&self) -> Kind {+ match self {+ Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc => Kind::Video,+ Codec::MpegAudio | Codec::AacAdts | Codec::AacLatm | Codec::Ac3 | Codec::Eac3 | Codec::Dts | Codec::TrueHd | Codec::LpcmBluray | Codec::LpcmDvd => {+ Kind::Audio+ }+ Codec::Subtitle(_) => Kind::Subtitle,+ Codec::Unknown(_) => Kind::Other,+ }+ }+}++/// MPEG-1/2 video picture properties of an access unit (its first picture).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct PictureInfo {+ /// 1 I, 2 P, 3 B, 4 D.+ pub coding_type: u8,+ pub temporal_reference: u16,+ /// 1 top field, 2 bottom field, 3 frame (two field pictures form one unit).+ pub structure: u8,+ pub top_field_first: bool,+ pub repeat_first_field: bool,+ pub progressive_frame: bool,+ /// A sequence header precedes the picture in this unit.+ pub sequence_header: bool,+ /// A GOP header precedes the picture (and its flags).+ pub gop: bool,+ pub closed_gop: bool,+ pub broken_link: bool,+}++/// One access unit (a coded frame, an audio frame, or an LPCM PES packet).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Unit {+ /// Presentation / decoding time stamps, 90 kHz, 33-bit wrap-around unwrapped.+ pub pts: Option<i64>,+ pub dts: Option<i64>,+ /// Decoding can start here (I / IDR / IRAP pictures; every audio frame).+ pub key: bool,+ /// No other unit depends on it (B pictures of MPEG-1/2 video, non-reference H.264/HEVC).+ pub disposable: bool,+ pub size: u32,+ /// TS: index of the packet holding the first byte; PS: byte offset of its PES packet.+ pub(crate) pos: u64,+ /// Offset of the first byte within that packet's elementary-stream payload.+ pub(crate) offset: u32,+ pub picture: Option<PictureInfo>,+}++/// DVD LPCM format (from the private stream 1 header).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct LpcmFormat {+ pub sample_rate: u32,+ pub channels: u32,+ pub bits: u32,+}++/// Where a stream's PES packets come from.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StreamId {+ /// Transport stream PID.+ Pid(u16),+ /// Program stream stream_id, and the private stream 1 sub-stream id.+ Ps { stream_id: u8, sub_id: Option<u8> },+}++#[derive(Clone, Debug)]+pub struct Stream {+ pub id: StreamId,+ /// PMT stream_type (TS), or the equivalent for program streams.+ pub stream_type: u8,+ pub codec: Codec,+ /// ISO 639 language code from the PMT.+ pub language: Option<String>,+ pub units: Vec<Unit>,+ pub lpcm: Option<LpcmFormat>,+ /// PES packets seen.+ pub pes_packets: u64,+ /// Bytes of payload ignored because the stream could not be split (e.g. before the first+ /// frame header).+ pub skipped_bytes: u64,+}++impl Stream {+ pub fn kind(&self) -> Kind {+ self.codec.kind()+ }+ /// First and last presentation timestamps (90 kHz) of the stream's units.+ pub fn pts_range(&self) -> Option<(i64, i64)> {+ let mut it = self.units.iter().filter_map(|u| u.pts);+ let first = it.next()?;+ Some(it.fold((first, first), |(a, b), p| (a.min(p), b.max(p))))+ }+}++/// A demuxed file: its streams with their access-unit tables.+#[derive(Clone, Debug)]+pub struct File {+ pub format: Format,+ pub streams: Vec<Stream>,+ /// Program number of the program the streams belong to (TS).+ pub program: Option<u16>,+ /// First and last PCR (27 MHz, unwrapped) or SCR.+ pub pcr_range: Option<(i64, i64)>,+ /// Problems found while scanning (lost sync, CRC errors, continuity errors…).+ pub warnings: Vec<String>,+}++impl File {+ /// The first stream of `kind` whose codec satisfies `f`.+ pub fn find(&self, kind: Kind, f: impl Fn(&Codec) -> bool) -> Option<usize> {+ self.streams.iter().position(|s| s.kind() == kind && !s.units.is_empty() && f(&s.codec))+ }++ /// Read access unit `i` of stream `s`.+ pub fn read_unit<S: ByteSource + ?Sized>(&self, src: &S, s: usize, i: usize) -> Result<Vec<u8>> {+ let st = self.streams.get(s).ok_or_else(|| Error::Invalid("no such stream".into()))?;+ let u = st.units.get(i).ok_or_else(|| Error::Invalid("no such unit".into()))?;+ let mut out = Vec::with_capacity(u.size as usize);+ match self.format {+ Format::Ts { packet_size, sync_offset } => ts::read(src, packet_size, sync_offset, st, u, &mut out)?,+ Format::Ps { .. } => ps::read(src, st, u, &mut out)?,+ }+ if out.len() < u.size as usize {+ return Err(Error::Invalid(format!("unit {i} truncated ({} of {} bytes)", out.len(), u.size)));+ }+ Ok(out)+ }+}++/// Scan a transport or program stream and index its access units.+pub fn open<S: ByteSource + ?Sized>(src: &S) -> Result<File> {+ let mut head = vec![0u8; 64 * 1024];+ let n = read_some(src, 0, &mut head)?;+ head.truncate(n);+ match sniff(&head).ok_or(Error::NotMpeg)? {+ Format::Ts { packet_size, sync_offset } => ts::scan(src, packet_size, sync_offset),+ Format::Ps { mpeg1 } => ps::scan(src, mpeg1),+ }+}++/// Unwraps 33-bit timestamps into a monotonic-ish i64 timeline (relative to the first one seen).+#[derive(Default, Clone, Copy)]+pub(crate) struct Unwrap {+ last: Option<i64>,+ base: i64,+}++impl Unwrap {+ const WRAP: i64 = 1 << 33;+ pub fn unwrap(&mut self, raw: i64) -> i64 {+ let mut v = raw + self.base;+ if let Some(l) = self.last {+ if v < l - Self::WRAP / 2 {+ self.base += Self::WRAP;+ v += Self::WRAP;+ } else if v > l + Self::WRAP / 2 && self.base > 0 {+ // a timestamp from before the wrap (B pictures, slightly out-of-order audio)+ v -= Self::WRAP;+ return v;+ }+ }+ self.last = Some(v);+ v+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/mpegts/src/pes.rs b/crates/mpegts/src/pes.rsnew file mode 100644index 000000000..8e5fea363--- /dev/null+++ b/crates/mpegts/src/pes.rs@@ -0,0 +1,111 @@+//! PES packet headers (H.222.0 §2.4.3.6; ISO/IEC 11172-1 §2.4.3.3 for MPEG-1 packets).++/// A parsed PES header.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct PesHeader {+ pub stream_id: u8,+ /// PES_packet_length (bytes after the length field; 0 = unbounded, video in TS).+ pub packet_length: usize,+ /// Bytes from the packet start code to the first payload byte.+ pub header_len: usize,+ /// Raw 33-bit timestamps.+ pub pts: Option<i64>,+ pub dts: Option<i64>,+}++/// Stream ids whose packets have no optional header (§2.4.3.7).+pub(crate) fn plain_stream(id: u8) -> bool {+ matches!(id, 0xBC | 0xBE | 0xBF | 0xF0 | 0xF1 | 0xF2 | 0xF8 | 0xFF)+}++pub(crate) fn timestamp(b: &[u8]) -> i64 {+ (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64+}++/// Parse a PES header at the start of `b` (which begins with `00 00 01 stream_id`). `None` when+/// `b` is too short to hold the whole header or it is malformed.+pub(crate) fn parse(b: &[u8]) -> Option<PesHeader> {+ if b.len() < 6 || b[0] != 0 || b[1] != 0 || b[2] != 1 {+ return None;+ }+ let stream_id = b[3];+ let packet_length = u16::from_be_bytes([b[4], b[5]]) as usize;+ if plain_stream(stream_id) {+ return Some(PesHeader { stream_id, packet_length, header_len: 6, pts: None, dts: None });+ }+ if b.len() >= 9 && b[6] & 0xC0 == 0x80 {+ // ISO/IEC 13818-1 syntax+ let flags = b[7];+ let header_len = 9 + b[8] as usize;+ if b.len() < header_len {+ return None;+ }+ let (mut pts, mut dts) = (None, None);+ if flags & 0x80 != 0 && header_len >= 14 {+ pts = Some(timestamp(&b[9..14]));+ if flags & 0x40 != 0 && header_len >= 19 {+ dts = Some(timestamp(&b[14..19]));+ }+ }+ return Some(PesHeader { stream_id, packet_length, header_len, pts, dts });+ }+ // ISO/IEC 11172-1 syntax: stuffing, STD buffer, timestamps+ let mut p = 6;+ let mut stuffing = 0;+ while b.get(p) == Some(&0xFF) {+ p += 1;+ stuffing += 1;+ if stuffing > 16 {+ return None;+ }+ }+ let c = *b.get(p)?;+ if c >> 6 == 1 {+ p += 2;+ }+ let c = *b.get(p)?;+ let (mut pts, mut dts) = (None, None);+ match c >> 4 {+ 2 => {+ pts = Some(timestamp(b.get(p..p + 5)?));+ p += 5;+ }+ 3 => {+ pts = Some(timestamp(b.get(p..p + 5)?));+ dts = Some(timestamp(b.get(p + 5..p + 10)?));+ p += 10;+ }+ 0 if c == 0x0F => p += 1,+ _ => return None,+ }+ Some(PesHeader { stream_id, packet_length, header_len: p, pts, dts })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] {+ [(prefix << 4) | (((v >> 30) & 7) as u8) << 1 | 1, (v >> 22) as u8, (((v >> 15) & 0x7F) as u8) << 1 | 1, (v >> 7) as u8, ((v & 0x7F) as u8) << 1 | 1]+ }++ #[test]+ fn mpeg2_and_mpeg1_headers() {+ let pts = 0x1_2345_6789i64;+ let dts = 0x0_8765_4321i64;+ let mut b = vec![0, 0, 1, 0xE0, 0, 0, 0x80, 0xC0, 10];+ b.extend(ts_bytes(3, pts));+ b.extend(ts_bytes(1, dts));+ b.push(0xAA);+ let h = parse(&b).unwrap();+ assert_eq!((h.stream_id, h.header_len, h.pts, h.dts), (0xE0, 19, Some(pts), Some(dts)));+ // MPEG-1: stuffing, STD buffer, PTS only+ let mut b = vec![0, 0, 1, 0xC0, 0, 20, 0xFF, 0xFF, 0x40, 0x20];+ b.extend(ts_bytes(2, 90_000));+ let h = parse(&b).unwrap();+ assert_eq!((h.header_len, h.pts, h.dts), (15, Some(90_000), None));+ assert_eq!(parse(&[0, 0, 1, 0xC0, 0, 1, 0x0F]).unwrap().header_len, 7);+ assert_eq!(parse(&[0, 0, 1, 0xBE, 0, 4]).unwrap().header_len, 6);+ assert!(parse(&[0, 0, 1, 0xE0, 0, 0, 0x80, 0x80]).is_none());+ }+}diff --git a/crates/mpegts/src/ps.rs b/crates/mpegts/src/ps.rsnew file mode 100644index 000000000..4ff123751--- /dev/null+++ b/crates/mpegts/src/ps.rs@@ -0,0 +1,268 @@+//! Program streams (H.222.0 §2.5; ISO/IEC 11172-1 §2.4.3): packs, system headers, the program+//! stream map, PES packets, and the DVD sub-streams of private stream 1.++use std::collections::HashMap;++use crate::es::Splitter;+use crate::pes;+use crate::{ByteSource, Codec, Error, File, Format, LpcmFormat, Result, Stream, StreamId, Unit, Unwrap, read_some};++/// Sequential reader with a refillable window.+struct Win<'a, S: ByteSource + ?Sized> {+ src: &'a S,+ buf: Vec<u8>,+ start: u64,+}++impl<'a, S: ByteSource + ?Sized> Win<'a, S> {+ fn new(src: &'a S) -> Self {+ Self { src, buf: Vec::new(), start: 0 }+ }+ /// The bytes [pos, pos + n) (fewer at the end of the file).+ fn get(&mut self, pos: u64, n: usize) -> Result<&[u8]> {+ let have = pos >= self.start && pos + n as u64 <= self.start + self.buf.len() as u64;+ if !have {+ let want = n.max(1 << 20);+ self.buf.resize(want, 0);+ let got = read_some(self.src, pos, &mut self.buf)?;+ self.buf.truncate(got);+ self.start = pos;+ }+ let i = (pos - self.start) as usize;+ let end = (i + n).min(self.buf.len());+ Ok(&self.buf[i.min(end)..end])+ }+}++/// How many bytes of a private stream 1 payload precede the elementary stream, by sub-stream id+/// (DVD-Video: AC-3 / DTS 4, LPCM 7, sub-pictures 1).+fn sub_header(sub: u8) -> usize {+ match sub {+ 0x80..=0x8F => 4,+ 0xA0..=0xAF => 7,+ _ => 1,+ }+}++fn codec_for(stream_id: u8, sub: Option<u8>, psm: &HashMap<u8, u8>, mpeg1: bool) -> Codec {+ if let Some(&t) = psm.get(&stream_id) {+ let c = crate::ts::codec_of(t, &[], false);+ if !matches!(c, Codec::Unknown(_)) {+ return c;+ }+ }+ match (stream_id, sub) {+ (0xE0..=0xEF, _) => {+ if mpeg1 {+ Codec::Mpeg1Video+ } else {+ Codec::Mpeg2Video+ }+ }+ (0xC0..=0xDF, _) => Codec::MpegAudio,+ (0xBD, Some(0x80..=0x87)) => Codec::Ac3,+ (0xBD, Some(0x88..=0x8F)) => Codec::Dts,+ (0xBD, Some(0xA0..=0xAF)) => Codec::LpcmDvd,+ (0xBD, Some(0x20..=0x3F)) => Codec::Subtitle("DVD sub-pictures"),+ (id, _) => Codec::Unknown(id),+ }+}++/// DVD LPCM header bytes after the sub-stream id (and the frame count / pointer).+fn lpcm_format(h: &[u8]) -> Option<LpcmFormat> {+ let b = *h.get(4)?;+ let bits = [16, 20, 24, 0][(b >> 6) as usize];+ let sample_rate = [48_000, 96_000, 44_100, 32_000][((b >> 4) & 3) as usize];+ let channels = (b & 7) as u32 + 1;+ (bits > 0).then_some(LpcmFormat { sample_rate, channels, bits })+}++struct EsState {+ stream: Stream,+ split: Splitter,+}++/// Length of the packet (pack header, system header, PES…) starting at `b` (which begins with a+/// start code), `None` if it is not one.+fn packet_len(b: &[u8]) -> Option<usize> {+ if b.len() < 6 || b[0] != 0 || b[1] != 0 || b[2] != 1 {+ return None;+ }+ match b[3] {+ 0xBA => {+ if b[4] >> 6 == 1 {+ let stuff = (*b.get(13)? & 7) as usize;+ Some(14 + stuff)+ } else if b[4] >> 4 == 2 {+ Some(12)+ } else {+ None+ }+ }+ 0xB9 => Some(4),+ 0xBB..=0xFF => Some(6 + u16::from_be_bytes([b[4], b[5]]) as usize),+ _ => None,+ }+}++pub(crate) fn scan<S: ByteSource + ?Sized>(src: &S, mpeg1: bool) -> Result<File> {+ let len = src.len();+ let mut win = Win::new(src);+ let mut pos = 0u64;+ let mut streams: HashMap<(u8, Option<u8>), EsState> = HashMap::new();+ let mut order = Vec::new();+ let mut psm: HashMap<u8, u8> = HashMap::new();+ let mut unwrap = Unwrap::default();+ let mut scr: Option<(i64, i64)> = None;+ let mut resyncs = 0u64;+ while pos + 4 <= len {+ let head = win.get(pos, 32)?.to_vec();+ let Some(plen) = packet_len(&head) else {+ // resynchronise on the next pack header or PES start code+ resyncs += 1;+ let mut p = pos + 1;+ let found = loop {+ let w = win.get(p, 1 << 16)?.to_vec();+ if w.len() < 4 {+ break None;+ }+ if let Some(i) = w.windows(4).position(|x| x[0] == 0 && x[1] == 0 && x[2] == 1 && (x[3] == 0xBA || (0xBD..=0xEF).contains(&x[3]))) {+ break Some(p + i as u64);+ }+ p += (w.len() - 3) as u64;+ };+ match found {+ Some(f) => {+ pos = f;+ continue;+ }+ None => break,+ }+ };+ let id = head[3];+ if id == 0xBA {+ // SCR (MPEG-2: 33 bits base, 9 bits extension; MPEG-1: 33 bits)+ let v = if head[4] >> 6 == 1 {+ let b = &head[4..10];+ let base = (((b[0] >> 3) & 7) as i64) << 30+ | ((b[0] & 3) as i64) << 28+ | (b[1] as i64) << 20+ | ((b[2] >> 3) as i64) << 15+ | ((b[2] & 3) as i64) << 13+ | (b[3] as i64) << 5+ | (b[4] >> 3) as i64;+ let ext = (((b[4] & 3) as i64) << 7) | (b[5] >> 1) as i64;+ base * 300 + ext+ } else {+ pes::timestamp(&head[4..9]) * 300+ };+ scr = Some(scr.map_or((v, v), |(a, b): (i64, i64)| (a.min(v), b.max(v))));+ } else if id == 0xBC {+ // program stream map: elementary stream id → stream_type+ let body = win.get(pos, plen)?.to_vec();+ if body.len() >= 12 {+ let info = u16::from_be_bytes([body[8], body[9]]) as usize;+ let mut i = 10 + info;+ if i + 2 <= body.len() {+ let map_len = u16::from_be_bytes([body[i], body[i + 1]]) as usize;+ i += 2;+ let end = (i + map_len).min(body.len());+ while i + 4 <= end {+ psm.insert(body[i + 1], body[i]);+ i += 4 + u16::from_be_bytes([body[i + 2], body[i + 3]]) as usize;+ }+ }+ }+ } else if id == 0xBD || (0xC0..=0xEF).contains(&id) || id == 0xFD {+ let pkt = win.get(pos, plen)?.to_vec();+ if pkt.len() < plen {+ break; // truncated+ }+ if let Some(h) = pes::parse(&pkt) {+ let payload = &pkt[h.header_len.min(plen)..];+ let (sub, skip) = if id == 0xBD {+ match payload.first() {+ Some(&s) => (Some(s), sub_header(s).min(payload.len())),+ None => (None, 0),+ }+ } else {+ (None, 0)+ };+ let key = (id, sub);+ let e = streams.entry(key).or_insert_with(|| {+ let codec = codec_for(id, sub, &psm, mpeg1);+ let lpcm = if codec == Codec::LpcmDvd { lpcm_format(&payload[1.min(payload.len())..]) } else { None };+ order.push(key);+ let stream = Stream {+ id: StreamId::Ps { stream_id: id, sub_id: sub },+ stream_type: psm.get(&id).copied().unwrap_or(0),+ codec: codec.clone(),+ language: None,+ units: Vec::new(),+ lpcm,+ pes_packets: 0,+ skipped_bytes: 0,+ };+ EsState { stream, split: Splitter::new(&codec) }+ });+ e.stream.pes_packets += 1;+ e.split.pes_start(h.pts.map(|t| unwrap.unwrap(t)), h.dts.map(|t| unwrap.unwrap(t)));+ e.split.feed(pos, &payload[skip..]);+ }+ }+ pos += plen as u64;+ }+ let mut warnings = Vec::new();+ if resyncs > 0 {+ warnings.push(format!("resynchronised {resyncs} time(s)"));+ }+ let mut out = Vec::new();+ for key in order {+ let mut e = streams.remove(&key).expect("stream");+ e.split.finish();+ e.stream.units = std::mem::take(&mut e.split.units);+ e.stream.skipped_bytes = e.split.skipped;+ out.push(e.stream);+ }+ if out.is_empty() {+ return Err(Error::Invalid("program stream without elementary streams".into()));+ }+ Ok(File { format: Format::Ps { mpeg1 }, streams: out, program: None, pcr_range: scr, warnings })+}++/// Collect unit `u` of stream `st`, starting at the PES packet at `u.pos`.+pub(crate) fn read<S: ByteSource + ?Sized>(src: &S, st: &Stream, u: &Unit, out: &mut Vec<u8>) -> Result<()> {+ let StreamId::Ps { stream_id, sub_id } = st.id else { return Err(Error::Invalid("not a PS stream".into())) };+ let need = u.size as usize;+ let mut skip = u.offset as usize;+ let mut pos = u.pos;+ let len = src.len();+ let mut win = Win::new(src);+ while out.len() < need && pos + 4 <= len {+ let head = win.get(pos, 32)?.to_vec();+ let Some(plen) = packet_len(&head) else {+ // corrupt: stop at what we have+ return Ok(());+ };+ if head[3] == stream_id {+ let pkt = win.get(pos, plen)?.to_vec();+ if let Some(h) = pes::parse(&pkt) {+ let payload = &pkt[h.header_len.min(pkt.len())..];+ let matches = stream_id != 0xBD || payload.first().copied() == sub_id;+ if matches {+ let s0 = if stream_id == 0xBD { sub_id.map_or(0, sub_header).min(payload.len()) } else { 0 };+ let mut bytes = &payload[s0..];+ if skip > 0 {+ let s = skip.min(bytes.len());+ skip -= s;+ bytes = &bytes[s..];+ }+ let take = bytes.len().min(need - out.len());+ out.extend_from_slice(&bytes[..take]);+ }+ }+ }+ pos += plen as u64;+ }+ Ok(())+}diff --git a/crates/mpegts/src/tests.rs b/crates/mpegts/src/tests.rsnew file mode 100644index 000000000..65eb083ec--- /dev/null+++ b/crates/mpegts/src/tests.rs@@ -0,0 +1,288 @@+//! Synthetic transport and program streams: a small muxer writes known access units, the+//! demuxer must give them back exactly (bytes, timestamps, flags); truncation and mutation never+//! panic.++use super::*;++fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] {+ let v = v & ((1 << 33) - 1);+ [(prefix << 4) | (((v >> 30) & 7) as u8) << 1 | 1, (v >> 22) as u8, (((v >> 15) & 0x7F) as u8) << 1 | 1, (v >> 7) as u8, ((v & 0x7F) as u8) << 1 | 1]+}++fn pes(stream_id: u8, pts: Option<i64>, dts: Option<i64>, payload: &[u8], bounded: bool) -> Vec<u8> {+ let mut h = Vec::new();+ match (pts, dts) {+ (Some(p), Some(d)) => {+ h.extend(ts_bytes(3, p));+ h.extend(ts_bytes(1, d));+ }+ (Some(p), None) => h.extend(ts_bytes(2, p)),+ _ => {}+ }+ let flags = match (pts, dts) {+ (Some(_), Some(_)) => 0xC0,+ (Some(_), None) => 0x80,+ _ => 0,+ };+ let len = if bounded { 3 + h.len() + payload.len() } else { 0 };+ let mut v = vec![0, 0, 1, stream_id, (len >> 8) as u8, len as u8, 0x80, flags, h.len() as u8];+ v.extend(h);+ v.extend_from_slice(payload);+ v+}++/// A tiny TS muxer: PAT, PMT and PES packets cut into 188-byte packets (192 with `m2ts`).+struct TsMux {+ out: Vec<u8>,+ cc: std::collections::HashMap<u16, u8>,+ m2ts: bool,+}++impl TsMux {+ fn new(m2ts: bool) -> Self {+ Self { out: Vec::new(), cc: Default::default(), m2ts }+ }+ fn packet(&mut self, pid: u16, pusi: bool, payload: &[u8]) -> usize {+ let cc = self.cc.entry(pid).or_insert(0);+ let mut p = vec![0x47, (pusi as u8) << 6 | (pid >> 8) as u8, pid as u8];+ let n = payload.len().min(184);+ if n < 184 {+ // adaptation field stuffing+ let al = 183 - n;+ p.push(0x30 | *cc);+ p.push(al as u8);+ if al > 0 {+ p.push(0);+ p.extend(std::iter::repeat_n(0xFF, al - 1));+ }+ } else {+ p.push(0x10 | *cc);+ }+ *cc = (*cc + 1) & 15;+ p.extend_from_slice(&payload[..n]);+ assert_eq!(p.len(), 188);+ if self.m2ts {+ self.out.extend_from_slice(&[0, 0, 0, 0]);+ }+ self.out.extend(p);+ n+ }+ fn section(&mut self, pid: u16, body: &[u8]) {+ let mut s = body.to_vec();+ let crc = crate::ts::crc32_mpeg(&s);+ s.extend(crc.to_be_bytes());+ let mut payload = vec![0];+ payload.extend(s);+ self.packet(pid, true, &payload);+ }+ fn psi(&mut self, streams: &[(u8, u16)]) {+ // PAT: program 1 → PMT PID 0x100+ let pat = [0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00];+ self.section(0, &pat);+ let mut pmt = vec![0x02, 0xB0, 0, 0, 1, 0xC1, 0, 0, 0xE1, 0x00, 0xF0, 0];+ for &(st, pid) in streams {+ pmt.extend([st, 0xE0 | (pid >> 8) as u8, pid as u8, 0xF0, 0]);+ }+ let len = pmt.len() - 3 + 4;+ pmt[1] = 0xB0 | (len >> 8) as u8;+ pmt[2] = len as u8;+ self.section(0x100, &pmt);+ }+ fn pes(&mut self, pid: u16, data: &[u8]) {+ let mut rest = data;+ let mut first = true;+ while !rest.is_empty() {+ let n = self.packet(pid, first, rest);+ rest = &rest[n..];+ first = false;+ }+ }+}++/// An MPEG-2 coded frame: sequence header (on I), GOP, picture header, picture coding+/// extension and a slice of filler; or a field pair.+fn mpeg2_frame(coding_type: u8, tref: u16, fields: bool, filler: usize) -> Vec<u8> {+ let mut v = Vec::new();+ if coding_type == 1 {+ v.extend([0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]);+ v.extend([0, 0, 1, 0xB8, 0, 8, 0, 0x40]);+ }+ let pics: &[u8] = if fields { &[1, 2] } else { &[3] };+ for &s in pics {+ v.extend([0, 0, 1, 0x00, (tref >> 2) as u8, ((tref & 3) << 6) as u8 | coding_type << 3, 0xFF, 0xF8]);+ v.extend([0, 0, 1, 0xB5, 0x8F, 0xFF, 0xF0 | s, 0x80, 0x80]);+ v.extend([0, 0, 1, 0x01]);+ v.extend((0..filler).map(|i| (i % 200) as u8 | 0x10));+ }+ v+}++/// MPEG-1 layer II frame, 48 kHz 192 kb/s (576 bytes).+fn mp2_frame(k: u8) -> Vec<u8> {+ let mut v = vec![0xFF, 0xFD, 0xA4, 0x00];+ v.extend((0..572).map(|i| (i as u8) ^ k));+ v+}++#[test]+fn transport_stream_units_round_trip() {+ for m2ts in [false, true] {+ let mut mux = TsMux::new(m2ts);+ mux.psi(&[(0x02, 0x1011), (0x03, 0x1100)]);+ // decode order I0 P3 B1 B2 with PTS = display time, DTS on anchors+ let frames = [(1u8, 0u16, false), (2, 3, false), (3, 1, true), (3, 2, false)];+ let mut expect_video = Vec::new();+ for (k, &(t, tref, fields)) in frames.iter().enumerate() {+ let f = mpeg2_frame(t, tref, fields, 300 + 97 * k);+ let pts = 90_000 + tref as i64 * 3600;+ let dts = (t != 3).then_some(90_000 - 3600 + k as i64 * 3600);+ mux.pes(0x1011, &pes(0xE0, Some(pts), dts, &f, false));+ expect_video.push((f, pts, t));+ // two audio frames per PES, the second without its own timestamp+ let a: Vec<u8> = [mp2_frame(2 * k as u8), mp2_frame(2 * k as u8 + 1)].concat();+ mux.pes(0x1100, &pes(0xC0, Some(90_000 + 2160 * 2 * k as i64), None, &a, true));+ }+ let data = mux.out;+ let f = open(&data).unwrap();+ assert_eq!(f.format, Format::Ts { packet_size: if m2ts { 192 } else { 188 }, sync_offset: if m2ts { 4 } else { 0 } });+ assert!(f.warnings.is_empty(), "{:?}", f.warnings);+ assert_eq!(f.program, Some(1));+ let v = f.find(Kind::Video, |_| true).unwrap();+ let s = &f.streams[v];+ assert_eq!(s.codec, Codec::Mpeg2Video);+ assert_eq!(s.units.len(), 4);+ for (i, (bytes, pts, t)) in expect_video.iter().enumerate() {+ let u = &s.units[i];+ assert_eq!(f.read_unit(&data, v, i).unwrap(), *bytes, "unit {i}");+ assert_eq!(u.pts, Some(*pts));+ assert_eq!(u.key, *t == 1);+ assert_eq!(u.disposable, *t == 3);+ assert_eq!(u.picture.unwrap().coding_type, *t);+ }+ assert_eq!(s.units[2].picture.unwrap().structure, 1, "field pair in one unit");+ assert!(s.units[0].picture.unwrap().sequence_header && s.units[0].picture.unwrap().gop);+ let a = f.find(Kind::Audio, |c| *c == Codec::MpegAudio).unwrap();+ let s = &f.streams[a];+ assert_eq!(s.units.len(), 8);+ for (i, u) in s.units.iter().enumerate() {+ assert_eq!(f.read_unit(&data, a, i).unwrap(), mp2_frame(i as u8));+ assert_eq!(u.pts, (i % 2 == 0).then_some(90_000 + 2160 * i as i64));+ }+ }+}++#[test]+fn program_stream_units_round_trip() {+ // packs of ≤ 2048 bytes: frames are split across PES packets+ let frames: Vec<Vec<u8>> = (0..5).map(|k| mpeg2_frame(if k == 0 { 1 } else { 2 }, k as u16, k == 3, 2500 + 300 * k)).collect();+ let es: Vec<u8> = frames.concat();+ let mut starts = Vec::new();+ let mut acc = 0;+ for f in &frames {+ starts.push(acc);+ acc += f.len();+ }+ let mut out = Vec::new();+ let mut p = 0;+ let mut a = 0u8;+ while p < es.len() {+ out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]);+ let n = (es.len() - p).min(2000);+ // a timestamp when a frame starts in this packet+ let k = starts.iter().position(|&s| s >= p && s < p + n);+ out.extend(pes(0xE0, k.map(|k| 3600 * k as i64), None, &es[p..p + n], true));+ p += n;+ // AC-3 in private stream 1 (sub-stream 0x80, 4-byte header), 448 kb/s frames+ let mut ac3 = vec![0x80, 1, 0, 1, 0x0B, 0x77, 0, 0, 30, 0x40];+ ac3.extend(std::iter::repeat_n(a, 1792 - 6));+ a += 1;+ out.extend(pes(0xBD, Some(1000 + 2880 * a as i64), None, &ac3, true));+ }+ out.extend([0, 0, 1, 0xB9]);+ let f = open(&out).unwrap();+ assert_eq!(f.format, Format::Ps { mpeg1: false });+ let v = f.find(Kind::Video, |_| true).unwrap();+ assert_eq!(f.streams[v].units.len(), 5);+ for (i, fr) in frames.iter().enumerate() {+ assert_eq!(&f.read_unit(&out, v, i).unwrap(), fr);+ assert_eq!(f.streams[v].units[i].pts, Some(3600 * i as i64));+ }+ let a = f.find(Kind::Audio, |c| *c == Codec::Ac3).unwrap();+ assert_eq!(f.streams[a].id, StreamId::Ps { stream_id: 0xBD, sub_id: Some(0x80) });+ assert_eq!(f.streams[a].units.len(), a_count(&out));+ let u0 = f.read_unit(&out, a, 0).unwrap();+ assert_eq!(&u0[..2], &[0x0B, 0x77]);+ assert_eq!(u0.len(), 1792);+}++fn a_count(ps: &[u8]) -> usize {+ ps.windows(4).filter(|w| *w == [0, 0, 1, 0xBD]).count()+}++#[test]+fn sniffing() {+ assert_eq!(sniff(&[0, 0, 1, 0xBA, 0x44]), Some(Format::Ps { mpeg1: false }));+ assert_eq!(sniff(&[0, 0, 1, 0xBA, 0x21]), Some(Format::Ps { mpeg1: true }));+ assert_eq!(sniff(&[0, 0, 1, 0xB3, 0x44]), None);+ let mut ts = vec![0u8; 188 * 6];+ for k in 0..6 {+ ts[k * 188] = 0x47;+ }+ assert!(matches!(sniff(&ts), Some(Format::Ts { packet_size: 188, .. })));+}++#[test]+fn truncation_and_mutation_never_panic() {+ let mut mux = TsMux::new(false);+ mux.psi(&[(0x02, 0x1011), (0x0F, 0x1100), (0x1B, 0x1200)]);+ for k in 0..6u16 {+ mux.pes(0x1011, &pes(0xE0, Some(3600 * k as i64), None, &mpeg2_frame(if k == 0 { 1 } else { 3 }, k, k % 2 == 1, 400), false));+ let mut adts = vec![0xFF, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC];+ adts.extend([0x21u8; 93]);+ mux.pes(0x1100, &pes(0xC0, Some(1920 * k as i64), None, &adts, true));+ mux.pes(0x1200, &pes(0xE1, Some(3600 * k as i64), None, &[0, 0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65, 0x88, 1, 2, 3], false));+ }+ let data = mux.out;+ let full = open(&data).unwrap();+ assert_eq!(full.streams.len(), 3);+ assert_eq!(full.streams[1].units.len(), 6, "ADTS frames");+ assert!(full.streams[2].units.iter().all(|u| u.key), "IDR access units");+ for cut in (0..data.len()).step_by(37) {+ if let Ok(f) = open(&data[..cut].to_vec()) {+ for (s, st) in f.streams.iter().enumerate() {+ for i in 0..st.units.len() {+ let _ = f.read_unit(&data[..cut].to_vec(), s, i);+ }+ }+ }+ }+ let mut x = 0x9E37_79B9u32;+ for _ in 0..400 {+ let mut m = data.clone();+ for _ in 0..8 {+ x ^= x << 13;+ x ^= x >> 17;+ x ^= x << 5;+ let i = x as usize % m.len();+ m[i] = (x >> 8) as u8;+ }+ if let Ok(f) = open(&m) {+ for (s, st) in f.streams.iter().enumerate() {+ for i in 0..st.units.len() {+ let _ = f.read_unit(&m, s, i);+ }+ }+ }+ }+}++#[test]+fn timestamps_unwrap_across_the_33_bit_wrap() {+ let mut u = Unwrap::default();+ let near = (1i64 << 33) - 3000;+ assert_eq!(u.unwrap(near), near);+ assert_eq!(u.unwrap(600), (1 << 33) + 600);+ // a B picture timestamp from just before the wrap+ assert_eq!(u.unwrap(near + 1000), near + 1000);+ assert_eq!(u.unwrap(4200), (1 << 33) + 4200);+}diff --git a/crates/mpegts/src/ts.rs b/crates/mpegts/src/ts.rsnew file mode 100644index 000000000..d39b4cfba--- /dev/null+++ b/crates/mpegts/src/ts.rs@@ -0,0 +1,432 @@+//! Transport streams (H.222.0 §2.4.3): packets, PSI (PAT/PMT), PES reassembly.++use std::collections::HashMap;++use crate::es::Splitter;+use crate::pes::{self, PesHeader};+use crate::{ByteSource, Codec, Error, File, Format, Result, Stream, StreamId, Unit, Unwrap, read_some};++/// CRC-32 of PSI sections (MSB-first, polynomial 0x04C11DB7, initial value all ones; Annex A).+pub(crate) fn crc32_mpeg(data: &[u8]) -> u32 {+ let mut crc = 0xFFFF_FFFFu32;+ for &b in data {+ crc ^= (b as u32) << 24;+ for _ in 0..8 {+ crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 };+ }+ }+ crc+}++/// A packet's fields.+struct Packet<'a> {+ pusi: bool,+ pid: u16,+ cc: u8,+ has_payload: bool,+ discontinuity: bool,+ pcr: Option<i64>,+ payload: &'a [u8],+}++fn packet(p: &[u8]) -> Option<Packet<'_>> {+ if p.len() < 188 || p[0] != 0x47 {+ return None;+ }+ let pusi = p[1] & 0x40 != 0;+ let pid = (((p[1] & 0x1F) as u16) << 8) | p[2] as u16;+ let afc = (p[3] >> 4) & 3;+ let cc = p[3] & 15;+ let mut start = 4;+ let mut pcr = None;+ let mut discontinuity = false;+ if afc & 2 != 0 {+ let al = p[4] as usize;+ start = 5 + al;+ if start > 188 {+ return None;+ }+ if al > 0 {+ let flags = p[5];+ discontinuity = flags & 0x80 != 0;+ if flags & 0x10 != 0 && al >= 7 {+ let base = ((p[6] as i64) << 25) | ((p[7] as i64) << 17) | ((p[8] as i64) << 9) | ((p[9] as i64) << 1) | (p[10] as i64 >> 7);+ let ext = (((p[10] & 1) as i64) << 8) | p[11] as i64;+ pcr = Some(base * 300 + ext);+ }+ }+ }+ let has_payload = afc & 1 != 0;+ Some(Packet { pusi, pid, cc, has_payload, discontinuity, pcr, payload: if has_payload { &p[start..188] } else { &[] } })+}++/// Reassembles a PES header that may span packets; yields each packet's elementary-stream bytes.+#[derive(Default)]+pub(crate) struct PesAsm {+ hdr: Vec<u8>,+ waiting: bool,+}++impl PesAsm {+ /// The PES header completed by this packet (if any) and the packet's ES payload bytes.+ pub fn packet<'a>(&mut self, pusi: bool, payload: &'a [u8]) -> (Option<PesHeader>, &'a [u8]) {+ if pusi {+ self.hdr.clear();+ self.waiting = true;+ } else if !self.waiting {+ return (None, payload);+ }+ let before = self.hdr.len();+ self.hdr.extend_from_slice(payload);+ if let Some(h) = pes::parse(&self.hdr)+ && self.hdr.len() >= h.header_len+ {+ self.waiting = false;+ let skip = (h.header_len - before).min(payload.len());+ return (Some(h), &payload[skip..]);+ }+ if self.hdr.len() > 1024 || (self.hdr.len() >= 6 && !(self.hdr[0] == 0 && self.hdr[1] == 0 && self.hdr[2] == 1)) {+ // not a PES packet after all: drop until the next unit start+ self.waiting = false;+ self.hdr.clear();+ return (None, &[]);+ }+ (None, &[])+ }+}++/// PSI section reassembly for one PID.+#[derive(Default)]+struct Psi {+ buf: Vec<u8>,+}++impl Psi {+ /// Feed a packet payload; returns completed sections.+ fn feed(&mut self, pusi: bool, payload: &[u8]) -> Vec<Vec<u8>> {+ let mut out = Vec::new();+ if pusi {+ let Some(&ptr) = payload.first() else { return out };+ let ptr = ptr as usize;+ if !self.buf.is_empty() {+ self.buf.extend_from_slice(payload.get(1..1 + ptr).unwrap_or(&[]));+ self.drain(&mut out);+ }+ self.buf = payload.get(1 + ptr..).unwrap_or(&[]).to_vec();+ } else if !self.buf.is_empty() {+ self.buf.extend_from_slice(payload);+ }+ self.drain(&mut out);+ out+ }++ fn drain(&mut self, out: &mut Vec<Vec<u8>>) {+ while self.buf.len() >= 3 {+ if self.buf[0] == 0xFF {+ self.buf.clear();+ return;+ }+ let total = 3 + ((((self.buf[1] & 0x0F) as usize) << 8) | self.buf[2] as usize);+ if self.buf.len() < total {+ if total > 4096 {+ self.buf.clear();+ }+ return;+ }+ out.push(self.buf[..total].to_vec());+ self.buf.drain(..total);+ }+ }+}++/// Elementary stream of the selected program.+struct EsState {+ stream: Stream,+ split: Splitter,+ asm: PesAsm,+ cc: Option<u8>,+}++/// Map a PMT stream_type (and the ES descriptors) to a codec. `hdmv`: a Blu-ray / AVCHD stream+/// (registration descriptor "HDMV", or 192-byte packets).+pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec {+ let mut tags = Vec::new();+ let mut reg = None;+ let mut i = 0;+ while i + 2 <= desc.len() {+ let (tag, len) = (desc[i], desc[i + 1] as usize);+ let body = desc.get(i + 2..i + 2 + len).unwrap_or(&[]);+ tags.push(tag);+ if tag == 5 && body.len() >= 4 {+ reg = Some([body[0], body[1], body[2], body[3]]);+ }+ i += 2 + len;+ }+ match stream_type {+ 0x01 => Codec::Mpeg1Video,+ 0x02 => Codec::Mpeg2Video,+ 0x03 | 0x04 => Codec::MpegAudio,+ 0x0F => Codec::AacAdts,+ 0x11 => Codec::AacLatm,+ 0x1B => Codec::H264,+ 0x24 => Codec::Hevc,+ 0x80 if hdmv => Codec::LpcmBluray,+ 0x80 => Codec::Mpeg2Video,+ 0x81 => Codec::Ac3,+ 0x82 | 0x85 | 0x86 | 0xA2 if hdmv => Codec::Dts,+ 0x83 if hdmv => Codec::TrueHd,+ 0x84 | 0xA1 if hdmv => Codec::Eac3,+ 0x87 => Codec::Eac3,+ 0x90 if hdmv => Codec::Subtitle("PGS subtitles"),+ 0x92 if hdmv => Codec::Subtitle("Text subtitles"),+ 0x06 => {+ if tags.contains(&0x6A) || reg == Some(*b"AC-3") {+ Codec::Ac3+ } else if tags.contains(&0x7A) || reg == Some(*b"EAC3") {+ Codec::Eac3+ } else if tags.contains(&0x7B) || matches!(reg, Some([b'D', b'T', b'S', _])) {+ Codec::Dts+ } else if tags.contains(&0x59) {+ Codec::Subtitle("DVB subtitles")+ } else if tags.contains(&0x56) {+ Codec::Subtitle("Teletext")+ } else {+ Codec::Unknown(6)+ }+ }+ t => Codec::Unknown(t),+ }+}++fn language(desc: &[u8]) -> Option<String> {+ let mut i = 0;+ while i + 2 <= desc.len() {+ let (tag, len) = (desc[i], desc[i + 1] as usize);+ if tag == 0x0A && len >= 3 {+ let b = desc.get(i + 2..i + 5)?;+ return Some(String::from_utf8_lossy(b).trim().to_string()).filter(|s| !s.is_empty());+ }+ i += 2 + len;+ }+ None+}++/// First file offset at which `packet_size`-byte packets line up (sync byte at `sync_offset`).+fn first_sync(head: &[u8], packet_size: usize, sync_offset: usize) -> Option<usize> {+ (0..packet_size.min(head.len())).find(|&s| (0..5).all(|k| head.get(s + sync_offset + k * packet_size) == Some(&0x47)))+}++pub(crate) fn scan<S: ByteSource + ?Sized>(src: &S, packet_size: usize, sync_offset: usize) -> Result<File> {+ let len = src.len();+ let mut head = vec![0u8; packet_size * 8];+ let n = read_some(src, 0, &mut head)?;+ let mut off = first_sync(&head[..n], packet_size, sync_offset).ok_or(Error::NotMpeg)? as u64;+ let mut warnings: Vec<String> = Vec::new();+ let mut pat = Psi::default();+ let mut pmt_pid: Option<u16> = None;+ let mut program = None;+ let mut pmt = Psi::default();+ let mut es: HashMap<u16, EsState> = HashMap::new();+ let mut order: Vec<u16> = Vec::new();+ let mut pmt_version: Option<u8> = None;+ let mut unwrap = Unwrap::default();+ let mut pcr_unwrap = 0i64;+ let mut last_pcr: Option<i64> = None;+ let mut pcr_range: Option<(i64, i64)> = None;+ let (mut lost_sync, mut cc_errors, mut crc_errors) = (0u64, 0u64, 0u64);+ const BLOCK: usize = 4096;+ let mut block = vec![0u8; BLOCK * packet_size];+ while off + packet_size as u64 <= len {+ let got = read_some(src, off, &mut block)?;+ let whole = got / packet_size;+ if whole == 0 {+ break;+ }+ let mut k = 0;+ while k < whole {+ let pos = off + (k * packet_size) as u64;+ let raw = &block[k * packet_size..(k + 1) * packet_size];+ let Some(pk) = packet(&raw[sync_offset..]) else {+ // lost sync: find the next offset where packets line up again+ lost_sync += 1;+ let rest = &block[k * packet_size + 1..got];+ match first_sync(rest, packet_size, sync_offset).or_else(|| rest.iter().position(|&b| b == 0x47).map(|p| p.saturating_sub(sync_offset))) {+ Some(s) => {+ off = pos + 1 + s as u64;+ }+ None => off = pos + got as u64,+ }+ k = usize::MAX;+ break;+ };+ k += 1;+ if let Some(pcr) = pk.pcr {+ // 33-bit base × 300 wraps at 2^33·300+ let wrap = (1i64 << 33) * 300;+ let mut v = pcr + pcr_unwrap;+ if let Some(l) = last_pcr+ && v < l - wrap / 2+ {+ pcr_unwrap += wrap;+ v += wrap;+ }+ last_pcr = Some(v);+ pcr_range = Some(pcr_range.map_or((v, v), |(a, b)| (a.min(v), b.max(v))));+ }+ if pk.pid == 0 {+ for sec in pat.feed(pk.pusi, pk.payload) {+ if sec.len() < 12 || sec[0] != 0 {+ continue;+ }+ if crc32_mpeg(&sec) != 0 {+ crc_errors += 1;+ continue;+ }+ let body = &sec[8..sec.len() - 4];+ for e in body.chunks_exact(4) {+ let num = u16::from_be_bytes([e[0], e[1]]);+ let pid = (((e[2] & 0x1F) as u16) << 8) | e[3] as u16;+ if num != 0 && pmt_pid.is_none() {+ pmt_pid = Some(pid);+ program = Some(num);+ }+ }+ }+ continue;+ }+ if Some(pk.pid) == pmt_pid {+ for sec in pmt.feed(pk.pusi, pk.payload) {+ if sec.len() < 16 || sec[0] != 2 {+ continue;+ }+ if crc32_mpeg(&sec) != 0 {+ crc_errors += 1;+ continue;+ }+ let version = (sec[5] >> 1) & 0x1F;+ if pmt_version == Some(version) {+ continue;+ }+ pmt_version = Some(version);+ let pinfo = (((sec[10] & 0x0F) as usize) << 8) | sec[11] as usize;+ let prog_desc = sec.get(12..12 + pinfo).unwrap_or(&[]);+ let hdmv = packet_size == 192 || prog_desc.windows(4).any(|w| w == b"HDMV");+ let mut i = 12 + pinfo;+ let end = sec.len() - 4;+ while i + 5 <= end {+ let st = sec[i];+ let pid = (((sec[i + 1] & 0x1F) as u16) << 8) | sec[i + 2] as u16;+ let ilen = (((sec[i + 3] & 0x0F) as usize) << 8) | sec[i + 4] as usize;+ let desc = sec.get(i + 5..(i + 5 + ilen).min(end)).unwrap_or(&[]);+ i += 5 + ilen;+ if es.contains_key(&pid) {+ continue;+ }+ let mut codec = codec_of(st, desc, hdmv);+ if codec == Codec::Unknown(6) && prog_desc.windows(4).any(|w| w == b"AC-3") {+ codec = Codec::Ac3;+ }+ let stream = Stream {+ id: StreamId::Pid(pid),+ stream_type: st,+ codec: codec.clone(),+ language: language(desc),+ units: Vec::new(),+ lpcm: None,+ pes_packets: 0,+ skipped_bytes: 0,+ };+ es.insert(pid, EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None });+ order.push(pid);+ }+ }+ continue;+ }+ let Some(e) = es.get_mut(&pk.pid) else { continue };+ if pk.has_payload {+ if let Some(prev) = e.cc+ && !pk.discontinuity+ && pk.cc != (prev + 1) & 15+ && pk.cc != prev+ {+ cc_errors += 1;+ }+ e.cc = Some(pk.cc);+ }+ let (hdr, bytes) = e.asm.packet(pk.pusi, pk.payload);+ if let Some(h) = hdr {+ e.stream.pes_packets += 1;+ let pts = h.pts.map(|t| unwrap.unwrap(t));+ let dts = h.dts.map(|t| unwrap.unwrap(t));+ e.split.pes_start(pts, dts);+ }+ e.split.feed(pos, bytes);+ }+ if k != usize::MAX {+ off += (whole * packet_size) as u64;+ }+ }+ if lost_sync > 0 {+ warnings.push(format!("lost packet sync {lost_sync} time(s)"));+ }+ if cc_errors > 0 {+ warnings.push(format!("{cc_errors} continuity counter error(s)"));+ }+ if crc_errors > 0 {+ warnings.push(format!("{crc_errors} PSI section(s) with bad CRC"));+ }+ if pmt_pid.is_none() {+ warnings.push("no program association table".into());+ }+ let mut streams = Vec::new();+ for pid in order {+ let mut e = es.remove(&pid).expect("stream");+ e.split.finish();+ e.stream.units = std::mem::take(&mut e.split.units);+ e.stream.skipped_bytes = e.split.skipped;+ streams.push(e.stream);+ }+ Ok(File { format: Format::Ts { packet_size, sync_offset }, streams, program, pcr_range, warnings })+}++/// Collect unit `u` of stream `st`: from the packet at `u.pos`, the PID's elementary-stream bytes.+pub(crate) fn read<S: ByteSource + ?Sized>(src: &S, packet_size: usize, sync_offset: usize, st: &Stream, u: &Unit, out: &mut Vec<u8>) -> Result<()> {+ let StreamId::Pid(pid) = st.id else { return Err(Error::Invalid("not a TS stream".into())) };+ let need = u.size as usize;+ let mut skip = u.offset as usize;+ let mut off = u.pos;+ let mut asm = PesAsm::default();+ let mut first = true;+ let mut block = vec![0u8; 512 * packet_size];+ while out.len() < need {+ let got = read_some(src, off, &mut block)?;+ let whole = got / packet_size;+ if whole == 0 {+ break;+ }+ for k in 0..whole {+ let raw = &block[k * packet_size..(k + 1) * packet_size];+ let Some(pk) = packet(&raw[sync_offset..]) else { return Ok(()) };+ if pk.pid != pid {+ continue;+ }+ // a unit starting in a PES packet's first packet: the header is skipped+ let (_, bytes) = if first && !pk.pusi { (None, pk.payload) } else { asm.packet(pk.pusi, pk.payload) };+ first = false;+ let bytes = if skip > 0 {+ let s = skip.min(bytes.len());+ skip -= s;+ &bytes[s..]+ } else {+ bytes+ };+ let take = bytes.len().min(need - out.len());+ out.extend_from_slice(&bytes[..take]);+ if out.len() >= need {+ return Ok(());+ }+ }+ off += (whole * packet_size) as u64;+ }+ Ok(())+}