diff --git a/crates/ec-matroska/examples/bench.rs b/crates/ec-matroska/examples/bench.rs deleted file mode 100644 index 78fb8297..00000000 --- a/crates/ec-matroska/examples/bench.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! bench: Matroska demux throughput for lanes/bench.md ("lane benchrest"). -//! -//! usage: -//! bench demux [reps] -//! -//! `demux` opens the file with `MatroskaDemuxer` and reads every packet of every track, `reps` -//! times (default 5), and keeps the best wall time. It prints packets per second and payload MB/s. -//! After timing, one untimed pass writes each track's packet payloads, concatenated in order, to -//! `.s.bin` so the bytes can be compared with ffmpeg's `-c copy -f data` output. -use std::fs::File; -use std::hint::black_box; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::{Demuxer, Packet, StreamInfo}; -use ec_matroska::MatroskaDemuxer; - -/// Read every packet of the file once, in file order. -fn read_all(path: &str) -> (Vec, Vec) { - let mut demux = - MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv"); - let streams = demux.streams().to_vec(); - let mut packets = Vec::new(); - loop { - match demux.next_packet() { - Ok(p) => packets.push(p), - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (streams, packets) -} - -/// One timed demux pass: sums the payload bytes so the work cannot be skipped. -fn demux_pass(path: &str) -> (usize, u64) { - let mut demux = - MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv"); - let (mut n, mut bytes) = (0usize, 0u64); - loop { - match demux.next_packet() { - Ok(p) => { - n += 1; - bytes += p.data.len() as u64; - black_box(&p.data); - } - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (n, bytes) -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("demux") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - assert!(reps >= 1, "reps must be at least 1"); - let file_bytes = std::fs::metadata(&args[2]).expect("stat").len(); - let (mut packets, mut bytes) = (0usize, 0u64); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - (packets, bytes) = demux_pass(black_box(&args[2])); - best = best.min(t.elapsed().as_secs_f64()); - } - // Untimed: per-track payload dumps for the ffmpeg byte comparison. - let (streams, all) = read_all(&args[2]); - for s in &streams { - let mut dump = Vec::new(); - for p in all.iter().filter(|p| p.stream == s.index) { - dump.extend_from_slice(&p.data); - } - std::fs::write(format!("{}.s{}.bin", args[3], s.index), &dump).expect("write dump"); - } - println!( - "packets={packets} payload_bytes={bytes} file_bytes={file_bytes} best_demux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}", - packets as f64 / best, - bytes as f64 / best / 1e6 - ); - } - _ => { - eprintln!("usage: bench demux [reps]"); - std::process::exit(2); - } - } -} diff --git a/crates/ec-mp4/examples/bench.rs b/crates/ec-mp4/examples/bench.rs deleted file mode 100644 index c8defd5b..00000000 --- a/crates/ec-mp4/examples/bench.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! bench: MP4 demux and mux throughput for lanes/bench.md ("lane benchaudio"). -//! -//! usage: -//! bench demux [reps] -//! bench mux [reps] -//! -//! `demux` opens the file with `Mp4Demuxer` and reads every packet of every track, `reps` times -//! (default 5), and keeps the best wall time. It prints packets per second and payload MB/s. After -//! timing, one untimed pass writes each track's packet payloads, concatenated in order, to -//! `.s.bin` so the bytes can be compared with ffmpeg's `-c copy -f data` output. -//! `mux` demuxes the input once (untimed), then times writing all packets into a new MP4 with -//! `Mp4Muxer`, best of `reps`; the last output is kept at `out.mp4`. -use std::fs::File; -use std::hint::black_box; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::{Demuxer, Muxer, Packet, StreamInfo}; -use ec_mp4::{Mp4Demuxer, Mp4Muxer}; - -/// Read every packet of the file once, in file order. -fn read_all(path: &str) -> (Vec, Vec) { - let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4"); - let streams = demux.streams().to_vec(); - let mut packets = Vec::new(); - loop { - match demux.next_packet() { - Ok(p) => packets.push(p), - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (streams, packets) -} - -/// One timed demux pass: sums the payload bytes so the work cannot be skipped. -fn demux_pass(path: &str) -> (usize, u64) { - let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4"); - let (mut n, mut bytes) = (0usize, 0u64); - loop { - match demux.next_packet() { - Ok(p) => { - n += 1; - bytes += p.data.len() as u64; - black_box(&p.data); - } - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (n, bytes) -} - -/// One timed mux pass into `out`. -fn mux_pass(out: &str, streams: &[StreamInfo], packets: &[Packet]) { - let file = File::create(out).expect("create"); - let mut mux = Mp4Muxer::new(file).expect("muxer"); - for s in streams { - mux.add_stream(s.clone()).expect("add stream"); - } - for p in packets { - mux.write_packet(p).expect("write packet"); - } - mux.finish().expect("finish"); -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("demux") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - let file_bytes = std::fs::metadata(&args[2]).expect("stat").len(); - let (mut packets, mut bytes) = (0usize, 0u64); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - (packets, bytes) = demux_pass(black_box(&args[2])); - best = best.min(t.elapsed().as_secs_f64()); - } - // Untimed: per-track payload dumps for the ffmpeg byte comparison. - let (streams, all) = read_all(&args[2]); - for s in &streams { - let mut dump = Vec::new(); - for p in all.iter().filter(|p| p.stream == s.index) { - dump.extend_from_slice(&p.data); - } - std::fs::write(format!("{}.s{}.bin", args[3], s.index), &dump).expect("write dump"); - } - println!( - "packets={packets} payload_bytes={bytes} file_bytes={file_bytes} best_demux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}", - packets as f64 / best, - bytes as f64 / best / 1e6 - ); - } - Some("mux") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - let (streams, packets) = read_all(&args[2]); - let bytes: u64 = packets.iter().map(|p| p.data.len() as u64).sum(); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - mux_pass(black_box(&args[3]), &streams, &packets); - best = best.min(t.elapsed().as_secs_f64()); - } - println!( - "packets={} payload_bytes={bytes} best_mux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}", - packets.len(), - packets.len() as f64 / best, - bytes as f64 / best / 1e6 - ); - } - _ => { - eprintln!( - "usage: bench demux [reps]\n bench mux [reps]" - ); - std::process::exit(2); - } - } -} diff --git a/crates/ec-mp4/src/config.rs b/crates/ec-mp4/src/config.rs index b1d08ad6..5e7278e1 100644 --- a/crates/ec-mp4/src/config.rs +++ b/crates/ec-mp4/src/config.rs @@ -1,45 +1,10 @@ //! Turns encoder output (Annex-B) into mp4 samples and sample-entry config records. -const NAL_IDR: u8 = 5; -const NAL_SEI: u8 = 6; -const NAL_SPS: u8 = 7; -const NAL_PPS: u8 = 8; -const NAL_AUD: u8 = 9; - const HEVC_VPS: u8 = 32; const HEVC_SPS: u8 = 33; const HEVC_PPS: u8 = 34; const HEVC_AUD: u8 = 35; -const AV1C_HEAD: [u8; 4] = [0x81, 0x1F, 0x0C, 0x00]; - -/// An H.264 sample, whether it is an IDR, and its first SPS and PPS when present. -pub type H264Split = (Vec, bool, Option<(Vec, Vec)>); - -/// Splits an H.264 Annex-B access unit into a length-prefixed sample. -/// -/// SPS, PPS, AUD and SEI are stripped from the sample. `None` when the unit holds no coded slice. -pub fn h264_split_annex_b(annex_b: &[u8]) -> Option { - let nals = split_annex_b(annex_b); - let first = |kind: u8| nals.iter().copied().find(|n| nal_type(n) == kind); - let params = match (first(NAL_SPS), first(NAL_PPS)) { - (Some(sps), Some(pps)) => Some((sps.to_vec(), pps.to_vec())), - _ => None, - }; - let mut out = Vec::with_capacity(annex_b.len()); - let mut is_idr = false; - for nal in nals { - match nal_type(nal) { - NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue, - NAL_IDR => is_idr = true, - _ => {} - } - out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); - out.extend_from_slice(nal); - } - (!out.is_empty()).then_some((out, is_idr, params)) -} - /// An H.264 `AVCDecoderConfigurationRecord` for one SPS and one PPS, with four-byte NAL length prefixes. pub fn avcc_record(sps: &[u8], pps: &[u8]) -> Vec { let profile = sps.get(1..4).unwrap_or(&[0, 0, 0]); @@ -112,17 +77,6 @@ pub fn annex_b_to_hvcc(annex_b: &[u8]) -> Option> { (!out.is_empty()).then_some(out) } -/// An `av1C` record: the four fixed bytes, then the sequence header OBU as the config OBUs. -pub fn av1c_record(ten_bit: bool, config_obus: &[u8]) -> Vec { - let mut head = AV1C_HEAD; - if ten_bit { - head[2] |= 0x40; - } - let mut out = head.to_vec(); - out.extend_from_slice(config_obus); - out -} - fn hevc_nal_type(nal: &[u8]) -> u8 { nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F) } @@ -165,7 +119,3 @@ fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) { nals.push(&nal[..end]); } } - -fn nal_type(nal: &[u8]) -> u8 { - nal.first().map_or(0, |b| b & 0x1F) -} diff --git a/crates/ec-mp4/src/demux.rs b/crates/ec-mp4/src/demux.rs index 6a86a114..e7118f93 100644 --- a/crates/ec-mp4/src/demux.rs +++ b/crates/ec-mp4/src/demux.rs @@ -960,7 +960,7 @@ impl<'a> SampleTable<'a> { } b"stsc" => { let (_, _, rest) = full(payload)?; - let count = count_of(rest, 12, file_len)?; + let count = count_of(rest, 12)?; me.stsc = Vec::with_capacity(count); for i in 0..count { me.stsc @@ -987,7 +987,7 @@ impl<'a> SampleTable<'a> { } b"co64" => { let (_, _, rest) = full(payload)?; - let count = count_of(rest, 8, file_len)?; + let count = count_of(rest, 8)?; me.chunks = Vec::with_capacity(count); for i in 0..count { me.chunks.push(be64(rest, 4 + i * 8)?); @@ -1731,7 +1731,7 @@ fn unpack_language(packed: u16) -> Option { /// The `(count, value)` pairs of an `stts`/`ctts` table. fn pairs(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result> { let (_, _, rest) = full(payload)?; - let count = count_of(rest, 8, u64::MAX)?; + let count = count_of(rest, 8)?; let mut out = Vec::with_capacity(count); for i in 0..count { out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?)); @@ -1741,7 +1741,7 @@ fn pairs(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result> { /// The `u32` table of an `stss`/`stco`. fn words(rest: &[u8]) -> Result> { - let count = count_of(rest, 4, u64::MAX)?; + let count = count_of(rest, 4)?; let mut out = Vec::with_capacity(count); for i in 0..count { out.push(be32(rest, 4 + i * 4)?); @@ -1751,7 +1751,7 @@ fn words(rest: &[u8]) -> Result> { /// An entry count, refused when the entries it claims do not fit the box it is /// in — the one check that keeps a crafted count from being allocated. -fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result { +fn count_of(rest: &[u8], width: usize) -> Result { let count = be32(rest, 0)? as usize; let have = rest.len().saturating_sub(4) / width; if count > have { @@ -1798,7 +1798,7 @@ fn display_rotation(a: i32, b: i32, c: i32, d: i32) -> Rotation { fn elst(payload: &[u8]) -> Result> { let (version, _, rest) = full(payload)?; let width = if version == 0 { 12 } else { 20 }; - let count = count_of(rest, width, u64::MAX)?; + let count = count_of(rest, width)?; let mut out = Vec::with_capacity(count); for i in 0..count { let at = 4 + i * width; diff --git a/crates/ec-mp4/tests/it/edith_parity.rs b/crates/ec-mp4/tests/it/edith_parity.rs deleted file mode 100644 index c982f99c..00000000 --- a/crates/ec-mp4/tests/it/edith_parity.rs +++ /dev/null @@ -1,402 +0,0 @@ -//! Parity with ffprobe, file by file: what ec-mp4 reads out of an mp4 or mov has -//! to be what ffprobe reads out of the same bytes, sample for sample and field -//! for field. This is the swap criterion for edith's `mp4::` demuxer: identical -//! packet bytes, identical timestamps, identical stream metadata. -//! -//! -//! Per track, the comparison is: codec, coded size, sample rate, channels, -//! timebase, rotation, and per sample the byte offset, size, presentation time -//! (`cts` against ffprobe `pts`), the sync flag, and the decode time up to one -//! constant. ffmpeg's `dts` carries a constant shift of its own (the largest -//! composition delay), so only its differences are the same claim. Edit lists -//! are applied on both sides, the same way ffmpeg applies them. -//! -//! Where edith's engine reads the file differently on purpose (it trims the -//! picture by the edit list where ffprobe shifts it, and ignores empty edits), -//! the edith-only values are printed in the table, not compared. See -//! `lanes/mp4demux.report.md`. - -use std::collections::HashMap; -use std::fs::File; -use std::io::BufReader; -use std::path::{Path, PathBuf}; - -use ec_core::{CodecId, Demuxer, MediaParameters}; -use ec_mp4::{Mp4Demuxer, Sample}; - -use crate::common::ffmpeg_name; - -/// One ffprobe `key=value` record block, keyed by field name. -type Record = HashMap; - -/// Every `stream=`/`packet=` block of `default=nw=1` output, split where the -/// `first` key starts a new block. -fn records(text: &str, first: &str) -> Vec { - let mut out: Vec = Vec::new(); - for line in text.lines() { - let Some((key, value)) = line.split_once('=') else { - continue; - }; - if key == first { - out.push(Record::new()); - } - if let Some(record) = out.last_mut() { - record.insert(key.to_string(), value.to_string()); - } - } - out -} - -fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"]) - .arg(path) - .output() - .expect("ffprobe runs"); - assert!( - out.status.success(), - "ffprobe refused {}: {}", - path.display(), - String::from_utf8_lossy(&out.stderr) - ); - records(&String::from_utf8_lossy(&out.stdout), first) -} - -/// What ffprobe says about one stream, `None` where a field is `N/A` or absent. -#[derive(Debug, Default)] -struct ProbeStream { - codec: String, - width: Option, - height: Option, - sample_rate: Option, - channels: Option, - time_base: String, - duration_ts: Option, - rotation: Option, - attached_pic: bool, -} - -#[derive(Debug, Clone, Copy)] -struct ProbePacket { - pts: Option, - dts: Option, - size: u64, - pos: Option, - key: bool, -} - -fn number(value: Option<&String>) -> Option { - value.and_then(|v| v.parse().ok()) -} - -fn probe_streams(path: &Path, rotations: &HashMap) -> Vec { - ffprobe( - path, - "stream=index,codec_name,codec_type,width,height,sample_rate,channels,time_base,duration_ts:stream_disposition=attached_pic", - "index", - ) - .into_iter() - .map(|r| { - let index = number::(r.get("index")).unwrap_or(u32::MAX); - ProbeStream { - codec: r.get("codec_name").cloned().unwrap_or_default(), - width: number(r.get("width")), - height: number(r.get("height")), - sample_rate: number(r.get("sample_rate")), - channels: number(r.get("channels")), - time_base: r.get("time_base").cloned().unwrap_or_default(), - duration_ts: number(r.get("duration_ts")), - rotation: rotations.get(&index).copied(), - attached_pic: r - .get("DISPOSITION:attached_pic") - .is_some_and(|v| v == "1"), - } - }) - .collect() -} - -/// Display rotation per stream index, from the `side_data_list` of the JSON -/// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film -/// ffprobe spends minutes decoding for it, while the JSON dump is immediate. -fn rotations(path: &Path) -> HashMap { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-show_streams", "-of", "json"]) - .arg(path) - .output() - .expect("ffprobe runs"); - let mut found = HashMap::new(); - let mut current = None; - for line in String::from_utf8_lossy(&out.stdout).lines() { - let line = line.trim(); - // Stream objects open with `"index": n,` at the stream's own indent. - if let Some(rest) = line.strip_prefix("\"index\": ") { - current = rest.trim_end_matches(',').parse::().ok(); - } else if let Some(rest) = line.strip_prefix("\"rotation\": ") - && let (Some(index), Ok(r)) = (current, rest.trim_end_matches(',').parse::()) - { - found.insert(index, r); - } - } - found -} - -/// Packets per ffprobe stream index, each list in the order ffprobe demuxes -/// them, which for one stream is decode order. -fn probe_packets(path: &Path) -> HashMap> { - let mut by_stream: HashMap> = HashMap::new(); - for r in ffprobe( - path, - "packet=stream_index,pts,dts,size,pos,flags", - "stream_index", - ) { - let Some(index) = number::(r.get("stream_index")) else { - continue; - }; - by_stream.entry(index).or_default().push(ProbePacket { - pts: number(r.get("pts")), - dts: number(r.get("dts")), - size: number(r.get("size")).unwrap_or(0), - pos: number(r.get("pos")), - key: r.get("flags").is_some_and(|f| f.starts_with('K')), - }); - } - by_stream -} - -/// ffprobe's rotation (counter-clockwise degrees) as this crate's clockwise -/// quarter turn: the same matrix, the other direction. -fn expected_rotation(rotation: Option) -> Option { - match rotation { - None => Some(0), - Some(r) if r % 90 == 0 => Some((-r / 90).rem_euclid(4) as u8), - Some(_) => None, - } -} - -/// One file, compared. Returns the table row and every mismatch it found. -fn compare(path: &Path) -> (String, Vec) { - let mut problems = Vec::new(); - let file = File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let demuxer = Mp4Demuxer::new(BufReader::new(file)) - .unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); - // Cover art is not a track: ffprobe lists an `covr` picture as a video stream - // with `attached_pic` set, and this crate does not list it (a player that - // shows an album cover as a video stream is the bug). Dropped on both sides. - let rotations = rotations(path); - let all_probed = probe_streams(path, &rotations); - let probed: Vec = all_probed.into_iter().filter(|p| !p.attached_pic).collect(); - let packets = probe_packets(path); - let tracks = demuxer.tracks().to_vec(); - if probed.len() != tracks.len() { - // The track position is the only index the two share, so the counts agree - // or the rest of the comparison is meaningless. - problems.push(format!("track count: ec {} ffprobe {}", tracks.len(), probed.len())); - } - let mut rows = Vec::new(); - for (position, track) in tracks.iter().enumerate() { - let Some(stream) = track.stream else { - continue; - }; - let Some(p) = probed.get(position) else { - problems.push(format!("track {position}: no ffprobe stream")); - continue; - }; - let info = demuxer.streams()[stream as usize].clone(); - let samples: Vec = demuxer.samples(stream).to_vec(); - let tag = format!("track {position} ({})", ffmpeg_name(info.params.codec)); - if ffmpeg_name(info.params.codec) != p.codec { - problems.push(format!("{tag}: codec, ffprobe says {}", p.codec)); - } - let tb = format!("{}/{}", info.time_base.num(), info.time_base.den()); - if tb != p.time_base { - problems.push(format!("{tag}: timebase {tb} vs {}", p.time_base)); - } - match &info.params.media { - MediaParameters::Video(v) => { - if Some((v.width, v.height)) != p.width.zip(p.height) { - problems.push(format!( - "{tag}: coded size {}x{} vs ffprobe {:?}x{:?}", - v.width, v.height, p.width, p.height - )); - } - // Both sides name the same matrix; ffprobe counts counter-clockwise. - if info.rotation.steps() != expected_rotation(p.rotation) { - problems.push(format!( - "{tag}: rotation {:?} vs ffprobe {:?}", - info.rotation, p.rotation - )); - } - } - MediaParameters::Audio(a) => { - // Implicit HE-AAC (SBR with no extension frequency in the config): - // ffprobe decodes the first frames for the doubled output rate, - // and so does edith (`mp4_aac_prime`); this reader reports the core's. - let implicit_sbr = info.params.codec == CodecId::Aac - && p.sample_rate == Some(a.sample_rate * 2); - if Some(a.sample_rate) != p.sample_rate && !implicit_sbr { - problems.push(format!("{tag}: rate {} vs {:?}", a.sample_rate, p.sample_rate)); - } - if Some(a.layout.channel_count() as u32) != p.channels { - problems.push(format!( - "{tag}: channels {} vs {:?}", - a.layout.channel_count(), - p.channels - )); - } - } - MediaParameters::Subtitle => {} - } - // Per sample, against ffprobe's packets of the same stream. - let theirs = packets.get(&(position as u32)).cloned().unwrap_or_default(); - // A subtitle track ends in a zero-duration sample at the movie's end, an - // end marker ffprobe does not hand out as a packet. Dropped on this side - // for the comparison only; the sample is still in the table. - let mut samples = samples; - if matches!(info.params.media, MediaParameters::Subtitle) - && samples.len() == theirs.len() + 1 - && samples.last().is_some_and(|s| s.duration == 0) - { - samples.pop(); - } - if theirs.len() != samples.len() { - problems.push(format!( - "{tag}: {} samples vs {} packets", - samples.len(), - theirs.len() - )); - } - // VP8 and VP9 carry no `stss` in these files, so the box makes every - // sample a sync sample, while ffprobe reads the key flag out of the - // bitstream. The box is what edith follows; the flag difference is named. - let box_says_all_sync = samples.iter().all(|s| s.sync); - let bitstream_keys = theirs.iter().filter(|p| p.key).count(); - let vp_box_only = matches!(info.params.codec, CodecId::Vp8 | CodecId::Vp9) - && box_says_all_sync - && bitstream_keys < samples.len(); - let mut dts_shift: Option = None; - let (mut bad_pos, mut bad_size, mut bad_pts, mut bad_sync, mut bad_dts) = (0, 0, 0, 0, 0); - for (ours, theirs) in samples.iter().zip(&theirs) { - if theirs.pos != Some(ours.offset) { - bad_pos += 1; - } - if u64::from(ours.size) != theirs.size { - bad_size += 1; - } - if theirs.pts != Some(ours.cts) { - bad_pts += 1; - } - if theirs.key != ours.sync && !vp_box_only { - bad_sync += 1; - } - match (theirs.dts, dts_shift) { - (Some(d), None) => dts_shift = Some(ours.dts - d), - (Some(d), Some(k)) if ours.dts - d != k => bad_dts += 1, - (None, _) => bad_dts += 1, - _ => {} - } - } - for (what, n) in [ - ("offset", bad_pos), - ("size", bad_size), - ("pts", bad_pts), - ("sync", bad_sync), - ("dts", bad_dts), - ] { - if n > 0 { - problems.push(format!("{tag}: {n} samples differ in {what}")); - } - } - let syncs = demuxer.sync_in_display_order(stream).len(); - rows.push(format!( - " t{position} {:<7} n={:<6} trim={:<8} first={:<6} dts-shift={:<6} edits={:?} display-syncs={syncs} duration_ts={:?}/{:?}", - ffmpeg_name(info.params.codec), - samples.len(), - format!("{:?}", demuxer.presentation_trim(stream)), - demuxer.first_frame_sample(stream), - dts_shift.map_or("-".into(), |k| k.to_string()), - track.edits.iter().map(|e| (e.segment_duration, e.media_time)).collect::>(), - p.duration_ts, - info.duration, - )); - } - let row = format!("{name}\n{}", rows.join("\n")); - (row, problems) -} - -/// Every mp4-family file under `dir`, recursively, into `files`. -fn collect(dir: &Path, files: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - collect(&path, files); - continue; - } - let name = path.to_string_lossy().to_ascii_lowercase(); - if [".mp4", ".m4a", ".m4v", ".mov"].iter().any(|ext| name.ends_with(ext)) { - files.push(path); - } - } -} - -fn corpus() -> Vec { - let mut files = Vec::new(); - collect(&ec_testkit::root().join("mp4corpus"), &mut files); - files.sort(); - files.dedup(); - files -} - -#[test] -fn every_corpus_file_matches_ffprobe_sample_for_sample() { - let files = corpus(); - assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/fixtures.sh"); - let mut report = Vec::new(); - let mut failures = Vec::new(); - for path in &files { - let (row, problems) = compare(path); - report.push(row); - if !problems.is_empty() { - failures.push(format!("{}:\n {}", path.display(), problems.join("\n "))); - } - } - println!("{}", report.join("\n")); - assert!( - failures.is_empty(), - "{} of {} files differ from ffprobe:\n{}", - failures.len(), - files.len(), - failures.join("\n") - ); -} - -/// The edith-side reading of the edit list and the sample table, on fixtures -/// whose answers are known: an AAC track whose edit list trims one 1024-sample -/// priming packet, and an open-GOP stream whose keyframes sit out of display -/// order. -#[test] -fn edith_trim_and_display_order_read_the_known_fixtures() { - let aac = ec_testkit::fixture("audio/aac-mp4-stereo-48000.mp4"); - let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture"))) - .expect("the fixture demuxes"); - assert_eq!(demuxer.presentation_trim(0), Some(1024)); - assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2"); - assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder"); - - let gop = ec_testkit::fixture("video/h264-open-gop.mp4"); - let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture"))) - .expect("the fixture demuxes"); - let syncs = demuxer.sync_in_display_order(0); - assert!(!syncs.is_empty(), "B-frames: the display table answers"); - assert!( - syncs.windows(2).all(|w| w[0].0 < w[1].0 && w[0].1 != w[1].1), - "display indices ascend: {syncs:?}" - ); - let samples = demuxer.samples(0); - for &(_, decode) in &syncs { - assert!(samples[decode as usize].sync, "decode {decode} is a sync sample"); - } -} diff --git a/crates/ec-mp4/tests/it/main.rs b/crates/ec-mp4/tests/it/main.rs index e76f617b..952cd984 100644 --- a/crates/ec-mp4/tests/it/main.rs +++ b/crates/ec-mp4/tests/it/main.rs @@ -7,7 +7,6 @@ mod chapters; mod common; mod dts; mod edit_trim; -mod edith_parity; mod fuzz_regressions; mod mp4; mod mux_entries; diff --git a/crates/ec-mpegts/Cargo.toml b/crates/ec-mpegts/Cargo.toml index 22ad19e1..4c2fa1f6 100644 --- a/crates/ec-mpegts/Cargo.toml +++ b/crates/ec-mpegts/Cargo.toml @@ -15,3 +15,6 @@ ec-truehd.workspace = true [dev-dependencies] ec-testkit.workspace = true + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(fuzzing)"] } diff --git a/crates/ec-mpegts/examples/bench.rs b/crates/ec-mpegts/examples/bench.rs deleted file mode 100644 index 562961fd..00000000 --- a/crates/ec-mpegts/examples/bench.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! Open, full read and seek timings: `cargo run --release -p ec-mpegts --example bench -- file`. -use std::fs::File; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::registry::{Demuxer, SeekMode}; -use ec_core::{TimeBase, Timestamp}; - -fn main() { - let path = std::env::args().nth(1).expect("usage: bench "); - let t = Instant::now(); - let mut d = - ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("demux"); - println!("open {:?}, duration {:?}", t.elapsed(), d.duration_secs()); - let t = Instant::now(); - let (mut n, mut bytes) = (0u64, 0u64); - while let Ok(p) = d.next_packet() { - n += 1; - bytes += p.data.len() as u64; - } - let e = t.elapsed(); - println!( - "read {n} packets, {} MB in {e:?} ({:.0} MB/s)", - bytes >> 20, - bytes as f64 / 1e6 / e.as_secs_f64() - ); - let dur = d.duration_secs().unwrap_or(1.0); - for frac in [0.1, 0.5, 0.9, 0.999] { - let t = Instant::now(); - let target = (dur * frac * 90_000.0) as i64 + d.streams()[0].start_time.unwrap_or(0); - d.seek( - 0, - Timestamp::new(target, TimeBase::new(1, 90_000)), - SeekMode::SyncBefore, - ) - .unwrap(); - let p = d.next_packet().unwrap(); - println!( - "seek {frac}: {:?} -> pts {:?} key {}", - t.elapsed(), - p.pts, - p.flags.keyframe - ); - } -} diff --git a/crates/ec-mpegts/examples/dump.rs b/crates/ec-mpegts/examples/dump.rs deleted file mode 100644 index 5cc224ab..00000000 --- a/crates/ec-mpegts/examples/dump.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! Lists the programs, tracks and streams of a transport stream and counts its -//! packets: `cargo run -p ec-mpegts --example dump -- file.m2ts`. - -use std::fs::File; -use std::io::BufReader; - -use ec_core::registry::Demuxer; -use ec_mpegts::TsDemuxer; - -fn main() { - let path = std::env::args().nth(1).expect("usage: dump "); - let mut d = TsDemuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("demux"); - println!("packet size {} bdav {}", d.packet_size(), d.is_bdav()); - for p in d.programs() { - println!( - "program {} pmt {:#x} pcr {:?} streams {}", - p.number, - p.pmt_pid, - p.pcr_pid, - p.streams.len() - ); - } - for t in d.tracks() { - println!( - "track pid {:#x} type {:#x} {:?} stream {:?} refusal {:?}", - t.pid, t.stream_type, t.kind, t.stream, t.refusal - ); - } - for s in d.streams() { - println!( - "stream {} {} start {:?} duration {:?}", - s.index, - s.params.codec.name(), - s.start_time, - s.duration - ); - } - println!("duration {:?}", d.duration_secs()); - let mut counts = vec![0u64; d.streams().len()]; - while let Ok(p) = d.next_packet() { - counts[p.stream as usize] += 1; - } - println!("packets {counts:?} stats {:?}", d.stats()); -} diff --git a/crates/ec-mpegts/examples/offs.rs b/crates/ec-mpegts/examples/offs.rs deleted file mode 100644 index 8888a0c2..00000000 --- a/crates/ec-mpegts/examples/offs.rs +++ /dev/null @@ -1,22 +0,0 @@ -use ec_core::registry::Demuxer; -use std::fs::File; -use std::io::BufReader; -fn main() { - let path = std::env::args().nth(1).unwrap(); - let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap(); - let mut n = 0; - while let Ok(p) = d.next_packet() { - println!( - "{} off {} pts {:?} dur {:?} len {}", - p.stream, - d.last_packet_offset(), - p.pts, - p.duration, - p.data.len() - ); - n += 1; - if n > 14 { - break; - } - } -} diff --git a/crates/ec-mpegts/examples/psdump.rs b/crates/ec-mpegts/examples/psdump.rs deleted file mode 100644 index 1f160e90..00000000 --- a/crates/ec-mpegts/examples/psdump.rs +++ /dev/null @@ -1,43 +0,0 @@ -use ec_core::registry::Demuxer; -use ec_mpegts::PsDemuxer; -fn main() { - let p = std::env::args().nth(1).unwrap(); - let mut d = PsDemuxer::new(std::io::BufReader::new(std::fs::File::open(p).unwrap())).unwrap(); - for s in d.streams() { - println!( - "stream {} {:?} start {:?} dur {:?}", - s.index, s.params.codec, s.start_time, s.duration - ); - } - for t in d.tracks() { - println!("track {:04x} {:?} {:?}", t.pid, t.kind, t.refusal); - } - println!("dur {:?} stats {:?}", d.duration_secs(), d.stats()); - if let Some(t) = std::env::args().nth(3) { - use ec_core::registry::SeekMode; - let t: i64 = t.parse().unwrap(); - d.seek( - 0, - ec_core::Timestamp::new(t, ec_core::TimeBase::new(1, 90000)), - SeekMode::SyncBefore, - ) - .unwrap(); - println!("landing {}", d.last_packet_offset()); - } - let n: usize = std::env::args() - .nth(2) - .map(|x| x.parse().unwrap()) - .unwrap_or(40); - for _ in 0..n { - let Ok(p) = d.next_packet() else { break }; - println!( - "s{} pts {:?} dts {:?} k{} len {} off {}", - p.stream, - p.pts, - p.dts, - p.flags.keyframe as u8, - p.data.len(), - d.last_packet_offset() - ); - } -} diff --git a/crates/ec-mpegts/src/demux.rs b/crates/ec-mpegts/src/demux.rs index 343f6912..4e2f1af0 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; } @@ -441,9 +411,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(); if !is_psi && tracked.is_none() { @@ -452,11 +419,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 +437,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 +467,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 +483,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 +501,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; @@ -649,9 +609,6 @@ impl TsDemuxer { if same { return; } - if self.pmt_seen { - self.stats.pmt_changes += 1; - } self.pmt_seen = true; for ti in 0..self.tracks.len() { let t = &self.tracks[ti]; @@ -747,7 +704,6 @@ impl TsDemuxer { self.frozen = false; tail?; self.reset_at(self.first_off, None); - self.stats = Stats::default(); Ok(()) } @@ -957,11 +913,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 5c391f0b..28f37bb4 100644 --- a/crates/ec-mpegts/src/lib.rs +++ b/crates/ec-mpegts/src/lib.rs @@ -61,6 +61,7 @@ mod track; mod ts; mod window; +#[cfg(fuzzing)] #[doc(hidden)] pub mod fuzz_api; @@ -68,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()); } diff --git a/crates/ec-ogg/examples/benchp1.rs b/crates/ec-ogg/examples/benchp1.rs deleted file mode 100644 index 8f8f46f9..00000000 --- a/crates/ec-ogg/examples/benchp1.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! benchp1: Ogg demux throughput for lanes/bench.md ("lane benchp1"). -//! -//! usage: benchp1 [reps] -//! -//! Opens the file and reads every packet with `OggDemuxer`, `reps` times (default 5), keeping the -//! best wall time. Prints the packet count and byte total (checked against ffprobe) and the time. -use std::fs::File; -use std::hint::black_box; -use std::io::BufReader; -use std::time::Instant; - -use ec_core::Demuxer; -use ec_ogg::OggDemuxer; - -/// Demux the whole file once: (packets, bytes). -fn demux_once(path: &str) -> (u64, u64) { - let mut demux = OggDemuxer::open(BufReader::new(File::open(path).expect("open"))).expect("open ogg"); - let (mut packets, mut bytes) = (0u64, 0u64); - loop { - match demux.next_packet() { - Ok(p) => { - packets += 1; - bytes += p.data.len() as u64; - black_box(&p); - } - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - } - } - (packets, bytes) -} - -fn main() { - let args: Vec = std::env::args().collect(); - let reps: usize = args.get(2).map_or(5, |s| s.parse().expect("reps")); - let (packets, bytes) = demux_once(&args[1]); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(demux_once(black_box(&args[1]))); - best = best.min(t.elapsed().as_secs_f64()); - } - println!( - "packets={packets} bytes={bytes} best_demux_s={best:.4} mb_s={:.2} reps={reps}", - bytes as f64 / best / 1e6 - ); -} diff --git a/crates/ec-ogg/src/demux.rs b/crates/ec-ogg/src/demux.rs index 975ef04d..6b4bb8cf 100644 --- a/crates/ec-ogg/src/demux.rs +++ b/crates/ec-ogg/src/demux.rs @@ -49,15 +49,12 @@ struct Track { mapping: Mapping, /// Header packets, in order, until [`Mapping::header_packets`] are in. headers: Vec>, - /// Bytes of a packet still being assembled across a page boundary. - partial: Vec, - /// A packet is mid-assembly (true even when its bytes so far are empty, - /// which happens when a page ends exactly on a 255-byte segment). - assembling: bool, - /// Granule position the next packet starts at. - pos: i64, - /// False between a packet of unknown duration and the next page granule. - pos_known: bool, + /// Bytes of a packet still being assembled across a page boundary; `Some` while + /// one is mid-assembly, even when its bytes so far are empty. + partial: Option>, + /// Granule position the next packet starts at; `None` after a packet of unknown + /// duration until the next page granule. + pos: Option, /// The stream has seen its end-of-stream page. eos: bool, } @@ -207,10 +204,10 @@ impl OggDemuxer { let mapping = self.tracks[index].mapping; let time_base = self.streams[index].time_base; - let mut packet = std::mem::take(&mut self.tracks[index].partial); - let mut assembling = self.tracks[index].assembling; + let carried = self.tracks[index].partial.take(); + let mut assembling = carried.is_some(); + let mut packet = carried.unwrap_or_default(); let mut pos = self.tracks[index].pos; - let mut pos_known = self.tracks[index].pos_known; let mut headers_done = self.tracks[index].headers_complete(); let mut at = 0usize; let mut segments = &page.header.segments[..]; @@ -270,32 +267,26 @@ impl OggDemuxer { } let duration = mapping.packet_duration(&done); let mut out = Packet::new(index as u32, time_base, done); - out.pts = pos_known.then_some(pos); + out.pts = pos; out.dts = out.pts; out.duration = duration; // Every Ogg audio packet is a decodable entry point as far // as the container is concerned; codec pre-roll (a Vorbis // block needs its predecessor to overlap) is the decoder's. out.flags.keyframe = true; - match duration { - // Past i64::MAX the position is no longer known, like an - // unknown duration: the next page granule re-anchors it. - Some(d) if pos_known => match pos.checked_add(d) { - Some(next) => pos = next, - None => pos_known = false, - }, - Some(_) => {} - None => pos_known = false, - } + // Past i64::MAX the position is no longer known, like an + // unknown duration: the next page granule re-anchors it. + pos = match (pos, duration) { + (Some(p), Some(d)) => p.checked_add(d), + _ => None, + }; self.queue.push_back(out); } } } let track = &mut self.tracks[index]; - track.partial = packet; - track.assembling = assembling; + track.partial = assembling.then_some(packet); track.pos = pos; - track.pos_known = pos_known; track.eos |= page.header.eos; // The granule is where the last packet finishing on this page ends, so @@ -309,8 +300,7 @@ impl OggDemuxer { .push(granule_side_data(page.header.granule)); } let track = &mut self.tracks[index]; - track.pos = page.header.granule; - track.pos_known = true; + track.pos = Some(page.header.granule); } Ok(()) } @@ -338,10 +328,8 @@ impl OggDemuxer { serial: page.header.serial, mapping, headers: Vec::new(), - partial: Vec::new(), - assembling: false, - pos: 0, - pos_known: true, + partial: None, + pos: Some(0), eos: false, }); Some(index) @@ -383,9 +371,8 @@ impl OggDemuxer { fn reset_state(&mut self) { self.queue.clear(); for track in &mut self.tracks { - track.partial.clear(); - track.assembling = false; - track.pos_known = false; + track.partial = None; + track.pos = None; track.eos = false; } } @@ -493,8 +480,7 @@ impl Demuxer for OggDemuxer { self.inner.seek(SeekFrom::Start(self.data_start))?; } let track = &mut self.tracks[index]; - track.pos = granule; - track.pos_known = true; + track.pos = Some(granule); Ok(()) } } diff --git a/crates/ec-ogg/tests/real_library.rs b/crates/ec-ogg/tests/real_library.rs deleted file mode 100644 index c2666f28..00000000 --- a/crates/ec-ogg/tests/real_library.rs +++ /dev/null @@ -1,315 +0,0 @@ -//! -//! Per file the oracle checks: -//! - packet count and every packet's size (ffprobe, audio stream 0); -//! - the concatenated packet payloads (ffmpeg `-c copy -f data`), byte for byte; -//! - the header block: Opus's `OpusHead` against ffprobe's `extradata_size` -//! exactly; Vorbis's three Xiph-laced packets by their lacing and magic (see -//! below for why the size is not compared); -//! - timing: where a packet carries a pts, it equals ffprobe's pts after the -//! Opus pre-skip shift; where a page ends on a packet, the granule position -//! equals that packet's ffprobe end (pts + duration) after the same shift. -//! -//! Timing rule, as ffmpeg's Ogg demuxer applies it (measured on these files): -//! - Vorbis: granule = the sample position at the packet's end, at the stream -//! rate; ffmpeg's pts = granule - duration. No shift. The first packet is the -//! one exception: ffmpeg starts it at minus its own length, while ec-ogg, by -//! its documented convention, starts the stream at zero and states no -//! duration for a Vorbis packet. Its pts is therefore not compared; its -//! granule still is. -//! - Opus: granule counts 48 kHz samples *including* the pre-skip; ffmpeg's pts -//! = granule - pre_skip - duration, so the end is `granule - pre_skip`. Our -//! packet pts start at zero, so ours = ffmpeg's pts + pre_skip. -//! -//! Header block: ffmpeg's stated Vorbis extradata size differs from ours on -//! some files (ours keeps the comment header verbatim, which the remux path -//! relies on for bit-identical output). ffprobe does not expose the extradata -//! bytes, so the Vorbis block is checked structurally and the size difference -//! is reported, not failed. -//! -//! Scope: demux only. The decoded PCM is not compared here. -//! - -use std::path::Path; - -use ec_core::Demuxer; -use ec_ogg::{Mapping, OggDemuxer, granule_of}; - -/// One packet as ffprobe reports it. -struct Probed { - pts: Option, - duration: Option, - size: usize, -} - -/// The verdict for one file, with the text the table prints. -enum Verdict { - Match(String), - Refused(String), - Failed(String), -} - -/// Parses an ffprobe csv cell: `N/A` and blanks are absent. -fn cell(s: &str) -> Option { - let s = s.trim(); - if s.is_empty() || s == "N/A" { - None - } else { - s.parse().ok() - } -} - -/// Audio stream 0's packets: header packets are not among them, as with ours. -fn ffprobe_packets(path: &Path) -> Result, String> { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "packet=pts,duration,size", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .map_err(|e| format!("ffprobe: {e}"))?; - if !out.status.success() { - return Err("ffprobe failed on the packets".into()); - } - let mut packets = Vec::new(); - for line in String::from_utf8_lossy(&out.stdout).lines() { - let f: Vec<&str> = line.split(',').collect(); - if f.len() < 3 { - return Err(format!("unexpected ffprobe packet row: {line}")); - } - let size = cell(f[2]).ok_or_else(|| format!("no packet size in: {line}"))?; - packets.push(Probed { - pts: cell(f[0]), - duration: cell(f[1]), - size: size as usize, - }); - } - Ok(packets) -} - -/// ffprobe's stated extradata size for audio stream 0. -fn ffprobe_extradata_size(path: &Path) -> Result { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "stream=extradata_size", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .map_err(|e| format!("ffprobe: {e}"))?; - let text = String::from_utf8_lossy(&out.stdout); - let first = text.lines().next().unwrap_or_default().trim_matches(','); - cell(first) - .map(|n| n as usize) - .ok_or_else(|| format!("no extradata_size: {text:?}")) -} - -/// ffmpeg's concatenated audio packet payloads, copied and not decoded. -fn ffmpeg_payload(path: &Path) -> Result, String> { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"]) - .output() - .map_err(|e| format!("ffmpeg: {e}"))?; - if !out.status.success() { - return Err(format!( - "ffmpeg failed to copy the packets: {}", - String::from_utf8_lossy(&out.stderr).trim() - )); - } - Ok(out.stdout) -} - -/// Reads one file with ec-ogg and compares it with the oracle. -fn check_file(path: &Path) -> Verdict { - let file = match std::fs::File::open(path) { - Ok(f) => f, - Err(e) => return Verdict::Failed(format!("open: {e}")), - }; - let mut demuxer = match OggDemuxer::open(file) { - Ok(d) => d, - Err(e) => { - let text = e.to_string(); - if text.contains("no logical stream with a known mapping") { - return Verdict::Refused(text); - } - return Verdict::Failed(format!("open: {text}")); - } - }; - let Some(mapping) = demuxer.mapping(0) else { - return Verdict::Refused("no audio stream with a known mapping".into()); - }; - let pre_skip = match mapping { - Mapping::Opus { pre_skip, .. } => i64::from(pre_skip), - _ => 0, - }; - let streams = demuxer.streams().to_vec(); - let block: &[u8] = streams[0].params.extradata.as_ref().map_or(&[], |b| &b[..]); - let vorbis = matches!(mapping, Mapping::Vorbis { .. }); - - let mut ours = Vec::new(); - loop { - match demuxer.next_packet() { - Ok(p) if p.stream == 0 => ours.push(p), - Ok(_) => {} - Err(e) if e.is_eof() => break, - Err(e) => return Verdict::Failed(format!("demux: {e}")), - } - } - if demuxer.damaged_pages() != 0 { - return Verdict::Failed(format!("{} damaged pages", demuxer.damaged_pages())); - } - - let probed = match ffprobe_packets(path) { - Ok(p) => p, - Err(e) => return Verdict::Failed(e), - }; - let payload = match ffmpeg_payload(path) { - Ok(p) => p, - Err(e) => return Verdict::Failed(e), - }; - let header_len = match ffprobe_extradata_size(path) { - Ok(n) => n, - Err(e) => return Verdict::Failed(e), - }; - - let mut problems: Vec = Vec::new(); - if ours.len() != probed.len() { - problems.push(format!( - "packet count {} (ffprobe {})", - ours.len(), - probed.len() - )); - } - let size_bad = ours - .iter() - .zip(&probed) - .filter(|(p, q)| p.data.len() != q.size) - .count(); - if size_bad > 0 { - problems.push(format!("{size_bad} packet sizes differ")); - } - let ours_payload: Vec = ours.iter().flat_map(|p| p.data.iter().copied()).collect(); - if ours_payload != payload { - let at = ours_payload - .iter() - .zip(&payload) - .position(|(a, b)| a != b) - .unwrap_or(ours_payload.len().min(payload.len())); - problems.push(format!( - "payload differs: {} bytes vs ffmpeg {}, first difference at byte {at}", - ours_payload.len(), - payload.len() - )); - } - if vorbis { - if let Some(p) = vorbis_header_problem(block) { - problems.push(p); - } - } else if block.len() != header_len { - problems.push(format!( - "header block {} bytes (ffprobe extradata {header_len})", - block.len() - )); - } - - // Timing, checked on the pairs both sides state. - let mut pts_checked = 0usize; - let mut pts_bad = 0usize; - let mut granule_checked = 0usize; - let mut granule_bad = 0usize; - let mut first_timing: Option = None; - for (i, (p, q)) in ours.iter().zip(&probed).enumerate() { - // The Vorbis first packet's start is the convention exception (see the - // module doc): not compared. - if let Some(pts) = p.pts.filter(|_| i > 0 || !vorbis) { - pts_checked += 1; - if q.pts.map(|f| f + pre_skip) != Some(pts) { - pts_bad += 1; - first_timing.get_or_insert(format!( - "packet {i}: pts {pts}, ffmpeg pts {:?} (+{pre_skip})", - q.pts - )); - } - } - if let Some(g) = granule_of(p) { - granule_checked += 1; - let end = q.pts.zip(q.duration).map(|(a, b)| a + b); - if end != Some(g - pre_skip) { - granule_bad += 1; - first_timing.get_or_insert(format!( - "packet {i}: granule {g}, ffmpeg end {end:?} (-{pre_skip})" - )); - } - } - } - if pts_bad > 0 { - problems.push(format!("{pts_bad} of {pts_checked} pts differ")); - } - if granule_bad > 0 { - problems.push(format!( - "{granule_bad} of {granule_checked} granule ends differ" - )); - } - if let Some(t) = first_timing { - problems.push(format!("first timing difference: {t}")); - } - - let summary = format!( - "{} packets, {} bytes, {} pts and {} granules checked", - ours.len(), - payload.len(), - pts_checked, - granule_checked - ); - if problems.is_empty() { - Verdict::Match(summary) - } else { - Verdict::Failed(format!("{summary}; {}", problems.join("; "))) - } -} - -/// Our Vorbis header block: three Xiph-laced packets, identification, -/// comment and setup, each carrying its own magic. `None` when it is sound. -fn vorbis_header_problem(block: &[u8]) -> Option { - let Ok(parts) = ec_ogg::xiph_unlace(block) else { - return Some("header block is not Xiph-laced".into()); - }; - if parts.len() != 3 { - return Some(format!("{} header packets, want 3", parts.len())); - } - for (part, kind) in parts.iter().zip([1u8, 3, 5]) { - if part.len() < 7 || part[0] != kind || &part[1..7] != b"vorbis" { - return Some(format!("header packet of kind {kind} lacks its magic")); - } - } - if parts[0].len() != 30 { - return Some(format!( - "identification header is {} bytes, want 30", - parts[0].len() - )); - } - None -} - -#[test] -fn real_library_ogg_streams_match_ffmpeg() { - let path = ec_testkit::fixture("open/sintel_trailer-480p.ogv"); - match check_file(&path) { - Verdict::Match(s) => eprintln!("{}: match: {s}", path.display()), - Verdict::Refused(e) | Verdict::Failed(e) => panic!("{}: {e}", path.display()), - } -} diff --git a/crates/ec-riff/examples/benchp1.rs b/crates/ec-riff/examples/benchp1.rs deleted file mode 100644 index f36be891..00000000 --- a/crates/ec-riff/examples/benchp1.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! benchp1: RIFF/WAVE read and write throughput for lanes/bench.md ("lane benchp1"). -//! -//! usage: -//! benchp1 read [reps] -//! Opens the file and decodes every sample to i32 with `WavReader::read_all_i32`, `reps` -//! times (default 5), keeping the best wall time. -//! benchp1 write [reps] -//! Reads the samples once (untimed), then writes them back with `WavWriter` at the same -//! spec, `reps` times (default 5), keeping the best wall time. `riff` takes the default -//! header; `rf64` forces the RF64 header (rf64_threshold 0). The last output is kept at -//! for the md5 round-trip check. -use std::hint::black_box; -use std::time::Instant; - -use ec_riff::{RF64_THRESHOLD, WavOptions, WavReader, WavWriter}; - -fn read_once(path: &str) -> (usize, f64) { - let t = Instant::now(); - let mut reader = WavReader::open(path).expect("open wav"); - let samples = reader.read_all_i32().expect("read samples"); - let secs = t.elapsed().as_secs_f64(); - black_box(&samples); - (samples.len(), secs) -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("read") => { - let reps: usize = args.get(3).map_or(5, |s| s.parse().expect("reps")); - let bytes = std::fs::metadata(&args[2]).expect("stat").len(); - let (samples, _) = read_once(&args[2]); - let best = (0..reps).map(|_| read_once(&args[2]).1).fold(f64::MAX, f64::min); - println!( - "samples={samples} bytes={bytes} best_read_s={best:.4} mb_s={:.2} reps={reps}", - bytes as f64 / best / 1e6 - ); - } - Some("write") => { - let (input, out, mode) = (&args[2], &args[3], args[4].as_str()); - let reps: usize = args.get(5).map_or(5, |s| s.parse().expect("reps")); - let mut reader = WavReader::open(input).expect("open wav"); - let spec = reader.spec(); - let samples = reader.read_all_i32().expect("read samples"); - let frames = samples.len() as u64 / u64::from(spec.channels); - let options = match mode { - "riff" => WavOptions { expected_frames: frames, rf64_threshold: RF64_THRESHOLD }, - "rf64" => WavOptions { expected_frames: frames, rf64_threshold: 0 }, - _ => panic!("mode must be riff or rf64"), - }; - let data_bytes = samples.len() as u64 * u64::from(spec.bits_per_sample) / 8; - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - let mut w = WavWriter::create_with_options(out, spec, options).expect("create"); - w.write_samples(&samples).expect("write samples"); - w.finalize().expect("finalize"); - best = best.min(t.elapsed().as_secs_f64()); - } - println!( - "mode={mode} samples={} data_bytes={data_bytes} best_write_s={best:.4} mb_s={:.2} reps={reps}", - samples.len(), - data_bytes as f64 / best / 1e6 - ); - } - _ => panic!("usage: benchp1 read [reps] | write [reps]"), - } -} diff --git a/crates/ec-riff/tests/it/rf64.rs b/crates/ec-riff/tests/it/rf64.rs index 98497550..77417e05 100644 --- a/crates/ec-riff/tests/it/rf64.rs +++ b/crates/ec-riff/tests/it/rf64.rs @@ -22,10 +22,6 @@ fn le64(bytes: &[u8], at: usize) -> u64 { u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()) } -fn le32(bytes: &[u8], at: usize) -> u32 { - u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) -} - /// Write `frames` frames of a ramp and return the finished file. fn write_file(s: WavSpec, frames: usize, options: WavOptions) -> Vec { let mut w = WavWriter::with_options(Cursor::new(Vec::new()), s, options).unwrap(); @@ -44,42 +40,6 @@ fn opts(frames: u64, threshold: u64) -> WavOptions { } } -#[test] -fn over_threshold_writes_rf64_with_exact_ds64_sizes() { - let s = spec(2, 16); - let frames = 1000; - let bytes = write_file(s, frames, opts(frames as u64, 64)); - - assert_eq!(&bytes[0..4], b"RF64"); - assert_eq!(le32(&bytes, 4), u32::MAX, "RIFF size is ds64's to hold"); - assert_eq!(&bytes[8..12], b"WAVE"); - assert_eq!(&bytes[12..16], b"ds64"); - assert_eq!(le32(&bytes, 16), 28, "ds64 body without a table"); - - let data_bytes = (frames * 4) as u64; - assert_eq!(le64(&bytes, 20), bytes.len() as u64 - 8, "riffSize"); - assert_eq!(le64(&bytes, 28), data_bytes, "dataSize"); - assert_eq!(le64(&bytes, 36), frames as u64, "sampleCount"); - assert_eq!(le32(&bytes, 44), 0, "tableLength"); - - // Stereo 16-bit is a plain PCM fmt with no fact chunk, then data with the sentinel. - let fmt = 48; - assert_eq!(&bytes[fmt..fmt + 4], b"fmt "); - // The `data` id sits right before its payload, at a fixed distance from the end. - let data = bytes.len() - 8 - data_bytes as usize; - assert_eq!(&bytes[data..data + 4], b"data"); - assert_eq!( - le32(&bytes, data + 4), - u32::MAX, - "data size is ds64's to hold" - ); - - let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap(); - assert_eq!(r.spec(), s); - assert_eq!(r.duration(), Some(frames as u64)); - assert_eq!(r.read_all_i32().unwrap().len(), frames * 2); -} - #[test] fn rf64_samples_match_the_riff_file_for_the_same_input() { for (channels, bits) in [(1u16, 8u16), (6, 24), (2, 16), (8, 32)] { @@ -101,52 +61,6 @@ fn rf64_samples_match_the_riff_file_for_the_same_input() { } } -#[test] -fn odd_rf64_data_gets_a_pad_byte_outside_its_size() { - let s = spec(1, 8); - let frames = 5; - let bytes = write_file(s, frames, opts(frames as u64, 1)); - // 5 data bytes: one pad byte follows, counted by riffSize but not dataSize. - assert_eq!(bytes.len() % 2, 0); - assert_eq!(le64(&bytes, 20), bytes.len() as u64 - 8); - assert_eq!(le64(&bytes, 28), 5); - let r = WavReader::new(Cursor::new(&bytes[..])).unwrap(); - assert_eq!(r.duration(), Some(5)); -} - -#[test] -fn extensible_rf64_keeps_fact_and_its_saturating_count() { - let s = spec(6, 24); - let frames = 50; - let bytes = write_file(s, frames, opts(frames as u64, 1)); - assert_eq!(&bytes[0..4], b"RF64"); - // Extensible fmt is 40 bytes, so `fact` follows it at 48 + 8 + 40. - let fact = 48 + 8 + 40; - assert_eq!(&bytes[fact..fact + 4], b"fact"); - assert_eq!(le32(&bytes, fact + 8), frames as u32); - let r = WavReader::new(Cursor::new(&bytes[..])).unwrap(); - assert_eq!(r.spec(), s); - assert_eq!(r.duration(), Some(frames as u64)); -} - -#[test] -fn under_threshold_stays_riff_byte_for_byte() { - let s = spec(2, 16); - let riff = write_file(s, 100, WavOptions::default()); - let below = write_file(s, 100, opts(100, 400 + 1)); - assert_eq!(riff, below); - assert_eq!(&riff[0..4], b"RIFF"); - assert_eq!(le32(&riff, 4) as usize, riff.len() - 8); -} - -#[test] -fn unknown_length_is_riff_and_oversize_riff_is_refused() { - let s = spec(2, 16); - let bytes = write_file(s, 10, WavOptions::default()); - assert_eq!(&bytes[0..4], b"RIFF"); - assert_eq!(le32(&bytes, 4) as usize, bytes.len() - 8); -} - /// Manual: writes 4.1 GiB of 16-bit stereo and reads its header back. Run with /// `cargo test -p ec-riff --test it rf64:: -- --ignored --nocapture`. #[test]