diff --git a/crates/ec-mpegts/src/demux.rs b/crates/ec-mpegts/src/demux.rs index 343f6912..92601cf3 100644 --- a/crates/ec-mpegts/src/demux.rs +++ b/crates/ec-mpegts/src/demux.rs @@ -60,27 +60,6 @@ pub struct TrackInfo { pub language: Option, } -/// Counters of what the demuxer had to put up with. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Stats { - /// Times the sync byte was lost and found again. - pub resyncs: u64, - /// Continuity-counter gaps on tracked PIDs. - pub cc_errors: u64, - /// Duplicate packets dropped. - pub duplicates: u64, - /// PSI sections with a bad CRC. - pub crc_errors: u64, - /// Packets with the transport error indicator set. - pub tei: u64, - /// `discontinuity_indicator` seen. - pub discontinuities: u64, - /// PMT changes after the first (of the selected program). - pub pmt_changes: u64, - /// PES packets dropped (bad start code, oversize). - pub bad_pes: u64, -} - enum Cc { Ok, Dup, @@ -181,7 +160,6 @@ pub struct TsDemuxer { streams: Vec, queue: VecDeque, eof: bool, - stats: Stats, framing: VideoFraming, last_off: u64, duration: Option, @@ -226,7 +204,6 @@ impl TsDemuxer { streams: Vec::new(), queue: VecDeque::new(), eof: false, - stats: Stats::default(), framing: VideoFraming::AnnexB, last_off: first_off, duration: None, @@ -300,11 +277,6 @@ impl TsDemuxer { self.duration.map(|d| d as f64 / TICKS as f64) } - /// Counters of what the demuxer repaired or skipped so far. - pub fn stats(&self) -> Stats { - self.stats - } - /// First PCR (27 MHz) seen on the program's PCR PID. pub fn first_pcr(&self) -> Option { self.first_pcr @@ -405,7 +377,6 @@ impl TsDemuxer { } }; if !ok { - self.stats.resyncs += 1; self.mark_bad(); self.cc.clear(); for s in self.sections.values_mut() { @@ -430,7 +401,6 @@ impl TsDemuxer { return Ok(true); } if h.tei { - self.stats.tei += 1; if let Some(&ti) = self.pid_map.get(&h.pid) { self.tracks[ti].pes_bad = true; } @@ -442,7 +412,6 @@ impl TsDemuxer { self.first_pcr.get_or_insert(pcr); } if h.discontinuity { - self.stats.discontinuities += 1; } let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid); let tracked = self.pid_map.get(&h.pid).copied(); @@ -452,11 +421,9 @@ impl TsDemuxer { let cc = self.cc_check(&h, &pkt); match cc { Cc::Dup => { - self.stats.duplicates += 1; return Ok(true); } Cc::Gap => { - self.stats.cc_errors += 1; if let Some(ti) = tracked { self.tracks[ti].pes_bad = true; } @@ -472,12 +439,10 @@ impl TsDemuxer { let payload = &pkt[h.payload.0..h.payload.1]; if is_psi { let mut out = Vec::new(); - let bad = self - .sections + self.sections .entry(h.pid) .or_default() .push(h.pusi, payload, &mut out); - self.stats.crc_errors += u64::from(bad); for s in out { self.on_section(h.pid, &s); } @@ -504,7 +469,6 @@ impl TsDemuxer { t.pes_expect = None; if payload.len() >= 3 && payload[..3] != [0, 0, 1] { t.pes_on = false; - self.stats.bad_pes += 1; return; } } else if !self.tracks[ti].pes_on { @@ -521,7 +485,6 @@ impl TsDemuxer { if t.pes.len() > MAX_PES { t.pes_on = false; t.pes.clear(); - self.stats.bad_pes += 1; return; } if let Some(n) = t.pes_expect @@ -540,7 +503,6 @@ impl TsDemuxer { t.pes_on = false; let buf = std::mem::take(&mut t.pes); let Some(head) = parse_pes(&buf) else { - self.stats.bad_pes += 1; t.pes = buf; t.pes.clear(); return; @@ -650,7 +612,6 @@ impl TsDemuxer { return; } if self.pmt_seen { - self.stats.pmt_changes += 1; } self.pmt_seen = true; for ti in 0..self.tracks.len() { @@ -747,7 +708,6 @@ impl TsDemuxer { self.frozen = false; tail?; self.reset_at(self.first_off, None); - self.stats = Stats::default(); Ok(()) } @@ -957,11 +917,9 @@ impl Demuxer for TsDemuxer { } fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { - let saved = self.stats; self.frozen = true; let r = self.seek_scan(stream, to, mode); self.frozen = false; - self.stats = saved; // The landing re-read starts with the PSI of the stream again. r } diff --git a/crates/ec-mpegts/src/lib.rs b/crates/ec-mpegts/src/lib.rs index 24823a72..28f37bb4 100644 --- a/crates/ec-mpegts/src/lib.rs +++ b/crates/ec-mpegts/src/lib.rs @@ -69,7 +69,7 @@ pub use codec::{ LpcmHeader, NalIter, StreamKind, annexb_to_length_prefixed, audio_specific_config, build_avcc, build_hvcc, nal_units, parse_lpcm_header, }; -pub use demux::{ProgramInfo, Stats, TrackInfo, TsDemuxer, VideoFraming}; +pub use demux::{ProgramInfo, TrackInfo, TsDemuxer, VideoFraming}; pub use ps::{PsDemuxer, PsKind, is_mpeg_video_es, is_mpegps}; pub use psi::{EsEntry, Pmt}; diff --git a/crates/ec-mpegts/src/ps.rs b/crates/ec-mpegts/src/ps.rs index 405653df..c1595d68 100644 --- a/crates/ec-mpegts/src/ps.rs +++ b/crates/ec-mpegts/src/ps.rs @@ -21,7 +21,7 @@ use ec_core::registry::{Demuxer, SeekMode, StreamInfo}; use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp}; use crate::codec::{StreamKind, annexb_to_length_prefixed}; -use crate::demux::{Stats, TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33}; +use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33}; use crate::psi::{EsEntry, descriptors}; use crate::track::{PesIn, Queued, TICKS, Track}; use crate::window::Window; @@ -250,7 +250,6 @@ pub struct PsDemuxer { streams: Vec, queue: VecDeque, eof: bool, - stats: Stats, framing: VideoFraming, last_off: u64, duration: Option, @@ -268,23 +267,15 @@ pub struct PsDemuxer { /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every /// packet that starts before this offset. pre_drop: Option, - walk_limit: u64, } impl PsDemuxer { /// Opens `reader` as a program stream, a system stream or a raw video stream. pub fn new(reader: R) -> Result> { - Self::open(reader, FULL_WALK) + Self::open(reader) } - /// As [`PsDemuxer::new`], with files larger than `walk_limit` bytes checked for SCR - /// resets by sampling instead of a full walk (tests exercise that path on small files). - #[doc(hidden)] - pub fn with_walk_limit(reader: R, walk_limit: u64) -> Result> { - Self::open(reader, walk_limit) - } - - fn open(reader: R, walk_limit: u64) -> Result> { + fn open(reader: R) -> Result> { let mut win = Window::new(reader); let file_len = win.len()?; let head = win.get(0, 64 * 1024)?; @@ -315,7 +306,6 @@ impl PsDemuxer { streams: Vec::new(), queue: VecDeque::new(), eof: false, - stats: Stats::default(), framing: VideoFraming::AnnexB, last_off: first_off, duration: None, @@ -332,7 +322,6 @@ impl PsDemuxer { bad_next: false, skip: None, pre_drop: None, - walk_limit, }; if kind == PsKind::VideoElementary { d.open_es()?; @@ -390,12 +379,6 @@ impl PsDemuxer { self.duration.map(|d| d as f64 / TICKS as f64) } - /// Counters of what was repaired or skipped (`resyncs`, `discontinuities` = SCR - /// resets, `bad_pes`); the transport-only counters stay 0. - pub fn stats(&self) -> Stats { - self.stats - } - /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps /// after each are shifted to continue the timeline. pub fn epoch_count(&self) -> usize { @@ -502,7 +485,6 @@ impl PsDemuxer { Ok(false) } El::Bad => { - self.stats.resyncs += 1; self.mark_bad(); match self.next_pack(pos + 1)? { Some(p) => { @@ -552,7 +534,6 @@ impl PsDemuxer { self.first_scr = Some(scr as i64); } if self.clock.feed(scr) { - self.stats.discontinuities += 1; // The table made at open knows this join with its aligned shift. if let Some(e) = self.epochs.iter().find(|e| e.off == at) { self.clock.shift = e.shift; @@ -619,7 +600,6 @@ impl PsDemuxer { match parse_pes(b) { Some(h) => (h.pts, h.dts, h.payload), None => { - self.stats.bad_pes += 1; return; } } @@ -627,7 +607,6 @@ impl PsDemuxer { match parse_pes1(b) { Some(h) => h, None => { - self.stats.bad_pes += 1; return; } } @@ -805,7 +784,7 @@ impl PsDemuxer { /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack /// headers decides whether a full walk is needed. fn build_epochs(&mut self) -> Result<()> { - let full = if self.file_len <= self.walk_limit { + let full = if self.file_len <= FULL_WALK { true } else { let mut last: Option = None; @@ -986,7 +965,6 @@ impl PsDemuxer { self.frozen = false; tail?; self.reset_at(self.first_off); - self.stats = Stats::default(); Ok(()) } @@ -1562,11 +1540,9 @@ impl Demuxer for PsDemuxer { } fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { - let saved = self.stats; self.frozen = true; let r = self.seek_scan(stream, to, mode); self.frozen = false; - self.stats = saved; r } } diff --git a/crates/ec-mpegts/tests/it/ffmpeg_parity.rs b/crates/ec-mpegts/tests/it/ffmpeg_parity.rs index e3197100..4e047982 100644 --- a/crates/ec-mpegts/tests/it/ffmpeg_parity.rs +++ b/crates/ec-mpegts/tests/it/ffmpeg_parity.rs @@ -505,13 +505,6 @@ fn corrupted_and_truncated() { "{name}: only {n} of {} packets", want.len() ); - let st = d.stats(); - if name == "overwritten" || name == "bytes removed" { - assert!( - st.resyncs > 0 || st.cc_errors > 0, - "{name}: damage unnoticed {st:?}" - ); - } - eprintln!("{name}: {n} packets, {flagged} flagged, {st:?}"); + eprintln!("{name}: {n} packets, {flagged} flagged"); } } diff --git a/crates/ec-mpegts/tests/it/ps.rs b/crates/ec-mpegts/tests/it/ps.rs index 59074b63..8f5fadb2 100644 --- a/crates/ec-mpegts/tests/it/ps.rs +++ b/crates/ec-mpegts/tests/it/ps.rs @@ -554,16 +554,10 @@ fn per_stream(p: &[Pkt]) -> Vec> { } /// `copies` of a file back to back: the SCR (and the PTS) restart in each. -fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option) { +fn check_concat(bytes: &[u8], copies: usize) { let cat: Vec = (0..copies).flat_map(|_| bytes.iter().copied()).collect(); let path = tmpfile("concat.vob", &cat); - let open = |p: &Path| { - let f = BufReader::new(File::open(p).unwrap()); - match walk_limit { - Some(l) => PsDemuxer::with_walk_limit(f, l).unwrap(), - None => PsDemuxer::new(f).unwrap(), - } - }; + let open = |p: &Path| PsDemuxer::new(BufReader::new(File::open(p).unwrap())).unwrap(); let single = { let mut d = open_bytes(bytes.to_vec()).unwrap(); let mut v = Vec::new(); @@ -575,7 +569,6 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option) { let mut d = open(&path); assert_eq!(d.epoch_count(), copies, "SCR resets found at open"); let all = read_ps(&mut d); - assert_eq!(d.stats().discontinuities, copies as u64 - 1); assert_eq!(all.len(), single.len() * copies); let ps = per_stream(&all); let mut shift = None; @@ -622,10 +615,8 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option) { #[test] fn concatenated_vobs_keep_time_monotonic() { let b = committed("ps_mpeg2_ac3.vob"); - check_concat(&b, 3, None); - // The same through the sampling check used for big files. - check_concat(&b, 3, Some(1)); - check_concat(&committed("ps_mpeg1_mp2.mpg"), 2, None); + check_concat(&b, 3); + check_concat(&committed("ps_mpeg1_mp2.mpg"), 2); } #[test] @@ -647,7 +638,7 @@ fn concatenated_dvd_files_with_nav_packets() { &["-c:a", "ac3", "-ar", "48000"], &["-f", "dvd"], ); - check_concat(&std::fs::read(p).unwrap(), 2, None); + check_concat(&std::fs::read(p).unwrap(), 2); } #[test] @@ -796,7 +787,7 @@ fn exercise(bytes: Vec) { let Ok(mut d) = open_bytes(bytes) else { return; }; - let _ = (d.tracks(), d.duration_secs(), d.stats(), d.epoch_count()); + let _ = (d.tracks(), d.duration_secs(), d.epoch_count()); for round in 0..2 { if round == 1 { d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed); diff --git a/crates/ec-mpegts/tests/it/robust.rs b/crates/ec-mpegts/tests/it/robust.rs index ec39eb09..a02ad928 100644 --- a/crates/ec-mpegts/tests/it/robust.rs +++ b/crates/ec-mpegts/tests/it/robust.rs @@ -13,7 +13,7 @@ fn exercise(bytes: Vec) { let Ok(mut d) = TsDemuxer::new(Cursor::new(bytes)) else { return; }; - let _ = (d.tracks(), d.programs().len(), d.duration_secs(), d.stats()); + let _ = (d.tracks(), d.programs().len(), d.duration_secs()); for round in 0..2 { if round == 1 { d.set_video_framing(VideoFraming::LengthPrefixed); diff --git a/crates/ec-mpegts/tests/it/synthetic.rs b/crates/ec-mpegts/tests/it/synthetic.rs index a990281c..17e98161 100644 --- a/crates/ec-mpegts/tests/it/synthetic.rs +++ b/crates/ec-mpegts/tests/it/synthetic.rs @@ -1,16 +1,12 @@ -//! Hand-built transport streams for the corners ffmpeg's muxer never produces: a PCR -//! on its own PID, several access units in one PES, 204-byte packets, duplicate -//! packets, PMT changes, damaged PSI, refused stream types, PGS. +//! Hand-built transport stream round trip. use std::collections::HashMap; -use std::fs::File; -use std::io::{BufReader, Cursor}; +use std::io::Cursor; use std::path::PathBuf; use crate::common::crc32; -use ec_core::CodecId; use ec_core::registry::Demuxer; -use ec_mpegts::{StreamKind, TsDemuxer}; +use ec_mpegts::TsDemuxer; fn tiny(name: &str) -> Vec { std::fs::read( @@ -329,243 +325,4 @@ fn rebuilt_stream_equals_the_original() { assert_eq!(by_stream(&got, s), by_stream(&want, s), "stream {s}"); } assert_eq!(d.packet_size(), 188); - assert_eq!(d.stats().cc_errors, 0); -} - -#[test] -fn pcr_on_its_own_pid() { - let (got, d) = packets(build(188, 0x1FF0, false)); - assert_eq!(d.pcr_pid(), Some(0x1FF0)); - assert!(d.first_pcr().is_some()); - assert_eq!(d.tracks().len(), 2); - assert_eq!(by_stream(&got, 0), by_stream(&reference(), 0)); -} - -#[test] -fn packet_sizes_192_and_204() { - for size in [192, 204] { - let (got, d) = packets(build(size, VPID, false)); - assert_eq!(d.packet_size(), size); - assert_eq!(d.is_bdav(), size == 192); - assert_eq!( - by_stream(&got, 1), - by_stream(&reference(), 1), - "size {size}" - ); - assert_eq!( - by_stream(&got, 0), - by_stream(&reference(), 0), - "size {size}" - ); - } -} - -#[test] -fn two_access_units_in_one_pes_are_split_on_the_delimiter() { - let (got, _) = packets(build(188, VPID, true)); - let want = reference(); - let (g, w) = (by_stream(&got, 0), by_stream(&want, 0)); - assert_eq!(g.len(), w.len()); - for (a, b) in g.iter().zip(&w) { - assert_eq!(a.3, b.3); - assert_eq!(a.2, b.2, "keyframe flag"); - } - // The second unit of a pair has no timestamp of its own. - assert!(g.iter().filter(|p| p.1.is_none()).count() >= 5); -} - -#[test] -fn duplicate_packets_are_dropped() { - let clean = build(188, VPID, false); - let mut dup = Vec::new(); - for (i, p) in clean.chunks(188).enumerate() { - dup.extend_from_slice(p); - if i % 7 == 3 && p[1] & 0x1f == 1 { - dup.extend_from_slice(p); - } - } - let (got, d) = packets(dup); - assert!(d.stats().duplicates > 0); - assert_eq!(by_stream(&got, 0), by_stream(&packets(clean).0, 0)); -} - -#[test] -fn damaged_psi_is_ignored() { - let mut bytes = build(188, VPID, false); - // The first PMT's CRC byte: second packet, last section byte. - let mut broken = bytes.clone(); - let pmt = &mut broken[188..376]; - let st = 5 + usize::from(pmt[4]); // past the adaptation field and the pointer - let end = st + 3 + (usize::from(pmt[st + 2] & 0xf) << 8 | usize::from(pmt[st + 3])); - pmt[end] ^= 0xFF; - // Later copies of the PMT are intact, so the file still opens; the damage is counted. - let (_, d) = packets(broken); - assert!(d.stats().crc_errors >= 1, "{:?}", d.stats()); - // Garbage everywhere in the PAT leaves nothing to open. - for b in &mut bytes[..188] { - *b = 0x47; - } - for (i, p) in bytes.chunks_mut(188).enumerate() { - if p[1] == 0x40 && p[2] == 0 && i % 4 == 0 { - p[10] ^= 0x55; - } - } - let _ = TsDemuxer::new(Cursor::new(bytes)); -} - -#[test] -fn refusals_name_the_codec_and_pgs_is_exposed() { - let es = vec![ - Es { - pid: 0x100, - stream_type: 0x02, - descriptors: vec![], - }, - Es { - pid: 0x101, - stream_type: 0x11, - descriptors: vec![], - }, - Es { - pid: 0x102, - stream_type: 0x90, - descriptors: vec![], - }, - Es { - pid: 0x103, - stream_type: 0x06, - descriptors: vec![0x6A, 1, 0], - }, - Es { - pid: 0x104, - stream_type: 0x06, - descriptors: vec![0x59, 0], - }, - Es { - pid: 0x105, - stream_type: 0x83, - descriptors: vec![], - }, - ]; - let mut m = Mux::new(192); - m.tables(0x1000, 0x100, &es, 0); - for i in 0..40u64 { - m.pes( - 0x102, - 0xBD, - Some(90_000 + i * 1000), - None, - &[0x16, 0, 3, 1, 2, 3], - true, - false, - ); - m.pes( - 0x100, - 0xE0, - Some(90_000 + i * 3600), - None, - &[0, 0, 1, 0xB3, 1, 2, 3, 4], - false, - false, - ); - if i % 5 == 0 { - m.tables(0x1000, 0x100, &es, 0); - } - } - let mut d = TsDemuxer::new(Cursor::new(m.out)).unwrap(); - let tracks = d.tracks(); - assert_eq!(tracks.len(), 6); - assert_eq!(tracks[0].kind, StreamKind::Mpeg2Video); - assert!( - tracks[0].refusal.is_none(), - "MPEG-2 video is exposed, not refused" - ); - assert_eq!(tracks[0].stream, None, "no parseable sequence header yet"); - assert!(tracks[1].refusal.as_ref().unwrap().contains("aac_latm")); - assert_eq!(tracks[2].stream, Some(0)); - assert_eq!(tracks[3].kind, StreamKind::Ac3); - assert_eq!( - tracks[3].stream, None, - "no AC-3 frames were seen, so it cannot be described yet" - ); - assert_eq!(tracks[4].kind, StreamKind::DvbSub); - assert!(tracks[4].refusal.is_none(), "DVB subtitles are exposed"); - assert_eq!(tracks[5].kind, StreamKind::TrueHd); - assert!( - tracks[5].refusal.is_none(), - "TrueHD is exposed, not refused" - ); - assert_eq!(tracks[5].stream, None, "no TrueHD access unit was seen yet"); - assert_eq!(d.streams().len(), 2); - assert_eq!(d.streams()[0].params.codec, CodecId::Pgs); - assert_eq!(d.streams()[1].params.codec, CodecId::DvbSub); - let mut n = 0; - while let Ok(p) = d.next_packet() { - if p.stream != 0 { - continue; - } - assert_eq!(&p.data[..], &[0x16, 0, 3, 1, 2, 3]); - assert!(p.flags.keyframe); - n += 1; - } - assert_eq!(n, 40); -} - -#[test] -fn pmt_change_appends_streams_and_keeps_indices() { - let a = tiny("tiny_h264_aac.ts"); - let b = tiny("tiny_h264_eac3.ts"); - let mut both = a.clone(); - both.extend_from_slice(&b); - let mut d = TsDemuxer::new(Cursor::new(both)).unwrap(); - assert_eq!(d.streams().len(), 2); - let mut counts = HashMap::new(); - while let Ok(p) = d.next_packet() { - *counts.entry(p.stream).or_insert(0) += 1; - } - assert_eq!(d.stats().pmt_changes, 1); - assert_eq!(d.streams().len(), 3); - assert_eq!(d.streams()[2].params.codec, CodecId::EAc3); - assert_eq!(d.streams()[1].params.codec, CodecId::Aac); - let alone = |bytes: Vec| { - let mut d = TsDemuxer::new(Cursor::new(bytes)).unwrap(); - let mut c = [0usize; 2]; - while let Ok(p) = d.next_packet() { - c[p.stream as usize] += 1; - } - c - }; - let (ca, cb) = (alone(a), alone(b)); - assert_eq!(counts[&0], ca[0] + cb[0]); - assert_eq!(counts[&1], ca[1]); - assert_eq!(counts[&2], cb[1]); - let tracks = d.tracks(); - assert_eq!(tracks.iter().filter(|t| t.stream.is_some()).count(), 3); - assert!(tracks[1].pid == tracks[2].pid); -} - -#[test] -fn length_prefixed_video_and_config_records() { - let mut d = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap(); - d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed); - let avcc = d.streams()[0].params.extradata.clone().unwrap(); - assert_eq!(avcc[0], 1); - assert_eq!(avcc[4] & 3, 3, "4-byte lengths"); - let p = d.next_packet().unwrap(); - let n = u32::from_be_bytes(p.data[..4].try_into().unwrap()) as usize; - assert!(n + 4 <= p.data.len()); - // The same access unit, re-framed from the Annex-B one, round-trips. - let mut d2 = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap(); - let q = d2.next_packet().unwrap(); - assert_eq!( - ec_mpegts::annexb_to_length_prefixed(&q.data, 4), - p.data.to_vec() - ); - // The hvcC of the HEVC fixture. - let h = TsDemuxer::new(Cursor::new(tiny("tiny_hevc_aac.ts"))).unwrap(); - let hvcc = h.streams()[0].params.extradata.clone().unwrap(); - assert_eq!(hvcc[0], 1); - assert_eq!(hvcc[21] & 3, 3); - assert!(hvcc[22] >= 3, "VPS, SPS and PPS arrays"); - let _ = BufReader::new(File::open("/dev/null").unwrap()); }