forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

common.rs276 lines, 7.3 KiBHistoryRawDownload
1//! Shared helpers: ffmpeg/ffprobe fixtures, packet dumps and the skip convention
2//! (`EC_REQUIRE_FIXTURES` turns a skip into a failure).
3#![allow(dead_code)]
4
5use std::collections::HashMap;
6use std::fs::File;
7use std::io::BufReader;
8use std::path::{Path, PathBuf};
9use std::process::Command;
10use std::sync::OnceLock;
11
12use ec_core::registry::Demuxer;
13use ec_mpegts::TsDemuxer;
14
15pub fn required() -> bool {
16 std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
17}
18
19/// True when ffmpeg and ffprobe can be run; otherwise prints a skip note (or panics
20/// when fixtures are required).
21pub fn have_ffmpeg() -> bool {
22 static OK: OnceLock<bool> = OnceLock::new();
23 let ok = *OK.get_or_init(|| {
24 ["ffmpeg", "ffprobe"].iter().all(|t| {
25 Command::new(t)
26 .arg("-version")
27 .output()
28 .is_ok_and(|o| o.status.success())
29 })
30 });
31 if !ok {
32 assert!(
33 !required(),
34 "EC_REQUIRE_FIXTURES is set but ffmpeg/ffprobe are missing"
35 );
36 eprintln!("skip: ffmpeg/ffprobe not available");
37 }
38 ok
39}
40
41pub fn fixture_dir() -> PathBuf {
42 static DIR: OnceLock<PathBuf> = OnceLock::new();
43 DIR.get_or_init(|| {
44 let d = std::env::temp_dir().join("ec-mpegts-fx");
45 std::fs::create_dir_all(&d).unwrap();
46 d
47 })
48 .clone()
49}
50
51pub const VIDEO_SRC: &[&str] = &[
52 "-f",
53 "lavfi",
54 "-i",
55 "testsrc2=size=320x240:rate=25:duration=3",
56];
57pub const AUDIO_SRC: &[&str] = &[
58 "-f",
59 "lavfi",
60 "-i",
61 "sine=frequency=440:sample_rate=48000:duration=3",
62];
63
64/// Runs ffmpeg; `Err` carries stderr. Unavailable encoders are a skip.
65pub fn ffmpeg(args: &[&str], out: &Path) -> Result<(), String> {
66 let o = Command::new("ffmpeg")
67 .args(["-v", "error", "-y"])
68 .args(args)
69 .arg(out)
70 .output()
71 .map_err(|e| e.to_string())?;
72 if o.status.success() {
73 Ok(())
74 } else {
75 Err(String::from_utf8_lossy(&o.stderr).into_owned())
76 }
77}
78
79/// Generates `name` with `args` (input options included) or returns `None` on skip.
80pub fn fixture(name: &str, args: &[&str]) -> Option<PathBuf> {
81 if !have_ffmpeg() {
82 return None;
83 }
84 // Tests run on threads of one process: one generates a given file at a time.
85 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
86 let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
87 let out = fixture_dir().join(name);
88 if out.exists() {
89 return Some(out);
90 }
91 let tmp = fixture_dir().join(format!("{name}.{}.tmp", std::process::id()));
92 match ffmpeg(args, &tmp) {
93 Ok(()) => {
94 std::fs::rename(&tmp, &out).unwrap();
95 Some(out)
96 }
97 Err(e) => {
98 assert!(!required(), "ffmpeg failed for {name}: {e}");
99 eprintln!("skip {name}: {e}");
100 None
101 }
102 }
103}
104
105pub fn open(path: &Path) -> TsDemuxer<BufReader<File>> {
106 TsDemuxer::new(BufReader::new(File::open(path).unwrap())).unwrap()
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct Pkt {
111 pub stream: u32,
112 pub pts: Option<i64>,
113 pub dts: Option<i64>,
114 pub key: bool,
115 pub off: u64,
116 pub data: Vec<u8>,
117}
118
119pub fn read_all(d: &mut TsDemuxer<BufReader<File>>) -> Vec<Pkt> {
120 let mut v = Vec::new();
121 while let Ok(p) = d.next_packet() {
122 v.push(Pkt {
123 stream: p.stream,
124 pts: p.pts,
125 dts: p.dts,
126 key: p.flags.keyframe,
127 off: d.last_packet_offset(),
128 data: p.data.to_vec(),
129 });
130 }
131 v
132}
133
134/// One row of `ffprobe -show_packets`.
135#[derive(Debug, Clone)]
136pub struct Row {
137 pub pid: u16,
138 pub pts: Option<i64>,
139 pub dts: Option<i64>,
140 pub dur: Option<i64>,
141 pub size: usize,
142 pub key: bool,
143}
144
145pub fn ffprobe_rows(path: &Path) -> HashMap<u16, (u32, Vec<Row>)> {
146 let streams = Command::new("ffprobe")
147 .args([
148 "-v",
149 "error",
150 "-show_entries",
151 "stream=index,id",
152 "-of",
153 "csv=p=0",
154 ])
155 .arg(path)
156 .output()
157 .unwrap();
158 let mut pid_of = HashMap::new();
159 for l in String::from_utf8_lossy(&streams.stdout).lines() {
160 let mut f = l.split(',');
161 let (Some(i), Some(id)) = (f.next(), f.next()) else {
162 continue;
163 };
164 if let (Ok(i), Some(h)) = (i.parse::<u32>(), id.strip_prefix("0x"))
165 && let Ok(p) = u16::from_str_radix(h, 16)
166 {
167 pid_of.insert(i, p);
168 }
169 }
170 let pk = Command::new("ffprobe")
171 .args([
172 "-v",
173 "error",
174 "-show_entries",
175 "packet=stream_index,pts,dts,duration,size,flags",
176 "-of",
177 "csv=p=0",
178 ])
179 .arg(path)
180 .output()
181 .unwrap();
182 let mut out: HashMap<u16, (u32, Vec<Row>)> = HashMap::new();
183 for l in String::from_utf8_lossy(&pk.stdout).lines() {
184 let f: Vec<&str> = l.split(',').collect();
185 if f.len() < 6 {
186 continue;
187 }
188 let si: u32 = f[0].parse().unwrap();
189 let Some(&pid) = pid_of.get(&si) else {
190 continue;
191 };
192 let num = |s: &str| s.parse::<i64>().ok();
193 out.entry(pid).or_insert((si, Vec::new())).1.push(Row {
194 pid,
195 pts: num(f[1]),
196 dts: num(f[2]),
197 dur: num(f[3]),
198 size: f[4].parse().unwrap(),
199 key: f[5].starts_with('K'),
200 });
201 }
202 out
203}
204
205/// ffmpeg's stream copy of stream `index`, as one byte string.
206pub fn ffmpeg_bytes(path: &Path, index: u32) -> Vec<u8> {
207 let o = Command::new("ffmpeg")
208 .args(["-v", "error", "-i"])
209 .arg(path)
210 .args([
211 "-map",
212 &format!("0:{index}"),
213 "-c",
214 "copy",
215 "-f",
216 "data",
217 "-",
218 ])
219 .output()
220 .unwrap();
221 o.stdout
222}
223
224/// ffmpeg's decode of an LPCM stream as big-endian 16-bit samples.
225pub fn ffmpeg_pcm_s16be(path: &Path, index: u32) -> Vec<u8> {
226 Command::new("ffmpeg")
227 .args(["-v", "error", "-i"])
228 .arg(path)
229 .args(["-map", &format!("0:{index}"), "-f", "s16be", "-"])
230 .output()
231 .unwrap()
232 .stdout
233}
234
235/// MPEG-2 CRC-32 (poly 0x04C11DB7, initial value all ones, no reflection).
236pub fn crc32(data: &[u8]) -> u32 {
237 let mut crc = 0xFFFF_FFFFu32;
238 for &b in data {
239 crc ^= u32::from(b) << 24;
240 for _ in 0..8 {
241 crc = if crc & 0x8000_0000 != 0 {
242 (crc << 1) ^ 0x04C1_1DB7
243 } else {
244 crc << 1
245 };
246 }
247 }
248 crc
249}
250
251/// FNV-1a over a byte iterator.
252pub fn fnv(bytes: impl Iterator<Item = u8>) -> u64 {
253 bytes.fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
254 (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
255 })
256}
257
258/// The committed fixtures directory (`tests/data`).
259pub fn data() -> PathBuf {
260 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data")
261}
262
263/// Seeded xorshift64 for the mutation tests.
264pub struct Rng(pub u64);
265
266impl Rng {
267 pub fn next(&mut self) -> u64 {
268 self.0 ^= self.0 << 13;
269 self.0 ^= self.0 >> 7;
270 self.0 ^= self.0 << 17;
271 self.0
272 }
273 pub fn below(&mut self, n: usize) -> usize {
274 (self.next() % n.max(1) as u64) as usize
275 }
276}