Merge the demux lane into main
Browse files at this commit3 changed files +389 -76
- crates/engine/src/demux.rs +223 -20
- crates/engine/tests/rotation.rs +128 -56
- scripts/gen_fixtures.sh +38 -0
crates/engine/src/demux.rsmodified+223 -20
| @@ -371,13 +371,17 @@ 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 for |
| 378 | - /// element) is written by nobody in practice while the `tkhd` matrix is how | 378 | + /// a projection that is not rectangular: on a spherical or cubemap one those |
| 379 | - /// every phone records it. That is a known gap and not a silent one: | 379 | + /// same pose elements describe how the *sphere* is oriented, which is no turn |
| 380 | - /// [`MkvDemuxer::open`] says where a reader for it would go. | 380 | + /// of the picture, so the pose is deliberately not applied and the file |
| 381 | + /// paints as a flat frame -- what every player does with a 360 clip, and | ||
| 382 | + /// cheaper than a refusal that would cost a file that plays. A turn that is | ||
| 383 | + /// not a quarter turn -- a mirror, a shear, an angle in between -- is refused | ||
| 384 | + /// at the door ([`UnsupportedRotation`]) rather than shown wrong. | ||
| 381 | pub rotation: Rotation, | 385 | pub rotation: Rotation, |
| 382 | } | 386 | } |
| 383 | 387 | ||
| @@ -1309,25 +1313,37 @@ impl MkvDemuxer { | |||
| 1309 | } | 1313 | } |
| 1310 | } | 1314 | } |
| 1311 | }; | 1315 | }; |
| 1316 | + // The coded size, swapped where the turn is a quarter one: a portrait | ||
| 1317 | + // `.mkv` stores a landscape picture plus the turn, so the displayed | ||
| 1318 | + // shape is the coded one turned -- the same two numbers the mp4 door | ||
| 1319 | + // swaps, off the same kind of turn. | ||
| 1320 | + let (width, height) = match video.rotation.swaps_axes() { | ||
| 1321 | + true => (video.height, video.width), | ||
| 1322 | + false => (video.width, video.height), | ||
| 1323 | + }; | ||
| 1312 | let meta = VideoMeta { | 1324 | let meta = VideoMeta { |
| 1313 | - width: video.width, | 1325 | + width, |
| 1314 | - height: video.height, | 1326 | + height, |
| 1315 | frame_rate, | 1327 | frame_rate, |
| 1316 | frame_count: mkv.frames as u32, | 1328 | frame_count: mkv.frames as u32, |
| 1317 | codec: video.codec, | 1329 | codec: video.codec, |
| 1318 | // `config` is the parameter sets by now -- Annex-B for H.264 and | 1330 | // `config` is the parameter sets by now -- Annex-B for H.264 and |
| 1319 | // HEVC, the sequence header OBU for AV1 -- which is what the | 1331 | // HEVC, the sequence header OBU for AV1 -- which is what the |
| 1320 | // bitstream tier reads. | 1332 | // bitstream tier reads. |
| 1333 | + // The height the picture is *shown* at, which is what the mp4 door | ||
| 1334 | + // feeds here and the whole reason both doors resolve their size the | ||
| 1335 | + // same way: the 720-line rule below is a guess about the material, and | ||
| 1336 | + // the material is the picture as displayed -- a device-held `.mkv` is | ||
| 1337 | + // 640 coded but 1280 shown, and the two sides of that rule disagree. | ||
| 1321 | color: ColorDescription::resolve( | 1338 | color: ColorDescription::resolve( |
| 1322 | video.tags, | 1339 | video.tags, |
| 1323 | bitstream_tags(video.codec, &mkv.config), | 1340 | bitstream_tags(video.codec, &mkv.config), |
| 1324 | - video.height, | 1341 | + height, |
| 1325 | ), | 1342 | ), |
| 1326 | - // FLAG: Matroska's turn is not read yet -- see [`VideoMeta::rotation`]. | 1343 | + // The turn off the track's `Projection` element ([`projection_rotation`]), |
| 1327 | - // Nothing in this tree writes a `ProjectionPoseYaw`, and the mkv | 1344 | + // 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 | 1345 | + // `tkhd` matrix. |
| 1329 | - // does carry one would play sideways until this is written. | 1346 | + rotation: video.rotation, |
| 1330 | - rotation: Rotation::None, | ||
| 1331 | }; | 1347 | }; |
| 1332 | Ok((meta, mkv)) | 1348 | Ok((meta, mkv)) |
| 1333 | } | 1349 | } |
| @@ -1784,7 +1800,11 @@ impl MkvDemuxer { | |||
| 1784 | Ok(Some(CodedBlock { | 1800 | Ok(Some(CodedBlock { |
| 1785 | bytes: &self.scratch, | 1801 | bytes: &self.scratch, |
| 1786 | key: block.key, | 1802 | key: block.key, |
| 1787 | - ts_ns: block.ts * self.timestamp_scale as i64, | 1803 | + // Widened and fallible, exactly as the subtitle walk's tick scale |
| 1804 | + // is ([`ticks_scaled`]): `block.ts` is whatever the file says, so the | ||
| 1805 | + // multiply overflows an `i64` on a crafted cluster and a copy would | ||
| 1806 | + // write a block time that wrapped negative. | ||
| 1807 | + ts_ns: ticks_scaled(block.ts, self.timestamp_scale, 1)?, | ||
| 1788 | })) | 1808 | })) |
| 1789 | } | 1809 | } |
| 1790 | } | 1810 | } |
| @@ -1994,6 +2014,9 @@ struct MkvVideo { | |||
| 1994 | number: u64, | 2014 | number: u64, |
| 1995 | width: u32, | 2015 | width: u32, |
| 1996 | height: u32, | 2016 | height: u32, |
| 2017 | + /// The quarter turn the track's `Projection` asks for; | ||
| 2018 | + /// [`Rotation::None`] where it states none. | ||
| 2019 | + rotation: Rotation, | ||
| 1997 | /// What the track's `Colour` element declared, empty when it has none. | 2020 | /// What the track's `Colour` element declared, empty when it has none. |
| 1998 | tags: Tags, | 2021 | tags: Tags, |
| 1999 | /// What that same element said about brightness (MaxCLL and the mastering | 2022 | /// What that same element said about brightness (MaxCLL and the mastering |
| @@ -2141,6 +2164,20 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 2141 | const VIDEO: u32 = 0xE0; | 2164 | const VIDEO: u32 = 0xE0; |
| 2142 | const PIXEL_WIDTH: u32 = 0xB0; | 2165 | const PIXEL_WIDTH: u32 = 0xB0; |
| 2143 | const PIXEL_HEIGHT: u32 = 0xBA; | 2166 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 2167 | +// The track's projection: how the flat picture sits in space. A roll on the | ||
| 2168 | +// rectangular projection (type 0) is how a Matroska muxer states what an mp4 | ||
| 2169 | +// states with its `tkhd` matrix -- mkvmerge has translated display matrices | ||
| 2170 | +// into roll since v95, and ffmpeg's Matroska muxer writes a `Projection` for | ||
| 2171 | +// rotated input -- so the same quarter turns are read off it. Anything else (a | ||
| 2172 | +// spherical or mesh projection, a yaw/pitch pose) is not a turn this engine can | ||
| 2173 | +// make, and is refused by name like the mp4 door refuses a matrix that is not a | ||
| 2174 | +// quarter turn; a spherical one's pose is the sphere's orientation rather than | ||
| 2175 | +// the picture's and is left alone ([`projection_rotation`]). | ||
| 2176 | +const PROJECTION: u32 = 0x7670; | ||
| 2177 | +const PROJECTION_TYPE: u32 = 0x7671; | ||
| 2178 | +const PROJECTION_POSE_YAW: u32 = 0x7673; | ||
| 2179 | +const PROJECTION_POSE_PITCH: u32 = 0x7674; | ||
| 2180 | +const PROJECTION_POSE_ROLL: u32 = 0x7675; | ||
| 2144 | // The `Colour` element and the three of its children this reads. Byte-verified | 2181 | // 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 | 2182 | // against real files rather than taken off a spec table: published tables that |
| 2146 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. | 2183 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. |
| @@ -2391,6 +2428,7 @@ fn mkv_track_entry( | |||
| 2391 | ) -> crate::Result<MkvEntry> { | 2428 | ) -> crate::Result<MkvEntry> { |
| 2392 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); | 2429 | 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()); | 2430 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); |
| 2431 | + let mut rotation = Rotation::None; | ||
| 2394 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); | 2432 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); |
| 2395 | let mut tags = Tags::default(); | 2433 | let mut tags = Tags::default(); |
| 2396 | let mut light = ContentLight::default(); | 2434 | let mut light = ContentLight::default(); |
| @@ -2417,6 +2455,26 @@ fn mkv_track_entry( | |||
| 2417 | match e.0 { | 2455 | match e.0 { |
| 2418 | PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, | 2456 | 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, | 2457 | PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, |
| 2458 | + PROJECTION => { | ||
| 2459 | + let (mut kind, mut yaw, mut pitch, mut roll) = | ||
| 2460 | + (0u64, 0.0f64, 0.0f64, 0.0f64); | ||
| 2461 | + let mut at = e.1; | ||
| 2462 | + while let Some(c) = ebml_element(file, at, e.2)? { | ||
| 2463 | + match c.0 { | ||
| 2464 | + PROJECTION_TYPE => kind = ebml_uint(file, c.1, c.2)?, | ||
| 2465 | + PROJECTION_POSE_YAW => yaw = ebml_float(file, c.1, c.2)?, | ||
| 2466 | + PROJECTION_POSE_PITCH => pitch = ebml_float(file, c.1, c.2)?, | ||
| 2467 | + PROJECTION_POSE_ROLL => roll = ebml_float(file, c.1, c.2)?, | ||
| 2468 | + // ProjectionPrivate: the spherical/mesh | ||
| 2469 | + // payload, which only matters where the | ||
| 2470 | + // type is one of those -- and those refuse | ||
| 2471 | + // below before it could be read. | ||
| 2472 | + _ => {} | ||
| 2473 | + } | ||
| 2474 | + at = c.2; | ||
| 2475 | + } | ||
| 2476 | + rotation = projection_rotation(kind, yaw, pitch, roll)?; | ||
| 2477 | + } | ||
| 2420 | // `Colour`: what the file says its picture's numbers | 2478 | // `Colour`: what the file says its picture's numbers |
| 2421 | // mean, in the same H.273 code points the bitstream | 2479 | // mean, in the same H.273 code points the bitstream |
| 2422 | // uses. An element the file leaves out stays 0, which | 2480 | // uses. An element the file leaves out stays 0, which |
| @@ -2541,6 +2599,7 @@ fn mkv_track_entry( | |||
| 2541 | number, | 2599 | number, |
| 2542 | width, | 2600 | width, |
| 2543 | height, | 2601 | height, |
| 2602 | + rotation, | ||
| 2544 | tags, | 2603 | tags, |
| 2545 | light, | 2604 | light, |
| 2546 | default_duration, | 2605 | default_duration, |
| @@ -2684,6 +2743,74 @@ fn rotation_of_matrix(a: i32, b: i32, c: i32, d: i32) -> crate::Result<Rotation> | |||
| 2684 | }) | 2743 | }) |
| 2685 | } | 2744 | } |
| 2686 | 2745 | ||
| 2746 | +/// The quarter turn a Matroska `ProjectionPoseRoll` asks for -- the mkv door's | ||
| 2747 | +/// half of [`rotation_of_matrix`], with the same half-degree tolerance and the | ||
| 2748 | +/// same refusal by name. | ||
| 2749 | +/// | ||
| 2750 | +/// **Measured against ffmpeg's own autorotate**, the same arbiter | ||
| 2751 | +/// [`rotation_of_matrix`] was measured against: `test_rotation{90,180,270}.mkv` | ||
| 2752 | +/// (`scripts/gen_fixtures.sh`) are the very quadrant source their `.mp4` twins | ||
| 2753 | +/// are, remuxed with `-display_rotation` asked for, and ffmpeg 8.1.2's matroska | ||
| 2754 | +/// muxer writes this element for it -- `+90.0`, `+180.0` and **`-90.0`**, an | ||
| 2755 | +/// 8-byte big-endian float, with no `ProjectionType` element at all (RFC 9559's | ||
| 2756 | +/// default of 0, rectangular). Its demuxer reads each of those back as the very | ||
| 2757 | +/// same `tkhd` matrix the mp4 twin carries, so both files autorotate to the same | ||
| 2758 | +/// four quadrants -- which is what `tests/rotation.rs` asserts, corner by corner. | ||
| 2759 | +/// | ||
| 2760 | +/// Hence the negation below: the element counts **counter-clockwise** degrees | ||
| 2761 | +/// about the viewing axis (RFC 9559 says so, and the measured layouts confirm | ||
| 2762 | +/// it), while the matrix this engine counts its quarter turns off is the | ||
| 2763 | +/// clockwise one `-display_rotation 90` writes -- so a roll of +90 is | ||
| 2764 | +/// [`Rotation::Cw270`] here, exactly as `a=0, b=-65536, c=65536, d=0` is. | ||
| 2765 | +fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> { | ||
| 2766 | + let steps = -(degrees / 90.0).round(); | ||
| 2767 | + if !degrees.is_finite() || (degrees + steps * 90.0).abs() > 0.5 { | ||
| 2768 | + return Err(UnsupportedRotation { | ||
| 2769 | + degrees: degrees.is_finite().then_some(degrees), | ||
| 2770 | + } | ||
| 2771 | + .into()); | ||
| 2772 | + } | ||
| 2773 | + Ok(match steps.rem_euclid(4.0) as u8 { | ||
| 2774 | + 0 => Rotation::None, | ||
| 2775 | + 1 => Rotation::Cw90, | ||
| 2776 | + 2 => Rotation::Cw180, | ||
| 2777 | + _ => Rotation::Cw270, | ||
| 2778 | + }) | ||
| 2779 | +} | ||
| 2780 | + | ||
| 2781 | +/// The turn a track's `Projection` asks for, or [`Rotation::None`] where it does | ||
| 2782 | +/// not ask for a turn of the picture at all. | ||
| 2783 | +/// | ||
| 2784 | +/// Only a **rectangular** projection has a pose that turns the *picture*, and | ||
| 2785 | +/// rectangular (0) is what an absent `ProjectionType` means. On an | ||
| 2786 | +/// equirectangular or cubemap one those same three elements state how the sphere | ||
| 2787 | +/// is oriented, which is not a turn of anything 2D: the pose is left alone, as a | ||
| 2788 | +/// flat player shows a 360° file, rather than refused -- refusing would cost a | ||
| 2789 | +/// file that plays right now and would not show it any righter. | ||
| 2790 | +/// | ||
| 2791 | +/// A rectangular projection whose **yaw or pitch** is off zero is refused by | ||
| 2792 | +/// name, though, and that is mkvmerge's spelling to watch for: since v95 it | ||
| 2793 | +/// translates an mp4 display matrix into roll *and* yaw, using yaw for a mirror. | ||
| 2794 | +/// A picture mirrored, or turned out of its own plane, is the one thing no | ||
| 2795 | +/// quarter turn here can make -- the same missing capability the mp4 door | ||
| 2796 | +/// refuses a 45-degree matrix for, so it gets the same refusal rather than a | ||
| 2797 | +/// sideways picture. | ||
| 2798 | +fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> { | ||
| 2799 | + if kind != 0 { | ||
| 2800 | + return Ok(Rotation::None); | ||
| 2801 | + } | ||
| 2802 | + let off_plane = [yaw, pitch] | ||
| 2803 | + .into_iter() | ||
| 2804 | + .any(|degrees| !degrees.is_finite() || degrees.abs() > 0.5); | ||
| 2805 | + match off_plane { | ||
| 2806 | + // No angle to name: a pose out of the picture's own plane -- a mirror | ||
| 2807 | + // through it, or a tilt of it -- is not a rotation in that plane whatever | ||
| 2808 | + // number it states, which is what the sentence without one says. | ||
| 2809 | + true => Err(UnsupportedRotation { degrees: None }.into()), | ||
| 2810 | + false => rotation_of_roll(roll), | ||
| 2811 | + } | ||
| 2812 | +} | ||
| 2813 | + | ||
| 2687 | /// Why an mp4 came back with no picture, by the fourcc of the video track it | 2814 | /// 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 | 2815 | /// 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. | 2816 | /// owner there is none sends them looking for a fault that is not in the file. |
| @@ -3105,7 +3232,7 @@ fn mkv_cluster( | |||
| 3105 | if block.number != number { | 3232 | if block.number != number { |
| 3106 | continue; | 3233 | continue; |
| 3107 | } | 3234 | } |
| 3108 | - let ts = cluster_ts + i64::from(block.rel); | 3235 | + let ts = block_ticks(cluster_ts, block.rel)?; |
| 3109 | if block.flags & 0x06 == 0 { | 3236 | if block.flags & 0x06 == 0 { |
| 3110 | blocks.push(Block { | 3237 | blocks.push(Block { |
| 3111 | at: block.at, | 3238 | at: block.at, |
| @@ -4312,7 +4439,10 @@ fn mkv_subtitle_blocks( | |||
| 4312 | const BLOCK_DURATION: u32 = 0x9B; | 4439 | const BLOCK_DURATION: u32 = 0x9B; |
| 4313 | // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is | 4440 | // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is |
| 4314 | // nanoseconds per tick and is a millisecond in every file anything writes. | 4441 | // nanoseconds per tick and is a millisecond in every file anything writes. |
| 4315 | - let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; | 4442 | + // [`ticks_scaled`] does the arithmetic: it is widened and fallible, and a |
| 4443 | + // corrupt cluster timestamp is refused rather than wrapped into a negative | ||
| 4444 | + // cue time -- see the test beside it. | ||
| 4445 | + let us = |ticks: i64| ticks_scaled(ticks, timestamp_scale, 1_000); | ||
| 4316 | let mut at = segment.0; | 4446 | let mut at = segment.0; |
| 4317 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | 4447 | 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. | 4448 | // The import's second walk, stopped by the same Cancel as its first. |
| @@ -4376,8 +4506,13 @@ fn mkv_subtitle_blocks( | |||
| 4376 | read_exact_at(file, at, &mut payload)?; | 4506 | read_exact_at(file, at, &mut payload)?; |
| 4377 | track.unpack.frame(&mut payload)?; | 4507 | track.unpack.frame(&mut payload)?; |
| 4378 | track.cues.push(MkvCue { | 4508 | track.cues.push(MkvCue { |
| 4379 | - start_us: us(cluster_ts + i64::from(block.rel)), | 4509 | + // The cluster's timestamp plus the block's own signed |
| 4380 | - duration_us: duration.map(us), | 4510 | + // offset, checked by [`block_ticks`]: the pair is where a |
| 4511 | + // corrupt file's two numbers can still overflow what an | ||
| 4512 | + // `i64` holds, one step before the scale above would refuse | ||
| 4513 | + // the result. | ||
| 4514 | + start_us: us(block_ticks(cluster_ts, block.rel)?)?, | ||
| 4515 | + duration_us: duration.map(us).transpose()?, | ||
| 4381 | payload, | 4516 | payload, |
| 4382 | }); | 4517 | }); |
| 4383 | } | 4518 | } |
| @@ -4386,6 +4521,39 @@ fn mkv_subtitle_blocks( | |||
| 4386 | Ok(()) | 4521 | Ok(()) |
| 4387 | } | 4522 | } |
| 4388 | 4523 | ||
| 4524 | +/// A block's absolute timestamp in ticks: the cluster's own, plus the block's | ||
| 4525 | +/// signed offset from it -- refused where the sum leaves what an `i64` holds. | ||
| 4526 | +/// | ||
| 4527 | +/// Both walks need it: the video block index a copy reads and the subtitle cues. | ||
| 4528 | +/// Both get `cluster_ts` from an EBML uint the file writes with no bound this | ||
| 4529 | +/// reader applies, so a crafted cluster near `i64::MAX` overflows the add one | ||
| 4530 | +/// step *before* [`ticks_scaled`] could refuse the product -- and the block would | ||
| 4531 | +/// be taken at a time that wrapped negative. | ||
| 4532 | +fn block_ticks(cluster_ts: i64, rel: i16) -> crate::Result<i64> { | ||
| 4533 | + cluster_ts | ||
| 4534 | + .checked_add(i64::from(rel)) | ||
| 4535 | + .ok_or_else(|| "a Matroska block at no timestamp a clock can hold".into()) | ||
| 4536 | +} | ||
| 4537 | + | ||
| 4538 | +/// A tick count scaled out of the file's own clock, or the refusal a corrupt one | ||
| 4539 | +/// earns: `ticks * TimestampScale / per_tick`, which is microseconds for the | ||
| 4540 | +/// subtitle walk (`per_tick` 1_000) and nanoseconds for the block walk a copy | ||
| 4541 | +/// reads (`per_tick` 1). | ||
| 4542 | +/// | ||
| 4543 | +/// The multiply is widened to `i128` rather than done in `i64`, and a result that | ||
| 4544 | +/// does not fit is refused rather than saturated: both numbers are the file's -- | ||
| 4545 | +/// a cluster or block timestamp is an EBML uint nothing bounds, and | ||
| 4546 | +/// `TimestampScale` is a scale it chooses -- so `ticks * timestamp_scale` | ||
| 4547 | +/// overflows on a crafted file, which is a panic in debug and a *negative* | ||
| 4548 | +/// timestamp in release, silently. Widened no product can overflow; a timestamp | ||
| 4549 | +/// that then does not fit its unit is the same class of corrupt as the oversized | ||
| 4550 | +/// block refused above, and gets the same loud refusal rather than a time no | ||
| 4551 | +/// clock can hold. | ||
| 4552 | +fn ticks_scaled(ticks: i64, timestamp_scale: u64, per_tick: u64) -> crate::Result<i64> { | ||
| 4553 | + i64::try_from(i128::from(ticks) * i128::from(timestamp_scale) / i128::from(per_tick)) | ||
| 4554 | + .map_err(|_| "a Matroska timestamp no clock can hold".into()) | ||
| 4555 | +} | ||
| 4556 | + | ||
| 4389 | /// A string element, without the trailing NULs a `Name` may be padded with. | 4557 | /// 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> { | 4558 | fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { |
| 4391 | let bytes = ebml_bytes(file, body, stop)?; | 4559 | let bytes = ebml_bytes(file, body, stop)?; |
| @@ -4398,6 +4566,41 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> { | |||
| 4398 | mod tests { | 4566 | mod tests { |
| 4399 | use super::*; | 4567 | use super::*; |
| 4400 | 4568 | ||
| 4569 | + /// Both walks that scale a file's own clock: the subtitle one | ||
| 4570 | + /// (microseconds, `per_tick` 1_000) and the block one a copy reads | ||
| 4571 | + /// (nanoseconds, `per_tick` 1). The product is where an `i64` overflows, so | ||
| 4572 | + /// these are the assertions that fail -- a panic in debug, a negative | ||
| 4573 | + /// timestamp in release -- without the widening. | ||
| 4574 | + #[test] | ||
| 4575 | + fn a_timestamp_no_clock_can_hold_is_refused() { | ||
| 4576 | + // A millisecond scale, which is every file anything writes: 1000 ticks | ||
| 4577 | + // is one second, in either unit. | ||
| 4578 | + assert_eq!(ticks_scaled(1_000, 1_000_000, 1_000).unwrap(), 1_000_000); | ||
| 4579 | + assert_eq!(ticks_scaled(0, 1_000_000, 1_000).unwrap(), 0); | ||
| 4580 | + assert_eq!(ticks_scaled(1_000, 1_000_000, 1).unwrap(), 1_000_000_000); | ||
| 4581 | + // A nanosecond scale and the largest tick count an EBML uint can cast | ||
| 4582 | + // to: tens of thousands of years of nanoseconds, which no `i64` holds. | ||
| 4583 | + assert!( | ||
| 4584 | + ticks_scaled(i64::MAX, 1_000_000_000, 1).is_err(), | ||
| 4585 | + "the block walk's product must not wrap into a negative time" | ||
| 4586 | + ); | ||
| 4587 | + assert!( | ||
| 4588 | + ticks_scaled(i64::MAX, 1_000_000_000, 1_000).is_err(), | ||
| 4589 | + "the subtitle walk's product must not wrap into a negative cue time" | ||
| 4590 | + ); | ||
| 4591 | + assert!(ticks_scaled(i64::MIN, 1_000_000_000, 1_000).is_err()); | ||
| 4592 | + // ...and the add that comes before either scale: a cluster timestamp near | ||
| 4593 | + // the top of what an `i64` holds plus a block's own offset still has to | ||
| 4594 | + // fit before any product is computed at all. | ||
| 4595 | + assert_eq!(block_ticks(1_000, -5).unwrap(), 995); | ||
| 4596 | + assert_eq!(block_ticks(0, 32_767).unwrap(), 32_767); | ||
| 4597 | + assert!( | ||
| 4598 | + block_ticks(i64::MAX, 1).is_err(), | ||
| 4599 | + "the add must not wrap negative" | ||
| 4600 | + ); | ||
| 4601 | + assert!(block_ticks(i64::MIN, -1).is_err()); | ||
| 4602 | + } | ||
| 4603 | + | ||
| 4401 | fn asset(name: &str) -> std::path::PathBuf { | 4604 | fn asset(name: &str) -> std::path::PathBuf { |
| 4402 | std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) | 4605 | std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 4403 | .join("../../assets") | 4606 | .join("../../assets") |
crates/engine/tests/rotation.rsmodified+128 -56
| @@ -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)); |
| @@ -195,58 +219,106 @@ fn the_preview_shows_a_turned_file_upright() { | |||
| 195 | #[test] | 219 | #[test] |
| 196 | fn an_export_of_a_turned_file_is_upright_and_portrait() { | 220 | fn an_export_of_a_turned_file_is_upright_and_portrait() { |
| 197 | let _seat = pin_software(); | 221 | let _seat = pin_software(); |
| 198 | - let source = asset("test_rotation90.mp4"); | 222 | + // Both doors, because the turn reaches the export through exactly one number |
| 199 | - let mut session = PlaybackSession::open(&source).expect("open the fixture"); | 223 | + // -- the source's `Rotation` in the export's rate table -- and an mkv states |
| 200 | - session.pause(); | 224 | + // it with a `Projection` roll where an mp4 states a `tkhd` matrix: a door |
| 201 | - assert_eq!( | 225 | + // that read its own spelling into that number differently would bake a |
| 202 | - [session.meta().width, session.meta().height], | 226 | + // different turn into the pixels, and nothing but this test would show it. |
| 203 | - [180, 320], | 227 | + for file in ["test_rotation90.mp4", "test_rotation90.mkv"] { |
| 204 | - "the timeline is the displayed shape, not the coded one" | 228 | + let source = asset(file); |
| 205 | - ); | 229 | + let mut session = PlaybackSession::open(&source).expect("open the fixture"); |
| 206 | - let out = out_path("upright"); | 230 | + session.pause(); |
| 207 | - let handle = session.export_to_with(&out, &ExportSettings::default()); | 231 | + assert_eq!( |
| 208 | - wait(&handle, Duration::from_secs(60)).expect("export"); | 232 | + [session.meta().width, session.meta().height], |
| 209 | - | 233 | + [180, 320], |
| 210 | - let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); | 234 | + "{file}: the timeline is the displayed shape, not the coded one" |
| 211 | - assert_eq!( | 235 | + ); |
| 212 | - [meta.width, meta.height], | 236 | + let out = out_path(&file.replace('.', "_")); |
| 213 | - [180, 320], | 237 | + let handle = session.export_to_with(&out, &ExportSettings::default()); |
| 214 | - "the written file is portrait" | 238 | + wait(&handle, Duration::from_secs(60)).expect("export"); |
| 215 | - ); | 239 | + |
| 216 | - assert_eq!( | 240 | + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); |
| 217 | - meta.rotation, | 241 | + assert_eq!( |
| 218 | - Rotation::None, | 242 | + [meta.width, meta.height], |
| 219 | - "and states no matrix: the turn is in the pixels" | 243 | + [180, 320], |
| 220 | - ); | 244 | + "{file}: the written file is portrait" |
| 221 | - assert_eq!(meta.frame_count, 30, "every timeline frame was written"); | 245 | + ); |
| 222 | - | 246 | + assert_eq!( |
| 223 | - let (width, height, bgra) = first_frame(&out); | 247 | + meta.rotation, |
| 224 | - assert_eq!([width, height], [180, 320]); | 248 | + Rotation::None, |
| 225 | - assert_eq!( | 249 | + "{file}: and states no matrix: the turn is in the pixels" |
| 226 | - corners(width, height, &bgra), | 250 | + ); |
| 227 | - ["green", "yellow", "blue", "red"], | 251 | + assert_eq!( |
| 228 | - "the exported pixels are the ones the preview showed" | 252 | + meta.frame_count, 30, |
| 229 | - ); | 253 | + "{file}: every timeline frame was written" |
| 254 | + ); | ||
| 255 | + | ||
| 256 | + let (width, height, bgra) = first_frame(&out); | ||
| 257 | + assert_eq!([width, height], [180, 320]); | ||
| 258 | + assert_eq!( | ||
| 259 | + corners(width, height, &bgra), | ||
| 260 | + ["green", "yellow", "blue", "red"], | ||
| 261 | + "{file}: the exported pixels are the ones the preview showed" | ||
| 262 | + ); | ||
| 263 | + } | ||
| 230 | } | 264 | } |
| 231 | 265 | ||
| 232 | -/// A matrix that is not a quarter turn is refused by name at the door, with the | 266 | +/// A turn that is not a quarter turn is refused by name at the door, with the |
| 233 | -/// angle in the sentence -- the honest answer to a picture this engine has no | 267 | +/// angle in the sentence -- the honest answer to a picture this engine has no way |
| 234 | -/// way to show right. The capability really is absent: nothing here turns by an | 268 | +/// to show right. The capability really is absent: nothing here turns by an |
| 235 | -/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters), | 269 | +/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters), and |
| 236 | -/// and the refusal is what says so instead of a sideways picture. | 270 | +/// the refusal is what says so instead of a sideways picture. |
| 271 | +/// | ||
| 272 | +/// **Both doors**, because they are two spellings of one question: an mp4 states | ||
| 273 | +/// the turn in a `tkhd` matrix and an mkv in a `Projection` roll, and a file | ||
| 274 | +/// whose picture is 45 degrees off is the same missing capability either way -- | ||
| 275 | +/// the mkv twin exists for exactly this assertion. | ||
| 237 | #[test] | 276 | #[test] |
| 238 | -fn a_matrix_that_is_not_a_quarter_turn_is_refused_by_name() { | 277 | +fn a_turn_that_is_not_a_quarter_turn_is_refused_by_name() { |
| 239 | - let error = match engine::demux::Demuxer::open(&asset("test_rotation45.mp4")) { | 278 | + for file in ["test_rotation45.mp4", "test_rotation45.mkv"] { |
| 240 | - Ok(_) => panic!("45 degrees is not a quarter turn, and opening it must not succeed"), | 279 | + let error = match engine::demux::Demuxer::open(&asset(file)) { |
| 241 | - Err(error) => error, | 280 | + Ok(_) => { |
| 242 | - }; | 281 | + panic!("45 degrees is not a quarter turn, and opening {file} must not succeed") |
| 243 | - assert!( | 282 | + } |
| 244 | - engine::UnsupportedRotation::is_it(&error), | 283 | + Err(error) => error, |
| 245 | - "the refusal is the named one, not a generic failure: {error}" | 284 | + }; |
| 246 | - ); | 285 | + assert!( |
| 247 | - let said = error.to_string(); | 286 | + engine::UnsupportedRotation::is_it(&error), |
| 248 | - assert!( | 287 | + "{file}: the refusal is the named one, not a generic failure: {error}" |
| 249 | - said.contains("45.0°") && said.contains("quarter turn"), | 288 | + ); |
| 250 | - "the refusal names the angle it cannot make: {said}" | 289 | + let said = error.to_string(); |
| 251 | - ); | 290 | + assert!( |
| 291 | + said.contains("45.0°") && said.contains("quarter turn"), | ||
| 292 | + "{file}: the refusal names the angle it cannot make: {said}" | ||
| 293 | + ); | ||
| 294 | + } | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +/// A rotated file whose *coded* height and *displayed* height sit on opposite | ||
| 298 | +/// sides of the 720-line rule an untagged stream's matrix is guessed from | ||
| 299 | +/// ([`engine::colorspace::ColorDescription::resolve`]): `test_rotation90tall` is | ||
| 300 | +/// 1280x640 as stored and 640x1280 as shown, and neither container tags it (the | ||
| 301 | +/// mkv's `Colour` element carries only chroma siting, the mp4 has no `colr` | ||
| 302 | +/// box), so that guess is the only thing deciding bt601 against bt709. | ||
| 303 | +/// | ||
| 304 | +/// Both doors must feed the height the picture is *shown* at -- bt709 here -- and | ||
| 305 | +/// this is the assertion that fails if a door reads the coded height instead | ||
| 306 | +/// (`video.height`, 640, is bt601). The two doors agreeing is the whole point of | ||
| 307 | +/// resolving the size the same way in both. | ||
| 308 | +#[test] | ||
| 309 | +fn a_turned_file_guesses_its_matrix_from_the_height_it_is_shown_at() { | ||
| 310 | + for file in ["test_rotation90tall.mp4", "test_rotation90tall.mkv"] { | ||
| 311 | + let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); | ||
| 312 | + assert_eq!( | ||
| 313 | + [meta.width, meta.height], | ||
| 314 | + [640, 1280], | ||
| 315 | + "{file}: the shown shape -- 1280x640 as stored, turned by the file" | ||
| 316 | + ); | ||
| 317 | + assert_eq!( | ||
| 318 | + meta.color.matrix, | ||
| 319 | + engine::colorspace::Matrix::Bt709, | ||
| 320 | + "{file}: the 1280-line *displayed* height is HD material; the 640-line coded one \ | ||
| 321 | + would guess bt601, so this is the coded-height bug showing" | ||
| 322 | + ); | ||
| 323 | + } | ||
| 252 | } | 324 | } |
scripts/gen_fixtures.shmodified+38 -0
| @@ -730,6 +730,44 @@ 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 | +# The one fixture where the coded and the displayed height disagree about what the | ||
| 754 | +# material is: `test_rotation90tall` is 1280x640 as stored and 640x1280 as shown, | ||
| 755 | +# and neither container tags its colour (the mkv's `Colour` element carries only | ||
| 756 | +# chroma siting, the mp4 has no `colr` box), so the 720-line rule an untagged | ||
| 757 | +# stream's matrix is guessed from reads a different side of itself depending on | ||
| 758 | +# which height a door feeds it. | ||
| 759 | +ffmpeg -y -f lavfi -i "color=c=red:s=640x320:d=1:r=30,format=yuv420p" \ | ||
| 760 | + -f lavfi -i "color=c=green:s=640x320:d=1:r=30,format=yuv420p" \ | ||
| 761 | + -f lavfi -i "color=c=blue:s=640x320:d=1:r=30,format=yuv420p" \ | ||
| 762 | + -f lavfi -i "color=c=yellow:s=640x320:d=1:r=30,format=yuv420p" \ | ||
| 763 | + -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \ | ||
| 764 | + -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 765 | + assets/.rotation_tall_src.mp4 | ||
| 766 | +for ext in mp4 mkv; do | ||
| 767 | + ffmpeg -y -display_rotation 90 -i assets/.rotation_tall_src.mp4 \ | ||
| 768 | + -c copy "assets/test_rotation90tall.$ext" | ||
| 769 | +done | ||
| 770 | +rm -f assets/.rotation_tall_src.mp4 | ||
| 771 | + | ||
| 772 | + | ||
| 735 | echo "fixtures written to assets/" | 773 | echo "fixtures written to assets/" |