forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

reallib.rs206 lines, 7.1 KiBHistoryRawDownload
1//! The ffmpeg and ffprobe references the real-library witnesses compare against,
2//! and the MD5 ffprobe prints for a packet's payload. Included by path from the
3//! `real_library_*` tests; not a test target of its own.
4#![allow(dead_code)]
5
6use std::collections::HashMap;
7use std::io::{BufReader, Read};
8use std::path::Path;
9use std::process::{Child, ChildStdout, Command, Stdio};
10
11/// True when `tool -version` runs. A tool that is absent skips its witness.
12pub fn have(tool: &str) -> bool {
13 Command::new(tool)
14 .arg("-version")
15 .stdout(Stdio::null())
16 .stderr(Stdio::null())
17 .status()
18 .map(|s| s.success())
19 .unwrap_or(false)
20}
21
22/// One stream as ffprobe states it.
23#[derive(Debug, Clone)]
24pub struct FfStream {
25 pub index: u32,
26 pub kind: String,
27 pub tag: String,
28 pub time_base: String,
29 pub width: Option<u32>,
30 pub height: Option<u32>,
31 pub sample_rate: Option<u32>,
32 pub channels: Option<u16>,
33 pub start_time: Option<f64>,
34 pub duration_ts: Option<i64>,
35}
36
37/// One packet row of `ffprobe -show_packets -show_data_hash md5`.
38#[derive(Debug, Clone)]
39pub struct FfPacket {
40 pub stream: u32,
41 pub pts: Option<i64>,
42 pub dts: Option<i64>,
43 pub duration: Option<i64>,
44 pub size: usize,
45 pub key: bool,
46 pub md5: String,
47}
48
49fn opt<T: std::str::FromStr>(field: &str) -> Option<T> {
50 field.trim().parse().ok()
51}
52
53/// Every stream of the file, in ffprobe's index order. Read as `key=value`
54/// lines, a new stream starting at each `index=` line, because ffprobe's CSV
55/// drops the fields a stream does not have and so cannot be read by column.
56pub fn ffprobe_streams(path: &Path) -> Vec<FfStream> {
57 let out = Command::new("ffprobe")
58 .args(["-v", "error", "-show_entries"])
59 .arg("stream=index,codec_type,codec_tag_string,time_base,width,height,sample_rate,channels,start_time,duration_ts")
60 .args(["-of", "default=noprint_wrappers=1"])
61 .arg(path)
62 .output()
63 .expect("run ffprobe");
64 assert!(out.status.success(), "ffprobe failed on {}", path.display());
65 let mut streams: Vec<HashMap<String, String>> = Vec::new();
66 for line in String::from_utf8_lossy(&out.stdout).lines() {
67 let Some((key, value)) = line.split_once('=') else {
68 continue;
69 };
70 if key == "index" {
71 streams.push(HashMap::new());
72 }
73 if let Some(cur) = streams.last_mut() {
74 cur.insert(key.to_string(), value.to_string());
75 }
76 }
77 streams
78 .iter()
79 .map(|f| {
80 let get = |k: &str| f.get(k).map(String::as_str).unwrap_or("N/A");
81 FfStream {
82 index: opt(get("index")).expect("stream index"),
83 kind: get("codec_type").to_string(),
84 tag: get("codec_tag_string").to_string(),
85 time_base: get("time_base").to_string(),
86 width: opt(get("width")),
87 height: opt(get("height")),
88 sample_rate: opt(get("sample_rate")),
89 channels: opt(get("channels")),
90 start_time: opt(get("start_time")),
91 duration_ts: opt(get("duration_ts")),
92 }
93 })
94 .collect()
95}
96
97/// Every packet of the file, in ffprobe's interleaved (decode-time) order.
98pub fn ffprobe_packets(path: &Path) -> Vec<FfPacket> {
99 let out = Command::new("ffprobe")
100 .args(["-v", "error", "-show_packets", "-show_data_hash", "md5"])
101 .args(["-show_entries"])
102 .arg("packet=stream_index,pts,dts,duration,size,flags,data_hash")
103 .args(["-of", "csv=p=0"])
104 .arg(path)
105 .output()
106 .expect("run ffprobe");
107 assert!(out.status.success(), "ffprobe failed on {}", path.display());
108 String::from_utf8_lossy(&out.stdout)
109 .lines()
110 .map(|line| {
111 let f: Vec<&str> = line.split(',').collect();
112 FfPacket {
113 stream: opt(f[0]).expect("stream index"),
114 pts: opt(f[1]),
115 dts: opt(f[2]),
116 duration: opt(f[3]),
117 size: opt(f[4]).expect("size"),
118 key: f[5].starts_with('K'),
119 md5: f[6].trim_start_matches("MD5:").to_string(),
120 }
121 })
122 .collect()
123}
124
125/// A child process whose stdout is read in exact pieces, stderr silenced.
126pub fn ffmpeg_pipe(args: &[&str], path: &Path) -> (Child, BufReader<ChildStdout>) {
127 let mut child = Command::new("ffmpeg")
128 .args(["-v", "error", "-nostdin", "-i"])
129 .arg(path)
130 .args(args)
131 .stdout(Stdio::piped())
132 .stderr(Stdio::null())
133 .spawn()
134 .expect("run ffmpeg");
135 let stdout = child.stdout.take().expect("piped stdout");
136 (child, BufReader::with_capacity(1 << 20, stdout))
137}
138
139/// Fills `buf` from `r`, returning how many bytes arrived (short only at EOF).
140pub fn fill(r: &mut impl Read, buf: &mut [u8]) -> usize {
141 let mut got = 0;
142 while got < buf.len() {
143 match r.read(&mut buf[got..]) {
144 Ok(0) => break,
145 Ok(n) => got += n,
146 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
147 Err(e) => panic!("reading ffmpeg output: {e}"),
148 }
149 }
150 got
151}
152
153/// RFC 1321 MD5 as lowercase hex, the digest ffprobe's `data_hash` prints.
154pub fn md5_hex(data: &[u8]) -> String {
155 const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
156 let k: [u32; 64] =
157 std::array::from_fn(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32);
158 let (mut a0, mut b0, mut c0, mut d0) = (
159 0x6745_2301u32,
160 0xefcd_ab89u32,
161 0x98ba_dcfeu32,
162 0x1032_5476u32,
163 );
164 let mut msg = data.to_vec();
165 let bits = (data.len() as u64).wrapping_mul(8);
166 msg.push(0x80);
167 while msg.len() % 64 != 56 {
168 msg.push(0);
169 }
170 msg.extend_from_slice(&bits.to_le_bytes());
171 for block in msg.as_chunks::<64>().0 {
172 let m: [u32; 16] = std::array::from_fn(|i| {
173 u32::from_le_bytes(block[4 * i..4 * i + 4].try_into().unwrap())
174 });
175 let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
176 for i in 0..64 {
177 let (f, g) = match i / 16 {
178 0 => ((b & c) | (!b & d), i),
179 1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
180 2 => (b ^ c ^ d, (3 * i + 5) % 16),
181 _ => (c ^ (b | !d), (7 * i) % 16),
182 };
183 let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
184 a = d;
185 d = c;
186 c = b;
187 b = b.wrapping_add(f.rotate_left(S[(i / 16) * 4 + i % 4]));
188 }
189 a0 = a0.wrapping_add(a);
190 b0 = b0.wrapping_add(b);
191 c0 = c0.wrapping_add(c);
192 d0 = d0.wrapping_add(d);
193 }
194 [a0, b0, c0, d0]
195 .iter()
196 .flat_map(|w| w.to_le_bytes())
197 .map(|b| format!("{b:02x}"))
198 .collect()
199}
200
201#[test]
202fn md5_matches_the_rfc_vectors() {
203 assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
204 assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
205 assert_eq!(md5_hex(&[b'a'; 1000]), "cabe45dcc9ae5b66ba86600cca6b8ba8");
206}