forge
Explore
Log in

Don't you dare go Hollow

Merge the demux lane into main

Browse files at this commit

de38f6e9f38b102b4a2a6e0d7c17235d6be18314Ahmet Kaan GümüşParent: ac734bc7a52aa1
  • fix
    • merge the demux lane into main
Show full message
🐛 fix(media): merge the demux lane into main

The turn and the shown size a file states, the block walk's unchecked
add and the unchecked subtitle-table copy are fixed here. Lane:
lane-bughunt-demux.
crates/engine/src/demux.rsmodified+223 -20
@@ -371,13 +371,17 @@ pub struct VideoMeta {
371371 /// which range -- resolved off the container's tags, the bitstream's, and
372372 /// the resolution, in that order. See [`crate::colorspace`].
373373 pub color: ColorDescription,
374- /// How far the picture must be turned to be seen right, off the
375- /// container's display matrix. [`Rotation::None`] for everything whose
376- /// container states no turn, and for a Matroska file: only the mp4 half is
377- /// read today, because Matroska's own spelling (a `ProjectionPoseYaw`
378- /// element) is written by nobody in practice while the `tkhd` matrix is how
379- /// every phone records it. That is a known gap and not a silent one:
380- /// [`MkvDemuxer::open`] says where a reader for it would go.
374+ /// How far the picture must be turned to be seen right, off the container's
375+ /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on
376+ /// a rectangular projection -- the same quarter turns read off either.
377+ /// [`Rotation::None`] for everything whose container states no turn, and for
378+ /// a projection that is not rectangular: on a spherical or cubemap one those
379+ /// same pose elements describe how the *sphere* is oriented, which is no turn
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.
381385 pub rotation: Rotation,
382386 }
383387
@@ -1309,25 +1313,37 @@ impl MkvDemuxer {
13091313 }
13101314 }
13111315 };
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+ };
13121324 let meta = VideoMeta {
1313- width: video.width,
1314- height: video.height,
1325+ width,
1326+ height,
13151327 frame_rate,
13161328 frame_count: mkv.frames as u32,
13171329 codec: video.codec,
13181330 // `config` is the parameter sets by now -- Annex-B for H.264 and
13191331 // HEVC, the sequence header OBU for AV1 -- which is what the
13201332 // 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.
13211338 color: ColorDescription::resolve(
13221339 video.tags,
13231340 bitstream_tags(video.codec, &mkv.config),
1324- video.height,
1341+ height,
13251342 ),
1326- // FLAG: Matroska's turn is not read yet -- see [`VideoMeta::rotation`].
1327- // Nothing in this tree writes a `ProjectionPoseYaw`, and the mkv
1328- // tracks a phone or a camera app produces are mp4s; a `.mkv` that
1329- // does carry one would play sideways until this is written.
1330- rotation: Rotation::None,
1343+ // The turn off the track's `Projection` element ([`projection_rotation`]),
1344+ // which is where a Matroska muxer states what an mp4 states with its
1345+ // `tkhd` matrix.
1346+ rotation: video.rotation,
13311347 };
13321348 Ok((meta, mkv))
13331349 }
@@ -1784,7 +1800,11 @@ impl MkvDemuxer {
17841800 Ok(Some(CodedBlock {
17851801 bytes: &self.scratch,
17861802 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)?,
17881808 }))
17891809 }
17901810 }
@@ -1994,6 +2014,9 @@ struct MkvVideo {
19942014 number: u64,
19952015 width: u32,
19962016 height: u32,
2017+ /// The quarter turn the track's `Projection` asks for;
2018+ /// [`Rotation::None`] where it states none.
2019+ rotation: Rotation,
19972020 /// What the track's `Colour` element declared, empty when it has none.
19982021 tags: Tags,
19992022 /// What that same element said about brightness (MaxCLL and the mastering
@@ -2141,6 +2164,20 @@ const DEFAULT_DURATION: u32 = 0x23E383;
21412164 const VIDEO: u32 = 0xE0;
21422165 const PIXEL_WIDTH: u32 = 0xB0;
21432166 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;
21442181 // The `Colour` element and the three of its children this reads. Byte-verified
21452182 // against real files rather than taken off a spec table: published tables that
21462183 // list Range as 0x55B3 are describing ChromaSubsamplingHorz.
@@ -2391,6 +2428,7 @@ fn mkv_track_entry(
23912428 ) -> crate::Result<MkvEntry> {
23922429 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
23932430 let (mut width, mut height, mut config) = (0, 0, Vec::new());
2431+ let mut rotation = Rotation::None;
23942432 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
23952433 let mut tags = Tags::default();
23962434 let mut light = ContentLight::default();
@@ -2417,6 +2455,26 @@ fn mkv_track_entry(
24172455 match e.0 {
24182456 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
24192457 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+ }
24202478 // `Colour`: what the file says its picture's numbers
24212479 // mean, in the same H.273 code points the bitstream
24222480 // uses. An element the file leaves out stays 0, which
@@ -2541,6 +2599,7 @@ fn mkv_track_entry(
25412599 number,
25422600 width,
25432601 height,
2602+ rotation,
25442603 tags,
25452604 light,
25462605 default_duration,
@@ -2684,6 +2743,74 @@ fn rotation_of_matrix(a: i32, b: i32, c: i32, d: i32) -> crate::Result<Rotation>
26842743 })
26852744 }
26862745
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+
26872814 /// Why an mp4 came back with no picture, by the fourcc of the video track it
26882815 /// does carry: `avc3` and `mp4v` are files with video in them, and telling their
26892816 /// owner there is none sends them looking for a fault that is not in the file.
@@ -3105,7 +3232,7 @@ fn mkv_cluster(
31053232 if block.number != number {
31063233 continue;
31073234 }
3108- let ts = cluster_ts + i64::from(block.rel);
3235+ let ts = block_ticks(cluster_ts, block.rel)?;
31093236 if block.flags & 0x06 == 0 {
31103237 blocks.push(Block {
31113238 at: block.at,
@@ -4312,7 +4439,10 @@ fn mkv_subtitle_blocks(
43124439 const BLOCK_DURATION: u32 = 0x9B;
43134440 // Ticks to microseconds, the unit `MkvCue` keeps. `TimestampScale` is
43144441 // 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);
43164446 let mut at = segment.0;
43174447 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
43184448 // The import's second walk, stopped by the same Cancel as its first.
@@ -4376,8 +4506,13 @@ fn mkv_subtitle_blocks(
43764506 read_exact_at(file, at, &mut payload)?;
43774507 track.unpack.frame(&mut payload)?;
43784508 track.cues.push(MkvCue {
4379- start_us: us(cluster_ts + i64::from(block.rel)),
4380- duration_us: duration.map(us),
4509+ // The cluster's timestamp plus the block's own signed
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()?,
43814516 payload,
43824517 });
43834518 }
@@ -4386,6 +4521,39 @@ fn mkv_subtitle_blocks(
43864521 Ok(())
43874522 }
43884523
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+
43894557 /// A string element, without the trailing NULs a `Name` may be padded with.
43904558 fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
43914559 let bytes = ebml_bytes(file, body, stop)?;
@@ -4398,6 +4566,41 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
43984566 mod tests {
43994567 use super::*;
44004568
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+
44014604 fn asset(name: &str) -> std::path::PathBuf {
44024605 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
44034606 .join("../../assets")
crates/engine/tests/rotation.rsmodified+128 -56
@@ -92,7 +92,12 @@ fn corners(width: u32, height: u32, bgra: &[u8]) -> [&'static str; 4] {
9292 tint(&bgra[index..index + 4])
9393 };
9494 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+ ]
96101 }
97102
98103 /// 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>) {
112117 /// machine, which is the arbiter a display matrix is read against.
113118 fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) {
114119 match file {
115- "test_rotation90.mp4" => (
120+ "test_rotation90.mp4" | "test_rotation90.mkv" => (
116121 [180, 320],
117122 Rotation::Cw270,
118123 ["green", "yellow", "blue", "red"],
119124 ),
120- "test_rotation180.mp4" => (
125+ "test_rotation180.mp4" | "test_rotation180.mkv" => (
121126 [320, 180],
122127 Rotation::Cw180,
123128 ["yellow", "blue", "red", "green"],
124129 ),
125- "test_rotation270.mp4" => (
130+ "test_rotation270.mp4" | "test_rotation270.mkv" => (
126131 [180, 320],
127132 Rotation::Cw90,
128133 ["blue", "red", "green", "yellow"],
@@ -135,10 +140,18 @@ fn expected(file: &str) -> ([u32; 2], Rotation, [&'static str; 4]) {
135140 /// displayed size and names the turn, and a half turn does neither.
136141 #[test]
137142 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.
138148 for file in [
139149 "test_rotation90.mp4",
150+ "test_rotation90.mkv",
140151 "test_rotation180.mp4",
152+ "test_rotation180.mkv",
141153 "test_rotation270.mp4",
154+ "test_rotation270.mkv",
142155 ] {
143156 let (size, rotation, _) = expected(file);
144157 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() {
147160 size,
148161 "{file}: the *displayed* size is what the engine reports"
149162 );
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+ );
151167 assert_eq!(
152168 rotation.swaps_axes(),
153169 size == [180, 320],
@@ -168,10 +184,18 @@ fn a_display_matrix_is_read_as_a_quarter_turn() {
168184 #[test]
169185 fn the_preview_shows_a_turned_file_upright() {
170186 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.
171192 for file in [
172193 "test_rotation90.mp4",
194+ "test_rotation90.mkv",
173195 "test_rotation180.mp4",
196+ "test_rotation180.mkv",
174197 "test_rotation270.mp4",
198+ "test_rotation270.mkv",
175199 ] {
176200 let (size, _, corners_expected) = expected(file);
177201 let (width, height, bgra) = first_frame(&asset(file));
@@ -195,58 +219,106 @@ fn the_preview_shows_a_turned_file_upright() {
195219 #[test]
196220 fn an_export_of_a_turned_file_is_upright_and_portrait() {
197221 let _seat = pin_software();
198- let source = asset("test_rotation90.mp4");
199- let mut session = PlaybackSession::open(&source).expect("open the fixture");
200- session.pause();
201- assert_eq!(
202- [session.meta().width, session.meta().height],
203- [180, 320],
204- "the timeline is the displayed shape, not the coded one"
205- );
206- let out = out_path("upright");
207- let handle = session.export_to_with(&out, &ExportSettings::default());
208- wait(&handle, Duration::from_secs(60)).expect("export");
209-
210- let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
211- assert_eq!(
212- [meta.width, meta.height],
213- [180, 320],
214- "the written file is portrait"
215- );
216- assert_eq!(
217- meta.rotation,
218- Rotation::None,
219- "and states no matrix: the turn is in the pixels"
220- );
221- assert_eq!(meta.frame_count, 30, "every timeline frame was written");
222-
223- let (width, height, bgra) = first_frame(&out);
224- assert_eq!([width, height], [180, 320]);
225- assert_eq!(
226- corners(width, height, &bgra),
227- ["green", "yellow", "blue", "red"],
228- "the exported pixels are the ones the preview showed"
229- );
222+ // Both doors, because the turn reaches the export through exactly one number
223+ // -- the source's `Rotation` in the export's rate table -- and an mkv states
224+ // it with a `Projection` roll where an mp4 states a `tkhd` matrix: a door
225+ // that read its own spelling into that number differently would bake a
226+ // different turn into the pixels, and nothing but this test would show it.
227+ for file in ["test_rotation90.mp4", "test_rotation90.mkv"] {
228+ let source = asset(file);
229+ let mut session = PlaybackSession::open(&source).expect("open the fixture");
230+ session.pause();
231+ assert_eq!(
232+ [session.meta().width, session.meta().height],
233+ [180, 320],
234+ "{file}: the timeline is the displayed shape, not the coded one"
235+ );
236+ let out = out_path(&file.replace('.', "_"));
237+ let handle = session.export_to_with(&out, &ExportSettings::default());
238+ wait(&handle, Duration::from_secs(60)).expect("export");
239+
240+ let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
241+ assert_eq!(
242+ [meta.width, meta.height],
243+ [180, 320],
244+ "{file}: the written file is portrait"
245+ );
246+ assert_eq!(
247+ meta.rotation,
248+ Rotation::None,
249+ "{file}: and states no matrix: the turn is in the pixels"
250+ );
251+ assert_eq!(
252+ meta.frame_count, 30,
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+ }
230264 }
231265
232-/// A matrix 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
234-/// way to show right. The capability really is absent: nothing here turns by an
235-/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters),
236-/// and the refusal is what says so instead of a sideways picture.
266+/// A turn that is not a quarter turn is refused by name at the door, with the
267+/// angle in the sentence -- the honest answer to a picture this engine has no way
268+/// to show right. The capability really is absent: nothing here turns by an
269+/// arbitrary angle ([`engine::scale::rotate_i420_90s`] takes whole quarters), and
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.
237276 #[test]
238-fn a_matrix_that_is_not_a_quarter_turn_is_refused_by_name() {
239- let error = match engine::demux::Demuxer::open(&asset("test_rotation45.mp4")) {
240- Ok(_) => panic!("45 degrees is not a quarter turn, and opening it must not succeed"),
241- Err(error) => error,
242- };
243- assert!(
244- engine::UnsupportedRotation::is_it(&error),
245- "the refusal is the named one, not a generic failure: {error}"
246- );
247- let said = error.to_string();
248- assert!(
249- said.contains("45.0°") && said.contains("quarter turn"),
250- "the refusal names the angle it cannot make: {said}"
251- );
277+fn a_turn_that_is_not_a_quarter_turn_is_refused_by_name() {
278+ for file in ["test_rotation45.mp4", "test_rotation45.mkv"] {
279+ let error = match engine::demux::Demuxer::open(&asset(file)) {
280+ Ok(_) => {
281+ panic!("45 degrees is not a quarter turn, and opening {file} must not succeed")
282+ }
283+ Err(error) => error,
284+ };
285+ assert!(
286+ engine::UnsupportedRotation::is_it(&error),
287+ "{file}: the refusal is the named one, not a generic failure: {error}"
288+ );
289+ let said = error.to_string();
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+ }
252324 }
scripts/gen_fixtures.shmodified+38 -0
@@ -730,6 +730,44 @@ for deg in 90 180 270 45; do
730730 ffmpeg -y -display_rotation "$deg" -i assets/.rotation_src.mp4 \
731731 -c copy "assets/test_rotation$deg.mp4"
732732 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
733751 rm -f assets/.rotation_src.mp4
734752
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+
735773 echo "fixtures written to assets/"