forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

display_unit.rs447 lines, 17.9 KiBHistoryRawDownload
1//! Matroska `DisplayUnit` 0: the `Display*` pair is in *pixels*, so a pair
2//! beside the coded size is the stretch, not a crop.
3//!
4//! The Matroska spec is explicit that unit 0 means the `DisplayWidth` and
5//! `DisplayHeight` pair *is* a pixel size. So `DisplayWidth=1920`,
6//! `DisplayHeight=1080` beside a `PixelWidth=1440`, `PixelHeight=1080` track
7//! is exactly the 4/3 anamorphic stretch -- the same picture
8//! `test_anamorphic.mkv` states the other two ways round, in SAR (4/3) and in
9//! DAR (16/9).
10//!
11//! No fixture stated it that way until this one: `scripts/gen_fixtures.sh`
12//! produces unit 3 (ffmpeg spells the aspect as a DAR), so the unit-0 arm of
13//! the reader had never been seen by a test, and it read as square -- the
14//! same answer as a file that says nothing at all. The picture was shown at
15//! 1440x1080 instead of 1920x1080, and nothing said so.
16//!
17//! The fixture is patched here from `test_anamorphic.mkv` rather than
18//! committed as a binary: the `Video` element keeps its exact byte length, so
19//! every absolute offset in the file -- the SeekHead and every CueCluster-
20//! Position -- stays correct and the copy seeks exactly as the original does.
21//!
22//! ```text
23//! cargo test -p engine --test display_unit -- --test-threads=1
24//! ```
25
26use std::path::{Path, PathBuf};
27
28use engine::demux::{Demuxer, PixelAspect};
29
30fn asset(name: &str) -> PathBuf {
31 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
32 .join("../../assets")
33 .join(name)
34}
35
36struct Scratch(PathBuf);
37
38impl Scratch {
39 fn new(tag: &str) -> Self {
40 let dir = std::env::temp_dir().join(format!("edith-display-unit-{tag}-{}", std::process::id()));
41 let _ = std::fs::remove_dir_all(&dir);
42 std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture");
43 Self(dir)
44 }
45
46 fn path(&self, name: &str) -> PathBuf {
47 self.0.join(name)
48 }
49}
50
51impl Drop for Scratch {
52 fn drop(&mut self) {
53 let _ = std::fs::remove_dir_all(&self.0);
54 }
55}
56
57/// The bytes of the `Video` element of `test_anamorphic.mkv`, as ffmpeg's
58/// Matroska muxer wrote them: a 1440x1080 track with its aspect stated as a
59/// 16/9 display aspect ratio.
60const VIDEO_UNIT_3: &str = concat!(
61 "e09e", // Video, 30 bytes
62 "b08205a0", // PixelWidth 1440
63 "ba820438", // PixelHeight 1080
64 "9a8102", // FlagInterlaced
65 "54b08110", // DisplayWidth 16
66 "54ba8109", // DisplayHeight 9
67 "54b28103", // DisplayUnit 3 -- a display aspect ratio
68 "55b084", "55b98101" // Colour { MatrixCoefficients 1 }
69);
70
71/// The same 30 bytes with the aspect stated the third way Matroska allows:
72/// unit 0, where the `Display*` pair is in pixels and so *is* the drawn
73/// size. 1920x1080 over a 1440x1080 coded track is the same 4/3 stretch.
74///
75/// Byte-for-byte the same length as [`VIDEO_UNIT_3`], which is what keeps
76/// the rest of the file's offsets honest: the `Display*` values grow from
77/// one-byte to two-byte payloads (+3 bytes with the wider unit encoding),
78/// `FlagInterlaced` is dropped (-3), and `MatrixCoefficients` is restated
79/// over two bytes instead of one (+1) inside the `Colour` element.
80const VIDEO_UNIT_0: &str = concat!(
81 "e09e", // Video, 30 bytes -- unchanged
82 "b08205a0", // PixelWidth 1440, unchanged: the samples are still these
83 "ba820438", // PixelHeight 1080, unchanged
84 "54b0820780", // DisplayWidth 1920 -- in *pixels*
85 "54ba820438", // DisplayHeight 1080 -- in *pixels*
86 "54b28100", // DisplayUnit 0 -- pixels
87 "55b085", "55b9820001" // Colour { MatrixCoefficients 1 }
88);
89
90/// The same `DisplayUnit 0` element with a different `Display*` pixel pair,
91/// for the ratios whose reduced form is not a small pair of integers.
92fn video_unit_0(display_width: u16, display_height: u16) -> String {
93 // Both `Display*` values are two-byte payloads, so a width past 0x7FFF
94 // would need three and change the element's length. The lengths here are
95 // all inside that range, which is what keeps every offset in the file
96 // honest.
97 format!(
98 "e09e\
99 b08205a0\
100 ba820438\
101 54b082{display_width:04x}\
102 54ba82{display_height:04x}\
103 54b28100\
104 55b085\
105 55b9820001"
106 )
107}
108/// A `DisplayUnit 3` (DAR) `Video` element: the coded size and the display
109/// aspect ratio, both length-preserving.
110fn video_unit_3(dar_width: u16, dar_height: u16, coded_width: u16, coded_height: u16) -> String {
111 format!(
112 "e09e\
113 b082{coded_width:04x}\
114 ba82{coded_height:04x}\
115 9a8102\
116 54b081{dar_width:02x}\
117 54ba81{dar_height:02x}\
118 54b28103\
119 55b084\
120 55b98101"
121 )
122}
123
124/// Patches the `Video` element into a copy of `source` and returns the byte
125/// offset it was written at, found by scanning the source rather than
126/// assumed, since the offset depends on the muxer's layout.
127fn with_video_element(source: &Path, into: &Path, element: &str) -> usize {
128 let from = hex(VIDEO_UNIT_3);
129 let to = hex(element);
130 assert_eq!(
131 from.len(),
132 to.len(),
133 "a length-preserving patch: {element} is {} bytes, {} are needed",
134 to.len(),
135 from.len()
136 );
137 let bytes = std::fs::read(source).expect("read the source fixture");
138 let at = bytes
139 .windows(from.len())
140 .position(|window| window == from)
141 .unwrap_or_else(|| panic!("the fixture carries the expected {VIDEO_UNIT_3} element"));
142 let mut patched = bytes.clone();
143 patched[at..at + from.len()].copy_from_slice(&to);
144 std::fs::write(into, patched).expect("write the patched fixture");
145 at
146}
147
148fn hex(text: &str) -> Vec<u8> {
149 (0..text.len() / 2)
150 .map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).expect("hex in the fixture"))
151 .collect()
152}
153
154/// The reduced form of a ratio, so a ratio stated unreduced (the DAR arm
155/// multiplies through by the coded size) compares equal to its simplest
156/// spelling -- the same comparison the anamorphic suite makes.
157fn reduced(aspect: PixelAspect) -> (u32, u32) {
158 let gcd = |mut a: u32, mut b: u32| {
159 while b != 0 {
160 (a, b) = (b, a % b);
161 }
162 a.max(1)
163 };
164 let g = gcd(aspect.h, aspect.v);
165 (aspect.h / g, aspect.v / g)
166}
167
168/// The three spellings of one anamorphic picture must name one picture.
169#[test]
170fn a_display_unit_of_zero_states_the_stretch_in_pixels() {
171 let scratch = Scratch::new("pixels");
172 let unit0 = scratch.path("display_unit0.mkv");
173 let aimed_at = with_video_element(&asset("test_anamorphic.mkv"), &unit0, VIDEO_UNIT_0);
174
175 // The patch landed, and it landed on a file the demuxer opens.
176 let patched = std::fs::read(&unit0).expect("read back the patched fixture");
177 let original = std::fs::read(asset("test_anamorphic.mkv")).expect("read the original");
178 assert_eq!(
179 patched.len(),
180 original.len(),
181 "the patch preserves the file length, so no offset in it moved"
182 );
183 let wanted = hex(VIDEO_UNIT_0);
184 assert_eq!(
185 patched
186 .windows(wanted.len())
187 .position(|window| window == wanted),
188 Some(aimed_at),
189 "the DisplayUnit-0 element is where it was aimed"
190 );
191
192 let (meta, _) = Demuxer::open(&unit0).expect("open the DisplayUnit-0 fixture");
193
194 // The samples are stored at the coded size, exactly as before the patch.
195 assert_eq!(
196 (meta.coded_width, meta.coded_height),
197 (1440, 1080),
198 "unit 0 changes what the file *says* about the picture, not how it is stored"
199 );
200
201 // Unit 0 means the pair IS a pixel size, so 1920x1080 beside a 1440x1080
202 // coded track is the 4/3 stretch -- and this is the whole defect: read as
203 // square, the picture was drawn at 1440x1080, a quarter-width picture of
204 // the same frame, with nothing to say so.
205 assert!(
206 !meta.pixel_aspect.is_square(),
207 "DisplayUnit 0 with a Display pair beside the coded one is a stretch, \
208 not a crop: got square ({:?})",
209 meta.pixel_aspect
210 );
211 assert_eq!(
212 (meta.width, meta.height),
213 (1920, 1080),
214 "the Display pair is the drawn size: 1920x1080 over a 1440x1080 coded track"
215 );
216
217 // ...and it is the *same* ratio the other two spellings name, so all three
218 // fixtures of one source agree on one drawn picture. Compared reduced,
219 // because a ratio is named by the picture and not by how it was spelled:
220 // the DAR arm multiplies through by the coded size and says 2073600 /
221 // 1555200 where the SAR arm says 4 / 3.
222 assert_eq!(
223 reduced(meta.pixel_aspect),
224 (4, 3),
225 "1920x1080 over a 1440x1080 coded track is the same 4/3 the SAR and \
226 DAR spellings name"
227 );
228 for sibling in ["test_anamorphic.mp4", "test_anamorphic.mkv"] {
229 let (other, _) = Demuxer::open(&asset(sibling)).expect("open the sibling fixture");
230 assert_eq!(
231 (other.width, other.height),
232 (meta.width, meta.height),
233 "{sibling} states the same picture the DisplayUnit spelling states"
234 );
235 }
236}
237
238/// Units 1 and 2 are physical sizes -- centimetres, inches -- which a picture
239/// this engine shows on a screen cannot mean anything by. They stay square,
240/// and saying so is the deliberate answer rather than an accident of the
241/// match falling through.
242#[test]
243fn a_physical_display_unit_is_read_as_square() {
244 let scratch = Scratch::new("physical");
245 for (unit, tag) in [(1u8, "cm"), (2u8, "in")] {
246 let element = VIDEO_UNIT_0.replacen("54b28100", &format!("54b2810{unit}"), 1);
247 let into = scratch.path(&format!("display_unit{unit}.mkv"));
248 with_video_element(&asset("test_anamorphic.mkv"), &into, &element);
249 let (meta, _) = Demuxer::open(&into).expect("open the physical-unit fixture");
250 assert!(
251 meta.pixel_aspect.is_square(),
252 "DisplayUnit {unit} ({tag}) is a physical size this engine cannot interpret, \
253 so the pixels stay square: got {:?}",
254 meta.pixel_aspect
255 );
256 }
257}
258/// The coded size is untrusted too, and it reaches an allocation directly:
259/// `decode.rs` sizes its stretched planes as `display_width * height`. The
260/// engine already has a bound for exactly this -- [`engine::MAX_RESOLUTION`],
261/// 8K, the size a per-frame buffer stops being sane at -- and the demux
262/// readers never applied it to a container-stated width or height.
263///
264/// The fixture patches the `PixelWidth`/`PixelHeight` payloads to 65535 each,
265/// which is a legal two-byte EBML integer, so the element keeps its exact
266/// length and the copy stays seekable.
267#[test]
268fn a_coded_size_past_the_resolution_bound_is_refused_not_allocated() {
269 let scratch = Scratch::new("huge");
270 let into = scratch.path("huge_dims.mkv");
271 with_video_element(
272 &asset("test_anamorphic.mkv"),
273 &into,
274 &VIDEO_UNIT_3
275 .replacen("b08205a0", "b082ffff", 1)
276 .replacen("ba820438", "ba82ffff", 1),
277 );
278
279 // Refused, and refused by name: the open fails with a message that says
280 // what the file claimed and what the maximum is, rather than succeeding
281 // and handing a caller a 65535x65535 to allocate.
282 let Err(why) = Demuxer::open(&into) else {
283 panic!("a 65535x65535 header is refused by name, never opened");
284 };
285 let said = why.to_string();
286 assert!(
287 said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()),
288 "the refusal names the size claimed and the maximum: {said}"
289 );
290 assert!(
291 engine::demux::UnsupportedDisplaySize::is_it(&why),
292 "and it is the named refusal a caller can match on, not a string"
293 );
294}
295
296/// The bound is a ceiling on a real picture, not a floor on a file: the
297/// largest size a real source states still opens, untouched.
298#[test]
299fn a_real_size_up_to_the_bound_still_opens() {
300 let (meta, _) = Demuxer::open(&asset("test_anamorphic.mkv")).expect("open the fixture");
301 assert!(
302 engine::is_resolution(meta.coded_width, meta.coded_height),
303 "the ordinary fixture is inside the bound, which is what keeps the \
304 bound from refusing the library"
305 );
306}
307
308/// The regression this arm must not carry: a `DisplayUnit 0` pair is a pixel
309/// SIZE, so its *reduced* form is the size against the coded size, not a small
310/// pair of integers -- and the common cinematic display ratios do not reduce
311/// small. A 1920x803 scope over a 1440x1080 coded track reduces to 1440:803,
312/// and 1920x1037 (1.85:1 flat) likewise.
313///
314/// The reduced-term bound is the right test for an mp4 `pasp`, where the pair
315/// *is* the ratio, and the wrong test here: applying it made the two most
316/// common letterbox ratios open square, on exactly the arm this fix newly
317/// enabled. The quantity that needs bounding on this door is the resulting
318/// display WIDTH, which `width_factor` already caps.
319#[test]
320fn a_cinematic_display_unit_zero_stretches_rather_than_reading_square() {
321 let scratch = Scratch::new("cinema");
322 for (dw, dh, ratio, tag) in [
323 (1920u16, 803u16, "2.39:1 scope", "scope"),
324 (1920, 1037, "1.85:1 flat", "flat"),
325 ] {
326 let into = scratch.path(&format!("{tag}.mkv"));
327 with_video_element(
328 &asset("test_anamorphic.mkv"),
329 &into,
330 &video_unit_0(dw, dh),
331 );
332
333 let (meta, _) = Demuxer::open(&into)
334 .unwrap_or_else(|why| panic!("{tag} ({ratio}): open failed: {why}"));
335 assert!(
336 !meta.pixel_aspect.is_square(),
337 "{tag} ({ratio}): a DisplayUnit 0 pixel pair of {dw}x{dh} over a \
338 1440x1080 coded track is a stretch, not square: got {:?}",
339 meta.pixel_aspect
340 );
341 // The stated DISPLAY WIDTH is the drawn width: unit 0 states it in
342 // pixels, so it is taken as stated, not re-derived. The height stays
343 // the coded one because a pixel aspect moves the width only in this
344 // engine -- `VideoMeta::height` is the coded height for every file, by
345 // design. A 1920x803 scope is therefore drawn 1920x1080 here: the
346 // width is the file's own claim and the height is this engine's
347 // documented model, and the two are not the same thing.
348 assert_eq!(
349 meta.width,
350 u32::from(dw),
351 "{tag} ({ratio}): the stated Display width is the drawn width"
352 );
353 assert_eq!(
354 meta.height,
355 1080,
356 "{tag} ({ratio}): a pixel aspect never moves the height; the coded one stands"
357 );
358 assert_eq!(
359 (meta.coded_width, meta.coded_height),
360 (1440, 1080),
361 "{tag} ({ratio}): the samples are still stored at the coded size"
362 );
363 }
364}
365
366/// The unit-3 arm, which is the same rule as unit 0 one arm away: a DAR is
367/// not a ratio either, because bringing it onto the coded frame multiplies by
368/// the coded size, and what reduces afterwards carries the *sizes*.
369///
370/// So the same 2.39:1 scope is judged differently by the frame it sits on,
371/// which is a bound measuring the wrong thing. Over a 1920x1080 coded track a
372/// 239:100 DAR derives 2151:1600 and over 3840x2160 the same -- both past any
373/// term bound -- while over 1440x1080 it derives 717:400 and passes. Base
374/// `9f780f7` opened all three at the widths below; the bound made the first
375/// two open square, a measured regression rather than a latent gap.
376///
377/// The expected widths are the ones BASE produced, measured by running base
378/// over these same fixtures. This is the property that matters: the arm must
379/// read the DAR the way it always did, so the test pins base's answers rather
380/// than a fresh computation of them.
381#[test]
382fn a_display_unit_three_dar_reads_the_same_on_every_coded_frame() {
383 let scratch = Scratch::new("dar");
384 for (coded, expected, tag) in [
385 ((1920u16, 1080u16), 2582u32, "1920x1080"), // 239:100 -> 2151:1600
386 ((3840, 2160), 5162, "3840x2160"), // 239:100 -> 2151:1600
387 ((720, 576), 1376, "720x576"), // 239:100 -> 239:125
388 ] {
389 let into = scratch.path(&format!("dar_{tag}.mkv"));
390 with_video_element(
391 &asset("test_anamorphic.mkv"),
392 &into,
393 &video_unit_3(239, 100, coded.0, coded.1),
394 );
395
396 let (meta, _) = Demuxer::open(&into)
397 .unwrap_or_else(|why| panic!("{tag}: open failed: {why}"));
398 assert_eq!(
399 (meta.coded_width, meta.coded_height),
400 (u32::from(coded.0), u32::from(coded.1)),
401 "{tag}: the coded frame the DAR is stated over"
402 );
403 assert!(
404 !meta.pixel_aspect.is_square(),
405 "{tag}: a 239:100 DAR is a 2.39:1 stretch whatever frame it sits \
406 on: got square ({:?})",
407 meta.pixel_aspect
408 );
409 assert_eq!(
410 meta.width, expected,
411 "{tag}: the display width base 9f780f7 produced for this DAR"
412 );
413 assert_eq!(
414 meta.height,
415 u32::from(coded.1),
416 "{tag}: a pixel aspect never moves the height; the coded one stands"
417 );
418 }
419}
420
421/// The term bound must survive where it belongs. The unit-4 SAR pair IS a
422/// ratio, so a hostile one is still refused -- this arm is what stops the
423/// split from reading as "the bound was dropped".
424#[test]
425fn a_hostile_sar_pair_is_still_refused_by_the_term_bound() {
426 // Reduced terms far past the bound, stated as a SAR pair: four chosen
427 // bytes, not a ratio.
428 for hostile in [(0xFFFF_FFFFu32, 0xFFFF_FFFFu32 - 1), (1, 0x00FF_FFFF)] {
429 assert_eq!(
430 PixelAspect::stated(hostile.0, hostile.1),
431 None,
432 "{hostile:?} is chosen bytes, not a ratio, and is refused as one"
433 );
434 }
435 // ...and a real SAR pair is still taken, so the bound is not simply
436 // refusing everything on this arm.
437 assert_eq!(
438 PixelAspect::stated(4, 3),
439 Some(PixelAspect { h: 4, v: 3 }),
440 "a 4:3 SAR is a ratio and is read as one"
441 );
442 assert_eq!(
443 PixelAspect::stated(16, 12),
444 Some(PixelAspect { h: 16, v: 12 }),
445 "an unreduced 4:3 spelling is judged by the ratio it names"
446 );
447}