forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

anamorphic.rs495 lines, 19.3 KiBHistoryRawDownload
1//! The sample aspect ratio: a file whose pixels are not square is drawn
2//! wider than they are stored, and every rendition this engine makes --
3//! the probe, the preview and the export -- is the drawn one.
4//!
5//! `test_anamorphic.mp4` and `test_anamorphic.mkv` (`scripts/gen_fixtures.sh`)
6//! are one 1440x1080 source with `setsar=4/3` asked of it: the classic
7//! anamorphic 16:9 frame on a 4:3 raster, the way a DVD rip says "widen me".
8//! The engine's answer is ffmpeg's own: the decode keeps the coded pixels,
9//! the container's ratio is read as metadata, and the stretch is applied
10//! exactly once, at the conversion to the square-pixel raster -- so the
11//! preview shows 1920x1080 and the corners of it are picture, not bars.
12//!
13//! The copy door is the other half of ffmpeg's behaviour: a copied file
14//! keeps the coded pixels and carries the ratio beside them (Matroska's
15//! `Display*` elements), and where the container cannot state it -- an mp4
16//! has no `pasp` in this writer -- a copy refuses by name rather than
17//! writing a header that lies about its own shape.
18//!
19//! ```text
20//! cargo test -p engine --release --test anamorphic -- --test-threads=1
21//! ```
22
23use std::path::PathBuf;
24use std::sync::Once;
25use std::time::{Duration, Instant};
26
27use engine::demux::Demuxer;
28use engine::export::{ExportSettings, Format};
29use engine::scratch::Scratch;
30use engine::PlaybackSession;
31
32fn asset(name: &str) -> PathBuf {
33 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
34 .join("../../assets")
35 .join(name)
36}
37
38/// Which seat an export takes is decided by *process-wide* environment
39/// variables, so a test binary that shares the machine has to borrow them
40/// rather than assume: this pins both decode and encode to software, which is
41/// the seat every machine has, and holds the borrow for the whole test binary.
42static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(());
43
44type Shared = std::sync::RwLockReadGuard<'static, ()>;
45
46#[must_use = "the seat pin holds only while its guard is alive"]
47fn pin_software() -> Shared {
48 let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner());
49 static PIN: Once = Once::new();
50 PIN.call_once(|| {
51 engine::envcfg::set("VE_SW", "1");
52 engine::envcfg::set("VE_SW_ENC", "1");
53 });
54 borrowed
55}
56
57/// Whether the VA-API plugin is here. `probe` is no answer for this: `pin_software`
58/// pins `VE_SW` for the whole binary, and a pinned probe says "software" on any box.
59/// The HEVC export tests need the plugin to read their source back, so this is
60/// the question they ask.
61fn plugin_here() -> bool {
62 engine::hw::caps().is_some()
63}
64
65fn wait(handle: &engine::ExportHandle, limit: Duration) -> engine::Result<()> {
66 let started = Instant::now();
67 while !handle.is_finished() {
68 assert!(
69 started.elapsed() < limit,
70 "export did not finish in {limit:?}"
71 );
72 std::thread::sleep(Duration::from_millis(20));
73 }
74 handle.result().expect("a finished export has an outcome")
75}
76
77/// The coded and displayed shapes every anamorphic test here agrees on:
78/// 1440x1080 stored, 4/3 drawn, 1920x1080 shown.
79const CODED: (u32, u32) = (1440, 1080);
80const DISPLAY: (u32, u32) = (1920, 1080);
81
82/// The reduced form of `h/v`, so a ratio stated unreduced (a DAR pair like
83/// ffmpeg's 17280/12960) compares equal to its simplest spelling.
84fn gcd(mut a: u32, mut b: u32) -> u32 {
85 while b != 0 {
86 (a, b) = (b, a % b);
87 }
88 a.max(1)
89}
90
91/// The header says what the samples are and what they are drawn at, and both
92/// doors say the same thing about the same picture.
93#[test]
94fn the_container_aspect_is_probed_off_both_doors() {
95 for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] {
96 let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture");
97 assert_eq!(
98 (meta.coded_width, meta.coded_height),
99 CODED,
100 "{file}: the samples are stored at the coded size"
101 );
102 assert_eq!(
103 (meta.width, meta.height),
104 DISPLAY,
105 "{file}: 4/3 over 1440x1080 is drawn 1920x1080"
106 );
107 // The mkv door reads ffmpeg's DAR spelling (16/9) and the mp4 door the
108 // SAR itself (4/3); both name the same drawn picture, so the test
109 // compares the reduced ratio, not the spelling.
110 let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v);
111 let g = gcd(h, v);
112 assert_eq!(
113 (h / g, v / g),
114 (4, 3),
115 "{file}: the ratio one coded pixel is drawn at"
116 );
117 assert!(!meta.pixel_aspect.is_square(), "{file}: it is not square");
118 assert_eq!(
119 meta.rotation,
120 engine::Rotation::None,
121 "{file}: no turn was asked of it"
122 );
123 }
124 // A square-pixel file states none of it, and both doors answer square:
125 // the default that makes the whole feature invisible to the ordinary
126 // library.
127 for file in ["test_baseline.mp4", "test_rotation90.mp4"] {
128 let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture");
129 assert!(
130 meta.pixel_aspect.is_square(),
131 "{file}: no container said an aspect, so the pixels are square"
132 );
133 // Drawn one to one: the displayed pair is the coded pair, swapped
134 // where the file's matrix turns it and never widened.
135 let (dw, dh) = match meta.rotation.swaps_axes() {
136 true => (meta.coded_height, meta.coded_width),
137 false => (meta.coded_width, meta.coded_height),
138 };
139 assert_eq!(
140 (meta.width, meta.height),
141 (dw, dh),
142 "{file}: drawn one to one, swapped only by the turn"
143 );
144 }
145 // The rotation still swaps on an anamorphic file whose *matrix* asks for
146 // a turn: the composition is stretch the coded width, then swap -- the
147 // order the render applies ([`crate::decode::Render::frame`]). The
148 // fixture carries a REAL display matrix (a `-display_rotation 90` remux,
149 // the gen_fixtures pattern), because a `setsar`-only file asserts nothing
150 // about the turn -- the case this whole block exists for.
151 let fixtures = Scratch::dir("ve_anamorphic_turned");
152 let turned = fixtures.join("turned.mp4");
153 let made = std::process::Command::new("ffmpeg")
154 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
155 .arg("testsrc2=size=1440x1080:rate=30:duration=1")
156 .args([
157 "-vf",
158 "setsar=4/3",
159 "-c:v",
160 "libx264",
161 "-profile:v",
162 "baseline",
163 "-pix_fmt",
164 "yuv420p",
165 ])
166 .arg(&turned)
167 .status()
168 .is_ok_and(|s| s.success());
169 if made {
170 // The same file with a 90-degree display matrix asked of it.
171 let matrix_on = fixtures.join("turned90.mp4");
172 let remuxed = std::process::Command::new("ffmpeg")
173 .args(["-y", "-v", "error", "-display_rotation", "90", "-i"])
174 .arg(&turned)
175 .args(["-c", "copy"])
176 .arg(&matrix_on)
177 .status()
178 .is_ok_and(|s| s.success());
179 if remuxed {
180 let (meta, _) = Demuxer::open(&matrix_on).expect("open the turned fixture");
181 // The probe: coded 1440x1080 stays; the SAR-4/3 widen of the
182 // coded width (1920) is what the turn swaps into the height, so
183 // the displayed pair is 1080x1920 -- DAR 9:16, the ratio ffprobe
184 // reports for the same file turned. A turn-then-stretch probe
185 // would declare 1440x1440 here; a stretch-on-the-wrong-axis
186 // render paints exactly that square into this 9:16 canvas.
187 assert_eq!(
188 (meta.coded_width, meta.coded_height),
189 (1440, 1080),
190 "the turned fixture's samples"
191 );
192 assert_eq!(
193 meta.rotation,
194 engine::Rotation::Cw270,
195 "the matrix was read as a quarter turn"
196 );
197 assert_eq!(
198 (meta.width, meta.height),
199 (1080, 1920),
200 "the aspect widens the coded width; the turn swaps the stretched pair"
201 );
202 // ...and the render agrees with the probe: the composed picture
203 // is handed out at the displayed pair, filled to the corners --
204 // the 1440x1440 failure the other order produces would fail both
205 // assertions.
206 let (_, frames, _) =
207 engine::DecodeSession::open_at(&matrix_on, 0).expect("open for a frame");
208 let frame = frames.recv().expect("a first frame");
209 assert_eq!(
210 (frame.width, frame.height),
211 (1080, 1920),
212 "the rendered picture is the displayed pair"
213 );
214 let (w, h) = (frame.width as usize, frame.height as usize);
215 let at = |x: usize, y: usize| {
216 let i = (y * w + x) * 4;
217 (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2])
218 };
219 let m = w / 10;
220 let corners = [
221 at(m, m),
222 at(w - 1 - m, m),
223 at(w - 1 - m, h - 1 - m),
224 at(m, h - 1 - m),
225 ];
226 assert!(
227 corners
228 .iter()
229 .all(|&(b, g, r)| u32::from(r) + u32::from(g) + u32::from(b) > 48),
230 "the corners are picture, not black: {corners:?}"
231 );
232 }
233 let _ = std::fs::remove_file(&turned);
234 let _ = std::fs::remove_file(&matrix_on);
235 }
236}
237
238/// The preview: the composed picture is the displayed shape, filled to the
239/// corners -- no letterbox, no squeeze, no coded-shaped picture drawn into a
240/// wider window. The corner gate is numeric: a picture that left bars would
241/// sample black.
242#[test]
243fn the_preview_shows_the_drawn_picture() {
244 let _seat = pin_software();
245 for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] {
246 let (_, frames, _) =
247 engine::DecodeSession::open_at(asset(file), 0).expect("open for a frame");
248 let frame = frames.recv().expect("a first frame");
249 assert_eq!(
250 (frame.width, frame.height),
251 DISPLAY,
252 "{file}: the composed picture is the drawn shape"
253 );
254 let (w, h) = (frame.width as usize, frame.height as usize);
255 let at = |x: usize, y: usize| {
256 let i = (y * w + x) * 4;
257 let (b, g, r) = (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2]);
258 (u32::from(r), u32::from(g), u32::from(b))
259 };
260 let m = w / 10;
261 let corners = [
262 at(m, m),
263 at(w - 1 - m, m),
264 at(w - 1 - m, h - 1 - m),
265 at(m, h - 1 - m),
266 ];
267 assert!(
268 corners.iter().all(|(r, g, b)| *r + *g + *b > 48),
269 "{file}: the corners are picture, not black: {corners:?}"
270 );
271 let dar = w as f64 / h as f64;
272 assert!(
273 (dar - 16.0 / 9.0).abs() < 0.01,
274 "{file}: the measured display aspect is 16:9, measured {dar:.4}"
275 );
276 }
277}
278
279/// The export: the drawn shape is what the file says, and the pixels are the
280/// ones the preview showed -- re-encoded, so the new file is square-pixel at
281/// the displayed size and states no aspect of its own.
282#[test]
283fn an_export_of_an_anamorphic_file_is_drawn_and_square() {
284 let _seat = pin_software();
285 let source = asset("test_anamorphic.mkv");
286 let mut session = PlaybackSession::open(&source).expect("open the fixture");
287 session.pause();
288 let preview = loop {
289 if let Some(frame) = session.try_frame() {
290 break frame;
291 }
292 std::thread::sleep(Duration::from_millis(10));
293 };
294 let out = Scratch::file("ve_anamorphic_export", "mp4");
295 let handle = session.export_to_with(&out, &ExportSettings::default());
296 wait(&handle, Duration::from_secs(120)).expect("export");
297
298 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
299 assert_eq!(
300 (meta.coded_width, meta.coded_height),
301 DISPLAY,
302 "the re-encoded file is coded at the displayed shape"
303 );
304 assert!(
305 meta.pixel_aspect.is_square(),
306 "the aspect was applied, not carried: the export states none"
307 );
308 // Preview vs export, same clip: the drawn picture to the byte.
309 let mut reopened = PlaybackSession::open(&out).expect("reopen the export");
310 let exported = loop {
311 if let Some(frame) = reopened.try_frame() {
312 break frame;
313 }
314 std::thread::sleep(Duration::from_millis(10));
315 };
316 assert_eq!(
317 (exported.width, exported.height),
318 DISPLAY,
319 "the export plays at the drawn shape"
320 );
321 // Encode is lossy, so the picture is measured, not diffed: a wrong shape
322 // or a squeezed picture would move far more than a rounding code.
323 let moved = preview
324 .bgra
325 .iter()
326 .zip(&exported.bgra)
327 .map(|(a, b)| u32::from(a.abs_diff(*b)))
328 .sum::<u32>();
329 let mean = moved as f64 / preview.bgra.len() as f64;
330 assert!(
331 mean < 2.0,
332 "the export is {mean:.2} mean codes from the preview -- not the same picture"
333 );
334
335 // The same contract for a ROTATED anamorphic source: the fixture carries a
336 // real display matrix, the probe declares 1080x1920, and the export must
337 // be that shape with the picture the preview showed -- the case a
338 // turn-then-stretch render filled with 1440x1440 and baked bars into.
339 let fixtures = Scratch::dir("ve_anamorphic_export_fixtures");
340 let plain = fixtures.join("src.mp4");
341 let matrix_on = fixtures.join("rot.mp4");
342 let made = std::process::Command::new("ffmpeg")
343 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
344 .arg("testsrc2=size=1440x1080:rate=30:duration=1")
345 .args([
346 "-vf",
347 "setsar=4/3",
348 "-c:v",
349 "libx264",
350 "-profile:v",
351 "baseline",
352 "-pix_fmt",
353 "yuv420p",
354 ])
355 .arg(&plain)
356 .status()
357 .is_ok_and(|s| s.success())
358 && std::process::Command::new("ffmpeg")
359 .args(["-y", "-v", "error", "-display_rotation", "90", "-i"])
360 .arg(&plain)
361 .args(["-c", "copy"])
362 .arg(&matrix_on)
363 .status()
364 .is_ok_and(|s| s.success());
365 if made {
366 let mut session = PlaybackSession::open(&matrix_on).expect("open the turned fixture");
367 session.pause();
368 let preview = loop {
369 if let Some(frame) = session.try_frame() {
370 break frame;
371 }
372 std::thread::sleep(Duration::from_millis(10));
373 };
374 assert_eq!((preview.width, preview.height), (1080, 1920));
375 let out = Scratch::file("ve_anamorphic_rot_export", "mp4");
376 let handle = session.export_to_with(&out, &ExportSettings::default());
377 wait(&handle, Duration::from_secs(120)).expect("export");
378 let (meta, _) = Demuxer::open(&out).expect("reopen the export");
379 assert_eq!(
380 (meta.coded_width, meta.coded_height),
381 (1080, 1920),
382 "the rotated export is coded at the displayed shape"
383 );
384 assert!(meta.pixel_aspect.is_square(), "no aspect left to state");
385 let mut reopened = PlaybackSession::open(&out).expect("reopen the export");
386 let exported = loop {
387 if let Some(frame) = reopened.try_frame() {
388 break frame;
389 }
390 std::thread::sleep(Duration::from_millis(10));
391 };
392 assert_eq!((exported.width, exported.height), (1080, 1920));
393 let moved = preview
394 .bgra
395 .iter()
396 .zip(&exported.bgra)
397 .map(|(a, b)| u32::from(a.abs_diff(*b)))
398 .sum::<u32>();
399 let mean = moved as f64 / preview.bgra.len() as f64;
400 assert!(
401 mean < 2.0,
402 "the rotated export is {mean:.2} mean codes from the preview"
403 );
404 let _ = std::fs::remove_file(&plain);
405 let _ = std::fs::remove_file(&matrix_on);
406 }
407}
408
409/// The copy door, Matroska side: an anamorphic source's Exact row copies the
410/// coded blocks and carries the aspect beside them -- read back as the same
411/// 4/3 off the same elements the probe reads.
412#[test]
413fn a_matroska_copy_keeps_the_pixel_aspect() {
414 // The copy itself decodes nothing, but the export that writes it reads the
415 // HEVC source back through the plugin, and a machine without the plugin skips
416 // on that read, as `video_copy`'s decode-back test does. (Playback and export
417 // both decode HEVC in software now; the skip is kept as it was.)
418 if !plugin_here() {
419 println!("no VA-API plugin: skipping the copy-keeps-aspect test");
420 return;
421 }
422 let session = PlaybackSession::open(asset("test_anamorphic_hevc.mkv"))
423 .expect("open test_anamorphic_hevc.mkv");
424 let out = Scratch::file("ve_anamorphic_copy", "mkv");
425 let handle = session.export_to_with(
426 &out,
427 &ExportSettings {
428 format: Format::Hevc,
429 ..Default::default()
430 },
431 );
432 while !handle.is_finished() {
433 std::thread::sleep(Duration::from_millis(20));
434 }
435 let encoders = handle.encoders().unwrap_or_default();
436 handle.result().expect("an outcome").expect("copy export");
437 assert!(
438 encoders.contains("copy"),
439 "an untouched anamorphic timeline copies: {encoders}"
440 );
441 let (meta, _) = Demuxer::open(&out).expect("reopen the copy");
442 assert_eq!(
443 (meta.coded_width, meta.coded_height),
444 CODED,
445 "the copied track declares the coded shape"
446 );
447 let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v);
448 let g = gcd(h, v);
449 assert_eq!(
450 (h / g, v / g),
451 (4, 3),
452 "the copied track states the aspect it was copied with"
453 );
454 assert_eq!(
455 (meta.width, meta.height),
456 DISPLAY,
457 "and so reads back as the drawn shape"
458 );
459}
460
461/// The copy door, mp4 side: the sample entry this writer produces has no
462/// `pasp` box, so an anamorphic source's Exact row refuses by name rather
463/// than writing a header that lies about its own shape -- and the export
464/// still re-encodes to the right shape when asked without Exact.
465#[test]
466fn an_mp4_copy_of_an_anamorphic_source_refuses_in_words() {
467 let _seat = pin_software();
468 // The refusal is decided at the header read, but the export reads the HEVC
469 // source back, and the test keeps the plugin-or-skip gate it had, as above.
470 if !plugin_here() {
471 println!("no VA-API plugin: skipping the mp4 exact refusal test");
472 return;
473 }
474 let session = PlaybackSession::open(asset("test_anamorphic_hevc.mkv"))
475 .expect("open test_anamorphic_hevc.mkv");
476 let out = Scratch::file("ve_anamorphic_exact_refused", "mp4");
477 let settings = ExportSettings {
478 format: Format::Mp4,
479 exact: true,
480 ..Default::default()
481 };
482 let handle = session.export_to_with(&out, &settings);
483 // `wait` takes the outcome off the handle, so the refusal is read from it.
484 let error = wait(&handle, Duration::from_secs(300))
485 .expect_err("an mp4 cannot honour exact for an anamorphic source")
486 .to_string();
487 assert!(
488 error.contains("pixel aspect"),
489 "the refusal names the aspect it would lose: {error}"
490 );
491 assert!(
492 !out.exists() || std::fs::read(&out).is_err(),
493 "no lying header was written"
494 );
495}