forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

rotation.rs386 lines, 15.6 KiBHistoryRawDownload
1//! The display matrix: a file that says "turn me" is turned -- in the preview
2//! and in the export, from the same numbers.
3//!
4//! A phone records a portrait video as a landscape picture plus a `tkhd` matrix
5//! saying which way to turn it. Before this the engine read neither: the
6//! preview showed a portrait clip on its side and an export re-coded the
7//! landscape pixels with a unity matrix, so the file played sideways anywhere
8//! -- the one rendition nobody ever wanted.
9//!
10//! `test_rotation90/180/270.mp4` (`scripts/gen_fixtures.sh`) are one 320x180
11//! source of four coloured quadrants written back out with a turn asked for, so
12//! a single sampled pixel per corner names the layout and a *wrong direction*
13//! cannot pass -- a 180-degree mix-up, a mirror, or "ignore it" each produce a
14//! different set of four corners. The layouts asserted here are ffmpeg's own
15//! autorotation of each file, measured rather than derived.
16//!
17//! `test_rotation45.mp4` is the other half of the contract: a matrix that is a
18//! rotation but not a quarter turn has no correct rendition here, and it is
19//! refused *by name* at the door rather than shown wrong.
20
21use std::path::{Path, PathBuf};
22use std::sync::Once;
23use std::time::{Duration, Instant};
24
25use engine::export::ExportSettings;
26use engine::scratch::Scratch;
27use engine::{DecodeSession, ExportHandle, PlaybackSession, Rotation};
28
29fn asset(name: &str) -> PathBuf {
30 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31 .join("../../assets")
32 .join(name)
33}
34
35/// Which seat an export takes is decided by *process-wide* environment
36/// variables, so a test binary that shares the machine has to borrow them
37/// rather than assume: this pins both decode and encode to software, which is
38/// the seat every machine has, and holds the borrow for the whole test binary.
39static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(());
40
41type Shared = std::sync::RwLockReadGuard<'static, ()>;
42
43#[must_use = "the seat pin holds only while its guard is alive"]
44fn pin_software() -> Shared {
45 let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner());
46 static PIN: Once = Once::new();
47 PIN.call_once(|| {
48 engine::envcfg::set("VE_SW", "1");
49 engine::envcfg::set("VE_SW_ENC", "1");
50 });
51 borrowed
52}
53
54fn out_path(name: &str) -> Scratch {
55 Scratch::file(&format!("ve_rotation_{name}"), "mp4")
56}
57
58fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
59 let started = Instant::now();
60 while !handle.is_finished() {
61 assert!(
62 started.elapsed() < limit,
63 "export did not finish in {limit:?}"
64 );
65 std::thread::sleep(Duration::from_millis(20));
66 }
67 handle.result().expect("a finished export has an outcome")
68}
69
70/// What colour a decoded BGRA pixel is, by the quadrant it came from. ffmpeg's
71/// `red`/`green`/`blue`/`yellow` are far apart enough that the chroma of a
72/// 4:2:0 edge never reaches a quadrant's centre, and the labels are what the
73/// fixture's own comment says it drew.
74fn tint(bgra: &[u8]) -> &'static str {
75 let (b, g, r) = (bgra[0], bgra[1], bgra[2]);
76 let (r, g, b) = (r > 110, g > 90, b > 110);
77 match (r, g, b) {
78 (true, true, false) => "yellow",
79 (true, false, false) => "red",
80 (false, true, false) => "green",
81 (false, false, true) => "blue",
82 other => panic!("a quadrant centre is not one of the four colours: {other:?}"),
83 }
84}
85
86/// The four corners of one tightly packed BGRA picture, top-left first and
87/// clockwise -- sampled deep enough inside each quadrant that a 4:2:0 boundary
88/// cannot colour the sample.
89fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] {
90 let at = |x: u32, y: u32| {
91 let index = ((y * width + x) * 4) as usize;
92 tint(&bgra[index..index + 4])
93 };
94 let (qx, qy) = (width / 4, height / 4);
95 [
96 at(qx, qy),
97 at(3 * qx, qy),
98 at(3 * qx, 3 * qy),
99 at(qx, 3 * qy),
100 ]
101}
102
103/// What the coded picture holds, before anything turns it: this is the layout
104/// every expectation below is *not*.
105const CODED: [&str; 4] = ["red", "green", "yellow", "blue"];
106
107/// One frame of `path` and the size it came out at: the preview path exactly
108/// ([`DecodeSession`] is the same funnel [`PlaybackSession`] paints from).
109fn first_frame(path: &Path) -> (u32, u32, Vec<u8>) {
110 let (_, frames, _) = DecodeSession::open_at(path, 0).expect("open for a frame");
111 let frame = frames.recv().expect("a first frame");
112 (frame.width, frame.height, frame.bgra)
113}
114
115/// The same four corners ffmpeg's own autorotation of each file produces --
116/// measured with `ffmpeg -i f.mp4 -f rawvideo -pix_fmt rgb24 -` on this
117/// machine, which is the arbiter a display matrix is read against.
118fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) {
119 match file {
120 "test_rotation90.mp4" | "test_rotation90.mkv" => (
121 [180, 320],
122 Rotation::Cw270,
123 ["green", "yellow", "blue", "red"],
124 ),
125 "test_rotation180.mp4" | "test_rotation180.mkv" => (
126 [320, 180],
127 Rotation::Cw180,
128 ["yellow", "blue", "red", "green"],
129 ),
130 "test_rotation270.mp4" | "test_rotation270.mkv" => (
131 [180, 320],
132 Rotation::Cw90,
133 ["blue", "red", "green", "yellow"],
134 ),
135 other => panic!("no expectation for {other}"),
136 }
137}
138
139/// The header says which way the picture lies: a quarter turn swaps the
140/// displayed size and names the turn, and a half turn does neither.
141#[test]
142fn a_display_matrix_is_read_as_a_quarter_turn() {
143 // Both doors, the same turn: the mkv twins are the same quadrant source
144 // remuxed with the same rotation asked for (`scripts/gen_fixtures.sh`), one
145 // stating it in a `Projection` roll and one in a `tkhd` matrix, and a roll
146 // read the wrong way round is a file that plays on its side in exactly one
147 // of the two.
148 for file in [
149 "test_rotation90.mp4",
150 "test_rotation90.mkv",
151 "test_rotation180.mp4",
152 "test_rotation180.mkv",
153 "test_rotation270.mp4",
154 "test_rotation270.mkv",
155 ] {
156 let (size, rotation, _) = expected(file);
157 let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture");
158 assert_eq!(
159 [meta.width, meta.height],
160 size,
161 "{file}: the *displayed* size is what the engine reports"
162 );
163 assert_eq!(
164 meta.rotation, rotation,
165 "{file}: which turn the file asks for"
166 );
167 assert_eq!(
168 rotation.swaps_axes(),
169 size == [180, 320],
170 "{file}: a swapped size and a swapping turn go together"
171 );
172 }
173 // ...and the fixture's own coded picture is the layout none of these are,
174 // which is what makes the assertions above about the turn and not about the
175 // source. `test_rotation180.mp4` keeps its coded size, so the picture is
176 // where the turn is visible.
177 let (width, height, bgra) = first_frame(&asset("test_rotation180.mp4"));
178 assert_eq!((width, height), (320, 180));
179 assert_ne!(corners(width, height, &bgra), CODED, "the turn was made");
180}
181
182/// The preview: the picture is turned before it is painted, at the size the
183/// turn gives it.
184#[test]
185fn the_preview_shows_a_turned_file_upright() {
186 let _seat = pin_software();
187 // Both doors, the same turn: the mkv twins are the same quadrant source
188 // remuxed with the same rotation asked for (`scripts/gen_fixtures.sh`), one
189 // stating it in a `Projection` roll and one in a `tkhd` matrix, and a roll
190 // read the wrong way round is a file that plays on its side in exactly one
191 // of the two.
192 for file in [
193 "test_rotation90.mp4",
194 "test_rotation90.mkv",
195 "test_rotation180.mp4",
196 "test_rotation180.mkv",
197 "test_rotation270.mp4",
198 "test_rotation270.mkv",
199 ] {
200 let (size, _, corners_expected) = expected(file);
201 let (width, height, bgra) = first_frame(&asset(file));
202 assert_eq!(
203 [width, height],
204 size,
205 "{file}: the painted picture is the displayed size"
206 );
207 assert_eq!(
208 corners(width, height, &bgra),
209 corners_expected,
210 "{file}: every quadrant landed where the turn puts it"
211 );
212 }
213}
214
215/// The export: the turn is baked into the pixels, so the file plays upright
216/// everywhere -- which means the output is portrait *and* declares no matrix of
217/// its own. A file that kept the source's matrix and the source's landscape
218/// pixels would satisfy neither half.
219#[test]
220fn an_export_of_a_turned_file_is_upright_and_portrait() {
221 let _seat = pin_software();
222 // Both doors, because the turn reaches the export through exactly one number
223 // -- the source's `Rotation` in the export's rate table -- and an mkv states
224 // it with a `Projection` roll where an mp4 states a `tkhd` matrix: a door
225 // that read its own spelling into that number differently would bake a
226 // different turn into the pixels, and nothing but this test would show it.
227 for file in ["test_rotation90.mp4", "test_rotation90.mkv"] {
228 let source = asset(file);
229 let mut session = PlaybackSession::open(&source).expect("open the fixture");
230 session.pause();
231 assert_eq!(
232 [session.meta().width, session.meta().height],
233 [180, 320],
234 "{file}: the timeline is the displayed shape, not the coded one"
235 );
236 let out = out_path(&file.replace('.', "_"));
237 let handle = session.export_to_with(&out, &ExportSettings::default());
238 wait(&handle, Duration::from_secs(60)).expect("export");
239
240 let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
241 assert_eq!(
242 [meta.width, meta.height],
243 [180, 320],
244 "{file}: the written file is portrait"
245 );
246 assert_eq!(
247 meta.rotation,
248 Rotation::None,
249 "{file}: and states no matrix: the turn is in the pixels"
250 );
251 assert_eq!(
252 meta.frame_count, 30,
253 "{file}: every timeline frame was written"
254 );
255
256 let (width, height, bgra) = first_frame(&out);
257 assert_eq!([width, height], [180, 320]);
258 assert_eq!(
259 corners(width, height, &bgra),
260 ["green", "yellow", "blue", "red"],
261 "{file}: the exported pixels are the ones the preview showed"
262 );
263 }
264}
265
266/// A turn that is not a quarter turn is refused by name at the door, with the
267/// angle in the sentence -- the honest answer to a picture this engine has no way
268/// to show right. The capability really is absent: nothing here turns by an
269/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters), and
270/// the refusal is what says so instead of a sideways picture.
271///
272/// **Both doors**, because they are two spellings of one question: an mp4 states
273/// the turn in a `tkhd` matrix and an mkv in a `Projection` roll, and a file
274/// whose picture is 45 degrees off is the same missing capability either way --
275/// the mkv twin exists for exactly this assertion.
276#[test]
277fn a_turn_that_is_not_a_quarter_turn_is_refused_by_name() {
278 for file in ["test_rotation45.mp4", "test_rotation45.mkv"] {
279 let error = match engine::demux::Demuxer::open(&asset(file)) {
280 Ok(_) => {
281 panic!("45 degrees is not a quarter turn, and opening {file} must not succeed")
282 }
283 Err(error) => error,
284 };
285 assert!(
286 engine::UnsupportedRotation::is_it(&error),
287 "{file}: the refusal is the named one, not a generic failure: {error}"
288 );
289 let said = error.to_string();
290 assert!(
291 said.contains("45.0°") && said.contains("quarter turn"),
292 "{file}: the refusal names the angle it cannot make: {said}"
293 );
294 }
295}
296
297/// The number a refusal states, as the sentence spells it: the text between
298/// "matrix of " and the degree sign.
299fn stated_degrees(said: &str) -> String {
300 let start = said.find("matrix of ").expect("the refusal states an angle") + "matrix of ".len();
301 let end = start + said[start..].find('°').expect("the angle is followed by a degree sign");
302 said[start..end].to_string()
303}
304
305/// The `rotation` side data ffprobe reports for the file's video track: the
306/// counter-clockwise angle, in ffprobe's own sign.
307fn ffprobe_rotation_degrees(path: &Path) -> f64 {
308 let out = std::process::Command::new("ffprobe")
309 .args([
310 "-v",
311 "error",
312 "-select_streams",
313 "v:0",
314 "-show_entries",
315 "side_data=rotation",
316 "-of",
317 "csv=p=0",
318 ])
319 .arg(path)
320 .output()
321 .expect("ffprobe runs");
322 assert!(out.status.success(), "ffprobe reads {}", path.display());
323 String::from_utf8_lossy(&out.stdout)
324 .lines()
325 .map(str::trim)
326 .find(|line| !line.is_empty())
327 .expect("ffprobe states a rotation for a turned file")
328 .parse()
329 .expect("ffprobe's rotation is a number")
330}
331
332/// The refused angle is stated in the same convention for both containers, and
333/// that convention is ffprobe's: a 45-degree matrix in an mp4 and the same turn
334/// as an mkv roll both say `45.0`, the counter-clockwise angle ffprobe reports
335/// for each (`-atan2(b, a)` on the mp4 side, the roll itself on the mkv side).
336#[test]
337fn a_refused_angle_states_ffprobes_counter_clockwise_sign_in_both_containers() {
338 let mut stated = Vec::new();
339 for file in ["test_rotation45.mp4", "test_rotation45.mkv"] {
340 let error = match engine::demux::Demuxer::open(&asset(file)) {
341 Ok(_) => panic!("45 degrees is not a quarter turn, and opening {file} must not succeed"),
342 Err(error) => error,
343 };
344 let text = stated_degrees(&error.to_string());
345 let ffprobe = ffprobe_rotation_degrees(&asset(file));
346 assert_eq!(
347 text,
348 format!("{ffprobe:.1}"),
349 "{file}: the angle it states is ffprobe's rotation, sign and all"
350 );
351 stated.push(text);
352 }
353 assert_eq!(
354 stated[0], stated[1],
355 "the mp4 and mkv twins state the same angle for the same turn"
356 );
357}
358
359/// A rotated file whose *coded* height and *displayed* height sit on opposite
360/// sides of the 720-line rule an untagged stream's matrix is guessed from
361/// ([`engine::colorspace::ColorDescription::resolve`]): `test_rotation90tall` is
362/// 1280x640 as stored and 640x1280 as shown, and neither container tags it (the
363/// mkv's `Colour` element carries only chroma siting, the mp4 has no `colr`
364/// box), so that guess is the only thing deciding bt601 against bt709.
365///
366/// Both doors must feed the height the picture is *shown* at -- bt709 here -- and
367/// this is the assertion that fails if a door reads the coded height instead
368/// (`video.height`, 640, is bt601). The two doors agreeing is the whole point of
369/// resolving the size the same way in both.
370#[test]
371fn a_turned_file_guesses_its_matrix_from_the_height_it_is_shown_at() {
372 for file in ["test_rotation90tall.mp4", "test_rotation90tall.mkv"] {
373 let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture");
374 assert_eq!(
375 [meta.width, meta.height],
376 [640, 1280],
377 "{file}: the shown shape -- 1280x640 as stored, turned by the file"
378 );
379 assert_eq!(
380 meta.color.matrix,
381 engine::colorspace::Matrix::Bt709,
382 "{file}: the 1280-line *displayed* height is HD material; the 640-line coded one \
383 would guess bt601, so this is the coded-height bug showing"
384 );
385 }
386}