diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 2ddd8ca..08cf612 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -403,6 +403,10 @@ impl Session { height: meta.height, frame_rate: meta.frame_rate, frame_count: meta.frame_count, + coded_width: meta.coded_width, + coded_height: meta.coded_height, + pixel_aspect_h: meta.pixel_aspect.h, + pixel_aspect_v: meta.pixel_aspect.v, }, ready: VecDeque::new(), pending: Vec::new(), @@ -935,6 +939,10 @@ impl VpxSession { height: meta.height, frame_rate: meta.frame_rate, frame_count: meta.frame_count, + coded_width: meta.coded_width, + coded_height: meta.coded_height, + pixel_aspect_h: meta.pixel_aspect.h, + pixel_aspect_v: meta.pixel_aspect.v, }, flushed: false, skip: 0, @@ -1110,6 +1118,10 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 (*out).height = meta.height; (*out).frame_rate = meta.frame_rate; (*out).frame_count = meta.frame_count; + (*out).coded_width = meta.coded_width; + (*out).coded_height = meta.coded_height; + (*out).pixel_aspect_h = meta.pixel_aspect_h; + (*out).pixel_aspect_v = meta.pixel_aspect_v; } 0 })) diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 2a59391..fb9e5c3 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -18,7 +18,7 @@ use ec_h264::H264Decoder; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::convert::{i420_to_bgra, i420_to_bgra_with}; -use crate::demux::{Codec, Demuxer, Rotation, VideoMeta}; +use crate::demux::{Codec, Demuxer, PixelAspect, Rotation, VideoMeta}; use crate::hw::HwSession; use crate::project::Speed; use crate::scale::Composer; @@ -562,6 +562,8 @@ impl DecodeSession { transform, // A still has no display matrix: what the file holds is what it is. Rotation::None, + // ...and no sample aspect either: a still is authored square. + PixelAspect::SQUARE, ColorDescription::default(), canvas, tonemap::Preset::default(), @@ -691,6 +693,9 @@ impl DecodeSession { transform, // Painted here, at the canvas's own size: nothing turned it. Rotation::None, + // ...and nothing drew it anamorphic: it is square by + // construction. + PixelAspect::SQUARE, ColorDescription::default(), canvas, tonemap::Preset::default(), @@ -1108,6 +1113,7 @@ fn run_span( color, transform, opened.meta.rotation, + opened.meta.pixel_aspect, opened.meta.color, canvas, tone, @@ -1197,6 +1203,12 @@ struct Render { /// every file that states no turn, which is the whole of an ordinary /// library. rotation: Rotation, + /// The ratio one coded pixel is drawn at ([`crate::demux::PixelAspect`]): + /// the file's sample aspect ratio, applied exactly once, at this one + /// conversion to the square-pixel raster -- the same place ffmpeg's swscale + /// applies it, and nowhere else. Square for every file that states no + /// aspect, which takes the branch by a bool and touches no byte. + pixel_aspect: PixelAspect, /// What the source's samples mean -- the stream's own matrix and range, /// which is what the conversion below is done in rather than the BT.601 it /// used to assume of every file. @@ -1215,6 +1227,10 @@ struct Render { /// asks for none, and resized once for one that does -- a steady-state /// buffer rather than three plane allocations per decoded frame. turned: (Vec, Vec, Vec), + /// The same, for the pixel-aspect stretch: the coded picture widened to + /// the displayed width, empty for every square-pixel file and sized once + /// for one that is not. + stretched: (Vec, Vec, Vec), /// Where [`Composer::place_transformed`]'s owned picture lands, so a /// transformed frame's planes live as long as `self` -- matching what /// [`Composer::place`] already hands back by borrowing `self.canvas`. @@ -1238,6 +1254,7 @@ impl Render { color: ColorParams, transform: TransformParams, rotation: Rotation, + pixel_aspect: PixelAspect, desc: ColorDescription, canvas: Composer, preset: tonemap::Preset, @@ -1247,6 +1264,7 @@ impl Render { color, transform, rotation, + pixel_aspect, desc, canvas, // corner-cut: the ceiling is that the map reads limited-range codes @@ -1261,6 +1279,7 @@ impl Render { }, graded: (Vec::new(), Vec::new(), Vec::new()), turned: (Vec::new(), Vec::new(), Vec::new()), + stretched: (Vec::new(), Vec::new(), Vec::new()), placed: (Vec::new(), Vec::new(), Vec::new()), } } @@ -1302,6 +1321,40 @@ impl Render { ) } }; + // 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. + let (y, u, v, width, height) = if self.pixel_aspect.is_square() { + (y, u, v, width, height) + } else { + // The aspect widens the *width*, always: 4:3 SAR over 1440x1080 + // shows 1920x1080. `width_factor` lands on the even grid 4:2:0 + // composes on, and a height is never touched by it. + let display_width = self.pixel_aspect.width_factor(width); + let (sy, su, sv) = &mut self.stretched; + crate::scale::scale_i420( + y, + u, + v, + width as usize, + height as usize, + sy, + su, + sv, + display_width as usize, + height as usize, + ); + ( + &sy[..display_width as usize * height as usize], + &su[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], + &sv[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], + display_width, + height, + ) + }; 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/export.rs b/crates/engine/src/export.rs index fbad59d..e869fcb 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1229,10 +1229,16 @@ struct Dissolve<'a> { /// B's own file's display-matrix turn, [`place_picture`]'s first stage; /// B is a different file and may be turned differently from A. rotation: Rotation, + /// B's own file's sample aspect, [`place_picture`]'s second stage, for + /// the same reason the turn is per file. + pixel_aspect: crate::demux::PixelAspect, canvas: Composer, /// The turn's, the grade's and the transform's scratch, exactly as A's /// span keeps them: refilled per picture, allocated once. rotated: (Vec, Vec, Vec), + /// The stretch's own scratch, [`place_picture`]'s second stage -- the + /// pixel aspect's, beside the turn's. + stretched: (Vec, Vec, Vec), graded: (Vec, Vec, Vec), transformed: (Vec, Vec, Vec), } @@ -2721,7 +2727,13 @@ fn run( // samples *mean* ([`ColorDescription`]), which is what decides whether they // are remapped on the way in. Real time for a still, a song and a // single-rate project, where every conversion below is the identity. - let rates: Vec<(Rate, ColorDescription, Option, Rotation)> = sources + let rates: Vec<( + Rate, + ColorDescription, + Option, + Rotation, + crate::demux::PixelAspect, + )> = sources .iter() .map(|source| source_rate(&source.path, meta.frame_rate)) .collect(); @@ -2740,7 +2752,7 @@ fn run( let preset = project.tone(); let tone: Vec> = rates .iter() - .map(|(_, color, peak, _)| match color.transfer { + .map(|(_, color, peak, _, _)| match color.transfer { // A preview file keeps the film's own curve and is tone-mapped when // it is *shown* ([`ExportSettings::keep_source_colour`]), which is // both cheaper and the only way the preset can still be changed @@ -2806,12 +2818,14 @@ fn run( // A's pixels on the CPU, so a dissolving span never asks for a GPU // buffer, not even outside its own window. let dissolve = dissolve_window(project, &span); - let (mut pictures, rate, in_frame, color, mapper, rotation) = match span.from { + let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = + match span.from + { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - let (rate, color, _peak, rotation) = rates[source]; + let (rate, color, _peak, rotation, pixel_aspect) = rates[source]; let mapper = tone[source].as_ref(); // Nothing on the way from this span's decoder to the encoder // touches a sample: no tone map, no matrix remap, no grade -- @@ -2831,8 +2845,12 @@ fn run( // A file whose display matrix asks for a turn is *not* // untouched, whatever else the timeline says: its pictures // have to be turned, which is a read-back no GPU buffer - // survives. + // survives. The sample aspect is the same refusal one + // stage later: its pictures have to be stretched to the + // square-pixel raster before an encoder sees them, which + // is the same kind of touch. && rotation.is_none() + && pixel_aspect.is_square() && dissolve.is_none(); let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the @@ -2852,13 +2870,21 @@ fn run( } else { ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? }; - (Some(pictures), rate, in_frame, Some(color), mapper, rotation) + (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect) } // A gap's black is 16/128/128, which is black in every matrix here // and on every curve: nothing to remap and nothing to tone-map, // which is what `None` says. A gap is no file either, so nothing // turns it. - None => (None, Rate::REAL_TIME, 0, None, None, Rotation::None), + None => ( + None, + Rate::REAL_TIME, + 0, + None, + None, + Rotation::None, + crate::demux::PixelAspect::SQUARE, + ), }; // Mixed spaces on one timeline: a clip coded against another matrix than // the one this file declares is rewritten into it, *after* the grade -- @@ -2885,8 +2911,10 @@ fn run( let mut transformed = (Vec::new(), Vec::new(), Vec::new()); // ...and one more for the file's own display-matrix turn, which happens // before all of those (see [`place_picture`]): empty for every source - // that states no turn. + // that states no turn. `stretched` is its twin for the pixel aspect, + // which happens right after it. let mut rotated = (Vec::new(), Vec::new(), Vec::new()); + let mut stretched = (Vec::new(), Vec::new(), Vec::new()); // ...and the canvas it is placed on, which is where a source of another // resolution becomes a picture at the project's. The same `Composer` // playback composes with, given the same policy, so an export is what @@ -2905,7 +2933,7 @@ fn run( let entry = sources.get(b_source).ok_or_else(|| { format!("clip names source {b_source} of {}", sources.len()) })?; - let (b_rate, b_color, _peak, b_rotation) = rates[b_source]; + let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; let b_mapper = tone[b_source].as_ref(); let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); Ok(Dissolve { @@ -2935,12 +2963,14 @@ fn run( .copied() .unwrap_or_default(), rotation: b_rotation, + pixel_aspect: b_pixel_aspect, canvas: Composer::new( meta.width, meta.height, project.composite_fit_at(b_start), ), rotated: (Vec::new(), Vec::new(), Vec::new()), + stretched: (Vec::new(), Vec::new(), Vec::new()), graded: (Vec::new(), Vec::new(), Vec::new()), transformed: (Vec::new(), Vec::new(), Vec::new()), }) @@ -3045,11 +3075,13 @@ fn run( width, height, rotation, + pixel_aspect, grade, transform, remap, mapper, &mut rotated, + &mut stretched, &mut graded, &mut transformed, &mut canvas, @@ -3079,9 +3111,10 @@ fn run( } Some(Frame::Pixels(by, bu, bv, bw, bh)) => { let (by, bu, bv, _, _) = place_picture( - by, bu, bv, bw, bh, d.rotation, d.grade, d.transform, - d.remap, d.mapper, &mut d.rotated, &mut d.graded, - &mut d.transformed, &mut d.canvas, + by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade, + d.transform, d.remap, d.mapper, &mut d.rotated, + &mut d.stretched, &mut d.graded, &mut d.transformed, + &mut d.canvas, ); let idx_in_window = done_here + r - d.tail_start; let t = dissolve_weight(idx_in_window, d.window); @@ -3236,11 +3269,13 @@ fn place_picture<'a>( width: u32, height: u32, rotation: Rotation, + pixel_aspect: crate::demux::PixelAspect, grade: Option, transform: TransformParams, remap: Option<(Matrix, Matrix)>, mapper: Option<&ToneMapper>, turned: &'a mut (Vec, Vec, Vec), + stretched: &'a mut (Vec, Vec, Vec), graded: &'a mut (Vec, Vec, Vec), transformed: &'a mut (Vec, Vec, Vec), canvas: &'a mut Composer, @@ -3264,6 +3299,35 @@ fn place_picture<'a>( (&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. + let (y, u, v, width, height) = if pixel_aspect.is_square() { + (y, u, v, width, height) + } else { + let display_width = pixel_aspect.width_factor(width); + crate::scale::scale_i420( + y, + u, + v, + width as usize, + height as usize, + &mut stretched.0, + &mut stretched.1, + &mut stretched.2, + display_width as usize, + height as usize, + ); + ( + &stretched.0[..], + &stretched.1[..], + &stretched.2[..], + display_width, + height, + ) + }; // 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. @@ -3334,13 +3398,26 @@ fn remap_into( fn source_rate( path: &Path, timeline_fps: f64, -) -> (Rate, ColorDescription, Option, Rotation) { +) -> ( + Rate, + ColorDescription, + Option, + Rotation, + crate::demux::PixelAspect, +) { if crate::is_image(path) || crate::is_audio(path) { // A still is BT.601 by construction whatever it was authored as: // `decode::rgb_to_i420` is the one matrix that turns its pixels into // planes. A song has no picture and the answer is never read. Neither - // has a display matrix to be turned by. - return (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None); + // has a display matrix to be turned by, nor an aspect to be widened + // by: both are authored square. + return ( + Rate::REAL_TIME, + ColorDescription::default(), + None, + Rotation::None, + crate::demux::PixelAspect::SQUARE, + ); } match Demuxer::open(path) { // ...and one whose rate cannot be named against the timeline's, which @@ -3357,10 +3434,19 @@ fn source_rate( // The file's own turn, so the encoder is fed the picture the // preview shows: the same header read, one more answer. meta.rotation, + // ...and its own sample aspect, for the same reason on the same + // read: the encoder is fed the shape the preview showed. + meta.pixel_aspect, ), // Unreadable here means unreadable below too, where the span dies with a // real message; the file's own space is the least of that. - Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None), + Err(_) => ( + Rate::REAL_TIME, + ColorDescription::default(), + None, + Rotation::None, + crate::demux::PixelAspect::SQUARE, + ), } } diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 5319ca3..1b5e6a0 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -15,7 +15,7 @@ //! path -- the same "no" it gives for an unsupported profile, and the caller's //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. -use std::ffi::{CString, c_char, c_void}; +use std::ffi::{c_char, c_void, CString}; use std::os::fd::FromRawFd; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -26,7 +26,18 @@ use crate::colorspace::ColorDescription; const LIB_NAME: &str = "libengine_hw.so"; -/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]. +/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]'s picture half -- +/// the four fields a session was opened with, plus the coded pair and the +/// sample aspect a display size can now differ from the coded one by. +/// +/// `width`/`height` are the *displayed* shape, exactly as [`crate::VideoMeta`] +/// promises: a plugin opened on a rotated file has always been handed a +/// swapped pair here, and the pictures it hands back are sized by its own +/// decoder's output, which is the coded pair. `coded_width`/`coded_height` +/// name that pair explicitly, and `pixel_aspect_h`/`_v` carry the ratio one +/// coded pixel is drawn at, so a caller that needs the stored shape (a copy +/// declaring a track, an encoder agreeing on a surface) asks the coded one and +/// a caller that draws asks the display one -- both answered, neither derived. #[repr(C)] #[derive(Default)] pub struct VhMeta { @@ -34,6 +45,13 @@ pub struct VhMeta { pub height: u32, pub frame_rate: f64, pub frame_count: u32, + /// What the samples are stored at, before any turn or stretch. + pub coded_width: u32, + pub coded_height: u32, + /// The sample aspect ratio, h over v, square as 1 and 1 -- or 0 and 0, + /// which is `Default` and reads square ([`crate::demux::PixelAspect`]). + pub pixel_aspect_h: u32, + pub pixel_aspect_v: u32, } /// One decoded picture as planar I420. Pointers belong to the plugin and stay @@ -371,7 +389,9 @@ impl HwSession { /// for a few pictures only: encode it before asking this for a few more. pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result>> { let Some(next_dma) = self.plugin.next_frame_dma else { - return Ok(self.next_frame()?.map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); + return Ok(self + .next_frame()? + .map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); }; let mut frame = VhFrame::default(); let mut dma = VhDma::default(); @@ -482,8 +502,9 @@ struct EncPlugin { /// neither and every picture reaches it as bytes, which is what it always /// did. dma_geometry: Option i32>, - frame_dma: - Option i32>, + frame_dma: Option< + unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32, + >, drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid.