forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

probe.rs212 lines, 8.5 KiBHistoryRawDownload
1//! The BD gate's source arming, shared with `examples/enc_probe` (lane-probe).
2//!
3//! The probe used to build its own ffmpeg command line and dropped the gate's
4//! `-ss` seek, so it read film B's black leader and every census taken through
5//! it was probe-relative (59 kB where the gate's own ladder point coded 89 kB
6//! of the same title). One definition now serves both: the gate's
7//! `clip_frames_vf` and the probe both call [`source`], so the two can only
8//! differ in the arguments they pass, which
9//! `encode::tests::the_probe_arms_the_gates_source` pins.
10
11use crate::encode::Picture;
12use std::process::Command;
13
14/// The video stream's coded size, from ffprobe.
15#[must_use]
16pub fn dims(clip: &str) -> Option<(usize, usize)> {
17 let out = Command::new("ffprobe")
18 .args(["-v", "error", "-select_streams", "v:0"])
19 .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"])
20 .arg(clip)
21 .output()
22 .ok()?;
23 let text = String::from_utf8_lossy(&out.stdout);
24 let mut f = text.trim().split(',');
25 Some((
26 f.next()?.trim().parse().ok()?,
27 f.next()?.trim().parse().ok()?,
28 ))
29}
30
31/// The native BD gate's window on `clip`: a whole number of 128-wide
32/// superblocks, at most 1920x1024, out of the MIDDLE of the coded frame, with
33/// even offsets for 4:2:0 -- as an ffmpeg `crop` filter plus its size.
34///
35/// This lives here because the probe used to be handed the crop by hand, and
36/// a hand-written `crop=1920:1024:960:568` (a 2160-high frame that film B,
37/// coded 3840x1608, is not) put the instrument on different pixels than the
38/// gate: 60 kB where the gate's own q=150 point coded 90 kB.
39///
40/// # Panics
41/// When ffprobe cannot read the size, or the frame is under one superblock.
42#[must_use]
43pub fn gate_crop(clip: &str) -> (String, usize, usize) {
44 let (nw, nh) = dims(clip).expect("ffprobe gave no size");
45 let cw = nw.min(1920) / 128 * 128;
46 let ch = nh.min(1024) / 128 * 128;
47 assert!(
48 cw >= 128 && ch >= 128,
49 "{nw}x{nh} is smaller than a superblock"
50 );
51 let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
52 (format!("crop={cw}:{ch}:{x}:{y}"), cw, ch)
53}
54
55/// `frames` pictures of `clip` from `skip` through the filter chain `vf`, as
56/// planar 8-bit 4:2:0 at `width`x`height` -- the BD gate's loader recipe.
57///
58/// # Panics
59/// When ffmpeg cannot be run, fails, or delivers a different number of frames.
60#[must_use]
61pub fn source(
62 clip: &str,
63 skip: &str,
64 vf: &str,
65 width: usize,
66 height: usize,
67 frames: usize,
68) -> Vec<Picture> {
69 let out = Command::new("ffmpeg")
70 .args(["-v", "error", "-ss", skip, "-i", clip])
71 .args(["-frames:v", &frames.to_string()])
72 .args(["-vf", vf])
73 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
74 .output()
75 .expect("ffmpeg failed to run");
76 assert!(
77 out.status.success(),
78 "ffmpeg: {}",
79 String::from_utf8_lossy(&out.stderr)
80 );
81 let (luma, chroma) = (width * height, width * height / 4);
82 let frame_len = luma + 2 * chroma;
83 assert_eq!(
84 out.stdout.len(),
85 frame_len * frames,
86 "expected {frames} 4:2:0 frames"
87 );
88 (0..frames)
89 .map(|i| {
90 let b = &out.stdout[i * frame_len..][..frame_len];
91 Picture {
92 width,
93 height,
94 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
95 u: b[luma..luma + chroma]
96 .iter()
97 .map(|&v| u16::from(v))
98 .collect(),
99 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
100 }
101 })
102 .collect()
103}
104
105/// Runs a test-harness child (`aomenc`, `ffmpeg`) with `input` on its stdin
106/// and all three pipes drained concurrently, returning the child's
107/// [`std::process::Output`] (status, stdout, stderr) for the caller to
108/// assert on.
109///
110/// The ONE spawn path for every test that feeds a child on stdin
111/// (lane-av1-pipedrain). Writing the input INLINE before
112/// `wait_with_output()` deadlocks as soon as the child's stdout pipe buffer
113/// (~64 KiB) fills before the last input byte is written: the child blocks
114/// in write(2), the test blocks in `write_all`, both at 0% CPU until the
115/// harness timeout -- measured at 45 minutes on a 1.1 MB fixture decoding
116/// to 150 MB of raw frames (lane-t900 r10), and four aomenc gates still sat
117/// on the inline pattern after that fix. Here a writer thread owns stdin
118/// while the parent drains stdout/stderr, so a multi-MB y4m always meets a
119/// reader, never a blocked writer.
120///
121/// A child that exits early (bad flags, refused input) breaks the writer's
122/// pipe: the EPIPE from `write_all` is swallowed on purpose, and the
123/// child's own exit status and stderr -- which the caller asserts on --
124/// carry the real diagnosis.
125///
126/// # Panics
127/// When the child cannot be spawned or reaped, when the writer thread
128/// panics, or when the child is still running after the deadline (below):
129/// it is killed and the test fails naming the command, the timeout and the
130/// kill -- the CFL suite lost 11h41m to a wedged aomenc child because the
131/// pre-pipedrain spawn had no bound (class: aomenc-stdin-pipe-deadlock).
132///
133/// The deadline is 1800 s per child, overridable with
134/// `EC_AV1_CHILD_TIMEOUT_SECS`. Every legitimate child here is an
135/// aomenc/ffmpeg over an at-most-a-few-MB fixture: seconds, not minutes.
136#[cfg(test)]
137pub(crate) fn run_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output {
138 crate::tool_cache::cached_output(cmd, Some(input), |c| run_child_with_stdin(c, input))
139}
140
141#[cfg(test)]
142fn run_child_with_stdin(cmd: &mut Command, input: &[u8]) -> std::process::Output {
143 use std::io::{Read, Write};
144 use std::process::Stdio;
145 use std::time::{Duration, Instant};
146
147 let timeout = std::env::var("EC_AV1_CHILD_TIMEOUT_SECS")
148 .ok()
149 .and_then(|s| s.parse::<u64>().ok())
150 .map_or(Duration::from_secs(1800), Duration::from_secs);
151
152 cmd.stdin(Stdio::piped())
153 .stdout(Stdio::piped())
154 .stderr(Stdio::piped());
155 let mut child = cmd.spawn().expect("encoder failed to start");
156 let mut stdin = child.stdin.take().expect("encoder stdin");
157 let mut stdout = child.stdout.take().expect("encoder stdout");
158 let mut stderr = child.stderr.take().expect("encoder stderr");
159 let program = cmd.get_program().to_string_lossy().into_owned();
160
161 let payload = input.to_vec();
162 let writer = std::thread::spawn(move || {
163 let _ = stdin.write_all(&payload);
164 });
165 // Both output pipes drained from the first millisecond: the child can
166 // never wedge on a full stdout/stderr pipe while we are still writing
167 // stdin (the pre-pipedrain inline `write_all` + `wait_with_output`
168 // pattern that deadlocked the CFL suite's census gate).
169 let out_reader = std::thread::spawn(move || {
170 let mut buf = Vec::new();
171 let _ = stdout.read_to_end(&mut buf);
172 buf
173 });
174 let err_reader = std::thread::spawn(move || {
175 let mut buf = Vec::new();
176 let _ = stderr.read_to_end(&mut buf);
177 buf
178 });
179
180 let deadline = Instant::now() + timeout;
181 let status = loop {
182 match child.try_wait().expect("encoder status") {
183 Some(status) => break status,
184 None if Instant::now() >= deadline => {
185 let _ = child.kill();
186 let killed = child.wait().expect("encoder reap");
187 // The dead child closed every pipe, so all three threads
188 // are out of their syscalls: the joins below are bounded.
189 let _ = writer.join();
190 let _ = out_reader.join();
191 let _ = err_reader.join();
192 panic!(
193 "{program}: still running {secs}s after spawn -- killed ({killed}). \
194 A live child here hangs the whole suite, which is how the CFL run lost \
195 11h41m to aomenc wedged in anon_pipe_write \
196 (class: aomenc-stdin-pipe-deadlock). Check its wchan/fds before blaming \
197 the decoder.",
198 secs = timeout.as_secs(),
199 );
200 }
201 None => std::thread::sleep(Duration::from_millis(50)),
202 }
203 };
204 let out = out_reader.join().expect("encoder stdout reader thread");
205 let err = err_reader.join().expect("encoder stderr reader thread");
206 writer.join().expect("encoder stdin writer thread");
207 std::process::Output {
208 status,
209 stdout: out,
210 stderr: err,
211 }
212}