forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

av1_software_export.rs331 lines, 13.0 KiBHistoryRawDownload
1//! The software export seat for AV1: the still-frame path (`compose_at`, which
2//! the export's decoder feeds) and a short software export, for sources the
3//! export used to refuse outright -- `ec-av1` is the decoder, the same one
4//! playback runs in software.
5//!
6//! ```text
7//! cargo test -p engine --release --test av1_software_export -- --nocapture
8//! ```
9
10use std::path::PathBuf;
11use std::time::{Duration, Instant};
12
13use engine::Clip;
14use engine::PlaybackSession;
15use engine::decode::Frame;
16use engine::demux::{Codec, Demuxer};
17use engine::export::{EncoderSeat, ExportSettings};
18use engine::project::{Lane, Speed};
19use engine::scale::FitPolicy;
20use engine::scratch::Scratch;
21
22fn asset(name: &str) -> PathBuf {
23 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
24 .join("../../assets")
25 .join(name)
26}
27
28/// Opens a session silently, the way the server opens one: no seat is pinned,
29/// so a machine with the plugin takes the hardware seat first and falls back
30/// to `ec-av1` exactly as a server session does.
31fn open(name: &str) -> PlaybackSession {
32 engine::ao::set_silent_output();
33 PlaybackSession::open(asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"))
34}
35
36/// Mean and standard deviation of BT.601 luma over a BGRA frame.
37fn luma_stats(bgra: &[u8]) -> (f64, f64) {
38 let ys: Vec<f64> = bgra
39 .as_chunks::<4>().0.iter()
40 .map(|p| 0.114 * f64::from(p[0]) + 0.587 * f64::from(p[1]) + 0.299 * f64::from(p[2]))
41 .collect();
42 let n = ys.len().max(1) as f64;
43 let mean = ys.iter().sum::<f64>() / n;
44 let var = ys.iter().map(|y| (y - mean) * (y - mean)).sum::<f64>() / n;
45 (mean, var.sqrt())
46}
47
48/// The first `count` pictures of an AV1 file as `ec-av1` decodes them, luma
49/// only, 8-bit (a 10-bit file's samples shifted down by two, as the seats do).
50/// Decoded straight from the demuxer's access units -- no export code between
51/// the reference and the picture under test.
52fn reference_luma(name: &str, count: usize) -> Vec<(usize, usize, Vec<u8>)> {
53 let (meta, mut demuxer) = Demuxer::open(&asset(name)).expect("demux");
54 assert_eq!(meta.codec, Codec::Av1, "{name} is AV1");
55 let shift = demuxer.bit_depth() - 8;
56 let mut stream = Vec::new();
57 while let Some(au) = demuxer.next_access_unit().expect("read") {
58 stream.extend_from_slice(&au);
59 }
60 let mut out = Vec::new();
61 let _ = ec_av1::stream::decode_stream_with(&stream, |picture, _, shown| {
62 if shown {
63 let y = picture.y.iter().map(|&s| (s >> shift) as u8).collect();
64 out.push((picture.width, picture.height, y));
65 }
66 if out.len() >= count {
67 return Err(ec_core::Error::Eof);
68 }
69 Ok(())
70 });
71 assert!(
72 out.len() >= count,
73 "{name}: {} pictures, wanted {count}",
74 out.len()
75 );
76 out.truncate(count);
77 out
78}
79
80/// Pearson correlation of two equal-length series.
81fn correlation(a: &[f64], b: &[f64]) -> f64 {
82 let n = a.len() as f64;
83 let (ma, mb) = (a.iter().sum::<f64>() / n, b.iter().sum::<f64>() / n);
84 let (mut cov, mut va, mut vb) = (0.0, 0.0, 0.0);
85 for (x, y) in a.iter().zip(b) {
86 cov += (x - ma) * (y - mb);
87 va += (x - ma) * (x - ma);
88 vb += (y - mb) * (y - mb);
89 }
90 cov / (va.sqrt() * vb.sqrt()).max(f64::MIN_POSITIVE)
91}
92
93/// The composed picture at `frame` must sit on the reference picture: same
94/// luma within what the BGRA round trip costs, and not a flat black or grey
95/// plane. Returns the composed frame for the caller's own checks.
96fn assert_composes_like_reference(
97 session: &PlaybackSession,
98 name: &str,
99 frame: u32,
100 source_frame: u32,
101) -> Frame {
102 let reference = reference_luma(name, source_frame as usize + 1);
103 let (rw, rh, ref_y) = &reference[source_frame as usize];
104 let f = session
105 .compose_at(frame, *rw as u32, *rh as u32)
106 .unwrap_or_else(|e| panic!("compose {name} frame {frame}: {e}"));
107 assert_eq!((f.width as usize, f.height as usize), (*rw, *rh), "{name}");
108 let (mean, sd) = luma_stats(&f.bgra);
109 let ref_mean = ref_y.iter().map(|&y| f64::from(y)).sum::<f64>() / ref_y.len() as f64;
110 eprintln!(
111 "{name} frame {frame}: composed luma mean {mean:.1} sd {sd:.1}; reference mean {ref_mean:.1}"
112 );
113 assert!(
114 mean > 16.0 && sd > 1.0,
115 "{name}: black or flat ({mean:.1}, {sd:.1})"
116 );
117 // Pixel by pixel: the composed luma of each pixel against the reference's.
118 // The BGRA round trip re-maps range and matrix, so the test asks for the
119 // same picture (correlation), not the same code values.
120 let ours: Vec<f64> = f
121 .bgra
122 .as_chunks::<4>().0.iter()
123 .map(|p| 0.114 * f64::from(p[0]) + 0.587 * f64::from(p[1]) + 0.299 * f64::from(p[2]))
124 .collect();
125 let theirs: Vec<f64> = ref_y.iter().map(|&y| f64::from(y)).collect();
126 let corr = correlation(&ours, &theirs);
127 eprintln!("{name} frame {frame}: luma correlation with the reference {corr:.4}");
128 assert!(
129 corr > 0.95,
130 "{name}: composed picture is not the reference picture (r {corr:.4})"
131 );
132 f
133}
134
135#[test]
136fn compose_at_takes_an_8_bit_av1_source() {
137 let session = open("test_av1.mkv");
138 let a = assert_composes_like_reference(&session, "test_av1.mkv", 0, 0);
139 // A later frame, past the first GOP's keyframe and into its inter frames.
140 assert_composes_like_reference(&session, "test_av1.mkv", 15, 15);
141 // Deterministic: the same frame again is the same picture.
142 let b = session
143 .compose_at(0, a.width, a.height)
144 .expect("frame 0 again");
145 assert!(a.bgra == b.bgra, "two composes of frame 0 differ");
146}
147
148#[test]
149fn compose_at_takes_a_ten_bit_av1_source() {
150 let session = open("test_av1_10.mkv");
151 assert_composes_like_reference(&session, "test_av1_10.mkv", 0, 0);
152 assert_composes_like_reference(&session, "test_av1_10.mkv", 10, 10);
153}
154
155#[test]
156fn compose_at_takes_an_mp4_av1_source_with_vui() {
157 let session = open("test_vui_av1.mp4");
158 assert_composes_like_reference(&session, "test_vui_av1.mp4", 0, 0);
159 assert_composes_like_reference(&session, "test_vui_av1.mp4", 15, 15);
160}
161
162/// The regression: an AV1 clip placed mid-timeline, with a non-zero in-point,
163/// composed at a frame inside it -- the path the server's `frame {at}` takes.
164/// Before the hardware-fallback fix this reported "ends before frame". The
165/// clip is source 15..45 placed at timeline frame 60, so timeline 60 is
166/// source 15 and timeline 75 is source 30.
167#[test]
168fn a_mid_clip_av1_frame_composes_with_a_start_and_an_in_point() {
169 let mut session = open("test_av1.mkv");
170 assert!(session.delete_clip(Lane::V1, 0), "drop the whole-file clip");
171 let clip = Clip {
172 speed_keys: Vec::new(),
173 reversed: false,
174 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
175 angle: Default::default(),
176 fade_in: 0,
177 fade_out: 0,
178 transition_out: 0,
179 transition_kind: Default::default(),
180 visualizer: 0,
181 viz_paint: 0,
182 gain_db: 0.0,
183 gain_keys: Vec::new(),
184 pan: 0,
185 pitch: 0.0,
186 transform_keys: Vec::new(),
187 opacity_keys: Vec::new(),
188 color_keys: Vec::new(),
189 effects: Vec::new(),
190 start: 60,
191 in_frame: 15,
192 out_frame: 45,
193 source: 0,
194 link: None,
195 eq: None,
196 color: None,
197 fit: FitPolicy::default(),
198 speed: Speed::NORMAL,
199 transform: None,
200 };
201 assert!(session.place_at(Lane::V1, 2.0, clip), "place it at 2 s");
202 assert_composes_like_reference(&session, "test_av1.mkv", 60, 15);
203 assert_composes_like_reference(&session, "test_av1.mkv", 75, 30);
204 // The last frame of the clip: timeline 89, source 44.
205 session
206 .compose_at(89, 1280, 720)
207 .expect("the clip's last frame composes");
208}
209
210/// The source-frame path the server's `frame {source}` takes, through the same
211/// decoder the playback worker opens: a frame past the first GOP, of each
212/// source the robustness pass named.
213#[test]
214fn a_source_frame_decodes_at_a_mid_stream_index() {
215 for name in ["test_av1.mkv", "test_av1_10.mkv", "test_vui_av1.mp4"] {
216 let path = asset(name);
217 let (_, rx, cancel) = engine::DecodeSession::open_range(&path, 15, 16)
218 .unwrap_or_else(|e| panic!("open {name}: {e}"));
219 let frame = rx
220 .recv()
221 .unwrap_or_else(|_| panic!("{name}: source frame 15 is past the end"));
222 cancel.store(true, std::sync::atomic::Ordering::Relaxed);
223 assert!(
224 frame.bgra.iter().any(|&b| b != 0),
225 "{name}: frame 15 is black"
226 );
227 }
228}
229
230/// A three-frame, 64x64 source: the stream is shorter than a GOP and the
231/// hardware seat gives it nothing. Compose and a full export must still work.
232#[test]
233fn a_tiny_av1_source_composes_and_exports() {
234 let session = open("test_av1_420.mkv");
235 assert_composes_like_reference(&session, "test_av1_420.mkv", 0, 0);
236 let session = open("test_av1_420.mkv");
237 let out = Scratch::file("ve_av1_tiny_export", "mp4");
238 let settings = ExportSettings {
239 seat: EncoderSeat::Software,
240 ..Default::default()
241 };
242 let handle = session.export_to_with(&out, &settings);
243 let started = Instant::now();
244 while !handle.is_finished() {
245 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
246 std::thread::sleep(Duration::from_millis(20));
247 }
248 handle.result().expect("outcome").expect("the tiny export");
249 let (meta, _) = Demuxer::open(&out).expect("reopen the tiny export");
250 assert_eq!(meta.frame_count, 3, "every frame of the tiny source");
251 std::fs::remove_file(&out).unwrap();
252}
253
254#[test]
255fn a_short_software_export_of_an_av1_source_succeeds() {
256 for name in ["test_av1.mkv", "test_av1_10.mkv"] {
257 let mut session = open(name);
258 assert!(session.cut_at(3.0 / 30.0), "three frames of it");
259 assert!(
260 session.delete_clip(Lane::V1, 1),
261 "drop everything after them"
262 );
263 let out = Scratch::file(&format!("ve_av1_sw_export_{name}"), "mp4");
264 let settings = ExportSettings {
265 seat: EncoderSeat::Software,
266 ..Default::default()
267 };
268 let handle = session.export_to_with(&out, &settings);
269 let started = Instant::now();
270 while !handle.is_finished() {
271 assert!(
272 started.elapsed() < Duration::from_secs(600),
273 "{name}: export hung"
274 );
275 std::thread::sleep(Duration::from_millis(20));
276 }
277 handle
278 .result()
279 .expect("outcome")
280 .unwrap_or_else(|e| panic!("{name}: software export refused: {e}"));
281 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
282 assert_eq!(meta.frame_count, 3, "{name}: every timeline frame is there");
283 std::fs::remove_file(&out).unwrap();
284 }
285}
286
287/// AV1 4:2:2, 4:4:4 and 12-bit open in both containers, at the depth they state.
288#[test]
289fn av1_422_444_and_12_bit_open_in_both_containers() {
290 for (name, depth) in [("test_av1_422", 8), ("test_av1_444", 8), ("test_av1_12bit", 12)] {
291 for ext in ["mkv", "mp4"] {
292 let file = asset(&format!("{name}.{ext}"));
293 let (_, demuxer) = Demuxer::open(&file).unwrap_or_else(|e| panic!("{name}.{ext}: {e}"));
294 assert!(demuxer.bit_depth() >= depth, "{name}.{ext}: {}", demuxer.bit_depth());
295 }
296 }
297}
298
299/// A 4:2:2 AV1 source (libaom, generated here) and the 12-bit fixture export end
300/// to end on the software seat: every frame comes out, in a file that reopens.
301#[test]
302fn a_422_and_a_12_bit_av1_source_export_end_to_end() {
303 let clip = Scratch::file("ve_av1_422_src", "mkv");
304 let made = std::process::Command::new("ffmpeg")
305 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=128x96:rate=30:duration=1"])
306 .args(["-frames:v", "6", "-c:v", "libaom-av1", "-cpu-used", "8", "-crf", "20", "-b:v", "0"])
307 .args(["-pix_fmt", "yuv422p"])
308 .arg(&*clip)
309 .output()
310 .expect("ffmpeg");
311 assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
312 for (label, path) in [("422", PathBuf::from(&*clip)), ("12bit", asset("test_av1_12bit.mkv"))] {
313 engine::ao::set_silent_output();
314 let session = PlaybackSession::open(&path).unwrap_or_else(|e| panic!("{label}: {e}"));
315 let (source, _) = Demuxer::open(&path).unwrap();
316 let out = Scratch::file(&format!("ve_av1_{label}_export"), "mp4");
317 let settings = ExportSettings {
318 seat: EncoderSeat::Software,
319 ..Default::default()
320 };
321 let handle = session.export_to_with(&out, &settings);
322 let started = Instant::now();
323 while !handle.is_finished() {
324 assert!(started.elapsed() < Duration::from_secs(600), "{label}: export hung");
325 std::thread::sleep(Duration::from_millis(20));
326 }
327 handle.result().expect("outcome").unwrap_or_else(|e| panic!("{label}: {e}"));
328 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
329 assert_eq!(meta.frame_count, source.frame_count, "{label}: every frame");
330 }
331}