forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(demux): the container header is bounded, and DisplayUnit 0/3 is judged by its raster

Browse files at this commit

2d4c4b4ed0a5773b54584786759d9f3541f483d6Ahmet Kaan GümüşParent: 8c1aee425cd3de
crates/engine/src/demux.rsmodified+432 -30
@@ -250,6 +250,40 @@ fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> {
250 #[derive(Debug)]250 #[derive(Debug)]
251 pub struct NoVideoTrack(String);251 pub struct NoVideoTrack(String);
252 252
253+/// A container that states a picture larger than this engine will compose:
254+/// past [`crate::MAX_RESOLUTION`], where a per-frame buffer stops being a
255+/// sane thing to allocate. Refused by name, like the other named refusals,
256+/// because "this file is too big to open" is something a user can act on and
257+/// a capacity overflow one layer down is not.
258+#[derive(Debug)]
259+pub struct UnsupportedDisplaySize(u64);
260+
261+impl std::fmt::Display for UnsupportedDisplaySize {
262+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263+ write!(
264+ f,
265+ "this file states a {} pixel picture, past the {} pixel maximum",
266+ self.0,
267+ crate::MAX_RESOLUTION
268+ )
269+ }
270+}
271+
272+impl std::error::Error for UnsupportedDisplaySize {}
273+
274+fn unsupported_display_size(stated: u64) -> crate::Error {
275+ UnsupportedDisplaySize(stated).into()
276+}
277+
278+impl UnsupportedDisplaySize {
279+ /// Whether an `error` is one of these, however deep in a `Box` it is --
280+ /// [`NoVideoTrack::is_it`]'s and [`UnsupportedRotation::is_it`]'s twin,
281+ /// for a caller that shows the refusal differently from the others.
282+ pub fn is_it(error: &crate::Error) -> bool {
283+ error.downcast_ref::<Self>().is_some()
284+ }
285+}
286+
253 impl std::fmt::Display for NoVideoTrack {287 impl std::fmt::Display for NoVideoTrack {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 f.write_str(&self.0)289 f.write_str(&self.0)
@@ -372,12 +406,136 @@ impl PixelAspect {
372 /// The square pixels everything before anamorphic sources was.406 /// The square pixels everything before anamorphic sources was.
373 pub const SQUARE: Self = Self { h: 1, v: 1 };407 pub const SQUARE: Self = Self { h: 1, v: 1 };
374 408
409+ /// The widest display raster this engine will stretch a coded frame into.
410+ /// A container can claim any ratio at all, but no real one needs more
411+ /// than a 16k canvas's worth of columns, and the bound is what keeps a
412+ /// header claim from sizing an allocation no machine can satisfy.
413+ const MAX_DISPLAY_WIDTH: u32 = 65_535;
414+
415+ /// The largest term a *reduced* aspect ratio may keep. A real display
416+ /// ratio is a small pair of integers however it was spelled -- 4:3, 16:9,
417+ /// 8:5, 12:11 -- and ffmpeg's unreduced DAR spellings reduce to one.
418+ /// A pair whose reduction still carries a term past this is not a ratio
419+ /// at all but four chosen bytes, and it is refused as one.
420+ const MAX_ASPECT_TERM: u32 = 1024;
421+
422+ /// The ratio a container stated, or [`None`] when it stated one this
423+ /// engine cannot draw. Both halves arrive from header bytes -- read
424+ /// straight out of an mp4 `pasp` box, or computed from a Matroska
425+ /// `Display*` pair beside the coded size -- so the test lives here, once,
426+ /// rather than in each door that reads one.
427+ ///
428+ /// Unusable means: a zero half (nothing to divide by), or a *reduced*
429+ /// pair carrying a term past [`Self::MAX_ASPECT_TERM`] (a pair of chosen
430+ /// bytes rather than a ratio). Judged reduced, so an unreduced spelling of
431+ /// a real one -- ffmpeg writes 17280/12960 for 16:9 -- is judged by the
432+ /// picture it names and not by how many digits it took.
433+ pub fn stated(h: u32, v: u32) -> Option<Self> {
434+ if h == 0 || v == 0 {
435+ return None;
436+ }
437+ let (mut a, mut b) = (h, v);
438+ while b != 0 {
439+ (a, b) = (b, a % b);
440+ }
441+ (h / a <= Self::MAX_ASPECT_TERM && v / a <= Self::MAX_ASPECT_TERM).then_some(Self { h, v })
442+ }
443+
444+ /// The ratio a Matroska `DisplayUnit 0` `Display*` pair names, or [`None`]
445+ /// when the pair is not a picture.
446+ ///
447+ /// This is deliberately *not* [`Self::stated`], and the reason is what a
448+ /// unit-0 pair reduces to. The pair is a pixel SIZE, so reducing it
449+ /// against the coded size carries the sizes, not terms: 1920x1080 over
450+ /// 1440x1080 reduces to 4:3, but a 1920x803 scope -- one of the two most
451+ /// common letterbox ratios there are -- reduces to 1440:803, and a
452+ /// 1920x1037 flat to 1440:1037. A term bound tight enough to catch chosen
453+ /// bytes refuses exactly the pictures this arm exists to show.
454+ ///
455+ /// Only the *width* half is taken, because width is the only axis an
456+ /// aspect moves in this engine: `VideoMeta::height` is the coded height
457+ /// for every file, by design and by its own documentation. So the pair
458+ /// states the display width and the height is left where it is -- the same
459+ /// answer a 4:3 SAR over 1440x1080 gives, 1920x1080.
460+ ///
461+ /// What needs bounding is the raster, and [`Self::width_factor`] bounds
462+ /// that with [`Self::MAX_DISPLAY_WIDTH`] on every path. So this has only
463+ /// to refuse the degenerate claims: a zero half.
464+ ///
465+ /// # A named design gap, not an oversight
466+ ///
467+ /// The stated display *height* is read, checked, and then dropped. That is
468+ /// correct against this engine's model today -- `VideoMeta::height` is the
469+ /// coded height for every file, every door builds the display pair as
470+ /// `width_factor(coded_width)` against the coded height, and every consumer
471+ /// (`decode.rs`, `export.rs`, `hw.rs`'s `pixel_aspect_h`/`_v` beside
472+ /// `coded_width`/`coded_height`) reads the aspect as width-only.
473+ ///
474+ /// It becomes a real defect the moment any path starts honouring a stated
475+ /// display height: a 1920x803 pair would then have to drive
476+ /// `VideoMeta::height`, and this function would be silently feeding it
477+ /// `coded.0` instead. So the drop is recorded here rather than left as a
478+ /// line that looks like an oversight, and whoever makes that change should
479+ /// start by reading this paragraph -- the height half is being discarded
480+ /// deliberately, and the reason it was safe to discard is exactly the thing
481+ /// that change would remove.
482+ pub fn stated_size(display_width: u64, display_height: u64, coded: (u32, u32)) -> Option<Self> {
483+ // The height is checked for the degenerate claim and then goes unused:
484+ // a zero-height pair is a header that lies, and one this engine reads
485+ // as stating nothing. A real height cannot reach an allocation on this
486+ // path, because `VideoMeta::height` is the *coded* height, which both
487+ // doors already bound against [`crate::MAX_RESOLUTION`].
488+ if display_width == 0 || display_height == 0 || coded.0 == 0 {
489+ return None;
490+ }
491+ Some(Self {
492+ h: display_width.min(u64::from(u32::MAX)) as u32,
493+ v: coded.0,
494+ })
495+ }
496+
497+ /// The ratio a Matroska `DisplayUnit 3` display *aspect ratio* names against
498+ /// the coded frame, or [`None`] when the ratio is degenerate.
499+ ///
500+ /// Deliberately not [`Self::stated`], and for the same reason as
501+ /// [`Self::stated_size`]: the SAR is the DAR brought onto the coded frame,
502+ /// which multiplies by the coded size, so what the result reduces to
503+ /// carries *sizes* rather than terms. A 239:100 scope -- 2.39:1, one of the
504+ /// most common letterbox ratios there are -- derives 2151:1600 over a
505+ /// 1920x1080 coded frame and the same over 3840x2160, both past any term
506+ /// bound, while over a 1440x1080 frame it derives 717:400 and passes. The
507+ /// same ratio judged differently by the frame it happens to sit on is a
508+ /// bound measuring the wrong thing.
509+ ///
510+ /// The pair itself is the engine's own model, unchanged: the DAR against
511+ /// the coded frame, `dar_w * coded_h : dar_h * coded_w`, which is what
512+ /// [`Self::width_factor`] has always multiplied the coded width by. So this
513+ /// returns it unreduced and lets `width_factor` do the arithmetic and apply
514+ /// [`Self::MAX_DISPLAY_WIDTH`] to the raster it produces -- a bound on the
515+ /// picture, rather than on the digits of a derivation.
516+ pub fn stated_ratio(dar_width: u64, dar_height: u64, coded: (u32, u32)) -> Option<Self> {
517+ if dar_width == 0 || dar_height == 0 || coded.0 == 0 || coded.1 == 0 {
518+ return None;
519+ }
520+ Some(Self {
521+ h: dar_width
522+ .saturating_mul(u64::from(coded.1))
523+ .min(u64::from(u32::MAX)) as u32,
524+ v: dar_height
525+ .saturating_mul(u64::from(coded.0))
526+ .min(u64::from(u32::MAX)) as u32,
527+ })
528+ }
529+
375 /// Whether the displayed picture is the coded one, drawn one to one.530 /// Whether the displayed picture is the coded one, drawn one to one.
531+ ///
532+ /// Both halves of the ratio are untrusted bytes -- four of them in an mp4
533+ /// `pasp` box, and a product of two header values on the Matroska door --
534+ /// so a half that is zero is a claim this engine cannot divide by, and it
535+ /// means square rather than a division by zero: the file states nothing
536+ /// usable, which is what every file that states no aspect at all states.
376 pub fn is_square(self) -> bool {537 pub fn is_square(self) -> bool {
377- // An unstated ratio (0) and a stated 1:1 are the same pixels, and a538+ self.h == 0 || self.v == 0 || self.h == self.v
378- // degenerate one a crafted header claimed is square rather than a
379- // division by zero.
380- self.v == 0 || self.h == self.v
381 }539 }
382 540
383 /// How many coded columns one displayed column is worth: the factor the541 /// How many coded columns one displayed column is worth: the factor the
@@ -394,8 +552,39 @@ impl PixelAspect {
394 // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly,552 // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly,
395 // and a ratio that does not divide evenly is widened to the nearest553 // and a ratio that does not divide evenly is widened to the nearest
396 // even column count rather than shown cropped or squeezed.554 // even column count rather than shown cropped or squeezed.
555+ //
556+ // This is the one function every door reaches, so it is also where the
557+ // arithmetic is made total -- a ratio may be *read* here ([`Self::stated`]),
558+ // *built* here from a `Display*` pixel pair ([`Self::stated_size`]), or
559+ // both, and this cannot tell which. So it bounds the one thing all
560+ // three agree on: the raster. `coded * h` cannot overflow a u64, but
561+ // the quotient is then *narrowed* to a u32 and can wrap -- 1920 *
562+ // 0x00FF_FFFF narrows to 2_147_481_728 -- and a narrowed zero becomes a
563+ // zero-column raster. Anything outside [`Self::MAX_DISPLAY_WIDTH`], in
564+ // either direction, is drawn at the coded size instead: the picture is
565+ // shown slightly wrong, which is what every unrenderable header
566+ // deserves, rather than aborting the decode worker on a capacity
567+ // overflow before a pixel is drawn.
568+ //
569+ // Judging the *ratio* instead would be the wrong test here: a
570+ // `DisplayUnit 0` pair is a pixel size, so its reduced form carries
571+ // the sizes (a 1920x803 scope reduces to 1440:803) and no term bound
572+ // can be both tight enough to catch chosen bytes and loose enough to
573+ // admit the two most common letterbox ratios. The raster bound has no
574+ // such conflict.
397 let wide = u64::from(coded_width) * u64::from(self.h);575 let wide = u64::from(coded_width) * u64::from(self.h);
398- (((wide + u64::from(self.v) - 1) / u64::from(self.v)) as u32 | 1) & !1576+ let scaled = (wide + u64::from(self.v) - 1) / u64::from(self.v);
577+ // Down to the even grid, not up: `(x | 1) & !1` is what this has always
578+ // done, and it is what an odd quotient rounds to. A 239:100 scope over
579+ // a 3840x2160 coded frame scales to 5163 and has always displayed
580+ // 5162, not 5164 -- `next_multiple_of` would round the other way and
581+ // silently change every existing anamorphic picture by two columns.
582+ let rounded = scaled | 1;
583+ let rounded = rounded & !1;
584+ if rounded == 0 || rounded > u64::from(Self::MAX_DISPLAY_WIDTH) {
585+ return coded_width;
586+ }
587+ rounded as u32
399 }588 }
400 }589 }
401 590
@@ -917,6 +1106,15 @@ impl Mp4Demuxer {
917 None => Rotation::None,1106 None => Rotation::None,
918 };1107 };
919 let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height()));1108 let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height()));
1109+ // The same bound the Matroska door applies, on the same values: the
1110+ // mp4 crate types a track's dimensions as `u16`, which is a smaller
1111+ // claim than Matroska's but still eight times past the 8K ceiling --
1112+ // 65535x65535 is a legal `tkhd`, and it sizes the same buffers.
1113+ for stated in [coded_w, coded_h] {
1114+ if stated > crate::MAX_RESOLUTION {
1115+ return Err(unsupported_display_size(u64::from(stated)));
1116+ }
1117+ }
920 // The ratio one coded pixel is drawn at, off the sample entry's `pasp`1118 // The ratio one coded pixel is drawn at, off the sample entry's `pasp`
921 // box: absent for the square-pixel file, which is the common case.1119 // box: absent for the square-pixel file, which is the common case.
922 let pixel_aspect = pasp_of(path, track_id);1120 let pixel_aspect = pasp_of(path, track_id);
@@ -2552,8 +2750,32 @@ fn mkv_track_entry(
2552 let mut at = body;2750 let mut at = body;
2553 while let Some(e) = ebml_element(file, at, stop)? {2751 while let Some(e) = ebml_element(file, at, stop)? {
2554 match e.0 {2752 match e.0 {
2555- PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,2753+ // A container may state any size at all, and these
2556- PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,2754+ // two reach a per-frame allocation directly
2755+ // (`decode.rs` sizes its planes as
2756+ // `display_width * height`). The engine already has
2757+ // the bound for this -- [`crate::MAX_RESOLUTION`],
2758+ // 8K -- and it was applied to a keystroke and to a
2759+ // `.edith` line but never to a header, so a
2760+ // 65535x65535 track opened and asked for a
2761+ // gigabyte-scale buffer. A size past the bound is
2762+ // refused by name here, where the file can be
2763+ // refused, rather than discovered as a capacity
2764+ // overflow one layer down.
2765+ PIXEL_WIDTH => {
2766+ let stated = ebml_uint(file, e.1, e.2)?;
2767+ if stated > u64::from(crate::MAX_RESOLUTION) {
2768+ return Err(unsupported_display_size(stated));
2769+ }
2770+ width = stated as u32;
2771+ }
2772+ PIXEL_HEIGHT => {
2773+ let stated = ebml_uint(file, e.1, e.2)?;
2774+ if stated > u64::from(crate::MAX_RESOLUTION) {
2775+ return Err(unsupported_display_size(stated));
2776+ }
2777+ height = stated as u32;
2778+ }
2557 DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?,2779 DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?,
2558 DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?,2780 DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?,
2559 DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?,2781 DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?,
@@ -2911,14 +3133,21 @@ fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> {
2911 ///3133 ///
2912 /// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and3134 /// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and
2913 /// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured),3135 /// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured),
2914-/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where3136+/// 4 spells the sample aspect ratio itself, and **0 spells pixels** -- which is
2915-/// a pair beside the coded one at all means a crop, not an aspect. 1 and 23137+/// the ordinary case and the one a `Display*` pair is *for*: the spec has the
2916-/// (centimetres, inches) are physical sizes a picture this engine shows cannot3138+/// pair in pixels, so `1920`x`1080` beside a `1440`x`1080` coded track is
2917-/// mean anything by, and read as square rather than guessed. Every unstated or3139+/// exactly the 4/3 stretch, stated the way this door below reads it. An absent
2918-/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's3140+/// pair is the file saying nothing, which is also square; a pair that *is*
2919-/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the3141+/// present and equal to the coded one is square by arithmetic, not by
2920-/// PixelWidth and PixelHeight" when they mean the same thing, so a file that3142+/// assumption.
2921-/// means square most often says nothing at all.3143+///
3144+/// 1 and 2 (centimetres, inches) are physical sizes a picture this engine
3145+/// shows on a screen cannot mean anything by, and read as square rather than
3146+/// guessed. Every unstated or unusable shape is [`PixelAspect::SQUARE`], which
3147+/// is also the answer the spec's own default gives: DisplayWidth and
3148+/// DisplayHeight "SHOULD be set to the PixelWidth and PixelHeight" when they
3149+/// mean the same thing, so a file that means square most often says nothing
3150+/// at all.
2922 fn pixel_aspect_of(3151 fn pixel_aspect_of(
2923 display_width: u64,3152 display_width: u64,
2924 display_height: u64,3153 display_height: u64,
@@ -2931,22 +3160,45 @@ fn pixel_aspect_of(
2931 if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 {3160 if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 {
2932 return PixelAspect::SQUARE;3161 return PixelAspect::SQUARE;
2933 }3162 }
3163+ // A stated pair is judged by what it *means*, never by how it was spelled,
3164+ // and the three units mean three different things:
3165+ //
3166+ // 4 -- the pair IS the sample aspect ratio. It is read as a ratio and
3167+ // judged by its terms, because a `pasp`-shaped claim is a claim
3168+ // about a ratio and chosen bytes do not reduce small.
3169+ // 3 -- the pair is a display aspect ratio, which has to be brought onto
3170+ // the coded frame to become one. That derivation multiplies by the
3171+ // coded size, so what reduces afterwards carries the *sizes*: a
3172+ // 239:100 DAR over a 1920x1080 coded track derives 2151:1600, over
3173+ // 3840x2160 the same, and both are past any term bound. So the
3174+ // width is computed directly from the ratio instead and only the
3175+ // degenerate case is refused.
3176+ // 0 -- the pair is a display pixel size, taken as the display width.
3177+ //
3178+ // Units 3 and 0 are the same rule: neither is a ratio, so neither may be
3179+ // judged by the terms its derived pair reduces to. What bounds both is the
3180+ // raster [`PixelAspect::width_factor`] produces, which cannot refuse a real
3181+ // ratio because it never looks at the ratio's terms at all.
3182+ let coded = (coded_width, coded_height);
2934 match display_unit {3183 match display_unit {
2935 // 4: the pair *is* the sample aspect ratio.3184 // 4: the pair *is* the sample aspect ratio.
2936- 4 => PixelAspect {3185+ 4 => PixelAspect::stated(
2937- h: display_width.min(u32::MAX as u64) as u32,3186+ display_width.min(u64::from(u32::MAX)) as u32,
2938- v: display_height.min(u32::MAX as u64) as u32,3187+ display_height.min(u64::from(u32::MAX)) as u32,
2939- },3188+ )
2940- // 3: the pair is the display aspect ratio -- display_w / display_h --3189+ .unwrap_or(PixelAspect::SQUARE),
2941- // which the SAR is that against the coded one: sar = dar * h / w.3190+ // 3: a display aspect ratio against the coded frame, taken unreduced so
2942- // 16/9 over 1440x1080 lands on 4/3.3191+ // the term bound never judges it -- `width_factor` multiplies the coded
2943- 3 => PixelAspect {3192+ // width by this and bounds the raster it produces, and a bound on the
2944- h: ((display_width * u64::from(coded_height))3193+ // picture has no conflict with a real ratio.
2945- .min(u32::MAX as u64 * u64::from(coded_width))) as u32,3194+ 3 => PixelAspect::stated_ratio(display_width, display_height, coded)
2946- v: ((display_height * u64::from(coded_width))3195+ .unwrap_or(PixelAspect::SQUARE),
2947- .min(u32::MAX as u64 * u64::from(coded_height))) as u32,3196+ // 0: a display pixel size -- the width the picture is drawn at.
2948- },3197+ // 1920x1080 over 1440x1080 is the 4/3 stretch; 1920x803 is a 2.39:1
2949- // Pixels (0) or a physical unit this engine cannot interpret: square.3198+ // scope. Bounded by the raster, not by the terms it reduces to.
3199+ 0 => PixelAspect::stated_size(display_width, display_height, coded)
3200+ .unwrap_or(PixelAspect::SQUARE),
3201+ // A physical unit this engine cannot interpret: square.
2950 _ => PixelAspect::SQUARE,3202 _ => PixelAspect::SQUARE,
2951 }3203 }
2952 }3204 }
@@ -4173,7 +4425,11 @@ fn pasp_of(path: &Path, track_id: u32) -> PixelAspect {
4173 ) else {4425 ) else {
4174 return PixelAspect::SQUARE;4426 return PixelAspect::SQUARE;
4175 };4427 };
4176- PixelAspect { h, v }4428+ // Eight bytes a file chose, read into a ratio that sizes every raster
4429+ // downstream, so they are judged by [`PixelAspect::stated`] here: the
4430+ // aspect this engine *reports* is one it can draw, not merely one it
4431+ // survived.
4432+ PixelAspect::stated(h, v).unwrap_or(PixelAspect::SQUARE)
4177 }4433 }
4178 4434
4179 /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says4435 /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
@@ -5613,6 +5869,152 @@ mod tests {
5613 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");5869 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
5614 }5870 }
5615 5871
5872+ /// Four bytes of an mp4 `pasp` box are four bytes of untrusted input, and
5873+ /// every one of them reaches the width an allocation is sized from. A
5874+ /// header that claims `h == 0`, or one whose ratio widens the coded width
5875+ /// past the whole `u32` range, must read as the picture it really is --
5876+ /// square, drawn at the coded size -- rather than as a zero-column or a
5877+ /// wrapped raster the decode worker tries to allocate.
5878+ #[test]
5879+ fn an_untrusted_pixel_aspect_cannot_size_a_zero_or_wrapped_raster() {
5880+ // Two contracts, held separately, because they are enforced in two
5881+ // places and conflating them is what would break a real ratio.
5882+ //
5883+ // 1. At the READ, a ratio is refused: a zero half, or a *reduced*
5884+ // pair carrying a term past the bound. This is where an mp4 `pasp`
5885+ // is judged, and it is right there because a `pasp` pair IS the
5886+ // ratio.
5887+ for hostile in [
5888+ PixelAspect { h: 0, v: 1 },
5889+ PixelAspect { h: 1, v: 0 },
5890+ PixelAspect { h: 0, v: 0 },
5891+ // Four chosen bytes, not a ratio: reduced terms stay enormous.
5892+ PixelAspect { h: 0xFFFF_FFFF, v: 0xFFFF_FFFF - 1 },
5893+ PixelAspect { h: 1, v: 0x00FF_FFFF },
5894+ ] {
5895+ assert_eq!(
5896+ PixelAspect::stated(hostile.h, hostile.v),
5897+ None,
5898+ "{hostile:?} is not a ratio this engine can draw"
5899+ );
5900+ }
5901+ // A `DisplayUnit 0` pixel pair is NOT a ratio, so it is judged by
5902+ // `stated_size` instead -- and the two most common letterbox ratios
5903+ // must survive that arm, because its reduced form carries sizes:
5904+ for (dw, dh) in [(1920u64, 1080u64), (1920, 803), (1920, 1037)] {
5905+ assert!(
5906+ PixelAspect::stated_size(dw, dh, (1440, 1080)).is_some(),
5907+ "a {dw}x{dh} Display pair over a 1440x1080 coded track is a real picture"
5908+ );
5909+ }
5910+
5911+ // 2. In the ARITHMETIC, whatever ratio arrived -- read or built --
5912+ // cannot produce a zero column or a raster past the bound. This is
5913+ // the contract that holds for every door, including the one that
5914+ // builds its ratio from a pixel size rather than reading one.
5915+ let wrong: Vec<String> = [
5916+ PixelAspect { h: 0, v: 1 },
5917+ PixelAspect { h: 1, v: 0 },
5918+ PixelAspect { h: 0, v: 0 },
5919+ // 1920 * 0x00FF_FFFF is 32_212_252_800: it wraps a u32 to
5920+ // 2_147_483_648, which is a plausible-looking "width" and an
5921+ // impossible one to allocate.
5922+ PixelAspect { h: 0x00FF_FFFF, v: 1 },
5923+ ]
5924+ .into_iter()
5925+ .filter_map(|hostile| {
5926+ let factor = hostile.width_factor(1920);
5927+ (factor == 0 || factor > PixelAspect::MAX_DISPLAY_WIDTH)
5928+ .then(|| format!("{hostile:?} -> {factor} (a zero column or an oversized raster)"))
5929+ })
5930+ .collect();
5931+ assert!(
5932+ wrong.is_empty(),
5933+ "an unusable ratio must not size a raster:\n{}",
5934+ wrong.join("\n")
5935+ );
5936+ // The wrap case lands on the coded width rather than on the wrapped
5937+ // number, which is the specific refusal the defect turned on.
5938+ assert_eq!(
5939+ PixelAspect { h: 0x00FF_FFFF, v: 1 }.width_factor(1920),
5940+ 1920,
5941+ "a wrapped multiply is drawn at the coded width, not at 2_147_481_728"
5942+ );
5943+
5944+ // The sane ratios still stretch, bit for bit as they always did: the
5945+ // hardening refuses the untrusted, it does not round the ordinary.
5946+ assert_eq!(PixelAspect { h: 4, v: 3 }.width_factor(1440), 1920);
5947+ assert_eq!(PixelAspect { h: 1, v: 1 }.width_factor(1920), 1920);
5948+ assert_eq!(PixelAspect::SQUARE.width_factor(1920), 1920);
5949+ // An unreduced spelling of the same 4:3 lands on the same picture.
5950+ assert_eq!(PixelAspect { h: 16, v: 12 }.width_factor(1440), 1920);
5951+ // And a 2.39:1 scope built from a pixel size widens the coded frame
5952+ // by its own ratio rather than being refused for carrying sizes.
5953+ assert_eq!(
5954+ PixelAspect::stated_size(1920, 803, (1440, 1080))
5955+ .expect("a scope is a picture")
5956+ .width_factor(1440),
5957+ 1920,
5958+ "a 1920-wide scope over 1440 coded columns widens to 1920"
5959+ );
5960+ }
5961+
5962+ /// The rule the two `Display*` units that are not ratios share, in one
5963+ /// place: bringing a pair onto the coded frame makes what reduces carry the
5964+ /// coded *sizes*, so no term bound can judge it. A 2.39:1 scope is the case
5965+ /// that proves it -- the same DAR over three coded frames, which a term
5966+ /// bound reads three different ways.
5967+ #[test]
5968+ fn a_derived_pair_is_read_by_its_raster_on_every_coded_frame() {
5969+ for (coded, display) in [
5970+ ((1920u32, 1080u32), 2582u32),
5971+ ((3840, 2160), 5162),
5972+ ((720, 576), 1376),
5973+ ] {
5974+ let derived = PixelAspect::stated_ratio(239, 100, coded).expect("a scope is a picture");
5975+ assert_eq!(
5976+ derived.width_factor(coded.0),
5977+ display,
5978+ "a 239:100 DAR over {coded:?} displays {display}, as base did"
5979+ );
5980+ // The trap this exists to hold, measured rather than described: the
5981+ // same DAR derives pairs that reduce on *both* sides of the bound,
5982+ // so a term bound judges the same ratio differently depending only
5983+ // on the frame it happens to sit on.
5984+ let (mut a, mut b) = (derived.h, derived.v);
5985+ while b != 0 {
5986+ (a, b) = (b, a % b);
5987+ }
5988+ let reduced = (derived.h / a, derived.v / a);
5989+ let past = reduced.0 > PixelAspect::MAX_ASPECT_TERM;
5990+ assert_eq!(
5991+ past,
5992+ coded.0 != 720,
5993+ "{coded:?}: a 239:100 DAR derives {reduced:?}, {} the {} bound -- \
5994+ the same ratio, on both sides of it",
5995+ if past { "past" } else { "inside" },
5996+ PixelAspect::MAX_ASPECT_TERM
5997+ );
5998+ }
5999+ // And the 1440x1080 frame -- the one this lane's own fixture sits on --
6000+ // reduces to 717:400, which the bound admits. So the same ratio is
6001+ // refused on two frames and accepted on a third, which is why the
6002+ // bound cannot be tuned instead of replaced: any threshold catching
6003+ // 2151:1600 would be chosen by the frame rather than by the picture.
6004+ let over_1440 = PixelAspect::stated_ratio(239, 100, (1440, 1080)).expect("a picture");
6005+ let (mut a, mut b) = (over_1440.h, over_1440.v);
6006+ while b != 0 {
6007+ (a, b) = (b, a % b);
6008+ }
6009+ assert!(
6010+ over_1440.h / a <= PixelAspect::MAX_ASPECT_TERM,
6011+ "the same DAR over a 1440x1080 frame reduces to {}:{}, which the \
6012+ bound admits -- the same ratio, judged either way by its frame",
6013+ over_1440.h / a,
6014+ over_1440.v / a
6015+ );
6016+ }
6017+
5616 #[test]6018 #[test]
5617 fn rejects_misparse() {6019 fn rejects_misparse() {
5618 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());6020 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err());
crates/engine/src/lib.rsmodified+12 -2
@@ -94,8 +94,18 @@ pub fn is_image(path: &std::path::Path) -> bool {
94 })94 })
95 }95 }
96 96
97-/// The largest picture this engine composes onto, either way: 8K, which is where97+/// The largest picture this engine composes onto, either way: 7680, which is
98-/// a per-frame buffer stops being a sane thing to allocate.98+/// where a per-frame buffer stops being a sane thing to allocate.
99+///
100+/// That is 8K **UHD** (7680x4320), not 8K DCI (8192x4320). A DCI-width master
101+/// -- a ProRes 4444 XQ feature, for instance -- is 8192 wide and is refused
102+/// here by name, which it was not before the container doors asked this bound
103+/// of a file's own header rather than only of a keystroke and a `.edith` line.
104+/// The bound is deliberately not raised to 8192 to admit it: `is_resolution`
105+/// gates those two doors at 7680 too, and widening the ceiling on every path
106+/// to accommodate a container is a wider decision than a header fix should
107+/// make. A caller that needs DCI width needs the ceiling raised deliberately,
108+/// on all four doors at once.
99 pub const MAX_RESOLUTION: u32 = 7680;109 pub const MAX_RESOLUTION: u32 = 7680;
100 110
101 /// Whether a project resolution is a picture at all: not zero either way, and111 /// Whether a project resolution is a picture at all: not zero either way, and
crates/engine/tests/display_unit.rsadded+443 -0
@@ -0,0 +1,443 @@
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+
26+use std::path::{Path, PathBuf};
27+
28+use engine::demux::{Demuxer, PixelAspect};
29+
30+fn asset(name: &str) -> PathBuf {
31+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
32+ .join("../../assets")
33+ .join(name)
34+}
35+
36+struct Scratch(PathBuf);
37+
38+impl Scratch {
39+ fn new(tag: &str) -> Self {
40+ let dir = std::env::temp_dir().join(format!("edith-display-unit-{tag}"));
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+
51+impl 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.
60+const 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.
80+const 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.
92+fn 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.
110+fn 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+fn with_video_element(source: &Path, into: &Path, element: &str) {
125+ let from = hex(VIDEO_UNIT_3);
126+ let to = hex(element);
127+ assert_eq!(
128+ from.len(),
129+ to.len(),
130+ "a length-preserving patch: {element} is {} bytes, {} are needed",
131+ to.len(),
132+ from.len()
133+ );
134+ let bytes = std::fs::read(source).expect("read the source fixture");
135+ let at = bytes
136+ .windows(from.len())
137+ .position(|window| window == from)
138+ .unwrap_or_else(|| panic!("the fixture carries the expected {VIDEO_UNIT_3} element"));
139+ let mut patched = bytes.clone();
140+ patched[at..at + from.len()].copy_from_slice(&to);
141+ std::fs::write(into, patched).expect("write the patched fixture");
142+}
143+
144+fn hex(text: &str) -> Vec<u8> {
145+ (0..text.len() / 2)
146+ .map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).expect("hex in the fixture"))
147+ .collect()
148+}
149+
150+/// The reduced form of a ratio, so a ratio stated unreduced (the DAR arm
151+/// multiplies through by the coded size) compares equal to its simplest
152+/// spelling -- the same comparison the anamorphic suite makes.
153+fn reduced(aspect: PixelAspect) -> (u32, u32) {
154+ let gcd = |mut a: u32, mut b: u32| {
155+ while b != 0 {
156+ (a, b) = (b, a % b);
157+ }
158+ a.max(1)
159+ };
160+ let g = gcd(aspect.h, aspect.v);
161+ (aspect.h / g, aspect.v / g)
162+}
163+
164+/// The three spellings of one anamorphic picture must name one picture.
165+#[test]
166+fn a_display_unit_of_zero_states_the_stretch_in_pixels() {
167+ let scratch = Scratch::new("pixels");
168+ let unit0 = scratch.path("display_unit0.mkv");
169+ with_video_element(&asset("test_anamorphic.mkv"), &unit0, VIDEO_UNIT_0);
170+
171+ // The patch landed, and it landed on a file the demuxer opens.
172+ let patched = std::fs::read(&unit0).expect("read back the patched fixture");
173+ let original = std::fs::read(asset("test_anamorphic.mkv")).expect("read the original");
174+ assert_eq!(
175+ patched.len(),
176+ original.len(),
177+ "the patch preserves the file length, so no offset in it moved"
178+ );
179+ let wanted = hex(VIDEO_UNIT_0);
180+ assert_eq!(
181+ patched
182+ .windows(wanted.len())
183+ .position(|window| window == wanted),
184+ Some(369),
185+ "the DisplayUnit-0 element is where it was aimed"
186+ );
187+
188+ let (meta, _) = Demuxer::open(&unit0).expect("open the DisplayUnit-0 fixture");
189+
190+ // The samples are stored at the coded size, exactly as before the patch.
191+ assert_eq!(
192+ (meta.coded_width, meta.coded_height),
193+ (1440, 1080),
194+ "unit 0 changes what the file *says* about the picture, not how it is stored"
195+ );
196+
197+ // Unit 0 means the pair IS a pixel size, so 1920x1080 beside a 1440x1080
198+ // coded track is the 4/3 stretch -- and this is the whole defect: read as
199+ // square, the picture was drawn at 1440x1080, a quarter-width picture of
200+ // the same frame, with nothing to say so.
201+ assert!(
202+ !meta.pixel_aspect.is_square(),
203+ "DisplayUnit 0 with a Display pair beside the coded one is a stretch, \
204+ not a crop: got square ({:?})",
205+ meta.pixel_aspect
206+ );
207+ assert_eq!(
208+ (meta.width, meta.height),
209+ (1920, 1080),
210+ "the Display pair is the drawn size: 1920x1080 over a 1440x1080 coded track"
211+ );
212+
213+ // ...and it is the *same* ratio the other two spellings name, so all three
214+ // fixtures of one source agree on one drawn picture. Compared reduced,
215+ // because a ratio is named by the picture and not by how it was spelled:
216+ // the DAR arm multiplies through by the coded size and says 2073600 /
217+ // 1555200 where the SAR arm says 4 / 3.
218+ assert_eq!(
219+ reduced(meta.pixel_aspect),
220+ (4, 3),
221+ "1920x1080 over a 1440x1080 coded track is the same 4/3 the SAR and \
222+ DAR spellings name"
223+ );
224+ for sibling in ["test_anamorphic.mp4", "test_anamorphic.mkv"] {
225+ let (other, _) = Demuxer::open(&asset(sibling)).expect("open the sibling fixture");
226+ assert_eq!(
227+ (other.width, other.height),
228+ (meta.width, meta.height),
229+ "{sibling} states the same picture the DisplayUnit spelling states"
230+ );
231+ }
232+}
233+
234+/// Units 1 and 2 are physical sizes -- centimetres, inches -- which a picture
235+/// this engine shows on a screen cannot mean anything by. They stay square,
236+/// and saying so is the deliberate answer rather than an accident of the
237+/// match falling through.
238+#[test]
239+fn a_physical_display_unit_is_read_as_square() {
240+ let scratch = Scratch::new("physical");
241+ for (unit, tag) in [(1u8, "cm"), (2u8, "in")] {
242+ let element = VIDEO_UNIT_0.replacen("54b28100", &format!("54b2810{unit}"), 1);
243+ let into = scratch.path(&format!("display_unit{unit}.mkv"));
244+ with_video_element(&asset("test_anamorphic.mkv"), &into, &element);
245+ let (meta, _) = Demuxer::open(&into).expect("open the physical-unit fixture");
246+ assert!(
247+ meta.pixel_aspect.is_square(),
248+ "DisplayUnit {unit} ({tag}) is a physical size this engine cannot interpret, \
249+ so the pixels stay square: got {:?}",
250+ meta.pixel_aspect
251+ );
252+ }
253+}
254+/// The coded size is untrusted too, and it reaches an allocation directly:
255+/// `decode.rs` sizes its stretched planes as `display_width * height`. The
256+/// engine already has a bound for exactly this -- [`engine::MAX_RESOLUTION`],
257+/// 8K, the size a per-frame buffer stops being sane at -- and the demux
258+/// readers never applied it to a container-stated width or height.
259+///
260+/// The fixture patches the `PixelWidth`/`PixelHeight` payloads to 65535 each,
261+/// which is a legal two-byte EBML integer, so the element keeps its exact
262+/// length and the copy stays seekable.
263+#[test]
264+fn a_coded_size_past_the_resolution_bound_is_refused_not_allocated() {
265+ let scratch = Scratch::new("huge");
266+ let into = scratch.path("huge_dims.mkv");
267+ with_video_element(
268+ &asset("test_anamorphic.mkv"),
269+ &into,
270+ &VIDEO_UNIT_3
271+ .replacen("b08205a0", "b082ffff", 1)
272+ .replacen("ba820438", "ba82ffff", 1),
273+ );
274+
275+ // Refused, and refused by name: the open fails with a message that says
276+ // what the file claimed and what the maximum is, rather than succeeding
277+ // and handing a caller a 65535x65535 to allocate.
278+ let Err(why) = Demuxer::open(&into) else {
279+ panic!("a 65535x65535 header is refused by name, never opened");
280+ };
281+ let said = why.to_string();
282+ assert!(
283+ said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()),
284+ "the refusal names the size claimed and the maximum: {said}"
285+ );
286+ assert!(
287+ engine::demux::UnsupportedDisplaySize::is_it(&why),
288+ "and it is the named refusal a caller can match on, not a string"
289+ );
290+}
291+
292+/// The bound is a ceiling on a real picture, not a floor on a file: the
293+/// largest size a real source states still opens, untouched.
294+#[test]
295+fn a_real_size_up_to_the_bound_still_opens() {
296+ let (meta, _) = Demuxer::open(&asset("test_anamorphic.mkv")).expect("open the fixture");
297+ assert!(
298+ engine::is_resolution(meta.coded_width, meta.coded_height),
299+ "the ordinary fixture is inside the bound, which is what keeps the \
300+ bound from refusing the library"
301+ );
302+}
303+
304+/// The regression this arm must not carry: a `DisplayUnit 0` pair is a pixel
305+/// SIZE, so its *reduced* form is the size against the coded size, not a small
306+/// pair of integers -- and the common cinematic display ratios do not reduce
307+/// small. A 1920x803 scope over a 1440x1080 coded track reduces to 1440:803,
308+/// and 1920x1037 (1.85:1 flat) likewise.
309+///
310+/// The reduced-term bound is the right test for an mp4 `pasp`, where the pair
311+/// *is* the ratio, and the wrong test here: applying it made the two most
312+/// common letterbox ratios open square, on exactly the arm this fix newly
313+/// enabled. The quantity that needs bounding on this door is the resulting
314+/// display WIDTH, which `width_factor` already caps.
315+#[test]
316+fn a_cinematic_display_unit_zero_stretches_rather_than_reading_square() {
317+ let scratch = Scratch::new("cinema");
318+ for (dw, dh, ratio, tag) in [
319+ (1920u16, 803u16, "2.39:1 scope", "scope"),
320+ (1920, 1037, "1.85:1 flat", "flat"),
321+ ] {
322+ let into = scratch.path(&format!("{tag}.mkv"));
323+ with_video_element(
324+ &asset("test_anamorphic.mkv"),
325+ &into,
326+ &video_unit_0(dw, dh),
327+ );
328+
329+ let (meta, _) = Demuxer::open(&into)
330+ .unwrap_or_else(|why| panic!("{tag} ({ratio}): open failed: {why}"));
331+ assert!(
332+ !meta.pixel_aspect.is_square(),
333+ "{tag} ({ratio}): a DisplayUnit 0 pixel pair of {dw}x{dh} over a \
334+ 1440x1080 coded track is a stretch, not square: got {:?}",
335+ meta.pixel_aspect
336+ );
337+ // The stated DISPLAY WIDTH is the drawn width: unit 0 states it in
338+ // pixels, so it is taken as stated, not re-derived. The height stays
339+ // the coded one because a pixel aspect moves the width only in this
340+ // engine -- `VideoMeta::height` is the coded height for every file, by
341+ // design. A 1920x803 scope is therefore drawn 1920x1080 here: the
342+ // width is the file's own claim and the height is this engine's
343+ // documented model, and the two are not the same thing.
344+ assert_eq!(
345+ meta.width,
346+ u32::from(dw),
347+ "{tag} ({ratio}): the stated Display width is the drawn width"
348+ );
349+ assert_eq!(
350+ meta.height,
351+ 1080,
352+ "{tag} ({ratio}): a pixel aspect never moves the height; the coded one stands"
353+ );
354+ assert_eq!(
355+ (meta.coded_width, meta.coded_height),
356+ (1440, 1080),
357+ "{tag} ({ratio}): the samples are still stored at the coded size"
358+ );
359+ }
360+}
361+
362+/// The unit-3 arm, which is the same rule as unit 0 one arm away: a DAR is
363+/// not a ratio either, because bringing it onto the coded frame multiplies by
364+/// the coded size, and what reduces afterwards carries the *sizes*.
365+///
366+/// So the same 2.39:1 scope is judged differently by the frame it sits on,
367+/// which is a bound measuring the wrong thing. Over a 1920x1080 coded track a
368+/// 239:100 DAR derives 2151:1600 and over 3840x2160 the same -- both past any
369+/// term bound -- while over 1440x1080 it derives 717:400 and passes. Base
370+/// `9f780f7` opened all three at the widths below; the bound made the first
371+/// two open square, a measured regression rather than a latent gap.
372+///
373+/// The expected widths are the ones BASE produced, measured by running base
374+/// over these same fixtures. This is the property that matters: the arm must
375+/// read the DAR the way it always did, so the test pins base's answers rather
376+/// than a fresh computation of them.
377+#[test]
378+fn a_display_unit_three_dar_reads_the_same_on_every_coded_frame() {
379+ let scratch = Scratch::new("dar");
380+ for (coded, expected, tag) in [
381+ ((1920u16, 1080u16), 2582u32, "1920x1080"), // 239:100 -> 2151:1600
382+ ((3840, 2160), 5162, "3840x2160"), // 239:100 -> 2151:1600
383+ ((720, 576), 1376, "720x576"), // 239:100 -> 239:125
384+ ] {
385+ let into = scratch.path(&format!("dar_{tag}.mkv"));
386+ with_video_element(
387+ &asset("test_anamorphic.mkv"),
388+ &into,
389+ &video_unit_3(239, 100, coded.0, coded.1),
390+ );
391+
392+ let (meta, _) = Demuxer::open(&into)
393+ .unwrap_or_else(|why| panic!("{tag}: open failed: {why}"));
394+ assert_eq!(
395+ (meta.coded_width, meta.coded_height),
396+ (u32::from(coded.0), u32::from(coded.1)),
397+ "{tag}: the coded frame the DAR is stated over"
398+ );
399+ assert!(
400+ !meta.pixel_aspect.is_square(),
401+ "{tag}: a 239:100 DAR is a 2.39:1 stretch whatever frame it sits \
402+ on: got square ({:?})",
403+ meta.pixel_aspect
404+ );
405+ assert_eq!(
406+ meta.width, expected,
407+ "{tag}: the display width base 9f780f7 produced for this DAR"
408+ );
409+ assert_eq!(
410+ meta.height,
411+ u32::from(coded.1),
412+ "{tag}: a pixel aspect never moves the height; the coded one stands"
413+ );
414+ }
415+}
416+
417+/// The term bound must survive where it belongs. The unit-4 SAR pair IS a
418+/// ratio, so a hostile one is still refused -- this arm is what stops the
419+/// split from reading as "the bound was dropped".
420+#[test]
421+fn a_hostile_sar_pair_is_still_refused_by_the_term_bound() {
422+ // Reduced terms far past the bound, stated as a SAR pair: four chosen
423+ // bytes, not a ratio.
424+ for hostile in [(0xFFFF_FFFFu32, 0xFFFF_FFFFu32 - 1), (1, 0x00FF_FFFF)] {
425+ assert_eq!(
426+ PixelAspect::stated(hostile.0, hostile.1),
427+ None,
428+ "{hostile:?} is chosen bytes, not a ratio, and is refused as one"
429+ );
430+ }
431+ // ...and a real SAR pair is still taken, so the bound is not simply
432+ // refusing everything on this arm.
433+ assert_eq!(
434+ PixelAspect::stated(4, 3),
435+ Some(PixelAspect { h: 4, v: 3 }),
436+ "a 4:3 SAR is a ratio and is read as one"
437+ );
438+ assert_eq!(
439+ PixelAspect::stated(16, 12),
440+ Some(PixelAspect { h: 16, v: 12 }),
441+ "an unreduced 4:3 spelling is judged by the ratio it names"
442+ );
443+}
crates/engine/tests/untrusted_header.rsadded+247 -0
@@ -0,0 +1,247 @@
1+//! What a container header claims is untrusted input, and the numbers it
2+//! claims them with reach every raster this engine sizes.
3+//!
4+//! An mp4 `pasp` box is eight bytes: two 32-bit big-endian integers, the ratio
5+//! one coded pixel is drawn at. Nothing in the file makes them sane. Four
6+//! chosen bytes are enough to make the probe report a zero width, or a width
7+//! that wrapped a `u32` on its way down from the multiply -- and both of those
8+//! go straight into the `resize` that sizes the decode worker's stretched
9+//! planes, before a single pixel is drawn.
10+//!
11+//! This test byte-patches a copy of the baseline fixture and opens it through
12+//! the ordinary door: the patched files live in a temp directory and are made
13+//! here, so no hostile bytes are committed to the repository.
14+//!
15+//! ```text
16+//! cargo test -p engine --test untrusted_header -- --test-threads=1
17+//! ```
18+
19+use std::path::{Path, PathBuf};
20+
21+use engine::demux::Demuxer;
22+
23+fn asset(name: &str) -> PathBuf {
24+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
25+ .join("../../assets")
26+ .join(name)
27+}
28+
29+/// A temp directory that cleans itself up, so a failing test does not leave a
30+/// hostile mp4 lying around for the next one to trip over.
31+struct Scratch(PathBuf);
32+
33+impl Scratch {
34+ fn new(tag: &str) -> Self {
35+ let dir = std::env::temp_dir().join(format!("edith-untrusted-header-{tag}"));
36+ let _ = std::fs::remove_dir_all(&dir);
37+ std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture");
38+ Self(dir)
39+ }
40+
41+ fn path(&self, name: &str) -> PathBuf {
42+ self.0.join(name)
43+ }
44+}
45+
46+impl Drop for Scratch {
47+ fn drop(&mut self) {
48+ let _ = std::fs::remove_dir_all(&self.0);
49+ }
50+}
51+
52+/// A copy of `source` with the eight bytes of its `pasp` payload replaced.
53+///
54+/// Returns the byte offset the payload was written at, so the test can name
55+/// the exact bytes it changed rather than asserting about a file whose
56+/// provenance is a fixture somebody might regenerate.
57+fn patch_pasp(source: &Path, into: &Path, h: u32, v: u32) -> usize {
58+ let bytes = std::fs::read(source).expect("read the source fixture");
59+ let at = bytes
60+ .windows(4)
61+ .position(|window| window == b"pasp")
62+ .expect("the fixture carries a pasp box")
63+ + 4; // the type is four bytes; the payload follows it
64+ let mut patched = bytes.clone();
65+ patched[at..at + 4].copy_from_slice(&h.to_be_bytes());
66+ patched[at + 4..at + 8].copy_from_slice(&v.to_be_bytes());
67+ std::fs::write(into, patched).expect("write the patched fixture");
68+ at
69+}
70+
71+/// The claims an mp4 can make about its pixels that are not a picture: a zero
72+/// half, which divides to nothing, and a huge half, whose multiply wraps a
73+/// `u32` on the way down.
74+#[test]
75+fn a_pasp_box_cannot_declare_a_zero_or_wrapped_display_width() {
76+ // Read the untouched fixture first: the patches below are asserted
77+ // against *its* numbers, so a regenerated fixture that stops carrying a
78+ // `pasp` box fails here loudly instead of silently passing.
79+ let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline");
80+ let coded = (baseline.coded_width, baseline.coded_height);
81+ assert_eq!(
82+ (baseline.width, baseline.height),
83+ coded,
84+ "the baseline fixture is square, so its display pair is its coded pair -- which is \
85+ what the patched files are asserted against"
86+ );
87+ assert!(
88+ baseline.pixel_aspect.is_square(),
89+ "the baseline fixture states 1:1, which is square"
90+ );
91+
92+ let scratch = Scratch::new("pasp");
93+ for (tag, h, v) in [
94+ ("zero_h", 0u32, 1u32),
95+ ("zero_v", 1, 0),
96+ ("both_zero", 0, 0),
97+ // 1920 * 0x00FF_FFFF = 32_212_252_800, which narrowed to a u32 is
98+ // 2_147_481_728: a width that looks plausible in a log and cannot be
99+ // allocated on any machine this runs on.
100+ ("wrap_h", 0x00FF_FFFF, 1),
101+ // 1:0x00FF_FFFF is the other end: a two-column strip of a picture.
102+ ("wrap_v", 1, 0x00FF_FFFF),
103+ ] {
104+ let name = format!("pasp_{tag}.mp4");
105+ let into = scratch.path(&name);
106+ let at = patch_pasp(&asset("test_baseline.mp4"), &into, h, v);
107+ assert_eq!(
108+ std::fs::read(&into).unwrap()[at..at + 8],
109+ [h.to_be_bytes(), v.to_be_bytes()].concat(),
110+ "{tag}: the patch landed where it was aimed"
111+ );
112+
113+ // The ordinary door: open the file the way a library open does.
114+ let (meta, _) = Demuxer::open(&into)
115+ .unwrap_or_else(|why| panic!("{tag} (pasp {h}:{v} at byte {at}): open failed: {why}"));
116+
117+ // A header that claims an unusable ratio is read as the picture it
118+ // really is: the coded one, square, drawn one to one.
119+ assert_eq!(
120+ (meta.width, meta.height),
121+ (baseline.width, baseline.height),
122+ "{tag} (pasp {h}:{v}): an unusable ratio must read as square, not as a \
123+ zero-column or wrapped raster"
124+ );
125+ assert!(
126+ meta.pixel_aspect.is_square(),
127+ "{tag} (pasp {h}:{v}): the reported aspect must be one this engine can draw"
128+ );
129+ assert!(
130+ meta.width > 0 && meta.height > 0,
131+ "{tag} (pasp {h}:{v}): a zero dimension here is what sizes an allocation to nothing"
132+ );
133+ }
134+}
135+
136+/// The half that matters is not the probe: it is the worker that sizes its
137+/// stretched planes from the same number. A decode that used to abort on a
138+/// capacity overflow here now returns the coded picture.
139+#[test]
140+fn a_hostile_pasp_decodes_the_coded_picture_instead_of_aborting() {
141+ let scratch = Scratch::new("decode");
142+ let into = scratch.path("pasp_wrap.mp4");
143+ patch_pasp(&asset("test_baseline.mp4"), &into, 0x00FF_FFFF, 1);
144+
145+ let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline");
146+ let coded = (baseline.width, baseline.height);
147+ let (meta, _) = Demuxer::open(&into).expect("a hostile header is still an openable file");
148+ let (_, frames, _) =
149+ engine::DecodeSession::open_at(&into, 0).expect("a hostile header does not stop the decoder");
150+ let frame = frames
151+ .recv()
152+ .expect("the first frame arrives rather than the worker aborting on its allocation");
153+ assert_eq!(
154+ frame.width,
155+ meta.width,
156+ "the decoded frame is drawn at the width the probe reported"
157+ );
158+ assert_eq!(
159+ (frame.width, frame.height),
160+ coded,
161+ "the coded picture, drawn square: a wrapped claim resizes nothing"
162+ );
163+}
164+/// The same bound, on the other door. An mp4 states its picture in a visual
165+/// sample entry's two `u16` fields -- a smaller claim than Matroska's EBML
166+/// integer, but still eight times past the 8K ceiling, and it reaches the same
167+/// `decode.rs` allocation.
168+#[test]
169+fn a_mp4_may_not_state_a_picture_past_the_resolution_bound() {
170+ let scratch = Scratch::new("mp4dims");
171+ let into = scratch.path("mp4_huge_dims.mp4");
172+ patch_sample_entry_size(&asset("test_baseline.mp4"), &into, 65535, 65535);
173+
174+ let Err(why) = Demuxer::open(&into) else {
175+ panic!("a 65535x65535 mp4 is refused by name, never opened");
176+ };
177+ let said = why.to_string();
178+ assert!(
179+ said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()),
180+ "the refusal names the size claimed and the maximum: {said}"
181+ );
182+ assert!(
183+ engine::demux::UnsupportedDisplaySize::is_it(&why),
184+ "and it is the named refusal a caller can match on, not a string"
185+ );
186+}
187+
188+/// A copy of `source` with the width and height of its first visual sample
189+/// entry set to `w`/`h` (ISO/IEC 14496-12 §12.1.3: two 16-bit fields, 24
190+/// bytes into the entry, after the 6 reserved bytes, the 2-byte data
191+/// reference index and the 16 bytes of pre-defined and reserved fields).
192+fn patch_sample_entry_size(source: &Path, into: &Path, w: u16, h: u16) {
193+ let mut bytes = std::fs::read(source).expect("read the source fixture");
194+ let stsd = find(&bytes, b"stsd").expect("the fixture has a sample description");
195+ // 'stsd' + version/flags + entry_count, then the first entry.
196+ let entry = stsd + 12;
197+ assert_eq!(&bytes[entry + 4..entry + 8], b"avc1", "the first entry is the video one");
198+ bytes[entry + 32..entry + 34].copy_from_slice(&w.to_be_bytes());
199+ bytes[entry + 34..entry + 36].copy_from_slice(&h.to_be_bytes());
200+ std::fs::write(into, bytes).expect("write the patched fixture");
201+}
202+
203+fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
204+ haystack
205+ .windows(needle.len())
206+ .position(|window| window == needle)
207+}
208+
209+/// The boundary of the bound, stated as a test rather than left as a surprise:
210+/// 7680 -- 8K UHD -- opens, and 8192 -- 8K DCI, a real ProRes 4444 XQ master
211+/// width -- is refused by name.
212+///
213+/// The refusal of a DCI-width master is a behaviour change this lane
214+/// introduced: before it, the bound was asked only of a keystroke and a
215+/// `.edith` line, never of a file's own header, so a container could state any
216+/// size at all. `MAX_RESOLUTION` stays 7680 rather than being raised to 8192,
217+/// because it gates those two doors at 7680 too and widening the ceiling on
218+/// every path to accommodate a container is a wider decision than a header fix
219+/// should make.
220+#[test]
221+fn the_resolution_bound_admits_uhd_and_refuses_dci_width_by_name() {
222+ let scratch = Scratch::new("dci");
223+ let coded_height = 720u16;
224+
225+ let uhd = scratch.path("uhd_7680.mp4");
226+ patch_sample_entry_size(&asset("test_baseline.mp4"), &uhd, 7680, coded_height);
227+ let (meta, _) = Demuxer::open(&uhd).expect("8K UHD is inside the bound and opens");
228+ assert_eq!(
229+ (meta.coded_width, meta.coded_height),
230+ (7680, u32::from(coded_height)),
231+ "an 8K UHD header is read as stated"
232+ );
233+
234+ let dci = scratch.path("dci_8192.mp4");
235+ patch_sample_entry_size(&asset("test_baseline.mp4"), &dci, 8192, coded_height);
236+ let Err(why) = Demuxer::open(&dci) else {
237+ panic!("an 8192-wide DCI master is refused by name, never opened");
238+ };
239+ assert!(
240+ engine::demux::UnsupportedDisplaySize::is_it(&why),
241+ "the refusal is the named one a caller can match: {why}"
242+ );
243+ assert!(
244+ why.to_string().contains("8192"),
245+ "and it names the width claimed: {why}"
246+ );
247+}