forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u18' into simplify/w1b

Browse files at this commit

1b43190b72fe64d0c3e8036e44032e1134e357c5Ahmet Kaan GümüşParent: 756d8d68cbf736
crates/ec-matroska/examples/bench.rsdeleted+0 -87
@@ -1,87 +0,0 @@
1-//! bench: Matroska demux throughput for lanes/bench.md ("lane benchrest").
2-//!
3-//! usage:
4-//! bench demux <in.mkv> <out_prefix> [reps]
5-//!
6-//! `demux` opens the file with `MatroskaDemuxer` and reads every packet of every track, `reps`
7-//! times (default 5), and keeps the best wall time. It prints packets per second and payload MB/s.
8-//! After timing, one untimed pass writes each track's packet payloads, concatenated in order, to
9-//! `<out_prefix>.s<N>.bin` so the bytes can be compared with ffmpeg's `-c copy -f data` output.
10-use std::fs::File;
11-use std::hint::black_box;
12-use std::io::BufReader;
13-use std::time::Instant;
14-
15-use ec_core::{Demuxer, Packet, StreamInfo};
16-use ec_matroska::MatroskaDemuxer;
17-
18-/// Read every packet of the file once, in file order.
19-fn read_all(path: &str) -> (Vec<StreamInfo>, Vec<Packet>) {
20- let mut demux =
21- MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv");
22- let streams = demux.streams().to_vec();
23- let mut packets = Vec::new();
24- loop {
25- match demux.next_packet() {
26- Ok(p) => packets.push(p),
27- Err(e) if e.is_eof() => break,
28- Err(e) => panic!("demux: {e}"),
29- }
30- }
31- (streams, packets)
32-}
33-
34-/// One timed demux pass: sums the payload bytes so the work cannot be skipped.
35-fn demux_pass(path: &str) -> (usize, u64) {
36- let mut demux =
37- MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv");
38- let (mut n, mut bytes) = (0usize, 0u64);
39- loop {
40- match demux.next_packet() {
41- Ok(p) => {
42- n += 1;
43- bytes += p.data.len() as u64;
44- black_box(&p.data);
45- }
46- Err(e) if e.is_eof() => break,
47- Err(e) => panic!("demux: {e}"),
48- }
49- }
50- (n, bytes)
51-}
52-
53-fn main() {
54- let args: Vec<String> = std::env::args().collect();
55- match args.get(1).map(String::as_str) {
56- Some("demux") if args.len() >= 4 => {
57- let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps"));
58- assert!(reps >= 1, "reps must be at least 1");
59- let file_bytes = std::fs::metadata(&args[2]).expect("stat").len();
60- let (mut packets, mut bytes) = (0usize, 0u64);
61- let mut best = f64::MAX;
62- for _ in 0..reps {
63- let t = Instant::now();
64- (packets, bytes) = demux_pass(black_box(&args[2]));
65- best = best.min(t.elapsed().as_secs_f64());
66- }
67- // Untimed: per-track payload dumps for the ffmpeg byte comparison.
68- let (streams, all) = read_all(&args[2]);
69- for s in &streams {
70- let mut dump = Vec::new();
71- for p in all.iter().filter(|p| p.stream == s.index) {
72- dump.extend_from_slice(&p.data);
73- }
74- std::fs::write(format!("{}.s{}.bin", args[3], s.index), &dump).expect("write dump");
75- }
76- println!(
77- "packets={packets} payload_bytes={bytes} file_bytes={file_bytes} best_demux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}",
78- packets as f64 / best,
79- bytes as f64 / best / 1e6
80- );
81- }
82- _ => {
83- eprintln!("usage: bench demux <in.mkv> <out_prefix> [reps]");
84- std::process::exit(2);
85- }
86- }
87-}
crates/ec-mp4/examples/bench.rsdeleted+0 -119
@@ -1,119 +0,0 @@
1-//! bench: MP4 demux and mux throughput for lanes/bench.md ("lane benchaudio").
2-//!
3-//! usage:
4-//! bench demux <in.mp4> <out_prefix> [reps]
5-//! bench mux <in.mp4> <out.mp4> [reps]
6-//!
7-//! `demux` opens the file with `Mp4Demuxer` and reads every packet of every track, `reps` times
8-//! (default 5), and keeps the best wall time. It prints packets per second and payload MB/s. After
9-//! timing, one untimed pass writes each track's packet payloads, concatenated in order, to
10-//! `<out_prefix>.s<N>.bin` so the bytes can be compared with ffmpeg's `-c copy -f data` output.
11-//! `mux` demuxes the input once (untimed), then times writing all packets into a new MP4 with
12-//! `Mp4Muxer`, best of `reps`; the last output is kept at `out.mp4`.
13-use std::fs::File;
14-use std::hint::black_box;
15-use std::io::BufReader;
16-use std::time::Instant;
17-
18-use ec_core::{Demuxer, Muxer, Packet, StreamInfo};
19-use ec_mp4::{Mp4Demuxer, Mp4Muxer};
20-
21-/// Read every packet of the file once, in file order.
22-fn read_all(path: &str) -> (Vec<StreamInfo>, Vec<Packet>) {
23- let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4");
24- let streams = demux.streams().to_vec();
25- let mut packets = Vec::new();
26- loop {
27- match demux.next_packet() {
28- Ok(p) => packets.push(p),
29- Err(e) if e.is_eof() => break,
30- Err(e) => panic!("demux: {e}"),
31- }
32- }
33- (streams, packets)
34-}
35-
36-/// One timed demux pass: sums the payload bytes so the work cannot be skipped.
37-fn demux_pass(path: &str) -> (usize, u64) {
38- let mut demux = Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4");
39- let (mut n, mut bytes) = (0usize, 0u64);
40- loop {
41- match demux.next_packet() {
42- Ok(p) => {
43- n += 1;
44- bytes += p.data.len() as u64;
45- black_box(&p.data);
46- }
47- Err(e) if e.is_eof() => break,
48- Err(e) => panic!("demux: {e}"),
49- }
50- }
51- (n, bytes)
52-}
53-
54-/// One timed mux pass into `out`.
55-fn mux_pass(out: &str, streams: &[StreamInfo], packets: &[Packet]) {
56- let file = File::create(out).expect("create");
57- let mut mux = Mp4Muxer::new(file).expect("muxer");
58- for s in streams {
59- mux.add_stream(s.clone()).expect("add stream");
60- }
61- for p in packets {
62- mux.write_packet(p).expect("write packet");
63- }
64- mux.finish().expect("finish");
65-}
66-
67-fn main() {
68- let args: Vec<String> = std::env::args().collect();
69- match args.get(1).map(String::as_str) {
70- Some("demux") if args.len() >= 4 => {
71- let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps"));
72- let file_bytes = std::fs::metadata(&args[2]).expect("stat").len();
73- let (mut packets, mut bytes) = (0usize, 0u64);
74- let mut best = f64::MAX;
75- for _ in 0..reps {
76- let t = Instant::now();
77- (packets, bytes) = demux_pass(black_box(&args[2]));
78- best = best.min(t.elapsed().as_secs_f64());
79- }
80- // Untimed: per-track payload dumps for the ffmpeg byte comparison.
81- let (streams, all) = read_all(&args[2]);
82- for s in &streams {
83- let mut dump = Vec::new();
84- for p in all.iter().filter(|p| p.stream == s.index) {
85- dump.extend_from_slice(&p.data);
86- }
87- std::fs::write(format!("{}.s{}.bin", args[3], s.index), &dump).expect("write dump");
88- }
89- println!(
90- "packets={packets} payload_bytes={bytes} file_bytes={file_bytes} best_demux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}",
91- packets as f64 / best,
92- bytes as f64 / best / 1e6
93- );
94- }
95- Some("mux") if args.len() >= 4 => {
96- let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps"));
97- let (streams, packets) = read_all(&args[2]);
98- let bytes: u64 = packets.iter().map(|p| p.data.len() as u64).sum();
99- let mut best = f64::MAX;
100- for _ in 0..reps {
101- let t = Instant::now();
102- mux_pass(black_box(&args[3]), &streams, &packets);
103- best = best.min(t.elapsed().as_secs_f64());
104- }
105- println!(
106- "packets={} payload_bytes={bytes} best_mux_s={best:.4} packets_per_s={:.0} mb_per_s={:.2} reps={reps}",
107- packets.len(),
108- packets.len() as f64 / best,
109- bytes as f64 / best / 1e6
110- );
111- }
112- _ => {
113- eprintln!(
114- "usage: bench demux <in.mp4> <out_prefix> [reps]\n bench mux <in.mp4> <out.mp4> [reps]"
115- );
116- std::process::exit(2);
117- }
118- }
119-}
crates/ec-mp4/src/config.rsmodified+0 -50
@@ -1,45 +1,10 @@
1 //! Turns encoder output (Annex-B) into mp4 samples and sample-entry config records.1 //! Turns encoder output (Annex-B) into mp4 samples and sample-entry config records.
2 2
3-const NAL_IDR: u8 = 5;
4-const NAL_SEI: u8 = 6;
5-const NAL_SPS: u8 = 7;
6-const NAL_PPS: u8 = 8;
7-const NAL_AUD: u8 = 9;
8-
9 const HEVC_VPS: u8 = 32;3 const HEVC_VPS: u8 = 32;
10 const HEVC_SPS: u8 = 33;4 const HEVC_SPS: u8 = 33;
11 const HEVC_PPS: u8 = 34;5 const HEVC_PPS: u8 = 34;
12 const HEVC_AUD: u8 = 35;6 const HEVC_AUD: u8 = 35;
13 7
14-const AV1C_HEAD: [u8; 4] = [0x81, 0x1F, 0x0C, 0x00];
15-
16-/// An H.264 sample, whether it is an IDR, and its first SPS and PPS when present.
17-pub type H264Split = (Vec<u8>, bool, Option<(Vec<u8>, Vec<u8>)>);
18-
19-/// Splits an H.264 Annex-B access unit into a length-prefixed sample.
20-///
21-/// SPS, PPS, AUD and SEI are stripped from the sample. `None` when the unit holds no coded slice.
22-pub fn h264_split_annex_b(annex_b: &[u8]) -> Option<H264Split> {
23- let nals = split_annex_b(annex_b);
24- let first = |kind: u8| nals.iter().copied().find(|n| nal_type(n) == kind);
25- let params = match (first(NAL_SPS), first(NAL_PPS)) {
26- (Some(sps), Some(pps)) => Some((sps.to_vec(), pps.to_vec())),
27- _ => None,
28- };
29- let mut out = Vec::with_capacity(annex_b.len());
30- let mut is_idr = false;
31- for nal in nals {
32- match nal_type(nal) {
33- NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue,
34- NAL_IDR => is_idr = true,
35- _ => {}
36- }
37- out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
38- out.extend_from_slice(nal);
39- }
40- (!out.is_empty()).then_some((out, is_idr, params))
41-}
42-
43 /// An H.264 `AVCDecoderConfigurationRecord` for one SPS and one PPS, with four-byte NAL length prefixes.8 /// An H.264 `AVCDecoderConfigurationRecord` for one SPS and one PPS, with four-byte NAL length prefixes.
44 pub fn avcc_record(sps: &[u8], pps: &[u8]) -> Vec<u8> {9 pub fn avcc_record(sps: &[u8], pps: &[u8]) -> Vec<u8> {
45 let profile = sps.get(1..4).unwrap_or(&[0, 0, 0]);10 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<Vec<u8>> {
112 (!out.is_empty()).then_some(out)77 (!out.is_empty()).then_some(out)
113 }78 }
114 79
115-/// An `av1C` record: the four fixed bytes, then the sequence header OBU as the config OBUs.
116-pub fn av1c_record(ten_bit: bool, config_obus: &[u8]) -> Vec<u8> {
117- let mut head = AV1C_HEAD;
118- if ten_bit {
119- head[2] |= 0x40;
120- }
121- let mut out = head.to_vec();
122- out.extend_from_slice(config_obus);
123- out
124-}
125-
126 fn hevc_nal_type(nal: &[u8]) -> u8 {80 fn hevc_nal_type(nal: &[u8]) -> u8 {
127 nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F)81 nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F)
128 }82 }
@@ -165,7 +119,3 @@ fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) {
165 nals.push(&nal[..end]);119 nals.push(&nal[..end]);
166 }120 }
167 }121 }
168-
169-fn nal_type(nal: &[u8]) -> u8 {
170- nal.first().map_or(0, |b| b & 0x1F)
171-}
crates/ec-mp4/src/demux.rsmodified+6 -6
@@ -960,7 +960,7 @@ impl<'a> SampleTable<'a> {
960 }960 }
961 b"stsc" => {961 b"stsc" => {
962 let (_, _, rest) = full(payload)?;962 let (_, _, rest) = full(payload)?;
963- let count = count_of(rest, 12, file_len)?;963+ let count = count_of(rest, 12)?;
964 me.stsc = Vec::with_capacity(count);964 me.stsc = Vec::with_capacity(count);
965 for i in 0..count {965 for i in 0..count {
966 me.stsc966 me.stsc
@@ -987,7 +987,7 @@ impl<'a> SampleTable<'a> {
987 }987 }
988 b"co64" => {988 b"co64" => {
989 let (_, _, rest) = full(payload)?;989 let (_, _, rest) = full(payload)?;
990- let count = count_of(rest, 8, file_len)?;990+ let count = count_of(rest, 8)?;
991 me.chunks = Vec::with_capacity(count);991 me.chunks = Vec::with_capacity(count);
992 for i in 0..count {992 for i in 0..count {
993 me.chunks.push(be64(rest, 4 + i * 8)?);993 me.chunks.push(be64(rest, 4 + i * 8)?);
@@ -1731,7 +1731,7 @@ fn unpack_language(packed: u16) -> Option<String> {
1731 /// The `(count, value)` pairs of an `stts`/`ctts` table.1731 /// The `(count, value)` pairs of an `stts`/`ctts` table.
1732 fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {1732 fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {
1733 let (_, _, rest) = full(payload)?;1733 let (_, _, rest) = full(payload)?;
1734- let count = count_of(rest, 8, u64::MAX)?;1734+ let count = count_of(rest, 8)?;
1735 let mut out = Vec::with_capacity(count);1735 let mut out = Vec::with_capacity(count);
1736 for i in 0..count {1736 for i in 0..count {
1737 out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?));1737 out.push(make(be32(rest, 4 + i * 8)?, be32(rest, 8 + i * 8)?));
@@ -1741,7 +1741,7 @@ fn pairs<T>(payload: &[u8], make: impl Fn(u32, u32) -> T) -> Result<Vec<T>> {
1741 1741
1742 /// The `u32` table of an `stss`/`stco`.1742 /// The `u32` table of an `stss`/`stco`.
1743 fn words(rest: &[u8]) -> Result<Vec<u32>> {1743 fn words(rest: &[u8]) -> Result<Vec<u32>> {
1744- let count = count_of(rest, 4, u64::MAX)?;1744+ let count = count_of(rest, 4)?;
1745 let mut out = Vec::with_capacity(count);1745 let mut out = Vec::with_capacity(count);
1746 for i in 0..count {1746 for i in 0..count {
1747 out.push(be32(rest, 4 + i * 4)?);1747 out.push(be32(rest, 4 + i * 4)?);
@@ -1751,7 +1751,7 @@ fn words(rest: &[u8]) -> Result<Vec<u32>> {
1751 1751
1752 /// An entry count, refused when the entries it claims do not fit the box it is1752 /// An entry count, refused when the entries it claims do not fit the box it is
1753 /// in — the one check that keeps a crafted count from being allocated.1753 /// in — the one check that keeps a crafted count from being allocated.
1754-fn count_of(rest: &[u8], width: usize, _file_len: u64) -> Result<usize> {1754+fn count_of(rest: &[u8], width: usize) -> Result<usize> {
1755 let count = be32(rest, 0)? as usize;1755 let count = be32(rest, 0)? as usize;
1756 let have = rest.len().saturating_sub(4) / width;1756 let have = rest.len().saturating_sub(4) / width;
1757 if count > have {1757 if count > have {
@@ -1798,7 +1798,7 @@ fn display_rotation(a: i32, b: i32, c: i32, d: i32) -> Rotation {
1798 fn elst(payload: &[u8]) -> Result<Vec<(u64, i64, u32)>> {1798 fn elst(payload: &[u8]) -> Result<Vec<(u64, i64, u32)>> {
1799 let (version, _, rest) = full(payload)?;1799 let (version, _, rest) = full(payload)?;
1800 let width = if version == 0 { 12 } else { 20 };1800 let width = if version == 0 { 12 } else { 20 };
1801- let count = count_of(rest, width, u64::MAX)?;1801+ let count = count_of(rest, width)?;
1802 let mut out = Vec::with_capacity(count);1802 let mut out = Vec::with_capacity(count);
1803 for i in 0..count {1803 for i in 0..count {
1804 let at = 4 + i * width;1804 let at = 4 + i * width;
crates/ec-mp4/tests/it/edith_parity.rsdeleted+0 -402
@@ -1,402 +0,0 @@
1-//! Parity with ffprobe, file by file: what ec-mp4 reads out of an mp4 or mov has
2-//! to be what ffprobe reads out of the same bytes, sample for sample and field
3-//! for field. This is the swap criterion for edith's `mp4::` demuxer: identical
4-//! packet bytes, identical timestamps, identical stream metadata.
5-//!
6-//!
7-//! Per track, the comparison is: codec, coded size, sample rate, channels,
8-//! timebase, rotation, and per sample the byte offset, size, presentation time
9-//! (`cts` against ffprobe `pts`), the sync flag, and the decode time up to one
10-//! constant. ffmpeg's `dts` carries a constant shift of its own (the largest
11-//! composition delay), so only its differences are the same claim. Edit lists
12-//! are applied on both sides, the same way ffmpeg applies them.
13-//!
14-//! Where edith's engine reads the file differently on purpose (it trims the
15-//! picture by the edit list where ffprobe shifts it, and ignores empty edits),
16-//! the edith-only values are printed in the table, not compared. See
17-//! `lanes/mp4demux.report.md`.
18-
19-use std::collections::HashMap;
20-use std::fs::File;
21-use std::io::BufReader;
22-use std::path::{Path, PathBuf};
23-
24-use ec_core::{CodecId, Demuxer, MediaParameters};
25-use ec_mp4::{Mp4Demuxer, Sample};
26-
27-use crate::common::ffmpeg_name;
28-
29-/// One ffprobe `key=value` record block, keyed by field name.
30-type Record = HashMap<String, String>;
31-
32-/// Every `stream=`/`packet=` block of `default=nw=1` output, split where the
33-/// `first` key starts a new block.
34-fn records(text: &str, first: &str) -> Vec<Record> {
35- let mut out: Vec<Record> = Vec::new();
36- for line in text.lines() {
37- let Some((key, value)) = line.split_once('=') else {
38- continue;
39- };
40- if key == first {
41- out.push(Record::new());
42- }
43- if let Some(record) = out.last_mut() {
44- record.insert(key.to_string(), value.to_string());
45- }
46- }
47- out
48-}
49-
50-fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec<Record> {
51- let out = ec_testkit::ffprobe()
52- .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"])
53- .arg(path)
54- .output()
55- .expect("ffprobe runs");
56- assert!(
57- out.status.success(),
58- "ffprobe refused {}: {}",
59- path.display(),
60- String::from_utf8_lossy(&out.stderr)
61- );
62- records(&String::from_utf8_lossy(&out.stdout), first)
63-}
64-
65-/// What ffprobe says about one stream, `None` where a field is `N/A` or absent.
66-#[derive(Debug, Default)]
67-struct ProbeStream {
68- codec: String,
69- width: Option<u32>,
70- height: Option<u32>,
71- sample_rate: Option<u32>,
72- channels: Option<u32>,
73- time_base: String,
74- duration_ts: Option<i64>,
75- rotation: Option<i32>,
76- attached_pic: bool,
77-}
78-
79-#[derive(Debug, Clone, Copy)]
80-struct ProbePacket {
81- pts: Option<i64>,
82- dts: Option<i64>,
83- size: u64,
84- pos: Option<u64>,
85- key: bool,
86-}
87-
88-fn number<T: std::str::FromStr>(value: Option<&String>) -> Option<T> {
89- value.and_then(|v| v.parse().ok())
90-}
91-
92-fn probe_streams(path: &Path, rotations: &HashMap<u32, i32>) -> Vec<ProbeStream> {
93- ffprobe(
94- path,
95- "stream=index,codec_name,codec_type,width,height,sample_rate,channels,time_base,duration_ts:stream_disposition=attached_pic",
96- "index",
97- )
98- .into_iter()
99- .map(|r| {
100- let index = number::<u32>(r.get("index")).unwrap_or(u32::MAX);
101- ProbeStream {
102- codec: r.get("codec_name").cloned().unwrap_or_default(),
103- width: number(r.get("width")),
104- height: number(r.get("height")),
105- sample_rate: number(r.get("sample_rate")),
106- channels: number(r.get("channels")),
107- time_base: r.get("time_base").cloned().unwrap_or_default(),
108- duration_ts: number(r.get("duration_ts")),
109- rotation: rotations.get(&index).copied(),
110- attached_pic: r
111- .get("DISPOSITION:attached_pic")
112- .is_some_and(|v| v == "1"),
113- }
114- })
115- .collect()
116-}
117-
118-/// Display rotation per stream index, from the `side_data_list` of the JSON
119-/// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film
120-/// ffprobe spends minutes decoding for it, while the JSON dump is immediate.
121-fn rotations(path: &Path) -> HashMap<u32, i32> {
122- let out = ec_testkit::ffprobe()
123- .args(["-v", "error", "-show_streams", "-of", "json"])
124- .arg(path)
125- .output()
126- .expect("ffprobe runs");
127- let mut found = HashMap::new();
128- let mut current = None;
129- for line in String::from_utf8_lossy(&out.stdout).lines() {
130- let line = line.trim();
131- // Stream objects open with `"index": n,` at the stream's own indent.
132- if let Some(rest) = line.strip_prefix("\"index\": ") {
133- current = rest.trim_end_matches(',').parse::<u32>().ok();
134- } else if let Some(rest) = line.strip_prefix("\"rotation\": ")
135- && let (Some(index), Ok(r)) = (current, rest.trim_end_matches(',').parse::<i32>())
136- {
137- found.insert(index, r);
138- }
139- }
140- found
141-}
142-
143-/// Packets per ffprobe stream index, each list in the order ffprobe demuxes
144-/// them, which for one stream is decode order.
145-fn probe_packets(path: &Path) -> HashMap<u32, Vec<ProbePacket>> {
146- let mut by_stream: HashMap<u32, Vec<ProbePacket>> = HashMap::new();
147- for r in ffprobe(
148- path,
149- "packet=stream_index,pts,dts,size,pos,flags",
150- "stream_index",
151- ) {
152- let Some(index) = number::<u32>(r.get("stream_index")) else {
153- continue;
154- };
155- by_stream.entry(index).or_default().push(ProbePacket {
156- pts: number(r.get("pts")),
157- dts: number(r.get("dts")),
158- size: number(r.get("size")).unwrap_or(0),
159- pos: number(r.get("pos")),
160- key: r.get("flags").is_some_and(|f| f.starts_with('K')),
161- });
162- }
163- by_stream
164-}
165-
166-/// ffprobe's rotation (counter-clockwise degrees) as this crate's clockwise
167-/// quarter turn: the same matrix, the other direction.
168-fn expected_rotation(rotation: Option<i32>) -> Option<u8> {
169- match rotation {
170- None => Some(0),
171- Some(r) if r % 90 == 0 => Some((-r / 90).rem_euclid(4) as u8),
172- Some(_) => None,
173- }
174-}
175-
176-/// One file, compared. Returns the table row and every mismatch it found.
177-fn compare(path: &Path) -> (String, Vec<String>) {
178- let mut problems = Vec::new();
179- let file = File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
180- let demuxer = Mp4Demuxer::new(BufReader::new(file))
181- .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
182- let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
183- // Cover art is not a track: ffprobe lists an `covr` picture as a video stream
184- // with `attached_pic` set, and this crate does not list it (a player that
185- // shows an album cover as a video stream is the bug). Dropped on both sides.
186- let rotations = rotations(path);
187- let all_probed = probe_streams(path, &rotations);
188- let probed: Vec<ProbeStream> = all_probed.into_iter().filter(|p| !p.attached_pic).collect();
189- let packets = probe_packets(path);
190- let tracks = demuxer.tracks().to_vec();
191- if probed.len() != tracks.len() {
192- // The track position is the only index the two share, so the counts agree
193- // or the rest of the comparison is meaningless.
194- problems.push(format!("track count: ec {} ffprobe {}", tracks.len(), probed.len()));
195- }
196- let mut rows = Vec::new();
197- for (position, track) in tracks.iter().enumerate() {
198- let Some(stream) = track.stream else {
199- continue;
200- };
201- let Some(p) = probed.get(position) else {
202- problems.push(format!("track {position}: no ffprobe stream"));
203- continue;
204- };
205- let info = demuxer.streams()[stream as usize].clone();
206- let samples: Vec<Sample> = demuxer.samples(stream).to_vec();
207- let tag = format!("track {position} ({})", ffmpeg_name(info.params.codec));
208- if ffmpeg_name(info.params.codec) != p.codec {
209- problems.push(format!("{tag}: codec, ffprobe says {}", p.codec));
210- }
211- let tb = format!("{}/{}", info.time_base.num(), info.time_base.den());
212- if tb != p.time_base {
213- problems.push(format!("{tag}: timebase {tb} vs {}", p.time_base));
214- }
215- match &info.params.media {
216- MediaParameters::Video(v) => {
217- if Some((v.width, v.height)) != p.width.zip(p.height) {
218- problems.push(format!(
219- "{tag}: coded size {}x{} vs ffprobe {:?}x{:?}",
220- v.width, v.height, p.width, p.height
221- ));
222- }
223- // Both sides name the same matrix; ffprobe counts counter-clockwise.
224- if info.rotation.steps() != expected_rotation(p.rotation) {
225- problems.push(format!(
226- "{tag}: rotation {:?} vs ffprobe {:?}",
227- info.rotation, p.rotation
228- ));
229- }
230- }
231- MediaParameters::Audio(a) => {
232- // Implicit HE-AAC (SBR with no extension frequency in the config):
233- // ffprobe decodes the first frames for the doubled output rate,
234- // and so does edith (`mp4_aac_prime`); this reader reports the core's.
235- let implicit_sbr = info.params.codec == CodecId::Aac
236- && p.sample_rate == Some(a.sample_rate * 2);
237- if Some(a.sample_rate) != p.sample_rate && !implicit_sbr {
238- problems.push(format!("{tag}: rate {} vs {:?}", a.sample_rate, p.sample_rate));
239- }
240- if Some(a.layout.channel_count() as u32) != p.channels {
241- problems.push(format!(
242- "{tag}: channels {} vs {:?}",
243- a.layout.channel_count(),
244- p.channels
245- ));
246- }
247- }
248- MediaParameters::Subtitle => {}
249- }
250- // Per sample, against ffprobe's packets of the same stream.
251- let theirs = packets.get(&(position as u32)).cloned().unwrap_or_default();
252- // A subtitle track ends in a zero-duration sample at the movie's end, an
253- // end marker ffprobe does not hand out as a packet. Dropped on this side
254- // for the comparison only; the sample is still in the table.
255- let mut samples = samples;
256- if matches!(info.params.media, MediaParameters::Subtitle)
257- && samples.len() == theirs.len() + 1
258- && samples.last().is_some_and(|s| s.duration == 0)
259- {
260- samples.pop();
261- }
262- if theirs.len() != samples.len() {
263- problems.push(format!(
264- "{tag}: {} samples vs {} packets",
265- samples.len(),
266- theirs.len()
267- ));
268- }
269- // VP8 and VP9 carry no `stss` in these files, so the box makes every
270- // sample a sync sample, while ffprobe reads the key flag out of the
271- // bitstream. The box is what edith follows; the flag difference is named.
272- let box_says_all_sync = samples.iter().all(|s| s.sync);
273- let bitstream_keys = theirs.iter().filter(|p| p.key).count();
274- let vp_box_only = matches!(info.params.codec, CodecId::Vp8 | CodecId::Vp9)
275- && box_says_all_sync
276- && bitstream_keys < samples.len();
277- let mut dts_shift: Option<i64> = None;
278- let (mut bad_pos, mut bad_size, mut bad_pts, mut bad_sync, mut bad_dts) = (0, 0, 0, 0, 0);
279- for (ours, theirs) in samples.iter().zip(&theirs) {
280- if theirs.pos != Some(ours.offset) {
281- bad_pos += 1;
282- }
283- if u64::from(ours.size) != theirs.size {
284- bad_size += 1;
285- }
286- if theirs.pts != Some(ours.cts) {
287- bad_pts += 1;
288- }
289- if theirs.key != ours.sync && !vp_box_only {
290- bad_sync += 1;
291- }
292- match (theirs.dts, dts_shift) {
293- (Some(d), None) => dts_shift = Some(ours.dts - d),
294- (Some(d), Some(k)) if ours.dts - d != k => bad_dts += 1,
295- (None, _) => bad_dts += 1,
296- _ => {}
297- }
298- }
299- for (what, n) in [
300- ("offset", bad_pos),
301- ("size", bad_size),
302- ("pts", bad_pts),
303- ("sync", bad_sync),
304- ("dts", bad_dts),
305- ] {
306- if n > 0 {
307- problems.push(format!("{tag}: {n} samples differ in {what}"));
308- }
309- }
310- let syncs = demuxer.sync_in_display_order(stream).len();
311- rows.push(format!(
312- " t{position} {:<7} n={:<6} trim={:<8} first={:<6} dts-shift={:<6} edits={:?} display-syncs={syncs} duration_ts={:?}/{:?}",
313- ffmpeg_name(info.params.codec),
314- samples.len(),
315- format!("{:?}", demuxer.presentation_trim(stream)),
316- demuxer.first_frame_sample(stream),
317- dts_shift.map_or("-".into(), |k| k.to_string()),
318- track.edits.iter().map(|e| (e.segment_duration, e.media_time)).collect::<Vec<_>>(),
319- p.duration_ts,
320- info.duration,
321- ));
322- }
323- let row = format!("{name}\n{}", rows.join("\n"));
324- (row, problems)
325-}
326-
327-/// Every mp4-family file under `dir`, recursively, into `files`.
328-fn collect(dir: &Path, files: &mut Vec<PathBuf>) {
329- let Ok(entries) = std::fs::read_dir(dir) else {
330- return;
331- };
332- for entry in entries.flatten() {
333- let path = entry.path();
334- if path.is_dir() {
335- collect(&path, files);
336- continue;
337- }
338- let name = path.to_string_lossy().to_ascii_lowercase();
339- if [".mp4", ".m4a", ".m4v", ".mov"].iter().any(|ext| name.ends_with(ext)) {
340- files.push(path);
341- }
342- }
343-}
344-
345-fn corpus() -> Vec<PathBuf> {
346- let mut files = Vec::new();
347- collect(&ec_testkit::root().join("mp4corpus"), &mut files);
348- files.sort();
349- files.dedup();
350- files
351-}
352-
353-#[test]
354-fn every_corpus_file_matches_ffprobe_sample_for_sample() {
355- let files = corpus();
356- assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/fixtures.sh");
357- let mut report = Vec::new();
358- let mut failures = Vec::new();
359- for path in &files {
360- let (row, problems) = compare(path);
361- report.push(row);
362- if !problems.is_empty() {
363- failures.push(format!("{}:\n {}", path.display(), problems.join("\n ")));
364- }
365- }
366- println!("{}", report.join("\n"));
367- assert!(
368- failures.is_empty(),
369- "{} of {} files differ from ffprobe:\n{}",
370- failures.len(),
371- files.len(),
372- failures.join("\n")
373- );
374-}
375-
376-/// The edith-side reading of the edit list and the sample table, on fixtures
377-/// whose answers are known: an AAC track whose edit list trims one 1024-sample
378-/// priming packet, and an open-GOP stream whose keyframes sit out of display
379-/// order.
380-#[test]
381-fn edith_trim_and_display_order_read_the_known_fixtures() {
382- let aac = ec_testkit::fixture("audio/aac-mp4-stereo-48000.mp4");
383- let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture")))
384- .expect("the fixture demuxes");
385- assert_eq!(demuxer.presentation_trim(0), Some(1024));
386- assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2");
387- assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder");
388-
389- let gop = ec_testkit::fixture("video/h264-open-gop.mp4");
390- let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture")))
391- .expect("the fixture demuxes");
392- let syncs = demuxer.sync_in_display_order(0);
393- assert!(!syncs.is_empty(), "B-frames: the display table answers");
394- assert!(
395- syncs.windows(2).all(|w| w[0].0 < w[1].0 && w[0].1 != w[1].1),
396- "display indices ascend: {syncs:?}"
397- );
398- let samples = demuxer.samples(0);
399- for &(_, decode) in &syncs {
400- assert!(samples[decode as usize].sync, "decode {decode} is a sync sample");
401- }
402-}
crates/ec-mp4/tests/it/main.rsmodified+0 -1
@@ -7,7 +7,6 @@ mod chapters;
7 mod common;7 mod common;
8 mod dts;8 mod dts;
9 mod edit_trim;9 mod edit_trim;
10-mod edith_parity;
11 mod fuzz_regressions;10 mod fuzz_regressions;
12 mod mp4;11 mod mp4;
13 mod mux_entries;12 mod mux_entries;
crates/ec-mpegts/Cargo.tomlmodified+3 -0
@@ -15,3 +15,6 @@ ec-truehd.workspace = true
15 15
16 [dev-dependencies]16 [dev-dependencies]
17 ec-testkit.workspace = true17 ec-testkit.workspace = true
18+
19+[lints.rust]
20+unexpected_cfgs = { level = "warn", check-cfg = ["cfg(fuzzing)"] }
crates/ec-mpegts/examples/bench.rsdeleted+0 -45
@@ -1,45 +0,0 @@
1-//! Open, full read and seek timings: `cargo run --release -p ec-mpegts --example bench -- file`.
2-use std::fs::File;
3-use std::io::BufReader;
4-use std::time::Instant;
5-
6-use ec_core::registry::{Demuxer, SeekMode};
7-use ec_core::{TimeBase, Timestamp};
8-
9-fn main() {
10- let path = std::env::args().nth(1).expect("usage: bench <file>");
11- let t = Instant::now();
12- let mut d =
13- ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("demux");
14- println!("open {:?}, duration {:?}", t.elapsed(), d.duration_secs());
15- let t = Instant::now();
16- let (mut n, mut bytes) = (0u64, 0u64);
17- while let Ok(p) = d.next_packet() {
18- n += 1;
19- bytes += p.data.len() as u64;
20- }
21- let e = t.elapsed();
22- println!(
23- "read {n} packets, {} MB in {e:?} ({:.0} MB/s)",
24- bytes >> 20,
25- bytes as f64 / 1e6 / e.as_secs_f64()
26- );
27- let dur = d.duration_secs().unwrap_or(1.0);
28- for frac in [0.1, 0.5, 0.9, 0.999] {
29- let t = Instant::now();
30- let target = (dur * frac * 90_000.0) as i64 + d.streams()[0].start_time.unwrap_or(0);
31- d.seek(
32- 0,
33- Timestamp::new(target, TimeBase::new(1, 90_000)),
34- SeekMode::SyncBefore,
35- )
36- .unwrap();
37- let p = d.next_packet().unwrap();
38- println!(
39- "seek {frac}: {:?} -> pts {:?} key {}",
40- t.elapsed(),
41- p.pts,
42- p.flags.keyframe
43- );
44- }
45-}
crates/ec-mpegts/examples/dump.rsdeleted+0 -44
@@ -1,44 +0,0 @@
1-//! Lists the programs, tracks and streams of a transport stream and counts its
2-//! packets: `cargo run -p ec-mpegts --example dump -- file.m2ts`.
3-
4-use std::fs::File;
5-use std::io::BufReader;
6-
7-use ec_core::registry::Demuxer;
8-use ec_mpegts::TsDemuxer;
9-
10-fn main() {
11- let path = std::env::args().nth(1).expect("usage: dump <file>");
12- let mut d = TsDemuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("demux");
13- println!("packet size {} bdav {}", d.packet_size(), d.is_bdav());
14- for p in d.programs() {
15- println!(
16- "program {} pmt {:#x} pcr {:?} streams {}",
17- p.number,
18- p.pmt_pid,
19- p.pcr_pid,
20- p.streams.len()
21- );
22- }
23- for t in d.tracks() {
24- println!(
25- "track pid {:#x} type {:#x} {:?} stream {:?} refusal {:?}",
26- t.pid, t.stream_type, t.kind, t.stream, t.refusal
27- );
28- }
29- for s in d.streams() {
30- println!(
31- "stream {} {} start {:?} duration {:?}",
32- s.index,
33- s.params.codec.name(),
34- s.start_time,
35- s.duration
36- );
37- }
38- println!("duration {:?}", d.duration_secs());
39- let mut counts = vec![0u64; d.streams().len()];
40- while let Ok(p) = d.next_packet() {
41- counts[p.stream as usize] += 1;
42- }
43- println!("packets {counts:?} stats {:?}", d.stats());
44-}
crates/ec-mpegts/examples/offs.rsdeleted+0 -22
@@ -1,22 +0,0 @@
1-use ec_core::registry::Demuxer;
2-use std::fs::File;
3-use std::io::BufReader;
4-fn main() {
5- let path = std::env::args().nth(1).unwrap();
6- let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap();
7- let mut n = 0;
8- while let Ok(p) = d.next_packet() {
9- println!(
10- "{} off {} pts {:?} dur {:?} len {}",
11- p.stream,
12- d.last_packet_offset(),
13- p.pts,
14- p.duration,
15- p.data.len()
16- );
17- n += 1;
18- if n > 14 {
19- break;
20- }
21- }
22-}
crates/ec-mpegts/examples/psdump.rsdeleted+0 -43
@@ -1,43 +0,0 @@
1-use ec_core::registry::Demuxer;
2-use ec_mpegts::PsDemuxer;
3-fn main() {
4- let p = std::env::args().nth(1).unwrap();
5- let mut d = PsDemuxer::new(std::io::BufReader::new(std::fs::File::open(p).unwrap())).unwrap();
6- for s in d.streams() {
7- println!(
8- "stream {} {:?} start {:?} dur {:?}",
9- s.index, s.params.codec, s.start_time, s.duration
10- );
11- }
12- for t in d.tracks() {
13- println!("track {:04x} {:?} {:?}", t.pid, t.kind, t.refusal);
14- }
15- println!("dur {:?} stats {:?}", d.duration_secs(), d.stats());
16- if let Some(t) = std::env::args().nth(3) {
17- use ec_core::registry::SeekMode;
18- let t: i64 = t.parse().unwrap();
19- d.seek(
20- 0,
21- ec_core::Timestamp::new(t, ec_core::TimeBase::new(1, 90000)),
22- SeekMode::SyncBefore,
23- )
24- .unwrap();
25- println!("landing {}", d.last_packet_offset());
26- }
27- let n: usize = std::env::args()
28- .nth(2)
29- .map(|x| x.parse().unwrap())
30- .unwrap_or(40);
31- for _ in 0..n {
32- let Ok(p) = d.next_packet() else { break };
33- println!(
34- "s{} pts {:?} dts {:?} k{} len {} off {}",
35- p.stream,
36- p.pts,
37- p.dts,
38- p.flags.keyframe as u8,
39- p.data.len(),
40- d.last_packet_offset()
41- );
42- }
43-}
crates/ec-mpegts/src/demux.rsmodified+1 -47
@@ -60,27 +60,6 @@ pub struct TrackInfo {
60 pub language: Option<String>,60 pub language: Option<String>,
61 }61 }
62 62
63-/// Counters of what the demuxer had to put up with.
64-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65-pub struct Stats {
66- /// Times the sync byte was lost and found again.
67- pub resyncs: u64,
68- /// Continuity-counter gaps on tracked PIDs.
69- pub cc_errors: u64,
70- /// Duplicate packets dropped.
71- pub duplicates: u64,
72- /// PSI sections with a bad CRC.
73- pub crc_errors: u64,
74- /// Packets with the transport error indicator set.
75- pub tei: u64,
76- /// `discontinuity_indicator` seen.
77- pub discontinuities: u64,
78- /// PMT changes after the first (of the selected program).
79- pub pmt_changes: u64,
80- /// PES packets dropped (bad start code, oversize).
81- pub bad_pes: u64,
82-}
83-
84 enum Cc {63 enum Cc {
85 Ok,64 Ok,
86 Dup,65 Dup,
@@ -181,7 +160,6 @@ pub struct TsDemuxer<R> {
181 streams: Vec<StreamInfo>,160 streams: Vec<StreamInfo>,
182 queue: VecDeque<Queued>,161 queue: VecDeque<Queued>,
183 eof: bool,162 eof: bool,
184- stats: Stats,
185 framing: VideoFraming,163 framing: VideoFraming,
186 last_off: u64,164 last_off: u64,
187 duration: Option<i64>,165 duration: Option<i64>,
@@ -226,7 +204,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
226 streams: Vec::new(),204 streams: Vec::new(),
227 queue: VecDeque::new(),205 queue: VecDeque::new(),
228 eof: false,206 eof: false,
229- stats: Stats::default(),
230 framing: VideoFraming::AnnexB,207 framing: VideoFraming::AnnexB,
231 last_off: first_off,208 last_off: first_off,
232 duration: None,209 duration: None,
@@ -300,11 +277,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
300 self.duration.map(|d| d as f64 / TICKS as f64)277 self.duration.map(|d| d as f64 / TICKS as f64)
301 }278 }
302 279
303- /// Counters of what the demuxer repaired or skipped so far.
304- pub fn stats(&self) -> Stats {
305- self.stats
306- }
307-
308 /// First PCR (27 MHz) seen on the program's PCR PID.280 /// First PCR (27 MHz) seen on the program's PCR PID.
309 pub fn first_pcr(&self) -> Option<u64> {281 pub fn first_pcr(&self) -> Option<u64> {
310 self.first_pcr282 self.first_pcr
@@ -405,7 +377,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
405 }377 }
406 };378 };
407 if !ok {379 if !ok {
408- self.stats.resyncs += 1;
409 self.mark_bad();380 self.mark_bad();
410 self.cc.clear();381 self.cc.clear();
411 for s in self.sections.values_mut() {382 for s in self.sections.values_mut() {
@@ -430,7 +401,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
430 return Ok(true);401 return Ok(true);
431 }402 }
432 if h.tei {403 if h.tei {
433- self.stats.tei += 1;
434 if let Some(&ti) = self.pid_map.get(&h.pid) {404 if let Some(&ti) = self.pid_map.get(&h.pid) {
435 self.tracks[ti].pes_bad = true;405 self.tracks[ti].pes_bad = true;
436 }406 }
@@ -441,9 +411,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
441 {411 {
442 self.first_pcr.get_or_insert(pcr);412 self.first_pcr.get_or_insert(pcr);
443 }413 }
444- if h.discontinuity {
445- self.stats.discontinuities += 1;
446- }
447 let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid);414 let is_psi = h.pid == 0 || self.programs.iter().any(|p| p.pmt_pid == h.pid);
448 let tracked = self.pid_map.get(&h.pid).copied();415 let tracked = self.pid_map.get(&h.pid).copied();
449 if !is_psi && tracked.is_none() {416 if !is_psi && tracked.is_none() {
@@ -452,11 +419,9 @@ impl<R: Read + Seek> TsDemuxer<R> {
452 let cc = self.cc_check(&h, &pkt);419 let cc = self.cc_check(&h, &pkt);
453 match cc {420 match cc {
454 Cc::Dup => {421 Cc::Dup => {
455- self.stats.duplicates += 1;
456 return Ok(true);422 return Ok(true);
457 }423 }
458 Cc::Gap => {424 Cc::Gap => {
459- self.stats.cc_errors += 1;
460 if let Some(ti) = tracked {425 if let Some(ti) = tracked {
461 self.tracks[ti].pes_bad = true;426 self.tracks[ti].pes_bad = true;
462 }427 }
@@ -472,12 +437,10 @@ impl<R: Read + Seek> TsDemuxer<R> {
472 let payload = &pkt[h.payload.0..h.payload.1];437 let payload = &pkt[h.payload.0..h.payload.1];
473 if is_psi {438 if is_psi {
474 let mut out = Vec::new();439 let mut out = Vec::new();
475- let bad = self440+ self.sections
476- .sections
477 .entry(h.pid)441 .entry(h.pid)
478 .or_default()442 .or_default()
479 .push(h.pusi, payload, &mut out);443 .push(h.pusi, payload, &mut out);
480- self.stats.crc_errors += u64::from(bad);
481 for s in out {444 for s in out {
482 self.on_section(h.pid, &s);445 self.on_section(h.pid, &s);
483 }446 }
@@ -504,7 +467,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
504 t.pes_expect = None;467 t.pes_expect = None;
505 if payload.len() >= 3 && payload[..3] != [0, 0, 1] {468 if payload.len() >= 3 && payload[..3] != [0, 0, 1] {
506 t.pes_on = false;469 t.pes_on = false;
507- self.stats.bad_pes += 1;
508 return;470 return;
509 }471 }
510 } else if !self.tracks[ti].pes_on {472 } else if !self.tracks[ti].pes_on {
@@ -521,7 +483,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
521 if t.pes.len() > MAX_PES {483 if t.pes.len() > MAX_PES {
522 t.pes_on = false;484 t.pes_on = false;
523 t.pes.clear();485 t.pes.clear();
524- self.stats.bad_pes += 1;
525 return;486 return;
526 }487 }
527 if let Some(n) = t.pes_expect488 if let Some(n) = t.pes_expect
@@ -540,7 +501,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
540 t.pes_on = false;501 t.pes_on = false;
541 let buf = std::mem::take(&mut t.pes);502 let buf = std::mem::take(&mut t.pes);
542 let Some(head) = parse_pes(&buf) else {503 let Some(head) = parse_pes(&buf) else {
543- self.stats.bad_pes += 1;
544 t.pes = buf;504 t.pes = buf;
545 t.pes.clear();505 t.pes.clear();
546 return;506 return;
@@ -649,9 +609,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
649 if same {609 if same {
650 return;610 return;
651 }611 }
652- if self.pmt_seen {
653- self.stats.pmt_changes += 1;
654- }
655 self.pmt_seen = true;612 self.pmt_seen = true;
656 for ti in 0..self.tracks.len() {613 for ti in 0..self.tracks.len() {
657 let t = &self.tracks[ti];614 let t = &self.tracks[ti];
@@ -747,7 +704,6 @@ impl<R: Read + Seek> TsDemuxer<R> {
747 self.frozen = false;704 self.frozen = false;
748 tail?;705 tail?;
749 self.reset_at(self.first_off, None);706 self.reset_at(self.first_off, None);
750- self.stats = Stats::default();
751 Ok(())707 Ok(())
752 }708 }
753 709
@@ -957,11 +913,9 @@ impl<R: Read + Seek + Send> Demuxer for TsDemuxer<R> {
957 }913 }
958 914
959 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {915 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
960- let saved = self.stats;
961 self.frozen = true;916 self.frozen = true;
962 let r = self.seek_scan(stream, to, mode);917 let r = self.seek_scan(stream, to, mode);
963 self.frozen = false;918 self.frozen = false;
964- self.stats = saved;
965 // The landing re-read starts with the PSI of the stream again.919 // The landing re-read starts with the PSI of the stream again.
966 r920 r
967 }921 }
crates/ec-mpegts/src/lib.rsmodified+2 -1
@@ -61,6 +61,7 @@ mod track;
61 mod ts;61 mod ts;
62 mod window;62 mod window;
63 63
64+#[cfg(fuzzing)]
64 #[doc(hidden)]65 #[doc(hidden)]
65 pub mod fuzz_api;66 pub mod fuzz_api;
66 67
@@ -68,7 +69,7 @@ pub use codec::{
68 LpcmHeader, NalIter, StreamKind, annexb_to_length_prefixed, audio_specific_config, build_avcc,69 LpcmHeader, NalIter, StreamKind, annexb_to_length_prefixed, audio_specific_config, build_avcc,
69 build_hvcc, nal_units, parse_lpcm_header,70 build_hvcc, nal_units, parse_lpcm_header,
70 };71 };
71-pub use demux::{ProgramInfo, Stats, TrackInfo, TsDemuxer, VideoFraming};72+pub use demux::{ProgramInfo, TrackInfo, TsDemuxer, VideoFraming};
72 pub use ps::{PsDemuxer, PsKind, is_mpeg_video_es, is_mpegps};73 pub use ps::{PsDemuxer, PsKind, is_mpeg_video_es, is_mpegps};
73 pub use psi::{EsEntry, Pmt};74 pub use psi::{EsEntry, Pmt};
74 75
crates/ec-mpegts/src/ps.rsmodified+4 -28
@@ -21,7 +21,7 @@ use ec_core::registry::{Demuxer, SeekMode, StreamInfo};
21 use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};21 use ec_core::{Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};
22 22
23 use crate::codec::{StreamKind, annexb_to_length_prefixed};23 use crate::codec::{StreamKind, annexb_to_length_prefixed};
24-use crate::demux::{Stats, TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33};24+use crate::demux::{TrackInfo, VideoFraming, parse_pes, read_ts, unwrap33};
25 use crate::psi::{EsEntry, descriptors};25 use crate::psi::{EsEntry, descriptors};
26 use crate::track::{PesIn, Queued, TICKS, Track};26 use crate::track::{PesIn, Queued, TICKS, Track};
27 use crate::window::Window;27 use crate::window::Window;
@@ -250,7 +250,6 @@ pub struct PsDemuxer<R> {
250 streams: Vec<StreamInfo>,250 streams: Vec<StreamInfo>,
251 queue: VecDeque<Queued>,251 queue: VecDeque<Queued>,
252 eof: bool,252 eof: bool,
253- stats: Stats,
254 framing: VideoFraming,253 framing: VideoFraming,
255 last_off: u64,254 last_off: u64,
256 duration: Option<i64>,255 duration: Option<i64>,
@@ -268,23 +267,15 @@ pub struct PsDemuxer<R> {
268 /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every267 /// After a seek that started reading earlier (see [`PsDemuxer::land`]): drop every
269 /// packet that starts before this offset.268 /// packet that starts before this offset.
270 pre_drop: Option<u64>,269 pre_drop: Option<u64>,
271- walk_limit: u64,
272 }270 }
273 271
274 impl<R: Read + Seek> PsDemuxer<R> {272 impl<R: Read + Seek> PsDemuxer<R> {
275 /// Opens `reader` as a program stream, a system stream or a raw video stream.273 /// Opens `reader` as a program stream, a system stream or a raw video stream.
276 pub fn new(reader: R) -> Result<PsDemuxer<R>> {274 pub fn new(reader: R) -> Result<PsDemuxer<R>> {
277- Self::open(reader, FULL_WALK)275+ Self::open(reader)
278 }276 }
279 277
280- /// As [`PsDemuxer::new`], with files larger than `walk_limit` bytes checked for SCR278+ fn open(reader: R) -> Result<PsDemuxer<R>> {
281- /// resets by sampling instead of a full walk (tests exercise that path on small files).
282- #[doc(hidden)]
283- pub fn with_walk_limit(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
284- Self::open(reader, walk_limit)
285- }
286-
287- fn open(reader: R, walk_limit: u64) -> Result<PsDemuxer<R>> {
288 let mut win = Window::new(reader);279 let mut win = Window::new(reader);
289 let file_len = win.len()?;280 let file_len = win.len()?;
290 let head = win.get(0, 64 * 1024)?;281 let head = win.get(0, 64 * 1024)?;
@@ -315,7 +306,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
315 streams: Vec::new(),306 streams: Vec::new(),
316 queue: VecDeque::new(),307 queue: VecDeque::new(),
317 eof: false,308 eof: false,
318- stats: Stats::default(),
319 framing: VideoFraming::AnnexB,309 framing: VideoFraming::AnnexB,
320 last_off: first_off,310 last_off: first_off,
321 duration: None,311 duration: None,
@@ -332,7 +322,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
332 bad_next: false,322 bad_next: false,
333 skip: None,323 skip: None,
334 pre_drop: None,324 pre_drop: None,
335- walk_limit,
336 };325 };
337 if kind == PsKind::VideoElementary {326 if kind == PsKind::VideoElementary {
338 d.open_es()?;327 d.open_es()?;
@@ -390,12 +379,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
390 self.duration.map(|d| d as f64 / TICKS as f64)379 self.duration.map(|d| d as f64 / TICKS as f64)
391 }380 }
392 381
393- /// Counters of what was repaired or skipped (`resyncs`, `discontinuities` = SCR
394- /// resets, `bad_pes`); the transport-only counters stay 0.
395- pub fn stats(&self) -> Stats {
396- self.stats
397- }
398-
399 /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps382 /// SCR resets found in the file (concatenated VOBs, cell boundaries): timestamps
400 /// after each are shifted to continue the timeline.383 /// after each are shifted to continue the timeline.
401 pub fn epoch_count(&self) -> usize {384 pub fn epoch_count(&self) -> usize {
@@ -502,7 +485,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
502 Ok(false)485 Ok(false)
503 }486 }
504 El::Bad => {487 El::Bad => {
505- self.stats.resyncs += 1;
506 self.mark_bad();488 self.mark_bad();
507 match self.next_pack(pos + 1)? {489 match self.next_pack(pos + 1)? {
508 Some(p) => {490 Some(p) => {
@@ -552,7 +534,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
552 self.first_scr = Some(scr as i64);534 self.first_scr = Some(scr as i64);
553 }535 }
554 if self.clock.feed(scr) {536 if self.clock.feed(scr) {
555- self.stats.discontinuities += 1;
556 // The table made at open knows this join with its aligned shift.537 // The table made at open knows this join with its aligned shift.
557 if let Some(e) = self.epochs.iter().find(|e| e.off == at) {538 if let Some(e) = self.epochs.iter().find(|e| e.off == at) {
558 self.clock.shift = e.shift;539 self.clock.shift = e.shift;
@@ -619,7 +600,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
619 match parse_pes(b) {600 match parse_pes(b) {
620 Some(h) => (h.pts, h.dts, h.payload),601 Some(h) => (h.pts, h.dts, h.payload),
621 None => {602 None => {
622- self.stats.bad_pes += 1;
623 return;603 return;
624 }604 }
625 }605 }
@@ -627,7 +607,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
627 match parse_pes1(b) {607 match parse_pes1(b) {
628 Some(h) => h,608 Some(h) => h,
629 None => {609 None => {
630- self.stats.bad_pes += 1;
631 return;610 return;
632 }611 }
633 }612 }
@@ -805,7 +784,7 @@ impl<R: Read + Seek> PsDemuxer<R> {
805 /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack784 /// Finds SCR resets: the whole file when it is small, otherwise a sample of pack
806 /// headers decides whether a full walk is needed.785 /// headers decides whether a full walk is needed.
807 fn build_epochs(&mut self) -> Result<()> {786 fn build_epochs(&mut self) -> Result<()> {
808- let full = if self.file_len <= self.walk_limit {787+ let full = if self.file_len <= FULL_WALK {
809 true788 true
810 } else {789 } else {
811 let mut last: Option<u64> = None;790 let mut last: Option<u64> = None;
@@ -986,7 +965,6 @@ impl<R: Read + Seek> PsDemuxer<R> {
986 self.frozen = false;965 self.frozen = false;
987 tail?;966 tail?;
988 self.reset_at(self.first_off);967 self.reset_at(self.first_off);
989- self.stats = Stats::default();
990 Ok(())968 Ok(())
991 }969 }
992 970
@@ -1562,11 +1540,9 @@ impl<R: Read + Seek + Send> Demuxer for PsDemuxer<R> {
1562 }1540 }
1563 1541
1564 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {1542 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1565- let saved = self.stats;
1566 self.frozen = true;1543 self.frozen = true;
1567 let r = self.seek_scan(stream, to, mode);1544 let r = self.seek_scan(stream, to, mode);
1568 self.frozen = false;1545 self.frozen = false;
1569- self.stats = saved;
1570 r1546 r
1571 }1547 }
1572 }1548 }
crates/ec-mpegts/tests/it/ffmpeg_parity.rsmodified+1 -8
@@ -505,13 +505,6 @@ fn corrupted_and_truncated() {
505 "{name}: only {n} of {} packets",505 "{name}: only {n} of {} packets",
506 want.len()506 want.len()
507 );507 );
508- let st = d.stats();508+ eprintln!("{name}: {n} packets, {flagged} flagged");
509- if name == "overwritten" || name == "bytes removed" {
510- assert!(
511- st.resyncs > 0 || st.cc_errors > 0,
512- "{name}: damage unnoticed {st:?}"
513- );
514- }
515- eprintln!("{name}: {n} packets, {flagged} flagged, {st:?}");
516 }509 }
517 }510 }
crates/ec-mpegts/tests/it/ps.rsmodified+6 -15
@@ -554,16 +554,10 @@ fn per_stream(p: &[Pkt]) -> Vec<Vec<&Pkt>> {
554 }554 }
555 555
556 /// `copies` of a file back to back: the SCR (and the PTS) restart in each.556 /// `copies` of a file back to back: the SCR (and the PTS) restart in each.
557-fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {557+fn check_concat(bytes: &[u8], copies: usize) {
558 let cat: Vec<u8> = (0..copies).flat_map(|_| bytes.iter().copied()).collect();558 let cat: Vec<u8> = (0..copies).flat_map(|_| bytes.iter().copied()).collect();
559 let path = tmpfile("concat.vob", &cat);559 let path = tmpfile("concat.vob", &cat);
560- let open = |p: &Path| {560+ let open = |p: &Path| PsDemuxer::new(BufReader::new(File::open(p).unwrap())).unwrap();
561- let f = BufReader::new(File::open(p).unwrap());
562- match walk_limit {
563- Some(l) => PsDemuxer::with_walk_limit(f, l).unwrap(),
564- None => PsDemuxer::new(f).unwrap(),
565- }
566- };
567 let single = {561 let single = {
568 let mut d = open_bytes(bytes.to_vec()).unwrap();562 let mut d = open_bytes(bytes.to_vec()).unwrap();
569 let mut v = Vec::new();563 let mut v = Vec::new();
@@ -575,7 +569,6 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {
575 let mut d = open(&path);569 let mut d = open(&path);
576 assert_eq!(d.epoch_count(), copies, "SCR resets found at open");570 assert_eq!(d.epoch_count(), copies, "SCR resets found at open");
577 let all = read_ps(&mut d);571 let all = read_ps(&mut d);
578- assert_eq!(d.stats().discontinuities, copies as u64 - 1);
579 assert_eq!(all.len(), single.len() * copies);572 assert_eq!(all.len(), single.len() * copies);
580 let ps = per_stream(&all);573 let ps = per_stream(&all);
581 let mut shift = None;574 let mut shift = None;
@@ -622,10 +615,8 @@ fn check_concat(bytes: &[u8], copies: usize, walk_limit: Option<u64>) {
622 #[test]615 #[test]
623 fn concatenated_vobs_keep_time_monotonic() {616 fn concatenated_vobs_keep_time_monotonic() {
624 let b = committed("ps_mpeg2_ac3.vob");617 let b = committed("ps_mpeg2_ac3.vob");
625- check_concat(&b, 3, None);618+ check_concat(&b, 3);
626- // The same through the sampling check used for big files.619+ check_concat(&committed("ps_mpeg1_mp2.mpg"), 2);
627- check_concat(&b, 3, Some(1));
628- check_concat(&committed("ps_mpeg1_mp2.mpg"), 2, None);
629 }620 }
630 621
631 #[test]622 #[test]
@@ -647,7 +638,7 @@ fn concatenated_dvd_files_with_nav_packets() {
647 &["-c:a", "ac3", "-ar", "48000"],638 &["-c:a", "ac3", "-ar", "48000"],
648 &["-f", "dvd"],639 &["-f", "dvd"],
649 );640 );
650- check_concat(&std::fs::read(p).unwrap(), 2, None);641+ check_concat(&std::fs::read(p).unwrap(), 2);
651 }642 }
652 643
653 #[test]644 #[test]
@@ -796,7 +787,7 @@ fn exercise(bytes: Vec<u8>) {
796 let Ok(mut d) = open_bytes(bytes) else {787 let Ok(mut d) = open_bytes(bytes) else {
797 return;788 return;
798 };789 };
799- let _ = (d.tracks(), d.duration_secs(), d.stats(), d.epoch_count());790+ let _ = (d.tracks(), d.duration_secs(), d.epoch_count());
800 for round in 0..2 {791 for round in 0..2 {
801 if round == 1 {792 if round == 1 {
802 d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);793 d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);
crates/ec-mpegts/tests/it/robust.rsmodified+1 -1
@@ -13,7 +13,7 @@ fn exercise(bytes: Vec<u8>) {
13 let Ok(mut d) = TsDemuxer::new(Cursor::new(bytes)) else {13 let Ok(mut d) = TsDemuxer::new(Cursor::new(bytes)) else {
14 return;14 return;
15 };15 };
16- let _ = (d.tracks(), d.programs().len(), d.duration_secs(), d.stats());16+ let _ = (d.tracks(), d.programs().len(), d.duration_secs());
17 for round in 0..2 {17 for round in 0..2 {
18 if round == 1 {18 if round == 1 {
19 d.set_video_framing(VideoFraming::LengthPrefixed);19 d.set_video_framing(VideoFraming::LengthPrefixed);
crates/ec-mpegts/tests/it/synthetic.rsmodified+3 -246
@@ -1,16 +1,12 @@
1-//! Hand-built transport streams for the corners ffmpeg's muxer never produces: a PCR1+//! Hand-built transport stream round trip.
2-//! on its own PID, several access units in one PES, 204-byte packets, duplicate
3-//! packets, PMT changes, damaged PSI, refused stream types, PGS.
4 2
5 use std::collections::HashMap;3 use std::collections::HashMap;
6-use std::fs::File;4+use std::io::Cursor;
7-use std::io::{BufReader, Cursor};
8 use std::path::PathBuf;5 use std::path::PathBuf;
9 6
10 use crate::common::crc32;7 use crate::common::crc32;
11-use ec_core::CodecId;
12 use ec_core::registry::Demuxer;8 use ec_core::registry::Demuxer;
13-use ec_mpegts::{StreamKind, TsDemuxer};9+use ec_mpegts::TsDemuxer;
14 10
15 fn tiny(name: &str) -> Vec<u8> {11 fn tiny(name: &str) -> Vec<u8> {
16 std::fs::read(12 std::fs::read(
@@ -329,243 +325,4 @@ fn rebuilt_stream_equals_the_original() {
329 assert_eq!(by_stream(&got, s), by_stream(&want, s), "stream {s}");325 assert_eq!(by_stream(&got, s), by_stream(&want, s), "stream {s}");
330 }326 }
331 assert_eq!(d.packet_size(), 188);327 assert_eq!(d.packet_size(), 188);
332- assert_eq!(d.stats().cc_errors, 0);
333-}
334-
335-#[test]
336-fn pcr_on_its_own_pid() {
337- let (got, d) = packets(build(188, 0x1FF0, false));
338- assert_eq!(d.pcr_pid(), Some(0x1FF0));
339- assert!(d.first_pcr().is_some());
340- assert_eq!(d.tracks().len(), 2);
341- assert_eq!(by_stream(&got, 0), by_stream(&reference(), 0));
342-}
343-
344-#[test]
345-fn packet_sizes_192_and_204() {
346- for size in [192, 204] {
347- let (got, d) = packets(build(size, VPID, false));
348- assert_eq!(d.packet_size(), size);
349- assert_eq!(d.is_bdav(), size == 192);
350- assert_eq!(
351- by_stream(&got, 1),
352- by_stream(&reference(), 1),
353- "size {size}"
354- );
355- assert_eq!(
356- by_stream(&got, 0),
357- by_stream(&reference(), 0),
358- "size {size}"
359- );
360- }
361-}
362-
363-#[test]
364-fn two_access_units_in_one_pes_are_split_on_the_delimiter() {
365- let (got, _) = packets(build(188, VPID, true));
366- let want = reference();
367- let (g, w) = (by_stream(&got, 0), by_stream(&want, 0));
368- assert_eq!(g.len(), w.len());
369- for (a, b) in g.iter().zip(&w) {
370- assert_eq!(a.3, b.3);
371- assert_eq!(a.2, b.2, "keyframe flag");
372- }
373- // The second unit of a pair has no timestamp of its own.
374- assert!(g.iter().filter(|p| p.1.is_none()).count() >= 5);
375-}
376-
377-#[test]
378-fn duplicate_packets_are_dropped() {
379- let clean = build(188, VPID, false);
380- let mut dup = Vec::new();
381- for (i, p) in clean.chunks(188).enumerate() {
382- dup.extend_from_slice(p);
383- if i % 7 == 3 && p[1] & 0x1f == 1 {
384- dup.extend_from_slice(p);
385- }
386- }
387- let (got, d) = packets(dup);
388- assert!(d.stats().duplicates > 0);
389- assert_eq!(by_stream(&got, 0), by_stream(&packets(clean).0, 0));
390-}
391-
392-#[test]
393-fn damaged_psi_is_ignored() {
394- let mut bytes = build(188, VPID, false);
395- // The first PMT's CRC byte: second packet, last section byte.
396- let mut broken = bytes.clone();
397- let pmt = &mut broken[188..376];
398- let st = 5 + usize::from(pmt[4]); // past the adaptation field and the pointer
399- let end = st + 3 + (usize::from(pmt[st + 2] & 0xf) << 8 | usize::from(pmt[st + 3]));
400- pmt[end] ^= 0xFF;
401- // Later copies of the PMT are intact, so the file still opens; the damage is counted.
402- let (_, d) = packets(broken);
403- assert!(d.stats().crc_errors >= 1, "{:?}", d.stats());
404- // Garbage everywhere in the PAT leaves nothing to open.
405- for b in &mut bytes[..188] {
406- *b = 0x47;
407- }
408- for (i, p) in bytes.chunks_mut(188).enumerate() {
409- if p[1] == 0x40 && p[2] == 0 && i % 4 == 0 {
410- p[10] ^= 0x55;
411- }
412- }
413- let _ = TsDemuxer::new(Cursor::new(bytes));
414-}
415-
416-#[test]
417-fn refusals_name_the_codec_and_pgs_is_exposed() {
418- let es = vec![
419- Es {
420- pid: 0x100,
421- stream_type: 0x02,
422- descriptors: vec![],
423- },
424- Es {
425- pid: 0x101,
426- stream_type: 0x11,
427- descriptors: vec![],
428- },
429- Es {
430- pid: 0x102,
431- stream_type: 0x90,
432- descriptors: vec![],
433- },
434- Es {
435- pid: 0x103,
436- stream_type: 0x06,
437- descriptors: vec![0x6A, 1, 0],
438- },
439- Es {
440- pid: 0x104,
441- stream_type: 0x06,
442- descriptors: vec![0x59, 0],
443- },
444- Es {
445- pid: 0x105,
446- stream_type: 0x83,
447- descriptors: vec![],
448- },
449- ];
450- let mut m = Mux::new(192);
451- m.tables(0x1000, 0x100, &es, 0);
452- for i in 0..40u64 {
453- m.pes(
454- 0x102,
455- 0xBD,
456- Some(90_000 + i * 1000),
457- None,
458- &[0x16, 0, 3, 1, 2, 3],
459- true,
460- false,
461- );
462- m.pes(
463- 0x100,
464- 0xE0,
465- Some(90_000 + i * 3600),
466- None,
467- &[0, 0, 1, 0xB3, 1, 2, 3, 4],
468- false,
469- false,
470- );
471- if i % 5 == 0 {
472- m.tables(0x1000, 0x100, &es, 0);
473- }
474- }
475- let mut d = TsDemuxer::new(Cursor::new(m.out)).unwrap();
476- let tracks = d.tracks();
477- assert_eq!(tracks.len(), 6);
478- assert_eq!(tracks[0].kind, StreamKind::Mpeg2Video);
479- assert!(
480- tracks[0].refusal.is_none(),
481- "MPEG-2 video is exposed, not refused"
482- );
483- assert_eq!(tracks[0].stream, None, "no parseable sequence header yet");
484- assert!(tracks[1].refusal.as_ref().unwrap().contains("aac_latm"));
485- assert_eq!(tracks[2].stream, Some(0));
486- assert_eq!(tracks[3].kind, StreamKind::Ac3);
487- assert_eq!(
488- tracks[3].stream, None,
489- "no AC-3 frames were seen, so it cannot be described yet"
490- );
491- assert_eq!(tracks[4].kind, StreamKind::DvbSub);
492- assert!(tracks[4].refusal.is_none(), "DVB subtitles are exposed");
493- assert_eq!(tracks[5].kind, StreamKind::TrueHd);
494- assert!(
495- tracks[5].refusal.is_none(),
496- "TrueHD is exposed, not refused"
497- );
498- assert_eq!(tracks[5].stream, None, "no TrueHD access unit was seen yet");
499- assert_eq!(d.streams().len(), 2);
500- assert_eq!(d.streams()[0].params.codec, CodecId::Pgs);
501- assert_eq!(d.streams()[1].params.codec, CodecId::DvbSub);
502- let mut n = 0;
503- while let Ok(p) = d.next_packet() {
504- if p.stream != 0 {
505- continue;
506- }
507- assert_eq!(&p.data[..], &[0x16, 0, 3, 1, 2, 3]);
508- assert!(p.flags.keyframe);
509- n += 1;
510- }
511- assert_eq!(n, 40);
512-}
513-
514-#[test]
515-fn pmt_change_appends_streams_and_keeps_indices() {
516- let a = tiny("tiny_h264_aac.ts");
517- let b = tiny("tiny_h264_eac3.ts");
518- let mut both = a.clone();
519- both.extend_from_slice(&b);
520- let mut d = TsDemuxer::new(Cursor::new(both)).unwrap();
521- assert_eq!(d.streams().len(), 2);
522- let mut counts = HashMap::new();
523- while let Ok(p) = d.next_packet() {
524- *counts.entry(p.stream).or_insert(0) += 1;
525- }
526- assert_eq!(d.stats().pmt_changes, 1);
527- assert_eq!(d.streams().len(), 3);
528- assert_eq!(d.streams()[2].params.codec, CodecId::EAc3);
529- assert_eq!(d.streams()[1].params.codec, CodecId::Aac);
530- let alone = |bytes: Vec<u8>| {
531- let mut d = TsDemuxer::new(Cursor::new(bytes)).unwrap();
532- let mut c = [0usize; 2];
533- while let Ok(p) = d.next_packet() {
534- c[p.stream as usize] += 1;
535- }
536- c
537- };
538- let (ca, cb) = (alone(a), alone(b));
539- assert_eq!(counts[&0], ca[0] + cb[0]);
540- assert_eq!(counts[&1], ca[1]);
541- assert_eq!(counts[&2], cb[1]);
542- let tracks = d.tracks();
543- assert_eq!(tracks.iter().filter(|t| t.stream.is_some()).count(), 3);
544- assert!(tracks[1].pid == tracks[2].pid);
545-}
546-
547-#[test]
548-fn length_prefixed_video_and_config_records() {
549- let mut d = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap();
550- d.set_video_framing(ec_mpegts::VideoFraming::LengthPrefixed);
551- let avcc = d.streams()[0].params.extradata.clone().unwrap();
552- assert_eq!(avcc[0], 1);
553- assert_eq!(avcc[4] & 3, 3, "4-byte lengths");
554- let p = d.next_packet().unwrap();
555- let n = u32::from_be_bytes(p.data[..4].try_into().unwrap()) as usize;
556- assert!(n + 4 <= p.data.len());
557- // The same access unit, re-framed from the Annex-B one, round-trips.
558- let mut d2 = TsDemuxer::new(Cursor::new(tiny("tiny_h264_aac.ts"))).unwrap();
559- let q = d2.next_packet().unwrap();
560- assert_eq!(
561- ec_mpegts::annexb_to_length_prefixed(&q.data, 4),
562- p.data.to_vec()
563- );
564- // The hvcC of the HEVC fixture.
565- let h = TsDemuxer::new(Cursor::new(tiny("tiny_hevc_aac.ts"))).unwrap();
566- let hvcc = h.streams()[0].params.extradata.clone().unwrap();
567- assert_eq!(hvcc[0], 1);
568- assert_eq!(hvcc[21] & 3, 3);
569- assert!(hvcc[22] >= 3, "VPS, SPS and PPS arrays");
570- let _ = BufReader::new(File::open("/dev/null").unwrap());
571 }328 }
crates/ec-ogg/examples/benchp1.rsdeleted+0 -47
@@ -1,47 +0,0 @@
1-//! benchp1: Ogg demux throughput for lanes/bench.md ("lane benchp1").
2-//!
3-//! usage: benchp1 <file.ogg> [reps]
4-//!
5-//! Opens the file and reads every packet with `OggDemuxer`, `reps` times (default 5), keeping the
6-//! best wall time. Prints the packet count and byte total (checked against ffprobe) and the time.
7-use std::fs::File;
8-use std::hint::black_box;
9-use std::io::BufReader;
10-use std::time::Instant;
11-
12-use ec_core::Demuxer;
13-use ec_ogg::OggDemuxer;
14-
15-/// Demux the whole file once: (packets, bytes).
16-fn demux_once(path: &str) -> (u64, u64) {
17- let mut demux = OggDemuxer::open(BufReader::new(File::open(path).expect("open"))).expect("open ogg");
18- let (mut packets, mut bytes) = (0u64, 0u64);
19- loop {
20- match demux.next_packet() {
21- Ok(p) => {
22- packets += 1;
23- bytes += p.data.len() as u64;
24- black_box(&p);
25- }
26- Err(e) if e.is_eof() => break,
27- Err(e) => panic!("demux: {e}"),
28- }
29- }
30- (packets, bytes)
31-}
32-
33-fn main() {
34- let args: Vec<String> = std::env::args().collect();
35- let reps: usize = args.get(2).map_or(5, |s| s.parse().expect("reps"));
36- let (packets, bytes) = demux_once(&args[1]);
37- let mut best = f64::MAX;
38- for _ in 0..reps {
39- let t = Instant::now();
40- black_box(demux_once(black_box(&args[1])));
41- best = best.min(t.elapsed().as_secs_f64());
42- }
43- println!(
44- "packets={packets} bytes={bytes} best_demux_s={best:.4} mb_s={:.2} reps={reps}",
45- bytes as f64 / best / 1e6
46- );
47-}
crates/ec-ogg/src/demux.rsmodified+23 -37
@@ -49,15 +49,12 @@ struct Track {
49 mapping: Mapping,49 mapping: Mapping,
50 /// Header packets, in order, until [`Mapping::header_packets`] are in.50 /// Header packets, in order, until [`Mapping::header_packets`] are in.
51 headers: Vec<Vec<u8>>,51 headers: Vec<Vec<u8>>,
52- /// Bytes of a packet still being assembled across a page boundary.52+ /// Bytes of a packet still being assembled across a page boundary; `Some` while
53- partial: Vec<u8>,53+ /// one is mid-assembly, even when its bytes so far are empty.
54- /// A packet is mid-assembly (true even when its bytes so far are empty,54+ partial: Option<Vec<u8>>,
55- /// which happens when a page ends exactly on a 255-byte segment).55+ /// Granule position the next packet starts at; `None` after a packet of unknown
56- assembling: bool,56+ /// duration until the next page granule.
57- /// Granule position the next packet starts at.57+ pos: Option<i64>,
58- pos: i64,
59- /// False between a packet of unknown duration and the next page granule.
60- pos_known: bool,
61 /// The stream has seen its end-of-stream page.58 /// The stream has seen its end-of-stream page.
62 eos: bool,59 eos: bool,
63 }60 }
@@ -207,10 +204,10 @@ impl<R: Read + Seek> OggDemuxer<R> {
207 204
208 let mapping = self.tracks[index].mapping;205 let mapping = self.tracks[index].mapping;
209 let time_base = self.streams[index].time_base;206 let time_base = self.streams[index].time_base;
210- let mut packet = std::mem::take(&mut self.tracks[index].partial);207+ let carried = self.tracks[index].partial.take();
211- let mut assembling = self.tracks[index].assembling;208+ let mut assembling = carried.is_some();
209+ let mut packet = carried.unwrap_or_default();
212 let mut pos = self.tracks[index].pos;210 let mut pos = self.tracks[index].pos;
213- let mut pos_known = self.tracks[index].pos_known;
214 let mut headers_done = self.tracks[index].headers_complete();211 let mut headers_done = self.tracks[index].headers_complete();
215 let mut at = 0usize;212 let mut at = 0usize;
216 let mut segments = &page.header.segments[..];213 let mut segments = &page.header.segments[..];
@@ -270,32 +267,26 @@ impl<R: Read + Seek> OggDemuxer<R> {
270 }267 }
271 let duration = mapping.packet_duration(&done);268 let duration = mapping.packet_duration(&done);
272 let mut out = Packet::new(index as u32, time_base, done);269 let mut out = Packet::new(index as u32, time_base, done);
273- out.pts = pos_known.then_some(pos);270+ out.pts = pos;
274 out.dts = out.pts;271 out.dts = out.pts;
275 out.duration = duration;272 out.duration = duration;
276 // Every Ogg audio packet is a decodable entry point as far273 // Every Ogg audio packet is a decodable entry point as far
277 // as the container is concerned; codec pre-roll (a Vorbis274 // as the container is concerned; codec pre-roll (a Vorbis
278 // block needs its predecessor to overlap) is the decoder's.275 // block needs its predecessor to overlap) is the decoder's.
279 out.flags.keyframe = true;276 out.flags.keyframe = true;
280- match duration {277+ // Past i64::MAX the position is no longer known, like an
281- // Past i64::MAX the position is no longer known, like an278+ // unknown duration: the next page granule re-anchors it.
282- // unknown duration: the next page granule re-anchors it.279+ pos = match (pos, duration) {
283- Some(d) if pos_known => match pos.checked_add(d) {280+ (Some(p), Some(d)) => p.checked_add(d),
284- Some(next) => pos = next,281+ _ => None,
285- None => pos_known = false,282+ };
286- },
287- Some(_) => {}
288- None => pos_known = false,
289- }
290 self.queue.push_back(out);283 self.queue.push_back(out);
291 }284 }
292 }285 }
293 }286 }
294 let track = &mut self.tracks[index];287 let track = &mut self.tracks[index];
295- track.partial = packet;288+ track.partial = assembling.then_some(packet);
296- track.assembling = assembling;
297 track.pos = pos;289 track.pos = pos;
298- track.pos_known = pos_known;
299 track.eos |= page.header.eos;290 track.eos |= page.header.eos;
300 291
301 // The granule is where the last packet finishing on this page ends, so292 // The granule is where the last packet finishing on this page ends, so
@@ -309,8 +300,7 @@ impl<R: Read + Seek> OggDemuxer<R> {
309 .push(granule_side_data(page.header.granule));300 .push(granule_side_data(page.header.granule));
310 }301 }
311 let track = &mut self.tracks[index];302 let track = &mut self.tracks[index];
312- track.pos = page.header.granule;303+ track.pos = Some(page.header.granule);
313- track.pos_known = true;
314 }304 }
315 Ok(())305 Ok(())
316 }306 }
@@ -338,10 +328,8 @@ impl<R: Read + Seek> OggDemuxer<R> {
338 serial: page.header.serial,328 serial: page.header.serial,
339 mapping,329 mapping,
340 headers: Vec::new(),330 headers: Vec::new(),
341- partial: Vec::new(),331+ partial: None,
342- assembling: false,332+ pos: Some(0),
343- pos: 0,
344- pos_known: true,
345 eos: false,333 eos: false,
346 });334 });
347 Some(index)335 Some(index)
@@ -383,9 +371,8 @@ impl<R: Read + Seek> OggDemuxer<R> {
383 fn reset_state(&mut self) {371 fn reset_state(&mut self) {
384 self.queue.clear();372 self.queue.clear();
385 for track in &mut self.tracks {373 for track in &mut self.tracks {
386- track.partial.clear();374+ track.partial = None;
387- track.assembling = false;375+ track.pos = None;
388- track.pos_known = false;
389 track.eos = false;376 track.eos = false;
390 }377 }
391 }378 }
@@ -493,8 +480,7 @@ impl<R: Read + Seek + Send> Demuxer for OggDemuxer<R> {
493 self.inner.seek(SeekFrom::Start(self.data_start))?;480 self.inner.seek(SeekFrom::Start(self.data_start))?;
494 }481 }
495 let track = &mut self.tracks[index];482 let track = &mut self.tracks[index];
496- track.pos = granule;483+ track.pos = Some(granule);
497- track.pos_known = true;
498 Ok(())484 Ok(())
499 }485 }
500 }486 }
crates/ec-ogg/tests/real_library.rsdeleted+0 -315
@@ -1,315 +0,0 @@
1-//!
2-//! Per file the oracle checks:
3-//! - packet count and every packet's size (ffprobe, audio stream 0);
4-//! - the concatenated packet payloads (ffmpeg `-c copy -f data`), byte for byte;
5-//! - the header block: Opus's `OpusHead` against ffprobe's `extradata_size`
6-//! exactly; Vorbis's three Xiph-laced packets by their lacing and magic (see
7-//! below for why the size is not compared);
8-//! - timing: where a packet carries a pts, it equals ffprobe's pts after the
9-//! Opus pre-skip shift; where a page ends on a packet, the granule position
10-//! equals that packet's ffprobe end (pts + duration) after the same shift.
11-//!
12-//! Timing rule, as ffmpeg's Ogg demuxer applies it (measured on these files):
13-//! - Vorbis: granule = the sample position at the packet's end, at the stream
14-//! rate; ffmpeg's pts = granule - duration. No shift. The first packet is the
15-//! one exception: ffmpeg starts it at minus its own length, while ec-ogg, by
16-//! its documented convention, starts the stream at zero and states no
17-//! duration for a Vorbis packet. Its pts is therefore not compared; its
18-//! granule still is.
19-//! - Opus: granule counts 48 kHz samples *including* the pre-skip; ffmpeg's pts
20-//! = granule - pre_skip - duration, so the end is `granule - pre_skip`. Our
21-//! packet pts start at zero, so ours = ffmpeg's pts + pre_skip.
22-//!
23-//! Header block: ffmpeg's stated Vorbis extradata size differs from ours on
24-//! some files (ours keeps the comment header verbatim, which the remux path
25-//! relies on for bit-identical output). ffprobe does not expose the extradata
26-//! bytes, so the Vorbis block is checked structurally and the size difference
27-//! is reported, not failed.
28-//!
29-//! Scope: demux only. The decoded PCM is not compared here.
30-//!
31-
32-use std::path::Path;
33-
34-use ec_core::Demuxer;
35-use ec_ogg::{Mapping, OggDemuxer, granule_of};
36-
37-/// One packet as ffprobe reports it.
38-struct Probed {
39- pts: Option<i64>,
40- duration: Option<i64>,
41- size: usize,
42-}
43-
44-/// The verdict for one file, with the text the table prints.
45-enum Verdict {
46- Match(String),
47- Refused(String),
48- Failed(String),
49-}
50-
51-/// Parses an ffprobe csv cell: `N/A` and blanks are absent.
52-fn cell(s: &str) -> Option<i64> {
53- let s = s.trim();
54- if s.is_empty() || s == "N/A" {
55- None
56- } else {
57- s.parse().ok()
58- }
59-}
60-
61-/// Audio stream 0's packets: header packets are not among them, as with ours.
62-fn ffprobe_packets(path: &Path) -> Result<Vec<Probed>, String> {
63- let out = ec_testkit::ffprobe()
64- .args([
65- "-v",
66- "error",
67- "-select_streams",
68- "a:0",
69- "-show_entries",
70- "packet=pts,duration,size",
71- "-of",
72- "csv=p=0",
73- ])
74- .arg(path)
75- .output()
76- .map_err(|e| format!("ffprobe: {e}"))?;
77- if !out.status.success() {
78- return Err("ffprobe failed on the packets".into());
79- }
80- let mut packets = Vec::new();
81- for line in String::from_utf8_lossy(&out.stdout).lines() {
82- let f: Vec<&str> = line.split(',').collect();
83- if f.len() < 3 {
84- return Err(format!("unexpected ffprobe packet row: {line}"));
85- }
86- let size = cell(f[2]).ok_or_else(|| format!("no packet size in: {line}"))?;
87- packets.push(Probed {
88- pts: cell(f[0]),
89- duration: cell(f[1]),
90- size: size as usize,
91- });
92- }
93- Ok(packets)
94-}
95-
96-/// ffprobe's stated extradata size for audio stream 0.
97-fn ffprobe_extradata_size(path: &Path) -> Result<usize, String> {
98- let out = ec_testkit::ffprobe()
99- .args([
100- "-v",
101- "error",
102- "-select_streams",
103- "a:0",
104- "-show_entries",
105- "stream=extradata_size",
106- "-of",
107- "csv=p=0",
108- ])
109- .arg(path)
110- .output()
111- .map_err(|e| format!("ffprobe: {e}"))?;
112- let text = String::from_utf8_lossy(&out.stdout);
113- let first = text.lines().next().unwrap_or_default().trim_matches(',');
114- cell(first)
115- .map(|n| n as usize)
116- .ok_or_else(|| format!("no extradata_size: {text:?}"))
117-}
118-
119-/// ffmpeg's concatenated audio packet payloads, copied and not decoded.
120-fn ffmpeg_payload(path: &Path) -> Result<Vec<u8>, String> {
121- let out = ec_testkit::ffmpeg()
122- .args(["-v", "error", "-i"])
123- .arg(path)
124- .args(["-map", "0:a:0", "-c", "copy", "-f", "data", "-"])
125- .output()
126- .map_err(|e| format!("ffmpeg: {e}"))?;
127- if !out.status.success() {
128- return Err(format!(
129- "ffmpeg failed to copy the packets: {}",
130- String::from_utf8_lossy(&out.stderr).trim()
131- ));
132- }
133- Ok(out.stdout)
134-}
135-
136-/// Reads one file with ec-ogg and compares it with the oracle.
137-fn check_file(path: &Path) -> Verdict {
138- let file = match std::fs::File::open(path) {
139- Ok(f) => f,
140- Err(e) => return Verdict::Failed(format!("open: {e}")),
141- };
142- let mut demuxer = match OggDemuxer::open(file) {
143- Ok(d) => d,
144- Err(e) => {
145- let text = e.to_string();
146- if text.contains("no logical stream with a known mapping") {
147- return Verdict::Refused(text);
148- }
149- return Verdict::Failed(format!("open: {text}"));
150- }
151- };
152- let Some(mapping) = demuxer.mapping(0) else {
153- return Verdict::Refused("no audio stream with a known mapping".into());
154- };
155- let pre_skip = match mapping {
156- Mapping::Opus { pre_skip, .. } => i64::from(pre_skip),
157- _ => 0,
158- };
159- let streams = demuxer.streams().to_vec();
160- let block: &[u8] = streams[0].params.extradata.as_ref().map_or(&[], |b| &b[..]);
161- let vorbis = matches!(mapping, Mapping::Vorbis { .. });
162-
163- let mut ours = Vec::new();
164- loop {
165- match demuxer.next_packet() {
166- Ok(p) if p.stream == 0 => ours.push(p),
167- Ok(_) => {}
168- Err(e) if e.is_eof() => break,
169- Err(e) => return Verdict::Failed(format!("demux: {e}")),
170- }
171- }
172- if demuxer.damaged_pages() != 0 {
173- return Verdict::Failed(format!("{} damaged pages", demuxer.damaged_pages()));
174- }
175-
176- let probed = match ffprobe_packets(path) {
177- Ok(p) => p,
178- Err(e) => return Verdict::Failed(e),
179- };
180- let payload = match ffmpeg_payload(path) {
181- Ok(p) => p,
182- Err(e) => return Verdict::Failed(e),
183- };
184- let header_len = match ffprobe_extradata_size(path) {
185- Ok(n) => n,
186- Err(e) => return Verdict::Failed(e),
187- };
188-
189- let mut problems: Vec<String> = Vec::new();
190- if ours.len() != probed.len() {
191- problems.push(format!(
192- "packet count {} (ffprobe {})",
193- ours.len(),
194- probed.len()
195- ));
196- }
197- let size_bad = ours
198- .iter()
199- .zip(&probed)
200- .filter(|(p, q)| p.data.len() != q.size)
201- .count();
202- if size_bad > 0 {
203- problems.push(format!("{size_bad} packet sizes differ"));
204- }
205- let ours_payload: Vec<u8> = ours.iter().flat_map(|p| p.data.iter().copied()).collect();
206- if ours_payload != payload {
207- let at = ours_payload
208- .iter()
209- .zip(&payload)
210- .position(|(a, b)| a != b)
211- .unwrap_or(ours_payload.len().min(payload.len()));
212- problems.push(format!(
213- "payload differs: {} bytes vs ffmpeg {}, first difference at byte {at}",
214- ours_payload.len(),
215- payload.len()
216- ));
217- }
218- if vorbis {
219- if let Some(p) = vorbis_header_problem(block) {
220- problems.push(p);
221- }
222- } else if block.len() != header_len {
223- problems.push(format!(
224- "header block {} bytes (ffprobe extradata {header_len})",
225- block.len()
226- ));
227- }
228-
229- // Timing, checked on the pairs both sides state.
230- let mut pts_checked = 0usize;
231- let mut pts_bad = 0usize;
232- let mut granule_checked = 0usize;
233- let mut granule_bad = 0usize;
234- let mut first_timing: Option<String> = None;
235- for (i, (p, q)) in ours.iter().zip(&probed).enumerate() {
236- // The Vorbis first packet's start is the convention exception (see the
237- // module doc): not compared.
238- if let Some(pts) = p.pts.filter(|_| i > 0 || !vorbis) {
239- pts_checked += 1;
240- if q.pts.map(|f| f + pre_skip) != Some(pts) {
241- pts_bad += 1;
242- first_timing.get_or_insert(format!(
243- "packet {i}: pts {pts}, ffmpeg pts {:?} (+{pre_skip})",
244- q.pts
245- ));
246- }
247- }
248- if let Some(g) = granule_of(p) {
249- granule_checked += 1;
250- let end = q.pts.zip(q.duration).map(|(a, b)| a + b);
251- if end != Some(g - pre_skip) {
252- granule_bad += 1;
253- first_timing.get_or_insert(format!(
254- "packet {i}: granule {g}, ffmpeg end {end:?} (-{pre_skip})"
255- ));
256- }
257- }
258- }
259- if pts_bad > 0 {
260- problems.push(format!("{pts_bad} of {pts_checked} pts differ"));
261- }
262- if granule_bad > 0 {
263- problems.push(format!(
264- "{granule_bad} of {granule_checked} granule ends differ"
265- ));
266- }
267- if let Some(t) = first_timing {
268- problems.push(format!("first timing difference: {t}"));
269- }
270-
271- let summary = format!(
272- "{} packets, {} bytes, {} pts and {} granules checked",
273- ours.len(),
274- payload.len(),
275- pts_checked,
276- granule_checked
277- );
278- if problems.is_empty() {
279- Verdict::Match(summary)
280- } else {
281- Verdict::Failed(format!("{summary}; {}", problems.join("; ")))
282- }
283-}
284-
285-/// Our Vorbis header block: three Xiph-laced packets, identification,
286-/// comment and setup, each carrying its own magic. `None` when it is sound.
287-fn vorbis_header_problem(block: &[u8]) -> Option<String> {
288- let Ok(parts) = ec_ogg::xiph_unlace(block) else {
289- return Some("header block is not Xiph-laced".into());
290- };
291- if parts.len() != 3 {
292- return Some(format!("{} header packets, want 3", parts.len()));
293- }
294- for (part, kind) in parts.iter().zip([1u8, 3, 5]) {
295- if part.len() < 7 || part[0] != kind || &part[1..7] != b"vorbis" {
296- return Some(format!("header packet of kind {kind} lacks its magic"));
297- }
298- }
299- if parts[0].len() != 30 {
300- return Some(format!(
301- "identification header is {} bytes, want 30",
302- parts[0].len()
303- ));
304- }
305- None
306-}
307-
308-#[test]
309-fn real_library_ogg_streams_match_ffmpeg() {
310- let path = ec_testkit::fixture("open/sintel_trailer-480p.ogv");
311- match check_file(&path) {
312- Verdict::Match(s) => eprintln!("{}: match: {s}", path.display()),
313- Verdict::Refused(e) | Verdict::Failed(e) => panic!("{}: {e}", path.display()),
314- }
315-}
crates/ec-riff/examples/benchp1.rsdeleted+0 -68
@@ -1,68 +0,0 @@
1-//! benchp1: RIFF/WAVE read and write throughput for lanes/bench.md ("lane benchp1").
2-//!
3-//! usage:
4-//! benchp1 read <in.wav> [reps]
5-//! Opens the file and decodes every sample to i32 with `WavReader::read_all_i32`, `reps`
6-//! times (default 5), keeping the best wall time.
7-//! benchp1 write <in.wav> <out.wav> <riff|rf64> [reps]
8-//! Reads the samples once (untimed), then writes them back with `WavWriter` at the same
9-//! spec, `reps` times (default 5), keeping the best wall time. `riff` takes the default
10-//! header; `rf64` forces the RF64 header (rf64_threshold 0). The last output is kept at
11-//! <out.wav> for the md5 round-trip check.
12-use std::hint::black_box;
13-use std::time::Instant;
14-
15-use ec_riff::{RF64_THRESHOLD, WavOptions, WavReader, WavWriter};
16-
17-fn read_once(path: &str) -> (usize, f64) {
18- let t = Instant::now();
19- let mut reader = WavReader::open(path).expect("open wav");
20- let samples = reader.read_all_i32().expect("read samples");
21- let secs = t.elapsed().as_secs_f64();
22- black_box(&samples);
23- (samples.len(), secs)
24-}
25-
26-fn main() {
27- let args: Vec<String> = std::env::args().collect();
28- match args.get(1).map(String::as_str) {
29- Some("read") => {
30- let reps: usize = args.get(3).map_or(5, |s| s.parse().expect("reps"));
31- let bytes = std::fs::metadata(&args[2]).expect("stat").len();
32- let (samples, _) = read_once(&args[2]);
33- let best = (0..reps).map(|_| read_once(&args[2]).1).fold(f64::MAX, f64::min);
34- println!(
35- "samples={samples} bytes={bytes} best_read_s={best:.4} mb_s={:.2} reps={reps}",
36- bytes as f64 / best / 1e6
37- );
38- }
39- Some("write") => {
40- let (input, out, mode) = (&args[2], &args[3], args[4].as_str());
41- let reps: usize = args.get(5).map_or(5, |s| s.parse().expect("reps"));
42- let mut reader = WavReader::open(input).expect("open wav");
43- let spec = reader.spec();
44- let samples = reader.read_all_i32().expect("read samples");
45- let frames = samples.len() as u64 / u64::from(spec.channels);
46- let options = match mode {
47- "riff" => WavOptions { expected_frames: frames, rf64_threshold: RF64_THRESHOLD },
48- "rf64" => WavOptions { expected_frames: frames, rf64_threshold: 0 },
49- _ => panic!("mode must be riff or rf64"),
50- };
51- let data_bytes = samples.len() as u64 * u64::from(spec.bits_per_sample) / 8;
52- let mut best = f64::MAX;
53- for _ in 0..reps {
54- let t = Instant::now();
55- let mut w = WavWriter::create_with_options(out, spec, options).expect("create");
56- w.write_samples(&samples).expect("write samples");
57- w.finalize().expect("finalize");
58- best = best.min(t.elapsed().as_secs_f64());
59- }
60- println!(
61- "mode={mode} samples={} data_bytes={data_bytes} best_write_s={best:.4} mb_s={:.2} reps={reps}",
62- samples.len(),
63- data_bytes as f64 / best / 1e6
64- );
65- }
66- _ => panic!("usage: benchp1 read <in.wav> [reps] | write <in.wav> <out.wav> <riff|rf64> [reps]"),
67- }
68-}
crates/ec-riff/tests/it/rf64.rsmodified+0 -86
@@ -22,10 +22,6 @@ fn le64(bytes: &[u8], at: usize) -> u64 {
22 u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())22 u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
23 }23 }
24 24
25-fn le32(bytes: &[u8], at: usize) -> u32 {
26- u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
27-}
28-
29 /// Write `frames` frames of a ramp and return the finished file.25 /// Write `frames` frames of a ramp and return the finished file.
30 fn write_file(s: WavSpec, frames: usize, options: WavOptions) -> Vec<u8> {26 fn write_file(s: WavSpec, frames: usize, options: WavOptions) -> Vec<u8> {
31 let mut w = WavWriter::with_options(Cursor::new(Vec::new()), s, options).unwrap();27 let mut w = WavWriter::with_options(Cursor::new(Vec::new()), s, options).unwrap();
@@ -44,42 +40,6 @@ fn opts(frames: u64, threshold: u64) -> WavOptions {
44 }40 }
45 }41 }
46 42
47-#[test]
48-fn over_threshold_writes_rf64_with_exact_ds64_sizes() {
49- let s = spec(2, 16);
50- let frames = 1000;
51- let bytes = write_file(s, frames, opts(frames as u64, 64));
52-
53- assert_eq!(&bytes[0..4], b"RF64");
54- assert_eq!(le32(&bytes, 4), u32::MAX, "RIFF size is ds64's to hold");
55- assert_eq!(&bytes[8..12], b"WAVE");
56- assert_eq!(&bytes[12..16], b"ds64");
57- assert_eq!(le32(&bytes, 16), 28, "ds64 body without a table");
58-
59- let data_bytes = (frames * 4) as u64;
60- assert_eq!(le64(&bytes, 20), bytes.len() as u64 - 8, "riffSize");
61- assert_eq!(le64(&bytes, 28), data_bytes, "dataSize");
62- assert_eq!(le64(&bytes, 36), frames as u64, "sampleCount");
63- assert_eq!(le32(&bytes, 44), 0, "tableLength");
64-
65- // Stereo 16-bit is a plain PCM fmt with no fact chunk, then data with the sentinel.
66- let fmt = 48;
67- assert_eq!(&bytes[fmt..fmt + 4], b"fmt ");
68- // The `data` id sits right before its payload, at a fixed distance from the end.
69- let data = bytes.len() - 8 - data_bytes as usize;
70- assert_eq!(&bytes[data..data + 4], b"data");
71- assert_eq!(
72- le32(&bytes, data + 4),
73- u32::MAX,
74- "data size is ds64's to hold"
75- );
76-
77- let mut r = WavReader::new(Cursor::new(&bytes[..])).unwrap();
78- assert_eq!(r.spec(), s);
79- assert_eq!(r.duration(), Some(frames as u64));
80- assert_eq!(r.read_all_i32().unwrap().len(), frames * 2);
81-}
82-
83 #[test]43 #[test]
84 fn rf64_samples_match_the_riff_file_for_the_same_input() {44 fn rf64_samples_match_the_riff_file_for_the_same_input() {
85 for (channels, bits) in [(1u16, 8u16), (6, 24), (2, 16), (8, 32)] {45 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() {
101 }61 }
102 }62 }
103 63
104-#[test]
105-fn odd_rf64_data_gets_a_pad_byte_outside_its_size() {
106- let s = spec(1, 8);
107- let frames = 5;
108- let bytes = write_file(s, frames, opts(frames as u64, 1));
109- // 5 data bytes: one pad byte follows, counted by riffSize but not dataSize.
110- assert_eq!(bytes.len() % 2, 0);
111- assert_eq!(le64(&bytes, 20), bytes.len() as u64 - 8);
112- assert_eq!(le64(&bytes, 28), 5);
113- let r = WavReader::new(Cursor::new(&bytes[..])).unwrap();
114- assert_eq!(r.duration(), Some(5));
115-}
116-
117-#[test]
118-fn extensible_rf64_keeps_fact_and_its_saturating_count() {
119- let s = spec(6, 24);
120- let frames = 50;
121- let bytes = write_file(s, frames, opts(frames as u64, 1));
122- assert_eq!(&bytes[0..4], b"RF64");
123- // Extensible fmt is 40 bytes, so `fact` follows it at 48 + 8 + 40.
124- let fact = 48 + 8 + 40;
125- assert_eq!(&bytes[fact..fact + 4], b"fact");
126- assert_eq!(le32(&bytes, fact + 8), frames as u32);
127- let r = WavReader::new(Cursor::new(&bytes[..])).unwrap();
128- assert_eq!(r.spec(), s);
129- assert_eq!(r.duration(), Some(frames as u64));
130-}
131-
132-#[test]
133-fn under_threshold_stays_riff_byte_for_byte() {
134- let s = spec(2, 16);
135- let riff = write_file(s, 100, WavOptions::default());
136- let below = write_file(s, 100, opts(100, 400 + 1));
137- assert_eq!(riff, below);
138- assert_eq!(&riff[0..4], b"RIFF");
139- assert_eq!(le32(&riff, 4) as usize, riff.len() - 8);
140-}
141-
142-#[test]
143-fn unknown_length_is_riff_and_oversize_riff_is_refused() {
144- let s = spec(2, 16);
145- let bytes = write_file(s, 10, WavOptions::default());
146- assert_eq!(&bytes[0..4], b"RIFF");
147- assert_eq!(le32(&bytes, 4) as usize, bytes.len() - 8);
148-}
149-
150 /// Manual: writes 4.1 GiB of 16-bit stereo and reads its header back. Run with64 /// Manual: writes 4.1 GiB of 16-bit stereo and reads its header back. Run with
151 /// `cargo test -p ec-riff --test it rf64:: -- --ignored --nocapture`.65 /// `cargo test -p ec-riff --test it rf64:: -- --ignored --nocapture`.
152 #[test]66 #[test]