diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index e1d64a0..17c5b78 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -374,10 +374,14 @@ pub struct VideoMeta { /// How far the picture must be turned to be seen right, off the container's /// display matrix: an mp4 `tkhd` matrix, or a Matroska `Projection` roll on /// a rectangular projection -- the same quarter turns read off either. - /// [`Rotation::None`] for everything whose container states no turn, and a - /// turn that is not a quarter turn (or a mirror, a shear, a spherical - /// projection) is refused at the door ([`UnsupportedRotation`]) rather than - /// shown wrong. + /// [`Rotation::None`] for everything whose container states no turn, and for + /// a projection that is not rectangular: on a spherical or cubemap one those + /// same pose elements describe how the *sphere* is oriented, which is no turn + /// of the picture, so the pose is deliberately not applied and the file + /// paints as a flat frame -- what every player does with a 360 clip, and + /// cheaper than a refusal that would cost a file that plays. A turn that is + /// not a quarter turn -- a mirror, a shear, an angle in between -- is refused + /// at the door ([`UnsupportedRotation`]) rather than shown wrong. pub rotation: Rotation, } @@ -1326,10 +1330,15 @@ impl MkvDemuxer { // `config` is the parameter sets by now -- Annex-B for H.264 and // HEVC, the sequence header OBU for AV1 -- which is what the // bitstream tier reads. + // The height the picture is *shown* at, which is what the mp4 door + // feeds here and the whole reason both doors resolve their size the + // same way: the 720-line rule below is a guess about the material, and + // the material is the picture as displayed -- a device-held `.mkv` is + // 640 coded but 1280 shown, and the two sides of that rule disagree. color: ColorDescription::resolve( video.tags, bitstream_tags(video.codec, &mkv.config), - video.height, + height, ), // The turn off the track's `Projection` element ([`projection_rotation`]), // which is where a Matroska muxer states what an mp4 states with its @@ -3223,7 +3232,7 @@ fn mkv_cluster( if block.number != number { continue; } - let ts = cluster_ts + i64::from(block.rel); + let ts = block_ticks(cluster_ts, block.rel)?; if block.flags & 0x06 == 0 { blocks.push(Block { at: block.at, @@ -4497,13 +4506,12 @@ fn mkv_subtitle_blocks( read_exact_at(file, at, &mut payload)?; track.unpack.frame(&mut payload)?; track.cues.push(MkvCue { - // The cluster's timestamp plus the block's own signed offset, - // checked: the pair is where a corrupt file's two numbers can - // still overflow what an `i64` holds, one step before the - // scale above would refuse the result. - start_us: us(cluster_ts - .checked_add(i64::from(block.rel)) - .ok_or("a Matroska subtitle block at no timestamp a clock can hold")?)?, + // The cluster's timestamp plus the block's own signed + // offset, checked by [`block_ticks`]: the pair is where a + // corrupt file's two numbers can still overflow what an + // `i64` holds, one step before the scale above would refuse + // the result. + start_us: us(block_ticks(cluster_ts, block.rel)?)?, duration_us: duration.map(us).transpose()?, payload, }); @@ -4513,6 +4521,20 @@ fn mkv_subtitle_blocks( Ok(()) } +/// A block's absolute timestamp in ticks: the cluster's own, plus the block's +/// signed offset from it -- refused where the sum leaves what an `i64` holds. +/// +/// Both walks need it: the video block index a copy reads and the subtitle cues. +/// Both get `cluster_ts` from an EBML uint the file writes with no bound this +/// reader applies, so a crafted cluster near `i64::MAX` overflows the add one +/// step *before* [`ticks_scaled`] could refuse the product -- and the block would +/// be taken at a time that wrapped negative. +fn block_ticks(cluster_ts: i64, rel: i16) -> crate::Result { + cluster_ts + .checked_add(i64::from(rel)) + .ok_or_else(|| "a Matroska block at no timestamp a clock can hold".into()) +} + /// A tick count scaled out of the file's own clock, or the refusal a corrupt one /// earns: `ticks * TimestampScale / per_tick`, which is microseconds for the /// subtitle walk (`per_tick` 1_000) and nanoseconds for the block walk a copy @@ -4567,6 +4589,16 @@ mod tests { "the subtitle walk's product must not wrap into a negative cue time" ); assert!(ticks_scaled(i64::MIN, 1_000_000_000, 1_000).is_err()); + // ...and the add that comes before either scale: a cluster timestamp near + // the top of what an `i64` holds plus a block's own offset still has to + // fit before any product is computed at all. + assert_eq!(block_ticks(1_000, -5).unwrap(), 995); + assert_eq!(block_ticks(0, 32_767).unwrap(), 32_767); + assert!( + block_ticks(i64::MAX, 1).is_err(), + "the add must not wrap negative" + ); + assert!(block_ticks(i64::MIN, -1).is_err()); } fn asset(name: &str) -> std::path::PathBuf { diff --git a/crates/engine/tests/rotation.rs b/crates/engine/tests/rotation.rs index 04793ff..c81fe91 100644 --- a/crates/engine/tests/rotation.rs +++ b/crates/engine/tests/rotation.rs @@ -219,38 +219,48 @@ fn the_preview_shows_a_turned_file_upright() { #[test] fn an_export_of_a_turned_file_is_upright_and_portrait() { let _seat = pin_software(); - let source = asset("test_rotation90.mp4"); - let mut session = PlaybackSession::open(&source).expect("open the fixture"); - session.pause(); - assert_eq!( - [session.meta().width, session.meta().height], - [180, 320], - "the timeline is the displayed shape, not the coded one" - ); - let out = out_path("upright"); - let handle = session.export_to_with(&out, &ExportSettings::default()); - wait(&handle, Duration::from_secs(60)).expect("export"); + // Both doors, because the turn reaches the export through exactly one number + // -- the source's `Rotation` in the export's rate table -- and an mkv states + // it with a `Projection` roll where an mp4 states a `tkhd` matrix: a door + // that read its own spelling into that number differently would bake a + // different turn into the pixels, and nothing but this test would show it. + for file in ["test_rotation90.mp4", "test_rotation90.mkv"] { + let source = asset(file); + let mut session = PlaybackSession::open(&source).expect("open the fixture"); + session.pause(); + assert_eq!( + [session.meta().width, session.meta().height], + [180, 320], + "{file}: the timeline is the displayed shape, not the coded one" + ); + let out = out_path(&file.replace('.', "_")); + let handle = session.export_to_with(&out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(60)).expect("export"); - let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); - assert_eq!( - [meta.width, meta.height], - [180, 320], - "the written file is portrait" - ); - assert_eq!( - meta.rotation, - Rotation::None, - "and states no matrix: the turn is in the pixels" - ); - assert_eq!(meta.frame_count, 30, "every timeline frame was written"); + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + [meta.width, meta.height], + [180, 320], + "{file}: the written file is portrait" + ); + assert_eq!( + meta.rotation, + Rotation::None, + "{file}: and states no matrix: the turn is in the pixels" + ); + assert_eq!( + meta.frame_count, 30, + "{file}: every timeline frame was written" + ); - let (width, height, bgra) = first_frame(&out); - assert_eq!([width, height], [180, 320]); - assert_eq!( - corners(width, height, &bgra), - ["green", "yellow", "blue", "red"], - "the exported pixels are the ones the preview showed" - ); + let (width, height, bgra) = first_frame(&out); + assert_eq!([width, height], [180, 320]); + assert_eq!( + corners(width, height, &bgra), + ["green", "yellow", "blue", "red"], + "{file}: the exported pixels are the ones the preview showed" + ); + } } /// A turn that is not a quarter turn is refused by name at the door, with the @@ -283,3 +293,32 @@ fn a_turn_that_is_not_a_quarter_turn_is_refused_by_name() { ); } } + +/// A rotated file whose *coded* height and *displayed* height sit on opposite +/// sides of the 720-line rule an untagged stream's matrix is guessed from +/// ([`engine::colorspace::ColorDescription::resolve`]): `test_rotation90tall` is +/// 1280x640 as stored and 640x1280 as shown, and neither container tags it (the +/// mkv's `Colour` element carries only chroma siting, the mp4 has no `colr` +/// box), so that guess is the only thing deciding bt601 against bt709. +/// +/// Both doors must feed the height the picture is *shown* at -- bt709 here -- and +/// this is the assertion that fails if a door reads the coded height instead +/// (`video.height`, 640, is bt601). The two doors agreeing is the whole point of +/// resolving the size the same way in both. +#[test] +fn a_turned_file_guesses_its_matrix_from_the_height_it_is_shown_at() { + for file in ["test_rotation90tall.mp4", "test_rotation90tall.mkv"] { + let (meta, _) = engine::demux::Demuxer::open(&asset(file)).expect("open a fixture"); + assert_eq!( + [meta.width, meta.height], + [640, 1280], + "{file}: the shown shape -- 1280x640 as stored, turned by the file" + ); + assert_eq!( + meta.color.matrix, + engine::colorspace::Matrix::Bt709, + "{file}: the 1280-line *displayed* height is HD material; the 640-line coded one \ + would guess bt601, so this is the coded-height bug showing" + ); + } +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index ab08a4d..0df6b04 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -750,5 +750,24 @@ for deg in 90 180 270 45; do done rm -f assets/.rotation_src.mp4 +# The one fixture where the coded and the displayed height disagree about what the +# material is: `test_rotation90tall` is 1280x640 as stored and 640x1280 as shown, +# and neither container tags its colour (the mkv's `Colour` element carries only +# chroma siting, the mp4 has no `colr` box), so the 720-line rule an untagged +# stream's matrix is guessed from reads a different side of itself depending on +# which height a door feeds it. +ffmpeg -y -f lavfi -i "color=c=red:s=640x320:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=green:s=640x320:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=blue:s=640x320:d=1:r=30,format=yuv420p" \ + -f lavfi -i "color=c=yellow:s=640x320:d=1:r=30,format=yuv420p" \ + -filter_complex "[0:v][1:v]hstack[top];[2:v][3:v]hstack[bot];[top][bot]vstack[v]" \ + -map "[v]" -frames:v 30 -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + assets/.rotation_tall_src.mp4 +for ext in mp4 mkv; do + ffmpeg -y -display_rotation 90 -i assets/.rotation_tall_src.mp4 \ + -c copy "assets/test_rotation90tall.$ext" +done +rm -f assets/.rotation_tall_src.mp4 + echo "fixtures written to assets/"