From f4bc699de9442218dd018b79ba8db59b948866cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 24 Sep 2026 20:44:02 +0300 Subject: [PATCH] fix(decode): stretch before the turn, so a rotated anamorphic file fills its canvas A 1440x1080 SAR-4/3 file with a 90-degree display matrix rendered 1440x1440: the render composed turn-then-stretch, landing the ratio on the coded height, and the square raster sat letterboxed inside the 1080x1920 canvas the probe declares -- bars in the preview and baked into the export. The ratio belongs to the axis that was horizontal BEFORE the turn: the coded width is stretched by h/v and the turn then swaps the stretched pair, which is what the probe has declared all along. Render::frame and place_picture now both stretch first, the one order that agrees with the probe. The suite's rotated case had been vacuous -- the in-test fixture was a setsar file with no display matrix, asserting nothing about the turn. It now remuxes a real 90-degree matrix on (-display_rotation 90, the gen_fixtures pattern), asserts the probe's swapped stretched pair (1080x1920, not 1440x1440), and drives the render through the same assertions; the export test grows the rotated clip with preview-vs-export equality. Mutation witness: with the render reverted to turn-then-stretch the new assertions fail with exactly left (1440, 1440) / right (1080, 1920). The demux comment now names the render's order and the failure the other one produces, so the two can't drift again. --- crates/engine/src/decode.rs | 71 +++++++------ crates/engine/src/demux.rs | 23 +++-- crates/engine/src/export.rs | 45 ++++---- crates/engine/tests/anamorphic.rs | 164 ++++++++++++++++++++++++++---- 4 files changed, 220 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index a3107b2..57fe1ab 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -1293,40 +1293,19 @@ impl Render { width: u32, height: u32, ) -> Frame { - // The file's own turn, before anything else: a phone's portrait video - // arrives as landscape planes, and the grade, the canvas and the - // conversion below all have to see the picture the way it is meant to - // be seen. Nothing here at all for the ordinary file that states no - // turn -- `Rotation::None` takes the planes by reference and not one - // byte is copied. - let (y, u, v, width, height) = match self.rotation.is_none() { - true => (y, u, v, width, height), - false => { - let steps = self.rotation.steps(); - let (rw, rh) = crate::scale::rotate_i420_90s_into( - y, - u, - v, - width, - height, - steps, - &mut self.turned, - ); - ( - &self.turned.0[..], - &self.turned.1[..], - &self.turned.2[..], - rw, - rh, - ) - } - }; // The pixel aspect, applied exactly once -- the single conversion to // the square-pixel raster this engine makes, where ffmpeg's swscale - // makes its own. Only a file whose samples are not square reaches the - // resample: a square one takes the branch by a bool and not one byte - // is touched, which is what keeps every existing picture identical to - // the day before anamorphic sources existed. + // makes its own -- *before* the display-matrix turn. The ratio belongs + // to the axis that was horizontal before the turn: the coded width is + // stretched by h/v and the turn then swaps the stretched pair, which + // is the composition the probe declares (a 1440x1080 SAR-4/3 file + // turned 90° displays 1080x1920, DAR 9:16). Stretching after the turn + // instead lands the ratio on the coded height and renders a + // 1440x1440 square into a 9:16 canvas -- letterboxed, and the bars + // baked into any export. Only a file whose samples are not square + // reaches the resample: a square one takes the branch by a bool and + // not one byte is touched, which is what keeps every existing picture + // identical to the day before anamorphic sources existed. let (y, u, v, width, height) = if self.pixel_aspect.is_square() { (y, u, v, width, height) } else { @@ -1365,6 +1344,34 @@ impl Render { height, ) }; + // The file's own turn, after the stretch: a phone's portrait video + // arrives as landscape planes, and the grade, the canvas and the + // conversion below all have to see the picture the way it is meant to + // be seen. Nothing here at all for the ordinary file that states no + // turn -- `Rotation::None` takes the planes by reference and not one + // byte is copied. + let (y, u, v, width, height) = match self.rotation.is_none() { + true => (y, u, v, width, height), + false => { + let steps = self.rotation.steps(); + let (rw, rh) = crate::scale::rotate_i420_90s_into( + y, + u, + v, + width, + height, + steps, + &mut self.turned, + ); + ( + &self.turned.0[..], + &self.turned.1[..], + &self.turned.2[..], + rw, + rh, + ) + } + }; let passthrough = self.canvas.is_passthrough(width, height); // A transform still has a picture to place even where the canvas // itself would hand this size back untouched -- moving, scaling, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 420b97a..8fea412 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1384,16 +1384,19 @@ impl MkvDemuxer { } } }; - // The displayed shape, in the order the two facts compose: the aspect - // widens the *coded* frame (180x320 at SAR 4/3 is drawn 240x320 -- - // ffprobe's own `display_aspect_ratio` of such a file, measured), then - // the quarter turn swaps that stretched pair the way it swaps the - // coded one. The other order is a different picture: 320x180 then - // widened by 4/3 lands at 426x180, and a pixel's drawn shape turns - // with the picture it belongs to. The SAR only ever widens a width, - // never a height; the displayed height is the coded one without a - // turn and the stretched coded width with one. The coded pair stays - // what the decoder hands back, and carries on to + // The displayed shape, in the order the two facts compose -- the same + // order the render applies them in + // ([`crate::decode::Render::frame`]): the aspect widens the *coded* + // frame (180x320 at SAR 4/3 is drawn 240x320 -- ffprobe's own + // `display_aspect_ratio` of such a file, measured), then the quarter + // turn swaps that stretched pair the way it swaps the coded one. The + // other order is a different picture: 320x180 then widened by 4/3 + // lands at 426x180, and a rotated anamorphic file rendered that way + // lands a square raster in the 9:16 canvas its probe declares -- + // letterboxed in the preview and in the export both. The SAR only + // ever widens a width, never a height; the displayed height is the + // coded one without a turn and the stretched coded width with one. + // The coded pair stays what the decoder hands back, and carries on to // [`VideoMeta::coded_width`]/[`VideoMeta::coded_height`]. let (width, height) = match video.rotation.swaps_axes() { true => (video.height, video.pixel_aspect.width_factor(video.width)), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index c005fa9..562dbdf 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -3344,30 +3344,12 @@ fn place_picture<'a>( transformed: &'a mut (Vec, Vec, Vec), canvas: &'a mut Composer, ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { - // The file's own turn, taken exactly as playback's decode funnel takes it - // ([`crate::decode`]): a phone's portrait video is landscape in the file, - // and the encoder must be fed what the preview showed. A file that states - // no turn skips this entirely -- the planes go on borrowed. - let (y, u, v, width, height) = match rotation.is_none() { - true => (y, u, v, width, height), - false => { - let (w, h) = crate::scale::rotate_i420_90s_into( - y, - u, - v, - width, - height, - rotation.steps(), - turned, - ); - (&turned.0[..], &turned.1[..], &turned.2[..], w, h) - } - }; // The pixel aspect, applied exactly once -- the same single conversion to // the square-pixel raster the decode funnel makes, in the same order - // (stretch after turn), so the encoder is fed the pixels the preview - // showed to the byte. A square-pixel file -- every file whose samples are - // one to one -- borrows the planes through. + // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s + // comment carries the 1440x1440 failure the other order produces). A + // square-pixel file -- every file whose samples are one to one -- borrows + // the planes through. let (y, u, v, width, height) = if pixel_aspect.is_square() { (y, u, v, width, height) } else { @@ -3399,6 +3381,25 @@ fn place_picture<'a>( height, ) }; + // The file's own turn, taken exactly as playback's decode funnel takes it + // ([`crate::decode`]): a phone's portrait video is landscape in the file, + // and the encoder must be fed what the preview showed. A file that states + // no turn skips this entirely -- the planes go on borrowed. + let (y, u, v, width, height) = match rotation.is_none() { + true => (y, u, v, width, height), + false => { + let (w, h) = crate::scale::rotate_i420_90s_into( + y, + u, + v, + width, + height, + rotation.steps(), + turned, + ); + (&turned.0[..], &turned.1[..], &turned.2[..], w, h) + } + }; // The planes are borrowed from the decoder (and `Black::picture` hands the // same slice as both u and v), so a grade cannot be applied in place: it // goes onto a copy, which the encoder then reads instead. diff --git a/crates/engine/tests/anamorphic.rs b/crates/engine/tests/anamorphic.rs index 1c0cf08..a83b6f6 100644 --- a/crates/engine/tests/anamorphic.rs +++ b/crates/engine/tests/anamorphic.rs @@ -135,13 +135,15 @@ fn the_container_aspect_is_probed_off_both_doors() { ); } // The rotation still swaps on an anamorphic file whose *matrix* asks for - // a turn: `turn_and_stretch` is the composed order -- the aspect widens - // the coded frame, then the quarter turn swaps the stretched pair -- the - // same composition ffmpeg's own probe reports for such a file. + // a turn: the composition is stretch the coded width, then swap -- the + // order the render applies ([`crate::decode::Render::frame`]). The + // fixture carries a REAL display matrix (a `-display_rotation 90` remux, + // the gen_fixtures pattern), because a `setsar`-only file asserts nothing + // about the turn -- the case this whole block exists for. let turned = asset(".anamorphic_turned.mp4"); - if std::process::Command::new("ffmpeg") + let made = std::process::Command::new("ffmpeg") .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) - .arg("testsrc2=size=180x320:rate=30:duration=1") + .arg("testsrc2=size=1440x1080:rate=30:duration=1") .args([ "-vf", "setsar=4/3", @@ -154,21 +156,73 @@ fn the_container_aspect_is_probed_off_both_doors() { ]) .arg(&turned) .status() - .is_ok_and(|s| s.success()) - { - let (meta, _) = Demuxer::open(&turned).expect("open the turned fixture"); - // 180x320 at SAR 4/3 draws 240x320; a 270-degree matrix turns it. - assert_eq!( - (meta.coded_width, meta.coded_height), - (180, 320), - "the turned fixture's samples" - ); - assert_eq!( - (meta.width, meta.height), - (240, 320), - "the aspect widens the coded frame before the turn swaps it" - ); + .is_ok_and(|s| s.success()); + if made { + // The same file with a 90-degree display matrix asked of it. + let matrix_on = asset(".anamorphic_turned90.mp4"); + let remuxed = std::process::Command::new("ffmpeg") + .args(["-y", "-v", "error", "-display_rotation", "90", "-i"]) + .arg(&turned) + .args(["-c", "copy"]) + .arg(&matrix_on) + .status() + .is_ok_and(|s| s.success()); + if remuxed { + let (meta, _) = Demuxer::open(&matrix_on).expect("open the turned fixture"); + // The probe: coded 1440x1080 stays; the SAR-4/3 widen of the + // coded width (1920) is what the turn swaps into the height, so + // the displayed pair is 1080x1920 -- DAR 9:16, the ratio ffprobe + // reports for the same file turned. A turn-then-stretch probe + // would declare 1440x1440 here; a stretch-on-the-wrong-axis + // render paints exactly that square into this 9:16 canvas. + assert_eq!( + (meta.coded_width, meta.coded_height), + (1440, 1080), + "the turned fixture's samples" + ); + assert_eq!( + meta.rotation, + engine::Rotation::Cw270, + "the matrix was read as a quarter turn" + ); + assert_eq!( + (meta.width, meta.height), + (1080, 1920), + "the aspect widens the coded width; the turn swaps the stretched pair" + ); + // ...and the render agrees with the probe: the composed picture + // is handed out at the displayed pair, filled to the corners -- + // the 1440x1440 failure the other order produces would fail both + // assertions. + let (_, frames, _) = + engine::DecodeSession::open_at(&matrix_on, 0).expect("open for a frame"); + let frame = frames.recv().expect("a first frame"); + assert_eq!( + (frame.width, frame.height), + (1080, 1920), + "the rendered picture is the displayed pair" + ); + let (w, h) = (frame.width as usize, frame.height as usize); + let at = |x: usize, y: usize| { + let i = (y * w + x) * 4; + (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2]) + }; + let m = w / 10; + let corners = [ + at(m, m), + at(w - 1 - m, m), + at(w - 1 - m, h - 1 - m), + at(m, h - 1 - m), + ]; + assert!( + corners + .iter() + .all(|&(b, g, r)| u32::from(r) + u32::from(g) + u32::from(b) > 48), + "the corners are picture, not black: {corners:?}" + ); + } let _ = std::fs::remove_file(&turned); + let _ = std::fs::remove_file(&matrix_on); } } @@ -268,6 +322,78 @@ fn an_export_of_an_anamorphic_file_is_drawn_and_square() { mean < 2.0, "the export is {mean:.2} mean codes from the preview -- not the same picture" ); + + // The same contract for a ROTATED anamorphic source: the fixture carries a + // real display matrix, the probe declares 1080x1920, and the export must + // be that shape with the picture the preview showed -- the case a + // turn-then-stretch render filled with 1440x1440 and baked bars into. + let plain = asset(".anamorphic_export_src.mp4"); + let matrix_on = asset(".anamorphic_export_rot.mp4"); + let made = std::process::Command::new("ffmpeg") + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) + .arg("testsrc2=size=1440x1080:rate=30:duration=1") + .args([ + "-vf", + "setsar=4/3", + "-c:v", + "libx264", + "-profile:v", + "baseline", + "-pix_fmt", + "yuv420p", + ]) + .arg(&plain) + .status() + .is_ok_and(|s| s.success()) + && std::process::Command::new("ffmpeg") + .args(["-y", "-v", "error", "-display_rotation", "90", "-i"]) + .arg(&plain) + .args(["-c", "copy"]) + .arg(&matrix_on) + .status() + .is_ok_and(|s| s.success()); + if made { + let mut session = PlaybackSession::open(&matrix_on).expect("open the turned fixture"); + session.pause(); + let preview = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!((preview.width, preview.height), (1080, 1920)); + let out = Scratch::file("ve_anamorphic_rot_export", "mp4"); + let handle = session.export_to_with(&out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(120)).expect("export"); + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + (meta.coded_width, meta.coded_height), + (1080, 1920), + "the rotated export is coded at the displayed shape" + ); + assert!(meta.pixel_aspect.is_square(), "no aspect left to state"); + let mut reopened = PlaybackSession::open(&out).expect("reopen the export"); + let exported = loop { + if let Some(frame) = reopened.try_frame() { + break frame; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!((exported.width, exported.height), (1080, 1920)); + let moved = preview + .bgra + .iter() + .zip(&exported.bgra) + .map(|(a, b)| u32::from(a.abs_diff(*b))) + .sum::(); + let mean = moved as f64 / preview.bgra.len() as f64; + assert!( + mean < 2.0, + "the rotated export is {mean:.2} mean codes from the preview" + ); + let _ = std::fs::remove_file(&plain); + let _ = std::fs::remove_file(&matrix_on); + } } /// The copy door, Matroska side: an anamorphic source's Exact row copies the