🐛 demux: read the turn and the shown size a file states for its picture
Browse files at this commit30b435d3ff3963c542bcf5574f5a63fb95a8e2a3Parent: 19dcc3e3 changed files +380 -27
- crates/engine/src/demux.rs +278 -22
- crates/engine/tests/rotation.rs +59 -5
- scripts/gen_fixtures.sh +43 -0
crates/engine/src/demux.rsmodified+278 -22
| @@ -371,13 +371,13 @@ pub struct VideoMeta { | |||
| 371 | /// which range -- resolved off the container's tags, the bitstream's, and | 371 | /// which range -- resolved off the container's tags, the bitstream's, and |
| 372 | /// the resolution, in that order. See [`crate::colorspace`]. | 372 | /// the resolution, in that order. See [`crate::colorspace`]. |
| 373 | pub color: ColorDescription, | 373 | pub color: ColorDescription, |
| 374 | - /// How far the picture must be turned to be seen right, off the | 374 | + /// How far the picture must be turned to be seen right, off the container's |
| 375 | - /// container's display matrix. [`Rotation::None`] for everything whose | 375 | + /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on |
| 376 | - /// container states no turn, and for a Matroska file: only the mp4 half is | 376 | + /// a rectangular projection -- the same quarter turns read off either. |
| 377 | - /// read today, because Matroska's own spelling (a `ProjectionPoseYaw` | 377 | + /// [`Rotation::None`] for everything whose container states no turn, and a |
| 378 | - /// element) is written by nobody in practice while the `tkhd` matrix is how | 378 | + /// turn that is not a quarter turn (or a mirror, a shear, a spherical |
| 379 | - /// every phone records it. That is a known gap and not a silent one: | 379 | + /// projection) is refused at the door ([`UnsupportedRotation`]) rather than |
| 380 | - /// [`MkvDemuxer::open`] says where a reader for it would go. | 380 | + /// shown wrong. |
| 381 | pub rotation: Rotation, | 381 | pub rotation: Rotation, |
| 382 | } | 382 | } |
| 383 | 383 | ||
| @@ -813,7 +813,7 @@ impl Mp4Demuxer { | |||
| 813 | // hev1 in that the parameter sets may not repeat in-band, which costs | 813 | // hev1 in that the parameter sets may not repeat in-band, which costs |
| 814 | // nothing: they are re-injected out of `hvcC` ahead of every sync sample | 814 | // nothing: they are re-injected out of `hvcC` ahead of every sync sample |
| 815 | // either way, exactly as an AV1 sequence header is out of `av1C`. | 815 | // either way, exactly as an AV1 sequence header is out of `av1C`. |
| 816 | - let (track, codec) = reader | 816 | + let (track, codec, entry) = reader |
| 817 | .moov | 817 | .moov |
| 818 | .traks | 818 | .traks |
| 819 | .iter() | 819 | .iter() |
| @@ -822,8 +822,8 @@ impl Mp4Demuxer { | |||
| 822 | matches!(t.track_type(), Ok(TrackType::Video)) | 822 | matches!(t.track_type(), Ok(TrackType::Video)) |
| 823 | .then(|| sample_entry(path, t.track_id()).ok()) | 823 | .then(|| sample_entry(path, t.track_id()).ok()) |
| 824 | .flatten() | 824 | .flatten() |
| 825 | - .and_then(|(kind, _)| mp4_codec(&kind)) | 825 | + .and_then(|(kind, entry)| mp4_codec(&kind).map(|codec| (codec, entry))) |
| 826 | - .map(|codec| (t, codec)) | 826 | + .map(|(codec, entry)| (t, codec, entry)) |
| 827 | }) | 827 | }) |
| 828 | // Named, for the same reason the Matroska door names it: "no video | 828 | // Named, for the same reason the Matroska door names it: "no video |
| 829 | // track" is a lie about a file that has one in a codec this does not | 829 | // track" is a lie about a file that has one in a codec this does not |
| @@ -852,9 +852,14 @@ impl Mp4Demuxer { | |||
| 852 | None => Rotation::None, | 852 | None => Rotation::None, |
| 853 | }; | 853 | }; |
| 854 | let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height())); | 854 | let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height())); |
| 855 | + // The picture's displayed shape, in the same two steps the Matroska door | ||
| 856 | + // resolves its `Display*` elements in: the aspect the sample entry | ||
| 857 | + // states, then the turn. A `pasp`-carrying file and the mkv remux of it | ||
| 858 | + // report one size. | ||
| 859 | + let shown = pasp_size(&entry, coded_w, coded_h).unwrap_or((coded_w, coded_h)); | ||
| 855 | let (width, height) = match rotation.swaps_axes() { | 860 | let (width, height) = match rotation.swaps_axes() { |
| 856 | - true => (coded_h, coded_w), | 861 | + true => (shown.1, shown.0), |
| 857 | - false => (coded_w, coded_h), | 862 | + false => shown, |
| 858 | }; | 863 | }; |
| 859 | let meta = VideoMeta { | 864 | let meta = VideoMeta { |
| 860 | width, | 865 | width, |
| @@ -1309,9 +1314,22 @@ impl MkvDemuxer { | |||
| 1309 | } | 1314 | } |
| 1310 | } | 1315 | } |
| 1311 | }; | 1316 | }; |
| 1317 | + // The picture's *displayed* shape, resolved exactly as the mp4 door | ||
| 1318 | + // resolves it: the size the file states its pictures are shown at | ||
| 1319 | + // ([`display_size`] -- an anamorphic track's `DisplayWidth`, which is | ||
| 1320 | + // the shape the coded pixels are stretched to and the shape a player | ||
| 1321 | + // shows), then swapped where the turn is a quarter one. The file states | ||
| 1322 | + // that size in the *coded* orientation -- it is a property of the | ||
| 1323 | + // picture, not of the screen -- so the turn comes second, here and | ||
| 1324 | + // there. | ||
| 1325 | + let shown = video.display.unwrap_or((video.width, video.height)); | ||
| 1326 | + let (width, height) = match video.rotation.swaps_axes() { | ||
| 1327 | + true => (shown.1, shown.0), | ||
| 1328 | + false => shown, | ||
| 1329 | + }; | ||
| 1312 | let meta = VideoMeta { | 1330 | let meta = VideoMeta { |
| 1313 | - width: video.width, | 1331 | + width, |
| 1314 | - height: video.height, | 1332 | + height, |
| 1315 | frame_rate, | 1333 | frame_rate, |
| 1316 | frame_count: mkv.frames as u32, | 1334 | frame_count: mkv.frames as u32, |
| 1317 | codec: video.codec, | 1335 | codec: video.codec, |
| @@ -1323,11 +1341,10 @@ impl MkvDemuxer { | |||
| 1323 | bitstream_tags(video.codec, &mkv.config), | 1341 | bitstream_tags(video.codec, &mkv.config), |
| 1324 | video.height, | 1342 | video.height, |
| 1325 | ), | 1343 | ), |
| 1326 | - // FLAG: Matroska's turn is not read yet -- see [`VideoMeta::rotation`]. | 1344 | + // The turn off the track's `Projection` element ([`projection_rotation`]), |
| 1327 | - // Nothing in this tree writes a `ProjectionPoseYaw`, and the mkv | 1345 | + // which is where a Matroska muxer states what an mp4 states with its |
| 1328 | - // tracks a phone or a camera app produces are mp4s; a `.mkv` that | 1346 | + // `tkhd` matrix. |
| 1329 | - // does carry one would play sideways until this is written. | 1347 | + rotation: video.rotation, |
| 1330 | - rotation: Rotation::None, | ||
| 1331 | }; | 1348 | }; |
| 1332 | Ok((meta, mkv)) | 1349 | Ok((meta, mkv)) |
| 1333 | } | 1350 | } |
| @@ -1994,6 +2011,13 @@ struct MkvVideo { | |||
| 1994 | number: u64, | 2011 | number: u64, |
| 1995 | width: u32, | 2012 | width: u32, |
| 1996 | height: u32, | 2013 | height: u32, |
| 2014 | + /// The size the file displays its pictures at (`DisplayWidth`/ | ||
| 2015 | + /// `DisplayHeight`, stated in the pixel unit), or `None` -- which is every | ||
| 2016 | + /// square-pixel file, and falls back to the pixel dims above. | ||
| 2017 | + display: Option<(u32, u32)>, | ||
| 2018 | + /// The quarter turn the track's `Projection` asks for; | ||
| 2019 | + /// [`Rotation::None`] where it states none. | ||
| 2020 | + rotation: Rotation, | ||
| 1997 | /// What the track's `Colour` element declared, empty when it has none. | 2021 | /// What the track's `Colour` element declared, empty when it has none. |
| 1998 | tags: Tags, | 2022 | tags: Tags, |
| 1999 | /// What that same element said about brightness (MaxCLL and the mastering | 2023 | /// What that same element said about brightness (MaxCLL and the mastering |
| @@ -2141,6 +2165,29 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 2141 | const VIDEO: u32 = 0xE0; | 2165 | const VIDEO: u32 = 0xE0; |
| 2142 | const PIXEL_WIDTH: u32 = 0xB0; | 2166 | const PIXEL_WIDTH: u32 = 0xB0; |
| 2143 | const PIXEL_HEIGHT: u32 = 0xBA; | 2167 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 2168 | +// ...and the size the track's pictures are *shown* at, which a square-pixel | ||
| 2169 | +// file -- the common case -- states none of, so absence falls back to the pixel | ||
| 2170 | +// dims above. IDs checked against RFC 9559 and byte-verified against an | ||
| 2171 | +// ffmpeg-written fixture before the test that reads them was trusted. | ||
| 2172 | +const DISPLAY_WIDTH: u32 = 0x54B0; | ||
| 2173 | +const DISPLAY_HEIGHT: u32 = 0x54BA; | ||
| 2174 | +/// The unit `DisplayWidth`/`DisplayHeight` are counted in: 0 pixels, then | ||
| 2175 | +/// centimetres, inches, a bare aspect, unknown. Only the pixel unit resolves | ||
| 2176 | +/// without a physical screen, so any other unit keeps the pixel dims. | ||
| 2177 | +const DISPLAY_UNIT: u32 = 0x54B2; | ||
| 2178 | +// The track's projection: how the flat picture sits in space. A roll on the | ||
| 2179 | +// rectangular projection (type 0) is how a Matroska muxer states what an mp4 | ||
| 2180 | +// states with its `tkhd` matrix -- mkvmerge has translated display matrices | ||
| 2181 | +// into roll since v95, and ffmpeg's Matroska muxer writes a `Projection` for | ||
| 2182 | +// rotated input -- so the same quarter turns are read off it. Anything else (a | ||
| 2183 | +// spherical or mesh projection, a yaw/pitch pose) is not a turn this engine can | ||
| 2184 | +// make, and is refused by name like the mp4 door refuses a matrix that is not a | ||
| 2185 | +// quarter turn. | ||
| 2186 | +const PROJECTION: u32 = 0x7670; | ||
| 2187 | +const PROJECTION_TYPE: u32 = 0x7671; | ||
| 2188 | +const PROJECTION_POSE_YAW: u32 = 0x7673; | ||
| 2189 | +const PROJECTION_POSE_PITCH: u32 = 0x7674; | ||
| 2190 | +const PROJECTION_POSE_ROLL: u32 = 0x7675; | ||
| 2144 | // The `Colour` element and the three of its children this reads. Byte-verified | 2191 | // The `Colour` element and the three of its children this reads. Byte-verified |
| 2145 | // against real files rather than taken off a spec table: published tables that | 2192 | // against real files rather than taken off a spec table: published tables that |
| 2146 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. | 2193 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. |
| @@ -2391,6 +2438,8 @@ fn mkv_track_entry( | |||
| 2391 | ) -> crate::Result<MkvEntry> { | 2438 | ) -> crate::Result<MkvEntry> { |
| 2392 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); | 2439 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); |
| 2393 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); | 2440 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); |
| 2441 | + let mut display = None; | ||
| 2442 | + let mut rotation = Rotation::None; | ||
| 2394 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); | 2443 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); |
| 2395 | let mut tags = Tags::default(); | 2444 | let mut tags = Tags::default(); |
| 2396 | let mut light = ContentLight::default(); | 2445 | let mut light = ContentLight::default(); |
| @@ -2413,10 +2462,34 @@ fn mkv_track_entry( | |||
| 2413 | CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?, | 2462 | CODEC_PRIVATE => config = ebml_bytes(file, body, stop)?, |
| 2414 | VIDEO => { | 2463 | VIDEO => { |
| 2415 | let mut at = body; | 2464 | let mut at = body; |
| 2465 | + let (mut display_width, mut display_height, mut display_unit) = (None, None, None); | ||
| 2416 | while let Some(e) = ebml_element(file, at, stop)? { | 2466 | while let Some(e) = ebml_element(file, at, stop)? { |
| 2417 | match e.0 { | 2467 | match e.0 { |
| 2418 | PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, | 2468 | PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, |
| 2419 | PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, | 2469 | PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, |
| 2470 | + DISPLAY_WIDTH => display_width = Some(ebml_uint(file, e.1, e.2)?), | ||
| 2471 | + DISPLAY_HEIGHT => display_height = Some(ebml_uint(file, e.1, e.2)?), | ||
| 2472 | + DISPLAY_UNIT => display_unit = Some(ebml_uint(file, e.1, e.2)?), | ||
| 2473 | + PROJECTION => { | ||
| 2474 | + let (mut kind, mut yaw, mut pitch, mut roll) = | ||
| 2475 | + (0u64, 0.0f64, 0.0f64, 0.0f64); | ||
| 2476 | + let mut at = e.1; | ||
| 2477 | + while let Some(c) = ebml_element(file, at, e.2)? { | ||
| 2478 | + match c.0 { | ||
| 2479 | + PROJECTION_TYPE => kind = ebml_uint(file, c.1, c.2)?, | ||
| 2480 | + PROJECTION_POSE_YAW => yaw = ebml_float(file, c.1, c.2)?, | ||
| 2481 | + PROJECTION_POSE_PITCH => pitch = ebml_float(file, c.1, c.2)?, | ||
| 2482 | + PROJECTION_POSE_ROLL => roll = ebml_float(file, c.1, c.2)?, | ||
| 2483 | + // ProjectionPrivate: the spherical/mesh | ||
| 2484 | + // payload, which only matters where the | ||
| 2485 | + // type is one of those -- and those refuse | ||
| 2486 | + // below before it could be read. | ||
| 2487 | + _ => {} | ||
| 2488 | + } | ||
| 2489 | + at = c.2; | ||
| 2490 | + } | ||
| 2491 | + rotation = projection_rotation(kind, yaw, pitch, roll)?; | ||
| 2492 | + } | ||
| 2420 | // `Colour`: what the file says its picture's numbers | 2493 | // `Colour`: what the file says its picture's numbers |
| 2421 | // mean, in the same H.273 code points the bitstream | 2494 | // mean, in the same H.273 code points the bitstream |
| 2422 | // uses. An element the file leaves out stays 0, which | 2495 | // uses. An element the file leaves out stays 0, which |
| @@ -2469,6 +2542,11 @@ fn mkv_track_entry( | |||
| 2469 | } | 2542 | } |
| 2470 | at = e.2; | 2543 | at = e.2; |
| 2471 | } | 2544 | } |
| 2545 | + // Resolved here rather than per element: `DisplayWidth` and | ||
| 2546 | + // `DisplayHeight` can come in either order and their unit is a | ||
| 2547 | + // *ratio*, so neither half means anything until the pixel dims | ||
| 2548 | + // and the unit are all in hand. | ||
| 2549 | + display = display_size(height, display_width, display_height, display_unit); | ||
| 2472 | } | 2550 | } |
| 2473 | _ => {} | 2551 | _ => {} |
| 2474 | } | 2552 | } |
| @@ -2541,6 +2619,8 @@ fn mkv_track_entry( | |||
| 2541 | number, | 2619 | number, |
| 2542 | width, | 2620 | width, |
| 2543 | height, | 2621 | height, |
| 2622 | + display, | ||
| 2623 | + rotation, | ||
| 2544 | tags, | 2624 | tags, |
| 2545 | light, | 2625 | light, |
| 2546 | default_duration, | 2626 | default_duration, |
| @@ -2684,6 +2764,138 @@ fn rotation_of_matrix(a: i32, b: i32, c: i32, d: i32) -> crate::Result<Rotation> | |||
| 2684 | }) | 2764 | }) |
| 2685 | } | 2765 | } |
| 2686 | 2766 | ||
| 2767 | +/// The quarter turn a Matroska `ProjectionPoseRoll` asks for -- the mkv door's | ||
| 2768 | +/// half of [`rotation_of_matrix`], with the same half-degree tolerance and the | ||
| 2769 | +/// same refusal by name. | ||
| 2770 | +/// | ||
| 2771 | +/// **Measured against ffmpeg's own autorotate**, the same arbiter | ||
| 2772 | +/// [`rotation_of_matrix`] was measured against: `test_rotation{90,180,270}.mkv` | ||
| 2773 | +/// (`scripts/gen_fixtures.sh`) are the very quadrant source their `.mp4` twins | ||
| 2774 | +/// are, remuxed with `-display_rotation` asked for, and ffmpeg 8.1.2's matroska | ||
| 2775 | +/// muxer writes this element for it -- `+90.0`, `+180.0` and **`-90.0`**, an | ||
| 2776 | +/// 8-byte big-endian float, with no `ProjectionType` element at all (RFC 9559's | ||
| 2777 | +/// default of 0, rectangular). Its demuxer reads each of those back as the very | ||
| 2778 | +/// same `tkhd` matrix the mp4 twin carries, so both files autorotate to the same | ||
| 2779 | +/// four quadrants -- which is what `tests/rotation.rs` asserts, corner by corner. | ||
| 2780 | +/// | ||
| 2781 | +/// Hence the negation below: the element counts **counter-clockwise** degrees | ||
| 2782 | +/// about the viewing axis (RFC 9559 says so, and the measured layouts confirm | ||
| 2783 | +/// it), while the matrix this engine counts its quarter turns off is the | ||
| 2784 | +/// clockwise one `-display_rotation 90` writes -- so a roll of +90 is | ||
| 2785 | +/// [`Rotation::Cw270`] here, exactly as `a=0, b=-65536, c=65536, d=0` is. | ||
| 2786 | +fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> { | ||
| 2787 | + let steps = -(degrees / 90.0).round(); | ||
| 2788 | + if !degrees.is_finite() || (degrees + steps * 90.0).abs() > 0.5 { | ||
| 2789 | + return Err(UnsupportedRotation { | ||
| 2790 | + degrees: degrees.is_finite().then_some(degrees), | ||
| 2791 | + } | ||
| 2792 | + .into()); | ||
| 2793 | + } | ||
| 2794 | + Ok(match steps.rem_euclid(4.0) as u8 { | ||
| 2795 | + 0 => Rotation::None, | ||
| 2796 | + 1 => Rotation::Cw90, | ||
| 2797 | + 2 => Rotation::Cw180, | ||
| 2798 | + _ => Rotation::Cw270, | ||
| 2799 | + }) | ||
| 2800 | +} | ||
| 2801 | + | ||
| 2802 | +/// The turn a track's `Projection` asks for, or [`Rotation::None`] where it does | ||
| 2803 | +/// not ask for a turn of the picture at all. | ||
| 2804 | +/// | ||
| 2805 | +/// Only a **rectangular** projection has a pose that turns the *picture*, and | ||
| 2806 | +/// rectangular (0) is what an absent `ProjectionType` means. On an | ||
| 2807 | +/// equirectangular or cubemap one those same three elements state how the sphere | ||
| 2808 | +/// is oriented, which is not a turn of anything 2D: the pose is left alone, as a | ||
| 2809 | +/// flat player shows a 360° file, rather than refused -- refusing would cost a | ||
| 2810 | +/// file that plays right now and would not show it any righter. | ||
| 2811 | +/// | ||
| 2812 | +/// A rectangular projection whose **yaw or pitch** is off zero is refused by | ||
| 2813 | +/// name, though, and that is mkvmerge's spelling to watch for: since v95 it | ||
| 2814 | +/// translates an mp4 display matrix into roll *and* yaw, using yaw for a mirror. | ||
| 2815 | +/// A picture mirrored, or turned out of its own plane, is the one thing no | ||
| 2816 | +/// quarter turn here can make -- the same missing capability the mp4 door | ||
| 2817 | +/// refuses a 45-degree matrix for, so it gets the same refusal rather than a | ||
| 2818 | +/// sideways picture. | ||
| 2819 | +fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> { | ||
| 2820 | + if kind != 0 { | ||
| 2821 | + return Ok(Rotation::None); | ||
| 2822 | + } | ||
| 2823 | + let off_plane = [yaw, pitch] | ||
| 2824 | + .into_iter() | ||
| 2825 | + .any(|degrees| !degrees.is_finite() || degrees.abs() > 0.5); | ||
| 2826 | + match off_plane { | ||
| 2827 | + // No angle to name: a pose out of the picture's own plane -- a mirror | ||
| 2828 | + // through it, or a tilt of it -- is not a rotation in that plane whatever | ||
| 2829 | + // number it states, which is what the sentence without one says. | ||
| 2830 | + true => Err(UnsupportedRotation { degrees: None }.into()), | ||
| 2831 | + false => rotation_of_roll(roll), | ||
| 2832 | + } | ||
| 2833 | +} | ||
| 2834 | + | ||
| 2835 | +/// The size a track's `Display*` elements say its pictures are shown at, or | ||
| 2836 | +/// `None` for a file that states none -- or states one in a unit nothing here can | ||
| 2837 | +/// resolve, which falls back to the pixel dims for the same reason. | ||
| 2838 | +/// | ||
| 2839 | +/// The mkv spelling of what an mp4 keeps in its sample entry's `pasp` box, and | ||
| 2840 | +/// resolved the same way round: the **coded height is kept** and the width is | ||
| 2841 | +/// the one the file's own numbers make it. That is what anamorphic video is: | ||
| 2842 | +/// HDV's 1440x1080 is 1920x1080 wide when shown, DVD's 720x576 is 1024x576 -- never | ||
| 2843 | +/// 1440x810 or 720x405, which is the vertical resolution thrown away. | ||
| 2844 | +/// | ||
| 2845 | +/// Only two of the five units can be resolved without a screen to show the | ||
| 2846 | +/// picture on: **pixels** (0, the spec's default where the file states no unit) | ||
| 2847 | +/// is the size itself, and the **display aspect ratio** (3) is the shape the | ||
| 2848 | +/// size is derived from. Centimetres, inches and "unknown" are left to the pixel | ||
| 2849 | +/// dims -- a physical size says nothing about how many pixels to show, and a DPI | ||
| 2850 | +/// guessed here would be this engine's invention rather than the file's word. | ||
| 2851 | +fn display_size( | ||
| 2852 | + pixel_height: u32, | ||
| 2853 | + display_width: Option<u64>, | ||
| 2854 | + display_height: Option<u64>, | ||
| 2855 | + display_unit: Option<u64>, | ||
| 2856 | +) -> Option<(u32, u32)> { | ||
| 2857 | + let (across, down) = match (display_width, display_height) { | ||
| 2858 | + (Some(across), Some(down)) if across > 0 && down > 0 => (across, down), | ||
| 2859 | + _ => return None, | ||
| 2860 | + }; | ||
| 2861 | + match display_unit.unwrap_or(0) { | ||
| 2862 | + 0 => Some((u32::try_from(across).ok()?, u32::try_from(down).ok()?)), | ||
| 2863 | + 3 => Some(( | ||
| 2864 | + u32::try_from((u64::from(pixel_height) * across + down / 2) / down).ok()?, | ||
| 2865 | + pixel_height, | ||
| 2866 | + )), | ||
| 2867 | + _ => None, | ||
| 2868 | + } | ||
| 2869 | +} | ||
| 2870 | + | ||
| 2871 | +/// The size a sample entry's `pasp` box says the pictures are shown at -- an | ||
| 2872 | +/// mp4's spelling of [`display_size`], read the same way: the box is a *sample* | ||
| 2873 | +/// aspect ratio, so the coded height is kept and the width is the one the ratio | ||
| 2874 | +/// makes it (1440x1080 at `pasp` 4:3 is the 1920x1080 an HDV file is meant to be | ||
| 2875 | +/// shown at). | ||
| 2876 | +/// | ||
| 2877 | +/// The box is one of the sample entry's *children*, so the walk starts after the | ||
| 2878 | +/// entry's own fixed fields rather than at its first byte: a `boxes` pass over a | ||
| 2879 | +/// whole `avc1` payload reads a length out of its `data_reference_index` and | ||
| 2880 | +/// finds nothing. | ||
| 2881 | +fn pasp_size(entry: &[u8], coded_w: u32, coded_h: u32) -> Option<(u32, u32)> { | ||
| 2882 | + let payload = child(entry.get(VISUAL_SAMPLE_ENTRY..)?, b"pasp")?; | ||
| 2883 | + let across = u32::from_be_bytes(payload.get(..4)?.try_into().ok()?); | ||
| 2884 | + let down = u32::from_be_bytes(payload.get(4..8)?.try_into().ok()?); | ||
| 2885 | + if across == 0 || down == 0 { | ||
| 2886 | + return None; | ||
| 2887 | + } | ||
| 2888 | + let width = (u64::from(coded_w) * u64::from(across) + u64::from(down) / 2) / u64::from(down); | ||
| 2889 | + Some((u32::try_from(width).ok()?, coded_h)) | ||
| 2890 | +} | ||
| 2891 | + | ||
| 2892 | +/// What a `VisualSampleEntry` states before its child boxes: the reserved word | ||
| 2893 | +/// and `data_reference_index` (8), the pre-defined and reserved words (16), the | ||
| 2894 | +/// coded width and height (4), the two fixed-point resolutions (8), a reserved | ||
| 2895 | +/// word (4), the frame count (2), the 32-byte compressor name, the depth (2) and | ||
| 2896 | +/// one more reserved word (2). | ||
| 2897 | +const VISUAL_SAMPLE_ENTRY: usize = 78; | ||
| 2898 | + | ||
| 2687 | /// Why an mp4 came back with no picture, by the fourcc of the video track it | 2899 | /// Why an mp4 came back with no picture, by the fourcc of the video track it |
| 2688 | /// does carry: `avc3` and `mp4v` are files with video in them, and telling their | 2900 | /// does carry: `avc3` and `mp4v` are files with video in them, and telling their |
| 2689 | /// owner there is none sends them looking for a fault that is not in the file. | 2901 | /// owner there is none sends them looking for a fault that is not in the file. |
| @@ -4312,7 +4524,10 @@ fn mkv_subtitle_blocks( | |||
| 4312 | const BLOCK_DURATION: u32 = 0x9B; | 4524 | const BLOCK_DURATION: u32 = 0x9B; |
| 4313 | // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is | 4525 | // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is |
| 4314 | // nanoseconds per tick and is a millisecond in every file anything writes. | 4526 | // nanoseconds per tick and is a millisecond in every file anything writes. |
| 4315 | - let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; | 4527 | + // [`ticks_to_us`] does the arithmetic: it is widened and fallible, and a |
| 4528 | + // corrupt cluster timestamp is refused rather than wrapped into a negative | ||
| 4529 | + // cue time -- see the test beside it. | ||
| 4530 | + let us = |ticks: i64| ticks_to_us(ticks, timestamp_scale); | ||
| 4316 | let mut at = segment.0; | 4531 | let mut at = segment.0; |
| 4317 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | 4532 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { |
| 4318 | // The import's second walk, stopped by the same Cancel as its first. | 4533 | // The import's second walk, stopped by the same Cancel as its first. |
| @@ -4376,8 +4591,14 @@ fn mkv_subtitle_blocks( | |||
| 4376 | read_exact_at(file, at, &mut payload)?; | 4591 | read_exact_at(file, at, &mut payload)?; |
| 4377 | track.unpack.frame(&mut payload)?; | 4592 | track.unpack.frame(&mut payload)?; |
| 4378 | track.cues.push(MkvCue { | 4593 | track.cues.push(MkvCue { |
| 4379 | - start_us: us(cluster_ts + i64::from(block.rel)), | 4594 | + // The cluster's timestamp plus the block's own signed offset, |
| 4380 | - duration_us: duration.map(us), | 4595 | + // checked: the pair is where a corrupt file's two numbers can |
| 4596 | + // still overflow what an `i64` holds, one step before the | ||
| 4597 | + // scale above would refuse the result. | ||
| 4598 | + start_us: us(cluster_ts | ||
| 4599 | + .checked_add(i64::from(block.rel)) | ||
| 4600 | + .ok_or("a Matroska subtitle block at no timestamp a clock can hold")?)?, | ||
| 4601 | + duration_us: duration.map(us).transpose()?, | ||
| 4381 | payload, | 4602 | payload, |
| 4382 | }); | 4603 | }); |
| 4383 | } | 4604 | } |
| @@ -4386,6 +4607,22 @@ fn mkv_subtitle_blocks( | |||
| 4386 | Ok(()) | 4607 | Ok(()) |
| 4387 | } | 4608 | } |
| 4388 | 4609 | ||
| 4610 | +/// A tick count as the microseconds [`MkvCue`] keeps, or the refusal a corrupt | ||
| 4611 | +/// one earns. | ||
| 4612 | +/// | ||
| 4613 | +/// The multiply is widened to `i128` rather than done in `i64`, and a result that | ||
| 4614 | +/// does not fit is refused rather than saturated: both numbers are the file's -- | ||
| 4615 | +/// a cluster timestamp is an EBML uint nothing bounds and `TimestampScale` is a | ||
| 4616 | +/// scale it chooses -- so `ticks * timestamp_scale` overflows on a crafted file, | ||
| 4617 | +/// which is a panic in debug and a *negative* cue time in release, silently. | ||
| 4618 | +/// Widened, no product can overflow; a timestamp that then does not fit the | ||
| 4619 | +/// answer is the same class of corrupt as the oversized block refused above, and | ||
| 4620 | +/// gets the same loud refusal rather than a cue at a time no clock can hold. | ||
| 4621 | +fn ticks_to_us(ticks: i64, timestamp_scale: u64) -> crate::Result<i64> { | ||
| 4622 | + i64::try_from(i128::from(ticks) * i128::from(timestamp_scale) / 1_000) | ||
| 4623 | + .map_err(|_| "a Matroska subtitle timestamp no clock can hold".into()) | ||
| 4624 | +} | ||
| 4625 | + | ||
| 4389 | /// A string element, without the trailing NULs a `Name` may be padded with. | 4626 | /// A string element, without the trailing NULs a `Name` may be padded with. |
| 4390 | fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | 4627 | fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { |
| 4391 | let bytes = ebml_bytes(file, body, stop)?; | 4628 | let bytes = ebml_bytes(file, body, stop)?; |
| @@ -4398,6 +4635,25 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | |||
| 4398 | mod tests { | 4635 | mod tests { |
| 4399 | use super::*; | 4636 | use super::*; |
| 4400 | 4637 | ||
| 4638 | + /// A corrupt cluster timestamp is refused, not wrapped: the product is where | ||
| 4639 | + /// an `i64` overflows, so this is the assertion that fails (as a panic in | ||
| 4640 | + /// debug, as a negative cue time in release) without the widening -- the | ||
| 4641 | + /// shape a hostile `.mkv` reaches through `mkv_subtitle_blocks`. | ||
| 4642 | + #[test] | ||
| 4643 | + fn a_subtitle_timestamp_no_clock_can_hold_is_refused() { | ||
| 4644 | + // A millisecond scale, which is every file anything writes: 1000 ticks | ||
| 4645 | + // is one second. | ||
| 4646 | + assert_eq!(ticks_to_us(1_000, 1_000_000).unwrap(), 1_000_000); | ||
| 4647 | + assert_eq!(ticks_to_us(0, 1_000_000).unwrap(), 0); | ||
| 4648 | + // A nanosecond scale and the largest tick count an EBML uint can cast | ||
| 4649 | + // to: 600 million years of microseconds, which no `i64` holds. | ||
| 4650 | + assert!( | ||
| 4651 | + ticks_to_us(i64::MAX, 1_000_000_000).is_err(), | ||
| 4652 | + "the product must not wrap into a negative cue time" | ||
| 4653 | + ); | ||
| 4654 | + assert!(ticks_to_us(i64::MIN, 1_000_000_000).is_err()); | ||
| 4655 | + } | ||
| 4656 | + | ||
| 4401 | fn asset(name: &str) -> std::path::PathBuf { | 4657 | fn asset(name: &str) -> std::path::PathBuf { |
| 4402 | std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) | 4658 | std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 4403 | .join("../../assets") | 4659 | .join("../../assets") |
crates/engine/tests/rotation.rsmodified+59 -5
| @@ -92,7 +92,12 @@ fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] { | |||
| 92 | tint(&bgra[index..index + 4]) | 92 | tint(&bgra[index..index + 4]) |
| 93 | }; | 93 | }; |
| 94 | let (qx, qy) = (width / 4, height / 4); | 94 | let (qx, qy) = (width / 4, height / 4); |
| 95 | - [at(qx, qy), at(3 * qx, qy), at(3 * qx, 3 * qy), at(qx, 3 * qy)] | 95 | + [ |
| 96 | + at(qx, qy), | ||
| 97 | + at(3 * qx, qy), | ||
| 98 | + at(3 * qx, 3 * qy), | ||
| 99 | + at(qx, 3 * qy), | ||
| 100 | + ] | ||
| 96 | } | 101 | } |
| 97 | 102 | ||
| 98 | /// What the coded picture holds, before anything turns it: this is the layout | 103 | /// What the coded picture holds, before anything turns it: this is the layout |
| @@ -112,17 +117,17 @@ fn first_frame(path: &Path) -> (u32, u32, Vec<u8>) { | |||
| 112 | /// machine, which is the arbiter a display matrix is read against. | 117 | /// machine, which is the arbiter a display matrix is read against. |
| 113 | fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) { | 118 | fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) { |
| 114 | match file { | 119 | match file { |
| 115 | - "test_rotation90.mp4" => ( | 120 | + "test_rotation90.mp4" | "test_rotation90.mkv" => ( |
| 116 | [180, 320], | 121 | [180, 320], |
| 117 | Rotation::Cw270, | 122 | Rotation::Cw270, |
| 118 | ["green", "yellow", "blue", "red"], | 123 | ["green", "yellow", "blue", "red"], |
| 119 | ), | 124 | ), |
| 120 | - "test_rotation180.mp4" => ( | 125 | + "test_rotation180.mp4" | "test_rotation180.mkv" => ( |
| 121 | [320, 180], | 126 | [320, 180], |
| 122 | Rotation::Cw180, | 127 | Rotation::Cw180, |
| 123 | ["yellow", "blue", "red", "green"], | 128 | ["yellow", "blue", "red", "green"], |
| 124 | ), | 129 | ), |
| 125 | - "test_rotation270.mp4" => ( | 130 | + "test_rotation270.mp4" | "test_rotation270.mkv" => ( |
| 126 | [180, 320], | 131 | [180, 320], |
| 127 | Rotation::Cw90, | 132 | Rotation::Cw90, |
| 128 | ["blue", "red", "green", "yellow"], | 133 | ["blue", "red", "green", "yellow"], |
| @@ -135,10 +140,18 @@ fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) { | |||
| 135 | /// displayed size and names the turn, and a half turn does neither. | 140 | /// displayed size and names the turn, and a half turn does neither. |
| 136 | #[test] | 141 | #[test] |
| 137 | fn a_display_matrix_is_read_as_a_quarter_turn() { | 142 | fn a_display_matrix_is_read_as_a_quarter_turn() { |
| 143 | + // Both doors, the same turn: the mkv twins are the same quadrant source | ||
| 144 | + // remuxed with the same rotation asked for (`scripts/gen_fixtures.sh`), one | ||
| 145 | + // stating it in a `Projection` roll and one in a `tkhd` matrix, and a roll | ||
| 146 | + // read the wrong way round is a file that plays on its side in exactly one | ||
| 147 | + // of the two. | ||
| 138 | for file in [ | 148 | for file in [ |
| 139 | "test_rotation90.mp4", | 149 | "test_rotation90.mp4", |
| 150 | + "test_rotation90.mkv", | ||
| 140 | "test_rotation180.mp4", | 151 | "test_rotation180.mp4", |
| 152 | + "test_rotation180.mkv", | ||
| 141 | "test_rotation270.mp4", | 153 | "test_rotation270.mp4", |
| 154 | + "test_rotation270.mkv", | ||
| 142 | ] { | 155 | ] { |
| 143 | let (size, rotation, _) = expected(file); | 156 | let (size, rotation, _) = expected(file); |
| 144 | let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); | 157 | let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); |
| @@ -147,7 +160,10 @@ fn a_display_matrix_is_read_as_a_quarter_turn() { | |||
| 147 | size, | 160 | size, |
| 148 | "{file}: the *displayed* size is what the engine reports" | 161 | "{file}: the *displayed* size is what the engine reports" |
| 149 | ); | 162 | ); |
| 150 | - assert_eq!(meta.rotation, rotation, "{file}: which turn the file asks for"); | 163 | + assert_eq!( |
| 164 | + meta.rotation, rotation, | ||
| 165 | + "{file}: which turn the file asks for" | ||
| 166 | + ); | ||
| 151 | assert_eq!( | 167 | assert_eq!( |
| 152 | rotation.swaps_axes(), | 168 | rotation.swaps_axes(), |
| 153 | size == [180, 320], | 169 | size == [180, 320], |
| @@ -168,10 +184,18 @@ fn a_display_matrix_is_read_as_a_quarter_turn() { | |||
| 168 | #[test] | 184 | #[test] |
| 169 | fn the_preview_shows_a_turned_file_upright() { | 185 | fn the_preview_shows_a_turned_file_upright() { |
| 170 | let _seat = pin_software(); | 186 | let _seat = pin_software(); |
| 187 | + // Both doors, the same turn: the mkv twins are the same quadrant source | ||
| 188 | + // remuxed with the same rotation asked for (`scripts/gen_fixtures.sh`), one | ||
| 189 | + // stating it in a `Projection` roll and one in a `tkhd` matrix, and a roll | ||
| 190 | + // read the wrong way round is a file that plays on its side in exactly one | ||
| 191 | + // of the two. | ||
| 171 | for file in [ | 192 | for file in [ |
| 172 | "test_rotation90.mp4", | 193 | "test_rotation90.mp4", |
| 194 | + "test_rotation90.mkv", | ||
| 173 | "test_rotation180.mp4", | 195 | "test_rotation180.mp4", |
| 196 | + "test_rotation180.mkv", | ||
| 174 | "test_rotation270.mp4", | 197 | "test_rotation270.mp4", |
| 198 | + "test_rotation270.mkv", | ||
| 175 | ] { | 199 | ] { |
| 176 | let (size, _, corners_expected) = expected(file); | 200 | let (size, _, corners_expected) = expected(file); |
| 177 | let (width, height, bgra) = first_frame(&asset(file)); | 201 | let (width, height, bgra) = first_frame(&asset(file)); |
| @@ -250,3 +274,33 @@ fn a_matrix_that_is_not_a_quarter_turn_is_refused_by_name() { | |||
| 250 | "the refusal names the angle it cannot make: {said}" | 274 | "the refusal names the angle it cannot make: {said}" |
| 251 | ); | 275 | ); |
| 252 | } | 276 | } |
| 277 | + | ||
| 278 | +/// An anamorphic file's own numbers decide the shape the engine reports: the | ||
| 279 | +/// pixels are 1440x1080 and the file says they are shown 1920x1080 wide, which is | ||
| 280 | +/// what a player shows -- so that is the shape this engine reports, and the shape | ||
| 281 | +/// the preview and the export must therefore place the coded pixels at. A | ||
| 282 | +/// squashed picture in a 4:3 frame is the same class of wrong as a portrait file | ||
| 283 | +/// on its side, and both are the file's own numbers being ignored. | ||
| 284 | +/// | ||
| 285 | +/// **Both spellings**, because they are what the two doors read and a file | ||
| 286 | +/// remuxed from one to the other must not change shape: Matroska states the | ||
| 287 | +/// *display aspect ratio* in `DisplayWidth`/`DisplayHeight` -- ffmpeg writes the | ||
| 288 | +/// ratio unit, so `16x9` and not `1920x1080` (`DisplayUnit` 3) -- while an mp4 | ||
| 289 | +/// states the *sample* aspect ratio in a `pasp` box beside its `avc1` (`4:3`). | ||
| 290 | +/// Both resolve to the coded height at that aspect. | ||
| 291 | +#[test] | ||
| 292 | +fn an_anamorphic_file_reports_the_shape_it_is_shown_at() { | ||
| 293 | + for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { | ||
| 294 | + let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); | ||
| 295 | + assert_eq!( | ||
| 296 | + [meta.width, meta.height], | ||
| 297 | + [1920, 1080], | ||
| 298 | + "{file}: the displayed shape, not the 1440x1080 the samples are stored at" | ||
| 299 | + ); | ||
| 300 | + assert_eq!( | ||
| 301 | + meta.rotation, | ||
| 302 | + Rotation::None, | ||
| 303 | + "{file}: no turn is asked for, and a non-square sample is not one" | ||
| 304 | + ); | ||
| 305 | + } | ||
| 306 | +} | ||
scripts/gen_fixtures.shmodified+43 -0
| @@ -730,6 +730,49 @@ for deg in 90 180 270 45; do | |||
| 730 | ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \ | 730 | ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \ |
| 731 | -c copy "assets/test_rotation$deg.mp4" | 731 | -c copy "assets/test_rotation$deg.mp4" |
| 732 | done | 732 | done |
| 733 | +# ...and the very same turn asked for inside a Matroska, from the very same | ||
| 734 | +# source: one set of expected layouts then covers both containers | ||
| 735 | +# (`tests/rotation.rs`), which is the point -- a roll read the wrong way round is | ||
| 736 | +# a file that plays on its side in exactly one of the two. | ||
| 737 | +# | ||
| 738 | +# What the muxer actually writes, byte-verified by walking the header rather than | ||
| 739 | +# taken off a table: a `Projection` master (`0x7670`) holding one | ||
| 740 | +# `ProjectionPoseRoll` (`0x7675`), an 8-byte big-endian float -- `+90.0`, `+180.0` | ||
| 741 | +# and *`-90.0`* for `-display_rotation 90/180/270` -- and no `ProjectionType` | ||
| 742 | +# element at all, which is the spec's default of 0 (rectangular). `ffprobe` | ||
| 743 | +# reports the same display matrix as the mp4 twin, which is what makes the | ||
| 744 | +# layouts above ffmpeg's own autorotation of either file. The roll counts | ||
| 745 | +# counter-clockwise where the matrix counts clockwise turns, which is why the | ||
| 746 | +# engine negates it. | ||
| 747 | +for deg in 90 180 270 45; do | ||
| 748 | + ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \ | ||
| 749 | + -c copy "assets/test_rotation$deg.mkv" | ||
| 750 | +done | ||
| 733 | rm -f assets/.rotation_src.mp4 | 751 | rm -f assets/.rotation_src.mp4 |
| 734 | 752 | ||
| 753 | +# Anamorphic: the same four coloured quadrants in a frame whose samples are not | ||
| 754 | +# square, so the file's own numbers say the picture is 1920x1080 while the pixels | ||
| 755 | +# it carries are 1440x1080 -- exactly HDV, and the shape `tests/rotation.rs` | ||
| 756 | +# asserts the engine reports and places the pixels at. Both containers state it | ||
| 757 | +# and neither door used to read either spelling, so an anamorphic source probed, | ||
| 758 | +# previewed and exported squashed. | ||
| 759 | +# | ||
| 760 | +# The two spellings, byte-verified the same way: Matroska in `DisplayWidth` | ||
| 761 | +# (`0x54B0`) / `DisplayHeight` (`0x54BA`) / `DisplayUnit` (`0x54B2`), where ffmpeg | ||
| 762 | +# writes the *display aspect ratio* unit (3) and therefore `16x9` rather than | ||
| 763 | +# `1920x1080`; mp4 in a `pasp` box beside the `avc1` sample entry, holding the | ||
| 764 | +# *sample* aspect ratio (`4:3`). Read the same way round out of both: the coded | ||
| 765 | +# height is kept and the width is the one the file's ratio makes it. | ||
| 766 | +ffmpeg -y -f lavfi -i "color=c=red:s=720x540:d=1:r=30,format=yuv420p" \ | ||
| 767 | + -f lavfi -i "color=c=green:s=720x540:d=1:r=30,format=yuv420p" \ | ||
| 768 | + -f lavfi -i "color=c=blue:s=720x540:d=1:r=30,format=yuv420p" \ | ||
| 769 | + -f lavfi -i "color=c=yellow:s=720x540:d=1:r=30,format=yuv420p" \ | ||
| 770 | + -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \ | ||
| 771 | + -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 772 | + assets/.anamorphic_src.mp4 | ||
| 773 | +ffmpeg -y -i assets/.anamorphic_src.mp4 -vf "setsar=4/3" -c:v libx264 \ | ||
| 774 | + -profile:v baseline -pix_fmt yuv420p assets/test_anamorphic.mp4 | ||
| 775 | +ffmpeg -y -i assets/test_anamorphic.mp4 -c copy assets/test_anamorphic.mkv | ||
| 776 | +rm -f assets/.anamorphic_src.mp4 | ||
| 777 | + | ||
| 735 | echo "fixtures written to assets/" | 778 | echo "fixtures written to assets/" |