diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 8fea412..c52426b 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -250,6 +250,40 @@ fn mp4_codec(fourcc: &[u8; 4]) -> Option { #[derive(Debug)] pub struct NoVideoTrack(String); +/// A container that states a picture larger than this engine will compose: +/// past [`crate::MAX_RESOLUTION`], where a per-frame buffer stops being a +/// sane thing to allocate. Refused by name, like the other named refusals, +/// because "this file is too big to open" is something a user can act on and +/// a capacity overflow one layer down is not. +#[derive(Debug)] +pub struct UnsupportedDisplaySize(u64); + +impl std::fmt::Display for UnsupportedDisplaySize { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "this file states a {} pixel picture, past the {} pixel maximum", + self.0, + crate::MAX_RESOLUTION + ) + } +} + +impl std::error::Error for UnsupportedDisplaySize {} + +fn unsupported_display_size(stated: u64) -> crate::Error { + UnsupportedDisplaySize(stated).into() +} + +impl UnsupportedDisplaySize { + /// Whether an `error` is one of these, however deep in a `Box` it is -- + /// [`NoVideoTrack::is_it`]'s and [`UnsupportedRotation::is_it`]'s twin, + /// for a caller that shows the refusal differently from the others. + pub fn is_it(error: &crate::Error) -> bool { + error.downcast_ref::().is_some() + } +} + impl std::fmt::Display for NoVideoTrack { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) @@ -372,12 +406,136 @@ impl PixelAspect { /// The square pixels everything before anamorphic sources was. pub const SQUARE: Self = Self { h: 1, v: 1 }; + /// The widest display raster this engine will stretch a coded frame into. + /// A container can claim any ratio at all, but no real one needs more + /// than a 16k canvas's worth of columns, and the bound is what keeps a + /// header claim from sizing an allocation no machine can satisfy. + const MAX_DISPLAY_WIDTH: u32 = 65_535; + + /// The largest term a *reduced* aspect ratio may keep. A real display + /// ratio is a small pair of integers however it was spelled -- 4:3, 16:9, + /// 8:5, 12:11 -- and ffmpeg's unreduced DAR spellings reduce to one. + /// A pair whose reduction still carries a term past this is not a ratio + /// at all but four chosen bytes, and it is refused as one. + const MAX_ASPECT_TERM: u32 = 1024; + + /// The ratio a container stated, or [`None`] when it stated one this + /// engine cannot draw. Both halves arrive from header bytes -- read + /// straight out of an mp4 `pasp` box, or computed from a Matroska + /// `Display*` pair beside the coded size -- so the test lives here, once, + /// rather than in each door that reads one. + /// + /// Unusable means: a zero half (nothing to divide by), or a *reduced* + /// pair carrying a term past [`Self::MAX_ASPECT_TERM`] (a pair of chosen + /// bytes rather than a ratio). Judged reduced, so an unreduced spelling of + /// a real one -- ffmpeg writes 17280/12960 for 16:9 -- is judged by the + /// picture it names and not by how many digits it took. + pub fn stated(h: u32, v: u32) -> Option { + if h == 0 || v == 0 { + return None; + } + let (mut a, mut b) = (h, v); + while b != 0 { + (a, b) = (b, a % b); + } + (h / a <= Self::MAX_ASPECT_TERM && v / a <= Self::MAX_ASPECT_TERM).then_some(Self { h, v }) + } + + /// The ratio a Matroska `DisplayUnit 0` `Display*` pair names, or [`None`] + /// when the pair is not a picture. + /// + /// This is deliberately *not* [`Self::stated`], and the reason is what a + /// unit-0 pair reduces to. The pair is a pixel SIZE, so reducing it + /// against the coded size carries the sizes, not terms: 1920x1080 over + /// 1440x1080 reduces to 4:3, but a 1920x803 scope -- one of the two most + /// common letterbox ratios there are -- reduces to 1440:803, and a + /// 1920x1037 flat to 1440:1037. A term bound tight enough to catch chosen + /// bytes refuses exactly the pictures this arm exists to show. + /// + /// Only the *width* half is taken, because width is the only axis an + /// aspect moves in this engine: `VideoMeta::height` is the coded height + /// for every file, by design and by its own documentation. So the pair + /// states the display width and the height is left where it is -- the same + /// answer a 4:3 SAR over 1440x1080 gives, 1920x1080. + /// + /// What needs bounding is the raster, and [`Self::width_factor`] bounds + /// that with [`Self::MAX_DISPLAY_WIDTH`] on every path. So this has only + /// to refuse the degenerate claims: a zero half. + /// + /// # A named design gap, not an oversight + /// + /// The stated display *height* is read, checked, and then dropped. That is + /// correct against this engine's model today -- `VideoMeta::height` is the + /// coded height for every file, every door builds the display pair as + /// `width_factor(coded_width)` against the coded height, and every consumer + /// (`decode.rs`, `export.rs`, `hw.rs`'s `pixel_aspect_h`/`_v` beside + /// `coded_width`/`coded_height`) reads the aspect as width-only. + /// + /// It becomes a real defect the moment any path starts honouring a stated + /// display height: a 1920x803 pair would then have to drive + /// `VideoMeta::height`, and this function would be silently feeding it + /// `coded.0` instead. So the drop is recorded here rather than left as a + /// line that looks like an oversight, and whoever makes that change should + /// start by reading this paragraph -- the height half is being discarded + /// deliberately, and the reason it was safe to discard is exactly the thing + /// that change would remove. + pub fn stated_size(display_width: u64, display_height: u64, coded: (u32, u32)) -> Option { + // The height is checked for the degenerate claim and then goes unused: + // a zero-height pair is a header that lies, and one this engine reads + // as stating nothing. A real height cannot reach an allocation on this + // path, because `VideoMeta::height` is the *coded* height, which both + // doors already bound against [`crate::MAX_RESOLUTION`]. + if display_width == 0 || display_height == 0 || coded.0 == 0 { + return None; + } + Some(Self { + h: display_width.min(u64::from(u32::MAX)) as u32, + v: coded.0, + }) + } + + /// The ratio a Matroska `DisplayUnit 3` display *aspect ratio* names against + /// the coded frame, or [`None`] when the ratio is degenerate. + /// + /// Deliberately not [`Self::stated`], and for the same reason as + /// [`Self::stated_size`]: the SAR is the DAR brought onto the coded frame, + /// which multiplies by the coded size, so what the result reduces to + /// carries *sizes* rather than terms. A 239:100 scope -- 2.39:1, one of the + /// most common letterbox ratios there are -- derives 2151:1600 over a + /// 1920x1080 coded frame and the same over 3840x2160, both past any term + /// bound, while over a 1440x1080 frame it derives 717:400 and passes. The + /// same ratio judged differently by the frame it happens to sit on is a + /// bound measuring the wrong thing. + /// + /// The pair itself is the engine's own model, unchanged: the DAR against + /// the coded frame, `dar_w * coded_h : dar_h * coded_w`, which is what + /// [`Self::width_factor`] has always multiplied the coded width by. So this + /// returns it unreduced and lets `width_factor` do the arithmetic and apply + /// [`Self::MAX_DISPLAY_WIDTH`] to the raster it produces -- a bound on the + /// picture, rather than on the digits of a derivation. + pub fn stated_ratio(dar_width: u64, dar_height: u64, coded: (u32, u32)) -> Option { + if dar_width == 0 || dar_height == 0 || coded.0 == 0 || coded.1 == 0 { + return None; + } + Some(Self { + h: dar_width + .saturating_mul(u64::from(coded.1)) + .min(u64::from(u32::MAX)) as u32, + v: dar_height + .saturating_mul(u64::from(coded.0)) + .min(u64::from(u32::MAX)) as u32, + }) + } + /// Whether the displayed picture is the coded one, drawn one to one. + /// + /// Both halves of the ratio are untrusted bytes -- four of them in an mp4 + /// `pasp` box, and a product of two header values on the Matroska door -- + /// so a half that is zero is a claim this engine cannot divide by, and it + /// means square rather than a division by zero: the file states nothing + /// usable, which is what every file that states no aspect at all states. pub fn is_square(self) -> bool { - // An unstated ratio (0) and a stated 1:1 are the same pixels, and a - // degenerate one a crafted header claimed is square rather than a - // division by zero. - self.v == 0 || self.h == self.v + self.h == 0 || self.v == 0 || self.h == self.v } /// How many coded columns one displayed column is worth: the factor the @@ -394,8 +552,39 @@ impl PixelAspect { // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly, // and a ratio that does not divide evenly is widened to the nearest // even column count rather than shown cropped or squeezed. + // + // This is the one function every door reaches, so it is also where the + // arithmetic is made total -- a ratio may be *read* here ([`Self::stated`]), + // *built* here from a `Display*` pixel pair ([`Self::stated_size`]), or + // both, and this cannot tell which. So it bounds the one thing all + // three agree on: the raster. `coded * h` cannot overflow a u64, but + // the quotient is then *narrowed* to a u32 and can wrap -- 1920 * + // 0x00FF_FFFF narrows to 2_147_481_728 -- and a narrowed zero becomes a + // zero-column raster. Anything outside [`Self::MAX_DISPLAY_WIDTH`], in + // either direction, is drawn at the coded size instead: the picture is + // shown slightly wrong, which is what every unrenderable header + // deserves, rather than aborting the decode worker on a capacity + // overflow before a pixel is drawn. + // + // Judging the *ratio* instead would be the wrong test here: a + // `DisplayUnit 0` pair is a pixel size, so its reduced form carries + // the sizes (a 1920x803 scope reduces to 1440:803) and no term bound + // can be both tight enough to catch chosen bytes and loose enough to + // admit the two most common letterbox ratios. The raster bound has no + // such conflict. let wide = u64::from(coded_width) * u64::from(self.h); - (((wide + u64::from(self.v) - 1) / u64::from(self.v)) as u32 | 1) & !1 + let scaled = (wide + u64::from(self.v) - 1) / u64::from(self.v); + // Down to the even grid, not up: `(x | 1) & !1` is what this has always + // done, and it is what an odd quotient rounds to. A 239:100 scope over + // a 3840x2160 coded frame scales to 5163 and has always displayed + // 5162, not 5164 -- `next_multiple_of` would round the other way and + // silently change every existing anamorphic picture by two columns. + let rounded = scaled | 1; + let rounded = rounded & !1; + if rounded == 0 || rounded > u64::from(Self::MAX_DISPLAY_WIDTH) { + return coded_width; + } + rounded as u32 } } @@ -917,6 +1106,15 @@ impl Mp4Demuxer { None => Rotation::None, }; let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height())); + // The same bound the Matroska door applies, on the same values: the + // mp4 crate types a track's dimensions as `u16`, which is a smaller + // claim than Matroska's but still eight times past the 8K ceiling -- + // 65535x65535 is a legal `tkhd`, and it sizes the same buffers. + for stated in [coded_w, coded_h] { + if stated > crate::MAX_RESOLUTION { + return Err(unsupported_display_size(u64::from(stated))); + } + } // The ratio one coded pixel is drawn at, off the sample entry's `pasp` // box: absent for the square-pixel file, which is the common case. let pixel_aspect = pasp_of(path, track_id); @@ -2552,8 +2750,32 @@ fn mkv_track_entry( let mut at = body; while let Some(e) = ebml_element(file, at, stop)? { match e.0 { - PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, - PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, + // A container may state any size at all, and these + // two reach a per-frame allocation directly + // (`decode.rs` sizes its planes as + // `display_width * height`). The engine already has + // the bound for this -- [`crate::MAX_RESOLUTION`], + // 8K -- and it was applied to a keystroke and to a + // `.edith` line but never to a header, so a + // 65535x65535 track opened and asked for a + // gigabyte-scale buffer. A size past the bound is + // refused by name here, where the file can be + // refused, rather than discovered as a capacity + // overflow one layer down. + PIXEL_WIDTH => { + let stated = ebml_uint(file, e.1, e.2)?; + if stated > u64::from(crate::MAX_RESOLUTION) { + return Err(unsupported_display_size(stated)); + } + width = stated as u32; + } + PIXEL_HEIGHT => { + let stated = ebml_uint(file, e.1, e.2)?; + if stated > u64::from(crate::MAX_RESOLUTION) { + return Err(unsupported_display_size(stated)); + } + height = stated as u32; + } DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?, DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?, DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?, @@ -2911,14 +3133,21 @@ fn rotation_of_roll(degrees: f64) -> crate::Result { /// /// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and /// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured), -/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where -/// a pair beside the coded one at all means a crop, not an aspect. 1 and 2 -/// (centimetres, inches) are physical sizes a picture this engine shows cannot -/// mean anything by, and read as square rather than guessed. Every unstated or -/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's -/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the -/// PixelWidth and PixelHeight" when they mean the same thing, so a file that -/// means square most often says nothing at all. +/// 4 spells the sample aspect ratio itself, and **0 spells pixels** -- which is +/// the ordinary case and the one a `Display*` pair is *for*: the spec has the +/// pair in pixels, so `1920`x`1080` beside a `1440`x`1080` coded track is +/// exactly the 4/3 stretch, stated the way this door below reads it. An absent +/// pair is the file saying nothing, which is also square; a pair that *is* +/// present and equal to the coded one is square by arithmetic, not by +/// assumption. +/// +/// 1 and 2 (centimetres, inches) are physical sizes a picture this engine +/// shows on a screen cannot mean anything by, and read as square rather than +/// guessed. Every unstated or unusable shape is [`PixelAspect::SQUARE`], which +/// is also the answer the spec's own default gives: DisplayWidth and +/// DisplayHeight "SHOULD be set to the PixelWidth and PixelHeight" when they +/// mean the same thing, so a file that means square most often says nothing +/// at all. fn pixel_aspect_of( display_width: u64, display_height: u64, @@ -2931,22 +3160,45 @@ fn pixel_aspect_of( if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 { return PixelAspect::SQUARE; } + // A stated pair is judged by what it *means*, never by how it was spelled, + // and the three units mean three different things: + // + // 4 -- the pair IS the sample aspect ratio. It is read as a ratio and + // judged by its terms, because a `pasp`-shaped claim is a claim + // about a ratio and chosen bytes do not reduce small. + // 3 -- the pair is a display aspect ratio, which has to be brought onto + // the coded frame to become one. That derivation multiplies by the + // coded size, so what reduces afterwards carries the *sizes*: a + // 239:100 DAR over a 1920x1080 coded track derives 2151:1600, over + // 3840x2160 the same, and both are past any term bound. So the + // width is computed directly from the ratio instead and only the + // degenerate case is refused. + // 0 -- the pair is a display pixel size, taken as the display width. + // + // Units 3 and 0 are the same rule: neither is a ratio, so neither may be + // judged by the terms its derived pair reduces to. What bounds both is the + // raster [`PixelAspect::width_factor`] produces, which cannot refuse a real + // ratio because it never looks at the ratio's terms at all. + let coded = (coded_width, coded_height); match display_unit { // 4: the pair *is* the sample aspect ratio. - 4 => PixelAspect { - h: display_width.min(u32::MAX as u64) as u32, - v: display_height.min(u32::MAX as u64) as u32, - }, - // 3: the pair is the display aspect ratio -- display_w / display_h -- - // which the SAR is that against the coded one: sar = dar * h / w. - // 16/9 over 1440x1080 lands on 4/3. - 3 => PixelAspect { - h: ((display_width * u64::from(coded_height)) - .min(u32::MAX as u64 * u64::from(coded_width))) as u32, - v: ((display_height * u64::from(coded_width)) - .min(u32::MAX as u64 * u64::from(coded_height))) as u32, - }, - // Pixels (0) or a physical unit this engine cannot interpret: square. + 4 => PixelAspect::stated( + display_width.min(u64::from(u32::MAX)) as u32, + display_height.min(u64::from(u32::MAX)) as u32, + ) + .unwrap_or(PixelAspect::SQUARE), + // 3: a display aspect ratio against the coded frame, taken unreduced so + // the term bound never judges it -- `width_factor` multiplies the coded + // width by this and bounds the raster it produces, and a bound on the + // picture has no conflict with a real ratio. + 3 => PixelAspect::stated_ratio(display_width, display_height, coded) + .unwrap_or(PixelAspect::SQUARE), + // 0: a display pixel size -- the width the picture is drawn at. + // 1920x1080 over 1440x1080 is the 4/3 stretch; 1920x803 is a 2.39:1 + // scope. Bounded by the raster, not by the terms it reduces to. + 0 => PixelAspect::stated_size(display_width, display_height, coded) + .unwrap_or(PixelAspect::SQUARE), + // A physical unit this engine cannot interpret: square. _ => PixelAspect::SQUARE, } } @@ -4173,7 +4425,11 @@ fn pasp_of(path: &Path, track_id: u32) -> PixelAspect { ) else { return PixelAspect::SQUARE; }; - PixelAspect { h, v } + // Eight bytes a file chose, read into a ratio that sizes every raster + // downstream, so they are judged by [`PixelAspect::stated`] here: the + // aspect this engine *reports* is one it can draw, not merely one it + // survived. + PixelAspect::stated(h, v).unwrap_or(PixelAspect::SQUARE) } /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says @@ -5613,6 +5869,152 @@ mod tests { assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim"); } + /// Four bytes of an mp4 `pasp` box are four bytes of untrusted input, and + /// every one of them reaches the width an allocation is sized from. A + /// header that claims `h == 0`, or one whose ratio widens the coded width + /// past the whole `u32` range, must read as the picture it really is -- + /// square, drawn at the coded size -- rather than as a zero-column or a + /// wrapped raster the decode worker tries to allocate. + #[test] + fn an_untrusted_pixel_aspect_cannot_size_a_zero_or_wrapped_raster() { + // Two contracts, held separately, because they are enforced in two + // places and conflating them is what would break a real ratio. + // + // 1. At the READ, a ratio is refused: a zero half, or a *reduced* + // pair carrying a term past the bound. This is where an mp4 `pasp` + // is judged, and it is right there because a `pasp` pair IS the + // ratio. + for hostile in [ + PixelAspect { h: 0, v: 1 }, + PixelAspect { h: 1, v: 0 }, + PixelAspect { h: 0, v: 0 }, + // Four chosen bytes, not a ratio: reduced terms stay enormous. + PixelAspect { h: 0xFFFF_FFFF, v: 0xFFFF_FFFF - 1 }, + PixelAspect { h: 1, v: 0x00FF_FFFF }, + ] { + assert_eq!( + PixelAspect::stated(hostile.h, hostile.v), + None, + "{hostile:?} is not a ratio this engine can draw" + ); + } + // A `DisplayUnit 0` pixel pair is NOT a ratio, so it is judged by + // `stated_size` instead -- and the two most common letterbox ratios + // must survive that arm, because its reduced form carries sizes: + for (dw, dh) in [(1920u64, 1080u64), (1920, 803), (1920, 1037)] { + assert!( + PixelAspect::stated_size(dw, dh, (1440, 1080)).is_some(), + "a {dw}x{dh} Display pair over a 1440x1080 coded track is a real picture" + ); + } + + // 2. In the ARITHMETIC, whatever ratio arrived -- read or built -- + // cannot produce a zero column or a raster past the bound. This is + // the contract that holds for every door, including the one that + // builds its ratio from a pixel size rather than reading one. + let wrong: Vec = [ + PixelAspect { h: 0, v: 1 }, + PixelAspect { h: 1, v: 0 }, + PixelAspect { h: 0, v: 0 }, + // 1920 * 0x00FF_FFFF is 32_212_252_800: it wraps a u32 to + // 2_147_483_648, which is a plausible-looking "width" and an + // impossible one to allocate. + PixelAspect { h: 0x00FF_FFFF, v: 1 }, + ] + .into_iter() + .filter_map(|hostile| { + let factor = hostile.width_factor(1920); + (factor == 0 || factor > PixelAspect::MAX_DISPLAY_WIDTH) + .then(|| format!("{hostile:?} -> {factor} (a zero column or an oversized raster)")) + }) + .collect(); + assert!( + wrong.is_empty(), + "an unusable ratio must not size a raster:\n{}", + wrong.join("\n") + ); + // The wrap case lands on the coded width rather than on the wrapped + // number, which is the specific refusal the defect turned on. + assert_eq!( + PixelAspect { h: 0x00FF_FFFF, v: 1 }.width_factor(1920), + 1920, + "a wrapped multiply is drawn at the coded width, not at 2_147_481_728" + ); + + // The sane ratios still stretch, bit for bit as they always did: the + // hardening refuses the untrusted, it does not round the ordinary. + assert_eq!(PixelAspect { h: 4, v: 3 }.width_factor(1440), 1920); + assert_eq!(PixelAspect { h: 1, v: 1 }.width_factor(1920), 1920); + assert_eq!(PixelAspect::SQUARE.width_factor(1920), 1920); + // An unreduced spelling of the same 4:3 lands on the same picture. + assert_eq!(PixelAspect { h: 16, v: 12 }.width_factor(1440), 1920); + // And a 2.39:1 scope built from a pixel size widens the coded frame + // by its own ratio rather than being refused for carrying sizes. + assert_eq!( + PixelAspect::stated_size(1920, 803, (1440, 1080)) + .expect("a scope is a picture") + .width_factor(1440), + 1920, + "a 1920-wide scope over 1440 coded columns widens to 1920" + ); + } + + /// The rule the two `Display*` units that are not ratios share, in one + /// place: bringing a pair onto the coded frame makes what reduces carry the + /// coded *sizes*, so no term bound can judge it. A 2.39:1 scope is the case + /// that proves it -- the same DAR over three coded frames, which a term + /// bound reads three different ways. + #[test] + fn a_derived_pair_is_read_by_its_raster_on_every_coded_frame() { + for (coded, display) in [ + ((1920u32, 1080u32), 2582u32), + ((3840, 2160), 5162), + ((720, 576), 1376), + ] { + let derived = PixelAspect::stated_ratio(239, 100, coded).expect("a scope is a picture"); + assert_eq!( + derived.width_factor(coded.0), + display, + "a 239:100 DAR over {coded:?} displays {display}, as base did" + ); + // The trap this exists to hold, measured rather than described: the + // same DAR derives pairs that reduce on *both* sides of the bound, + // so a term bound judges the same ratio differently depending only + // on the frame it happens to sit on. + let (mut a, mut b) = (derived.h, derived.v); + while b != 0 { + (a, b) = (b, a % b); + } + let reduced = (derived.h / a, derived.v / a); + let past = reduced.0 > PixelAspect::MAX_ASPECT_TERM; + assert_eq!( + past, + coded.0 != 720, + "{coded:?}: a 239:100 DAR derives {reduced:?}, {} the {} bound -- \ + the same ratio, on both sides of it", + if past { "past" } else { "inside" }, + PixelAspect::MAX_ASPECT_TERM + ); + } + // And the 1440x1080 frame -- the one this lane's own fixture sits on -- + // reduces to 717:400, which the bound admits. So the same ratio is + // refused on two frames and accepted on a third, which is why the + // bound cannot be tuned instead of replaced: any threshold catching + // 2151:1600 would be chosen by the frame rather than by the picture. + let over_1440 = PixelAspect::stated_ratio(239, 100, (1440, 1080)).expect("a picture"); + let (mut a, mut b) = (over_1440.h, over_1440.v); + while b != 0 { + (a, b) = (b, a % b); + } + assert!( + over_1440.h / a <= PixelAspect::MAX_ASPECT_TERM, + "the same DAR over a 1440x1080 frame reduces to {}:{}, which the \ + bound admits -- the same ratio, judged either way by its frame", + over_1440.h / a, + over_1440.v / a + ); + } + #[test] fn rejects_misparse() { assert!(append_annex_b(&[0, 0, 0, 9, 0x65], 4, &mut Vec::new()).is_err()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 40356d5..03f9b56 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -94,8 +94,18 @@ pub fn is_image(path: &std::path::Path) -> bool { }) } -/// The largest picture this engine composes onto, either way: 8K, which is where -/// a per-frame buffer stops being a sane thing to allocate. +/// The largest picture this engine composes onto, either way: 7680, which is +/// where a per-frame buffer stops being a sane thing to allocate. +/// +/// That is 8K **UHD** (7680x4320), not 8K DCI (8192x4320). A DCI-width master +/// -- a ProRes 4444 XQ feature, for instance -- is 8192 wide and is refused +/// here by name, which it was not before the container doors asked this bound +/// of a file's own header rather than only of a keystroke and a `.edith` line. +/// The bound is deliberately not raised to 8192 to admit it: `is_resolution` +/// gates those two doors at 7680 too, and widening the ceiling on every path +/// to accommodate a container is a wider decision than a header fix should +/// make. A caller that needs DCI width needs the ceiling raised deliberately, +/// on all four doors at once. pub const MAX_RESOLUTION: u32 = 7680; /// Whether a project resolution is a picture at all: not zero either way, and diff --git a/crates/engine/tests/display_unit.rs b/crates/engine/tests/display_unit.rs new file mode 100644 index 0000000..d862796 --- /dev/null +++ b/crates/engine/tests/display_unit.rs @@ -0,0 +1,443 @@ +//! Matroska `DisplayUnit` 0: the `Display*` pair is in *pixels*, so a pair +//! beside the coded size is the stretch, not a crop. +//! +//! The Matroska spec is explicit that unit 0 means the `DisplayWidth` and +//! `DisplayHeight` pair *is* a pixel size. So `DisplayWidth=1920`, +//! `DisplayHeight=1080` beside a `PixelWidth=1440`, `PixelHeight=1080` track +//! is exactly the 4/3 anamorphic stretch -- the same picture +//! `test_anamorphic.mkv` states the other two ways round, in SAR (4/3) and in +//! DAR (16/9). +//! +//! No fixture stated it that way until this one: `scripts/gen_fixtures.sh` +//! produces unit 3 (ffmpeg spells the aspect as a DAR), so the unit-0 arm of +//! the reader had never been seen by a test, and it read as square -- the +//! same answer as a file that says nothing at all. The picture was shown at +//! 1440x1080 instead of 1920x1080, and nothing said so. +//! +//! The fixture is patched here from `test_anamorphic.mkv` rather than +//! committed as a binary: the `Video` element keeps its exact byte length, so +//! every absolute offset in the file -- the SeekHead and every CueCluster- +//! Position -- stays correct and the copy seeks exactly as the original does. +//! +//! ```text +//! cargo test -p engine --test display_unit -- --test-threads=1 +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::demux::{Demuxer, PixelAspect}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("edith-display-unit-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture"); + Self(dir) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The bytes of the `Video` element of `test_anamorphic.mkv`, as ffmpeg's +/// Matroska muxer wrote them: a 1440x1080 track with its aspect stated as a +/// 16/9 display aspect ratio. +const VIDEO_UNIT_3: &str = concat!( + "e09e", // Video, 30 bytes + "b08205a0", // PixelWidth 1440 + "ba820438", // PixelHeight 1080 + "9a8102", // FlagInterlaced + "54b08110", // DisplayWidth 16 + "54ba8109", // DisplayHeight 9 + "54b28103", // DisplayUnit 3 -- a display aspect ratio + "55b084", "55b98101" // Colour { MatrixCoefficients 1 } +); + +/// The same 30 bytes with the aspect stated the third way Matroska allows: +/// unit 0, where the `Display*` pair is in pixels and so *is* the drawn +/// size. 1920x1080 over a 1440x1080 coded track is the same 4/3 stretch. +/// +/// Byte-for-byte the same length as [`VIDEO_UNIT_3`], which is what keeps +/// the rest of the file's offsets honest: the `Display*` values grow from +/// one-byte to two-byte payloads (+3 bytes with the wider unit encoding), +/// `FlagInterlaced` is dropped (-3), and `MatrixCoefficients` is restated +/// over two bytes instead of one (+1) inside the `Colour` element. +const VIDEO_UNIT_0: &str = concat!( + "e09e", // Video, 30 bytes -- unchanged + "b08205a0", // PixelWidth 1440, unchanged: the samples are still these + "ba820438", // PixelHeight 1080, unchanged + "54b0820780", // DisplayWidth 1920 -- in *pixels* + "54ba820438", // DisplayHeight 1080 -- in *pixels* + "54b28100", // DisplayUnit 0 -- pixels + "55b085", "55b9820001" // Colour { MatrixCoefficients 1 } +); + +/// The same `DisplayUnit 0` element with a different `Display*` pixel pair, +/// for the ratios whose reduced form is not a small pair of integers. +fn video_unit_0(display_width: u16, display_height: u16) -> String { + // Both `Display*` values are two-byte payloads, so a width past 0x7FFF + // would need three and change the element's length. The lengths here are + // all inside that range, which is what keeps every offset in the file + // honest. + format!( + "e09e\ + b08205a0\ + ba820438\ + 54b082{display_width:04x}\ + 54ba82{display_height:04x}\ + 54b28100\ + 55b085\ + 55b9820001" + ) +} +/// A `DisplayUnit 3` (DAR) `Video` element: the coded size and the display +/// aspect ratio, both length-preserving. +fn video_unit_3(dar_width: u16, dar_height: u16, coded_width: u16, coded_height: u16) -> String { + format!( + "e09e\ + b082{coded_width:04x}\ + ba82{coded_height:04x}\ + 9a8102\ + 54b081{dar_width:02x}\ + 54ba81{dar_height:02x}\ + 54b28103\ + 55b084\ + 55b98101" + ) +} + +fn with_video_element(source: &Path, into: &Path, element: &str) { + let from = hex(VIDEO_UNIT_3); + let to = hex(element); + assert_eq!( + from.len(), + to.len(), + "a length-preserving patch: {element} is {} bytes, {} are needed", + to.len(), + from.len() + ); + let bytes = std::fs::read(source).expect("read the source fixture"); + let at = bytes + .windows(from.len()) + .position(|window| window == from) + .unwrap_or_else(|| panic!("the fixture carries the expected {VIDEO_UNIT_3} element")); + let mut patched = bytes.clone(); + patched[at..at + from.len()].copy_from_slice(&to); + std::fs::write(into, patched).expect("write the patched fixture"); +} + +fn hex(text: &str) -> Vec { + (0..text.len() / 2) + .map(|i| u8::from_str_radix(&text[i * 2..i * 2 + 2], 16).expect("hex in the fixture")) + .collect() +} + +/// The reduced form of a ratio, so a ratio stated unreduced (the DAR arm +/// multiplies through by the coded size) compares equal to its simplest +/// spelling -- the same comparison the anamorphic suite makes. +fn reduced(aspect: PixelAspect) -> (u32, u32) { + let gcd = |mut a: u32, mut b: u32| { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) + }; + let g = gcd(aspect.h, aspect.v); + (aspect.h / g, aspect.v / g) +} + +/// The three spellings of one anamorphic picture must name one picture. +#[test] +fn a_display_unit_of_zero_states_the_stretch_in_pixels() { + let scratch = Scratch::new("pixels"); + let unit0 = scratch.path("display_unit0.mkv"); + with_video_element(&asset("test_anamorphic.mkv"), &unit0, VIDEO_UNIT_0); + + // The patch landed, and it landed on a file the demuxer opens. + let patched = std::fs::read(&unit0).expect("read back the patched fixture"); + let original = std::fs::read(asset("test_anamorphic.mkv")).expect("read the original"); + assert_eq!( + patched.len(), + original.len(), + "the patch preserves the file length, so no offset in it moved" + ); + let wanted = hex(VIDEO_UNIT_0); + assert_eq!( + patched + .windows(wanted.len()) + .position(|window| window == wanted), + Some(369), + "the DisplayUnit-0 element is where it was aimed" + ); + + let (meta, _) = Demuxer::open(&unit0).expect("open the DisplayUnit-0 fixture"); + + // The samples are stored at the coded size, exactly as before the patch. + assert_eq!( + (meta.coded_width, meta.coded_height), + (1440, 1080), + "unit 0 changes what the file *says* about the picture, not how it is stored" + ); + + // Unit 0 means the pair IS a pixel size, so 1920x1080 beside a 1440x1080 + // coded track is the 4/3 stretch -- and this is the whole defect: read as + // square, the picture was drawn at 1440x1080, a quarter-width picture of + // the same frame, with nothing to say so. + assert!( + !meta.pixel_aspect.is_square(), + "DisplayUnit 0 with a Display pair beside the coded one is a stretch, \ + not a crop: got square ({:?})", + meta.pixel_aspect + ); + assert_eq!( + (meta.width, meta.height), + (1920, 1080), + "the Display pair is the drawn size: 1920x1080 over a 1440x1080 coded track" + ); + + // ...and it is the *same* ratio the other two spellings name, so all three + // fixtures of one source agree on one drawn picture. Compared reduced, + // because a ratio is named by the picture and not by how it was spelled: + // the DAR arm multiplies through by the coded size and says 2073600 / + // 1555200 where the SAR arm says 4 / 3. + assert_eq!( + reduced(meta.pixel_aspect), + (4, 3), + "1920x1080 over a 1440x1080 coded track is the same 4/3 the SAR and \ + DAR spellings name" + ); + for sibling in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { + let (other, _) = Demuxer::open(&asset(sibling)).expect("open the sibling fixture"); + assert_eq!( + (other.width, other.height), + (meta.width, meta.height), + "{sibling} states the same picture the DisplayUnit spelling states" + ); + } +} + +/// Units 1 and 2 are physical sizes -- centimetres, inches -- which a picture +/// this engine shows on a screen cannot mean anything by. They stay square, +/// and saying so is the deliberate answer rather than an accident of the +/// match falling through. +#[test] +fn a_physical_display_unit_is_read_as_square() { + let scratch = Scratch::new("physical"); + for (unit, tag) in [(1u8, "cm"), (2u8, "in")] { + let element = VIDEO_UNIT_0.replacen("54b28100", &format!("54b2810{unit}"), 1); + let into = scratch.path(&format!("display_unit{unit}.mkv")); + with_video_element(&asset("test_anamorphic.mkv"), &into, &element); + let (meta, _) = Demuxer::open(&into).expect("open the physical-unit fixture"); + assert!( + meta.pixel_aspect.is_square(), + "DisplayUnit {unit} ({tag}) is a physical size this engine cannot interpret, \ + so the pixels stay square: got {:?}", + meta.pixel_aspect + ); + } +} +/// The coded size is untrusted too, and it reaches an allocation directly: +/// `decode.rs` sizes its stretched planes as `display_width * height`. The +/// engine already has a bound for exactly this -- [`engine::MAX_RESOLUTION`], +/// 8K, the size a per-frame buffer stops being sane at -- and the demux +/// readers never applied it to a container-stated width or height. +/// +/// The fixture patches the `PixelWidth`/`PixelHeight` payloads to 65535 each, +/// which is a legal two-byte EBML integer, so the element keeps its exact +/// length and the copy stays seekable. +#[test] +fn a_coded_size_past_the_resolution_bound_is_refused_not_allocated() { + let scratch = Scratch::new("huge"); + let into = scratch.path("huge_dims.mkv"); + with_video_element( + &asset("test_anamorphic.mkv"), + &into, + &VIDEO_UNIT_3 + .replacen("b08205a0", "b082ffff", 1) + .replacen("ba820438", "ba82ffff", 1), + ); + + // Refused, and refused by name: the open fails with a message that says + // what the file claimed and what the maximum is, rather than succeeding + // and handing a caller a 65535x65535 to allocate. + let Err(why) = Demuxer::open(&into) else { + panic!("a 65535x65535 header is refused by name, never opened"); + }; + let said = why.to_string(); + assert!( + said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()), + "the refusal names the size claimed and the maximum: {said}" + ); + assert!( + engine::demux::UnsupportedDisplaySize::is_it(&why), + "and it is the named refusal a caller can match on, not a string" + ); +} + +/// The bound is a ceiling on a real picture, not a floor on a file: the +/// largest size a real source states still opens, untouched. +#[test] +fn a_real_size_up_to_the_bound_still_opens() { + let (meta, _) = Demuxer::open(&asset("test_anamorphic.mkv")).expect("open the fixture"); + assert!( + engine::is_resolution(meta.coded_width, meta.coded_height), + "the ordinary fixture is inside the bound, which is what keeps the \ + bound from refusing the library" + ); +} + +/// The regression this arm must not carry: a `DisplayUnit 0` pair is a pixel +/// SIZE, so its *reduced* form is the size against the coded size, not a small +/// pair of integers -- and the common cinematic display ratios do not reduce +/// small. A 1920x803 scope over a 1440x1080 coded track reduces to 1440:803, +/// and 1920x1037 (1.85:1 flat) likewise. +/// +/// The reduced-term bound is the right test for an mp4 `pasp`, where the pair +/// *is* the ratio, and the wrong test here: applying it made the two most +/// common letterbox ratios open square, on exactly the arm this fix newly +/// enabled. The quantity that needs bounding on this door is the resulting +/// display WIDTH, which `width_factor` already caps. +#[test] +fn a_cinematic_display_unit_zero_stretches_rather_than_reading_square() { + let scratch = Scratch::new("cinema"); + for (dw, dh, ratio, tag) in [ + (1920u16, 803u16, "2.39:1 scope", "scope"), + (1920, 1037, "1.85:1 flat", "flat"), + ] { + let into = scratch.path(&format!("{tag}.mkv")); + with_video_element( + &asset("test_anamorphic.mkv"), + &into, + &video_unit_0(dw, dh), + ); + + let (meta, _) = Demuxer::open(&into) + .unwrap_or_else(|why| panic!("{tag} ({ratio}): open failed: {why}")); + assert!( + !meta.pixel_aspect.is_square(), + "{tag} ({ratio}): a DisplayUnit 0 pixel pair of {dw}x{dh} over a \ + 1440x1080 coded track is a stretch, not square: got {:?}", + meta.pixel_aspect + ); + // The stated DISPLAY WIDTH is the drawn width: unit 0 states it in + // pixels, so it is taken as stated, not re-derived. The height stays + // the coded one because a pixel aspect moves the width only in this + // engine -- `VideoMeta::height` is the coded height for every file, by + // design. A 1920x803 scope is therefore drawn 1920x1080 here: the + // width is the file's own claim and the height is this engine's + // documented model, and the two are not the same thing. + assert_eq!( + meta.width, + u32::from(dw), + "{tag} ({ratio}): the stated Display width is the drawn width" + ); + assert_eq!( + meta.height, + 1080, + "{tag} ({ratio}): a pixel aspect never moves the height; the coded one stands" + ); + assert_eq!( + (meta.coded_width, meta.coded_height), + (1440, 1080), + "{tag} ({ratio}): the samples are still stored at the coded size" + ); + } +} + +/// The unit-3 arm, which is the same rule as unit 0 one arm away: a DAR is +/// not a ratio either, because bringing it onto the coded frame multiplies by +/// the coded size, and what reduces afterwards carries the *sizes*. +/// +/// So the same 2.39:1 scope is judged differently by the frame it sits on, +/// which is a bound measuring the wrong thing. Over a 1920x1080 coded track a +/// 239:100 DAR derives 2151:1600 and over 3840x2160 the same -- both past any +/// term bound -- while over 1440x1080 it derives 717:400 and passes. Base +/// `9f780f7` opened all three at the widths below; the bound made the first +/// two open square, a measured regression rather than a latent gap. +/// +/// The expected widths are the ones BASE produced, measured by running base +/// over these same fixtures. This is the property that matters: the arm must +/// read the DAR the way it always did, so the test pins base's answers rather +/// than a fresh computation of them. +#[test] +fn a_display_unit_three_dar_reads_the_same_on_every_coded_frame() { + let scratch = Scratch::new("dar"); + for (coded, expected, tag) in [ + ((1920u16, 1080u16), 2582u32, "1920x1080"), // 239:100 -> 2151:1600 + ((3840, 2160), 5162, "3840x2160"), // 239:100 -> 2151:1600 + ((720, 576), 1376, "720x576"), // 239:100 -> 239:125 + ] { + let into = scratch.path(&format!("dar_{tag}.mkv")); + with_video_element( + &asset("test_anamorphic.mkv"), + &into, + &video_unit_3(239, 100, coded.0, coded.1), + ); + + let (meta, _) = Demuxer::open(&into) + .unwrap_or_else(|why| panic!("{tag}: open failed: {why}")); + assert_eq!( + (meta.coded_width, meta.coded_height), + (u32::from(coded.0), u32::from(coded.1)), + "{tag}: the coded frame the DAR is stated over" + ); + assert!( + !meta.pixel_aspect.is_square(), + "{tag}: a 239:100 DAR is a 2.39:1 stretch whatever frame it sits \ + on: got square ({:?})", + meta.pixel_aspect + ); + assert_eq!( + meta.width, expected, + "{tag}: the display width base 9f780f7 produced for this DAR" + ); + assert_eq!( + meta.height, + u32::from(coded.1), + "{tag}: a pixel aspect never moves the height; the coded one stands" + ); + } +} + +/// The term bound must survive where it belongs. The unit-4 SAR pair IS a +/// ratio, so a hostile one is still refused -- this arm is what stops the +/// split from reading as "the bound was dropped". +#[test] +fn a_hostile_sar_pair_is_still_refused_by_the_term_bound() { + // Reduced terms far past the bound, stated as a SAR pair: four chosen + // bytes, not a ratio. + for hostile in [(0xFFFF_FFFFu32, 0xFFFF_FFFFu32 - 1), (1, 0x00FF_FFFF)] { + assert_eq!( + PixelAspect::stated(hostile.0, hostile.1), + None, + "{hostile:?} is chosen bytes, not a ratio, and is refused as one" + ); + } + // ...and a real SAR pair is still taken, so the bound is not simply + // refusing everything on this arm. + assert_eq!( + PixelAspect::stated(4, 3), + Some(PixelAspect { h: 4, v: 3 }), + "a 4:3 SAR is a ratio and is read as one" + ); + assert_eq!( + PixelAspect::stated(16, 12), + Some(PixelAspect { h: 16, v: 12 }), + "an unreduced 4:3 spelling is judged by the ratio it names" + ); +} diff --git a/crates/engine/tests/untrusted_header.rs b/crates/engine/tests/untrusted_header.rs new file mode 100644 index 0000000..91a79d8 --- /dev/null +++ b/crates/engine/tests/untrusted_header.rs @@ -0,0 +1,247 @@ +//! What a container header claims is untrusted input, and the numbers it +//! claims them with reach every raster this engine sizes. +//! +//! An mp4 `pasp` box is eight bytes: two 32-bit big-endian integers, the ratio +//! one coded pixel is drawn at. Nothing in the file makes them sane. Four +//! chosen bytes are enough to make the probe report a zero width, or a width +//! that wrapped a `u32` on its way down from the multiply -- and both of those +//! go straight into the `resize` that sizes the decode worker's stretched +//! planes, before a single pixel is drawn. +//! +//! This test byte-patches a copy of the baseline fixture and opens it through +//! the ordinary door: the patched files live in a temp directory and are made +//! here, so no hostile bytes are committed to the repository. +//! +//! ```text +//! cargo test -p engine --test untrusted_header -- --test-threads=1 +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::demux::Demuxer; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// A temp directory that cleans itself up, so a failing test does not leave a +/// hostile mp4 lying around for the next one to trip over. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("edith-untrusted-header-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("a temp directory for the patched fixture"); + Self(dir) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A copy of `source` with the eight bytes of its `pasp` payload replaced. +/// +/// Returns the byte offset the payload was written at, so the test can name +/// the exact bytes it changed rather than asserting about a file whose +/// provenance is a fixture somebody might regenerate. +fn patch_pasp(source: &Path, into: &Path, h: u32, v: u32) -> usize { + let bytes = std::fs::read(source).expect("read the source fixture"); + let at = bytes + .windows(4) + .position(|window| window == b"pasp") + .expect("the fixture carries a pasp box") + + 4; // the type is four bytes; the payload follows it + let mut patched = bytes.clone(); + patched[at..at + 4].copy_from_slice(&h.to_be_bytes()); + patched[at + 4..at + 8].copy_from_slice(&v.to_be_bytes()); + std::fs::write(into, patched).expect("write the patched fixture"); + at +} + +/// The claims an mp4 can make about its pixels that are not a picture: a zero +/// half, which divides to nothing, and a huge half, whose multiply wraps a +/// `u32` on the way down. +#[test] +fn a_pasp_box_cannot_declare_a_zero_or_wrapped_display_width() { + // Read the untouched fixture first: the patches below are asserted + // against *its* numbers, so a regenerated fixture that stops carrying a + // `pasp` box fails here loudly instead of silently passing. + let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline"); + let coded = (baseline.coded_width, baseline.coded_height); + assert_eq!( + (baseline.width, baseline.height), + coded, + "the baseline fixture is square, so its display pair is its coded pair -- which is \ + what the patched files are asserted against" + ); + assert!( + baseline.pixel_aspect.is_square(), + "the baseline fixture states 1:1, which is square" + ); + + let scratch = Scratch::new("pasp"); + for (tag, h, v) in [ + ("zero_h", 0u32, 1u32), + ("zero_v", 1, 0), + ("both_zero", 0, 0), + // 1920 * 0x00FF_FFFF = 32_212_252_800, which narrowed to a u32 is + // 2_147_481_728: a width that looks plausible in a log and cannot be + // allocated on any machine this runs on. + ("wrap_h", 0x00FF_FFFF, 1), + // 1:0x00FF_FFFF is the other end: a two-column strip of a picture. + ("wrap_v", 1, 0x00FF_FFFF), + ] { + let name = format!("pasp_{tag}.mp4"); + let into = scratch.path(&name); + let at = patch_pasp(&asset("test_baseline.mp4"), &into, h, v); + assert_eq!( + std::fs::read(&into).unwrap()[at..at + 8], + [h.to_be_bytes(), v.to_be_bytes()].concat(), + "{tag}: the patch landed where it was aimed" + ); + + // The ordinary door: open the file the way a library open does. + let (meta, _) = Demuxer::open(&into) + .unwrap_or_else(|why| panic!("{tag} (pasp {h}:{v} at byte {at}): open failed: {why}")); + + // A header that claims an unusable ratio is read as the picture it + // really is: the coded one, square, drawn one to one. + assert_eq!( + (meta.width, meta.height), + (baseline.width, baseline.height), + "{tag} (pasp {h}:{v}): an unusable ratio must read as square, not as a \ + zero-column or wrapped raster" + ); + assert!( + meta.pixel_aspect.is_square(), + "{tag} (pasp {h}:{v}): the reported aspect must be one this engine can draw" + ); + assert!( + meta.width > 0 && meta.height > 0, + "{tag} (pasp {h}:{v}): a zero dimension here is what sizes an allocation to nothing" + ); + } +} + +/// The half that matters is not the probe: it is the worker that sizes its +/// stretched planes from the same number. A decode that used to abort on a +/// capacity overflow here now returns the coded picture. +#[test] +fn a_hostile_pasp_decodes_the_coded_picture_instead_of_aborting() { + let scratch = Scratch::new("decode"); + let into = scratch.path("pasp_wrap.mp4"); + patch_pasp(&asset("test_baseline.mp4"), &into, 0x00FF_FFFF, 1); + + let (baseline, _) = Demuxer::open(&asset("test_baseline.mp4")).expect("open the baseline"); + let coded = (baseline.width, baseline.height); + let (meta, _) = Demuxer::open(&into).expect("a hostile header is still an openable file"); + let (_, frames, _) = + engine::DecodeSession::open_at(&into, 0).expect("a hostile header does not stop the decoder"); + let frame = frames + .recv() + .expect("the first frame arrives rather than the worker aborting on its allocation"); + assert_eq!( + frame.width, + meta.width, + "the decoded frame is drawn at the width the probe reported" + ); + assert_eq!( + (frame.width, frame.height), + coded, + "the coded picture, drawn square: a wrapped claim resizes nothing" + ); +} +/// The same bound, on the other door. An mp4 states its picture in a visual +/// sample entry's two `u16` fields -- a smaller claim than Matroska's EBML +/// integer, but still eight times past the 8K ceiling, and it reaches the same +/// `decode.rs` allocation. +#[test] +fn a_mp4_may_not_state_a_picture_past_the_resolution_bound() { + let scratch = Scratch::new("mp4dims"); + let into = scratch.path("mp4_huge_dims.mp4"); + patch_sample_entry_size(&asset("test_baseline.mp4"), &into, 65535, 65535); + + let Err(why) = Demuxer::open(&into) else { + panic!("a 65535x65535 mp4 is refused by name, never opened"); + }; + let said = why.to_string(); + assert!( + said.contains("65535") && said.contains(&engine::MAX_RESOLUTION.to_string()), + "the refusal names the size claimed and the maximum: {said}" + ); + assert!( + engine::demux::UnsupportedDisplaySize::is_it(&why), + "and it is the named refusal a caller can match on, not a string" + ); +} + +/// A copy of `source` with the width and height of its first visual sample +/// entry set to `w`/`h` (ISO/IEC 14496-12 ยง12.1.3: two 16-bit fields, 24 +/// bytes into the entry, after the 6 reserved bytes, the 2-byte data +/// reference index and the 16 bytes of pre-defined and reserved fields). +fn patch_sample_entry_size(source: &Path, into: &Path, w: u16, h: u16) { + let mut bytes = std::fs::read(source).expect("read the source fixture"); + let stsd = find(&bytes, b"stsd").expect("the fixture has a sample description"); + // 'stsd' + version/flags + entry_count, then the first entry. + let entry = stsd + 12; + assert_eq!(&bytes[entry + 4..entry + 8], b"avc1", "the first entry is the video one"); + bytes[entry + 32..entry + 34].copy_from_slice(&w.to_be_bytes()); + bytes[entry + 34..entry + 36].copy_from_slice(&h.to_be_bytes()); + std::fs::write(into, bytes).expect("write the patched fixture"); +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + haystack + .windows(needle.len()) + .position(|window| window == needle) +} + +/// The boundary of the bound, stated as a test rather than left as a surprise: +/// 7680 -- 8K UHD -- opens, and 8192 -- 8K DCI, a real ProRes 4444 XQ master +/// width -- is refused by name. +/// +/// The refusal of a DCI-width master is a behaviour change this lane +/// introduced: before it, the bound was asked only of a keystroke and a +/// `.edith` line, never of a file's own header, so a container could state any +/// size at all. `MAX_RESOLUTION` stays 7680 rather than being raised to 8192, +/// because it gates those two doors at 7680 too and widening the ceiling on +/// every path to accommodate a container is a wider decision than a header fix +/// should make. +#[test] +fn the_resolution_bound_admits_uhd_and_refuses_dci_width_by_name() { + let scratch = Scratch::new("dci"); + let coded_height = 720u16; + + let uhd = scratch.path("uhd_7680.mp4"); + patch_sample_entry_size(&asset("test_baseline.mp4"), &uhd, 7680, coded_height); + let (meta, _) = Demuxer::open(&uhd).expect("8K UHD is inside the bound and opens"); + assert_eq!( + (meta.coded_width, meta.coded_height), + (7680, u32::from(coded_height)), + "an 8K UHD header is read as stated" + ); + + let dci = scratch.path("dci_8192.mp4"); + patch_sample_entry_size(&asset("test_baseline.mp4"), &dci, 8192, coded_height); + let Err(why) = Demuxer::open(&dci) else { + panic!("an 8192-wide DCI master is refused by name, never opened"); + }; + assert!( + engine::demux::UnsupportedDisplaySize::is_it(&why), + "the refusal is the named one a caller can match: {why}" + ); + assert!( + why.to_string().contains("8192"), + "and it names the width claimed: {why}" + ); +}