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..57fe1ab 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()), } } @@ -1274,7 +1293,58 @@ impl Render { width: u32, height: u32, ) -> Frame { - // The file's own turn, before anything else: a phone's portrait video + // The pixel aspect, applied exactly once -- the single conversion to + // the square-pixel raster this engine makes, where ffmpeg's swscale + // 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 { + // 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; + // Sized for `scale_i420`'s exact-planes assertion, once for the + // worker's whole range: steady-state buffers, not per-frame + // allocations ([`turned`]'s reason). + let (dcw, dch) = ( + display_width.div_ceil(2) as usize, + height.div_ceil(2) as usize, + ); + sy.resize(display_width as usize * height as usize, 0); + su.resize(dcw * dch, 0); + sv.resize(dcw * dch, 0); + 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, + ) + }; + // 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 diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 6329f57..8fea412 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -357,13 +357,74 @@ impl UnsupportedRotation { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PixelAspect { + /// Horizontal sample size: the width a coded pixel is drawn at, relative to + /// [`PixelAspect::v`]. 1 and 1 together are square pixels, which is every + /// file that states no aspect anywhere in its container. + pub h: u32, + /// The vertical half of the same ratio; zero means the container said + /// nothing usable and the pixels are square. + pub v: u32, +} + +impl PixelAspect { + /// The square pixels everything before anamorphic sources was. + pub const SQUARE: Self = Self { h: 1, v: 1 }; + + /// Whether the displayed picture is the coded one, drawn one to one. + pub fn is_square(self) -> bool { + // An unstated ratio (0) and a stated 1:1 are the same pixels, and a + // degenerate one a crafted header claimed is square rather than a + // division by zero. + self.v == 0 || self.h == self.v + } + + /// How many coded columns one displayed column is worth: the factor the + /// width is stretched by, exactly as swscale takes it. 1 for square. + /// + /// Rounded to the even grid 4:2:0 composes on, so a ratio that is not a + /// whole number of columns still lands on a picture the chroma planes + /// cover -- the same rounding swscale applies, and the same one that keeps + /// the stretch a whole-sample operation rather than a smear. + pub fn width_factor(self, coded_width: u32) -> u32 { + if self.is_square() { + return coded_width; + } + // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly, + // and a ratio that does not divide evenly is widened to the nearest + // even column count rather than shown cropped or squeezed. + let wide = u64::from(coded_width) * u64::from(self.h); + (((wide + u64::from(self.v) - 1) / u64::from(self.v)) as u32 | 1) & !1 + } +} + #[derive(Debug, Clone, Copy, PartialEq)] pub struct VideoMeta { /// The displayed width: the coded one, swapped where the file's display - /// matrix is a 90- or 270-degree turn (see [`Rotation`]). + /// matrix is a 90- or 270-degree turn (see [`Rotation`]) *and* stretched + /// where the file's pixel aspect is not square (see [`PixelAspect`]) -- the + /// size a player draws the picture at, which is what a timeline is cut in. + /// The picture as stored is [`VideoMeta::coded_width`] by + /// [`VideoMeta::coded_height`]. pub width: u32, - /// The displayed height; see [`VideoMeta::width`]. + /// The displayed height; see [`VideoMeta::width`]. The aspect never touches + /// it: a non-square pixel stretches the width, always -- 4:3 SAR over + /// 1440x1080 displays 1920x1080, and the height is the coded one either way. pub height: u32, + /// The size the samples are stored at, before the display-matrix turn and + /// the pixel stretch: what a decoder hands back, what a copy carries, and + /// the shape every container header of a *copied* file has to declare. The + /// displayed pair above is derived; this one is read. + pub coded_width: u32, + /// The stored height; see [`VideoMeta::coded_width`]. + pub coded_height: u32, + /// The sample aspect ratio the container states, square where it states + /// none. Metadata about the pixels, like [`VideoMeta::rotation`] is about + /// their orientation: the decode keeps the coded pixels and everything + /// downstream is told the ratio, which is what applies it exactly once -- + /// at the conversion to the square-pixel raster. + pub pixel_aspect: PixelAspect, pub frame_rate: f64, pub frame_count: u32, pub codec: Codec, @@ -856,13 +917,23 @@ impl Mp4Demuxer { None => Rotation::None, }; let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height())); + // The ratio one coded pixel is drawn at, off the sample entry's `pasp` + // box: absent for the square-pixel file, which is the common case. + let pixel_aspect = pasp_of(path, track_id); + // The aspect widens the *coded* frame, then the turn swaps that + // stretched pair the way it swaps the coded one (`pixel_aspect_of`'s + // twin comment in the Matroska door carries the measured proof). The + // SAR only ever widens a width, never a height. let (width, height) = match rotation.swaps_axes() { - true => (coded_h, coded_w), - false => (coded_w, coded_h), + true => (coded_h, pixel_aspect.width_factor(coded_w)), + false => (pixel_aspect.width_factor(coded_w), coded_h), }; let meta = VideoMeta { width, height, + coded_width: coded_w, + coded_height: coded_h, + pixel_aspect, frame_rate: frame_rate(track), frame_count: 0, codec, @@ -1313,17 +1384,30 @@ impl MkvDemuxer { } } }; - // The coded size, swapped where the turn is a quarter one: a portrait - // `.mkv` stores a landscape picture plus the turn, so the displayed - // shape is the coded one turned -- the same two numbers the mp4 door - // swaps, off the same kind of turn. + // 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.width), - false => (video.width, video.height), + true => (video.height, video.pixel_aspect.width_factor(video.width)), + false => (video.pixel_aspect.width_factor(video.width), video.height), }; let meta = VideoMeta { width, height, + coded_width: video.width, + coded_height: video.height, + pixel_aspect: video.pixel_aspect, frame_rate, frame_count: mkv.frames as u32, codec: video.codec, @@ -2014,6 +2098,10 @@ struct MkvVideo { number: u64, width: u32, height: u32, + /// The sample aspect ratio the track's `Display*` elements state, square + /// where they state none ([`PixelAspect::SQUARE`]) -- the same reading + /// every Matroska reader makes of their absence. + pixel_aspect: PixelAspect, /// The quarter turn the track's `Projection` asks for; /// [`Rotation::None`] where it states none. rotation: Rotation, @@ -2164,6 +2252,14 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +// How the picture is drawn: Matroska carries the aspect as a `Display*` pair +// in *display units* (0x54B2) -- 0 pixels, 1 centimetres, 2 inches, 3 a display +// aspect ratio, 4 the sample aspect ratio itself. Absent, the pixels are the +// coded ones: every square-pixel file states none of these, which is what makes +// their absence the square answer rather than an error. +const DISPLAY_WIDTH: u32 = 0x54B0; +const DISPLAY_HEIGHT: u32 = 0x54BA; +const DISPLAY_UNIT: u32 = 0x54B2; // The track's projection: how the flat picture sits in space. A roll on the // rectangular projection (type 0) is how a Matroska muxer states what an mp4 // states with its `tkhd` matrix -- mkvmerge has translated display matrices @@ -2428,6 +2524,9 @@ fn mkv_track_entry( ) -> crate::Result { let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); let (mut width, mut height, mut config) = (0, 0, Vec::new()); + // The `Display*` elements: unstated for the square-pixel file, which is + // most of them. + let (mut display_width, mut display_height, mut display_unit) = (0u64, 0u64, 0u64); let mut rotation = Rotation::None; let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); let mut tags = Tags::default(); @@ -2455,6 +2554,9 @@ fn mkv_track_entry( match e.0 { PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, + DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?, + DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?, + DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?, PROJECTION => { let (mut kind, mut yaw, mut pitch, mut roll) = (0u64, 0.0f64, 0.0f64, 0.0f64); @@ -2599,6 +2701,13 @@ fn mkv_track_entry( number, width, height, + pixel_aspect: pixel_aspect_of( + display_width, + display_height, + display_unit, + width, + height, + ), rotation, tags, light, @@ -2795,6 +2904,53 @@ fn rotation_of_roll(degrees: f64) -> crate::Result { /// quarter turn here can make -- the same missing capability the mp4 door /// refuses a 45-degree matrix for, so it gets the same refusal rather than a /// sideways picture. + +/// The sample aspect ratio a Matroska `TrackEntry`'s `Video` element states, +/// from its `DisplayWidth`/`DisplayHeight`/`DisplayUnit` children and the coded +/// size beside them. +/// +/// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and +/// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured), +/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where +/// a pair beside the coded one at all means a crop, not an aspect. 1 and 2 +/// (centimetres, inches) are physical sizes a picture this engine shows cannot +/// mean anything by, and read as square rather than guessed. Every unstated or +/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's +/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the +/// PixelWidth and PixelHeight" when they mean the same thing, so a file that +/// means square most often says nothing at all. +fn pixel_aspect_of( + display_width: u64, + display_height: u64, + display_unit: u64, + coded_width: u32, + coded_height: u32, +) -> PixelAspect { + // A zero pair (unstated, or a header that lies about it) and a zero coded + // size are all square: there is nothing to divide by and nothing to stretch. + if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 { + return PixelAspect::SQUARE; + } + match display_unit { + // 4: the pair *is* the sample aspect ratio. + 4 => PixelAspect { + h: display_width.min(u32::MAX as u64) as u32, + v: display_height.min(u32::MAX as u64) as u32, + }, + // 3: the pair is the display aspect ratio -- display_w / display_h -- + // which the SAR is that against the coded one: sar = dar * h / w. + // 16/9 over 1440x1080 lands on 4/3. + 3 => PixelAspect { + h: ((display_width * u64::from(coded_height)) + .min(u32::MAX as u64 * u64::from(coded_width))) as u32, + v: ((display_height * u64::from(coded_width)) + .min(u32::MAX as u64 * u64::from(coded_height))) as u32, + }, + // Pixels (0) or a physical unit this engine cannot interpret: square. + _ => PixelAspect::SQUARE, + } +} + fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result { if kind != 0 { return Ok(Rotation::None); @@ -3993,6 +4149,33 @@ fn colr_tags(path: &Path, track_id: u32) -> Option { Some(Tags::from_codes(code(8)?, code(6)?, range)) } +/// The `pasp` box of `track_id`'s sample entry (ISO/IEC 14496-12 §6.2.3, the +/// pixel aspect ratio box a visual sample entry may carry): two 32-bit +/// big-endian integers, hSpacing then vSpacing, the ratio one coded pixel is +/// drawn at. ffmpeg writes it for a `setsar=4/3` source and writes 1/1 for a +/// square one (both measured); a box absent -- most mp4s there are -- is square +/// pixels, the same answer Matroska's absent `Display*` elements give. +/// +/// [`None`] rather than an error for a file with no such box, which is most of +/// them -- an untagged mp4 is not a broken one. +fn pasp_of(path: &Path, track_id: u32) -> PixelAspect { + let Ok((_, entry)) = sample_entry(path, track_id) else { + return PixelAspect::SQUARE; + }; + // The same fixed 78-byte VisualSampleEntry header `colr` and `hvcC` sit + // behind; `pasp` is one of their siblings. + let Some(pasp) = child(entry.get(78..).unwrap_or_default(), b"pasp") else { + return PixelAspect::SQUARE; + }; + let (Some(h), Some(v)) = ( + pasp.get(..4).map(|b| u32::from_be_bytes(b.try_into().unwrap())), + pasp.get(4..8).map(|b| u32::from_be_bytes(b.try_into().unwrap())), + ) else { + return PixelAspect::SQUARE; + }; + PixelAspect { h, v } +} + /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says /// about how bright its pictures get, beside the `colr` that says what their /// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 5c6e745..562dbdf 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), } @@ -1737,8 +1743,15 @@ struct CopyPlan { /// copy. private: Vec, colour: ColorDescription, + /// The coded shape the copied track declares: the samples under it are the + /// source's own, so the header names what they are stored at -- not the + /// shape they are drawn at. width: u32, height: u32, + /// The aspect the copied samples are drawn at, written into the file as + /// display metadata ([`CopyParams::pixel_aspect`]): square for every + /// ordinary source, so the header gains nothing. + pixel_aspect: crate::demux::PixelAspect, } /// A run of source blocks copied in one piece: what a cut leaves behind, and @@ -1772,6 +1785,30 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { return None; } + // An anamorphic source asked of a format that cannot state the aspect: the + // blocks would copy, but the sample entry this writer produces has no + // `pasp` box to carry it in, and a header that declares the coded pair + // while the pixels are drawn 4/3 wide is a file that lies about its own + // shape. Refused by name -- the sentence a reader is owed -- before the + // container's codec question, because this is the *nearer* reason: a + // Matroska copy needs no refusal at all (its track carries the aspect + // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own + // copy behaviour), so an anamorphic source's Exact row only ever dies on + // this for an mp4. + if !settings.format.is_mkv() { + let anamorphic = project.sources().iter().any(|source| { + Demuxer::open(&source.path) + .ok() + .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square()) + }); + if anamorphic { + return Some( + "a copy would lose the pixel aspect — this format cannot state it beside the \ + coded picture, so the export re-encodes it into the square pixels it is drawn at" + .to_string(), + ); + } + } let codec = match settings.format { Format::Hevc => Codec::Hevc, Format::Av1 => Codec::Av1, @@ -1782,6 +1819,12 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti )); } }; + // The turn-baking corner-cut (a copied packet is the source's own coded + // picture; this export bakes a display-matrix turn into the pixels) and + // the rest of the reasons a copy says something other than what the + // timeline says are [`CopyPlan::of`]'s own gates, so the container and + // edit sentences below are checked the same way rather than duplicated + // with different words. let carries = project.sources().iter().all(|source| { crate::demux::is_matroska(&source.path) && Demuxer::open(&source.path) @@ -1811,7 +1854,7 @@ impl CopyPlan { }; let entries = project.sources(); let mut sources: Vec> = (0..entries.len()).map(|_| None).collect(); - let mut declared: Option<(Vec, ColorDescription)> = None; + let mut declared: Option<(Vec, ColorDescription, crate::demux::PixelAspect)> = None; let mut regions: Vec = Vec::new(); let r_start = settings.range.map_or(0, |(s, _)| s); for span in export_spans(project, settings.range) { @@ -1869,20 +1912,42 @@ impl CopyPlan { // this export bakes the turn into the pixels -- so a copy would // ship the file sideways. Re-encoding is the only honest // answer here. + // + // The size the copy declares is the source's *coded* pair, so + // that is what the comparison asks: coded to coded. A display + // comparison would refuse every anamorphic source that happens + // to sit at the project's displayed shape and then write a + // track that lies about its own samples -- and a square + // source's coded pair is its display pair, so this asks nothing + // new of the ordinary file. + // + // A source whose samples are not square is the *other* kind of + // picture a copy cannot carry here: the blocks are its own + // coded pixels and this engine's Matroska writer can now state + // the aspect beside them -- but only this engine's + // ([`MkvMuxer::create_copy`] writes the `Display*` elements), + // and the copy's declared shape must stay the coded one. The + // aspect travels with the track instead of being baked in, + // which is ffmpeg's own copy behaviour, so an anamorphic + // source is copyable *into Matroska* and nowhere else. if !source_meta.rotation.is_none() || source_meta.codec != codec - || source_meta.width != meta.width - || source_meta.height != meta.height + || source_meta.coded_width != meta.coded_width + || source_meta.coded_height != meta.coded_height || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? != Rate::REAL_TIME || !demuxer.plain_blocks() { return None; } - // One track, one configuration record and one `Colour`: two - // sources that disagree about either are two streams, and this - // writes one. - let declares = (demuxer.codec_private().to_vec(), source_meta.color); + // Two sources that disagree about their pixel aspect are two + // displayed pictures under one track; the copy declares one + // aspect or none. + let declares = ( + demuxer.codec_private().to_vec(), + source_meta.color, + source_meta.pixel_aspect, + ); if declared.get_or_insert(declares.clone()) != &declares { return None; } @@ -1920,15 +1985,19 @@ impl CopyPlan { }), } } - let (private, colour) = declared?; + let (private, colour, pixel_aspect) = declared?; Some(Self { sources, regions, codec_id, private, colour, - width: meta.width, - height: meta.height, + // The track the copy declares is the source's coded shape -- the + // samples under it are the source's own -- with the aspect beside + // it as the display metadata ([`CopyParams::pixel_aspect`]). + width: meta.coded_width, + height: meta.coded_height, + pixel_aspect, }) } @@ -1952,6 +2021,7 @@ impl CopyPlan { codec_id: self.codec_id, codec_private: &self.private, colour: self.colour, + pixel_aspect: self.pixel_aspect, }, audio, subs, @@ -2721,7 +2791,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 +2816,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 +2882,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 +2909,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 +2934,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 +2975,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 +2997,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 +3027,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 +3139,13 @@ fn run( width, height, rotation, + pixel_aspect, grade, transform, remap, mapper, &mut rotated, + &mut stretched, &mut graded, &mut transformed, &mut canvas, @@ -3079,9 +3175,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,15 +3333,54 @@ 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, ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { + // The pixel aspect, applied exactly once -- the same single conversion to + // the square-pixel raster the decode funnel makes, in the same order + // (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 { + let display_width = pixel_aspect.width_factor(width); + let (dcw, dch) = ( + display_width.div_ceil(2) as usize, + height.div_ceil(2) as usize, + ); + stretched.0.resize(display_width as usize * height as usize, 0); + stretched.1.resize(dcw * dch, 0); + stretched.2.resize(dcw * dch, 0); + 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 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 @@ -3334,13 +3470,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 +3506,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, + ), } } @@ -5488,6 +5646,11 @@ mod tests { codec: crate::demux::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; // 1280 * 720 * 30 * 0.1 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); @@ -5540,6 +5703,11 @@ mod tests { codec: crate::demux::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no + // container wrote, so nothing was read to disagree with it. + coded_width: width, + coded_height: height, + pixel_aspect: 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. diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 3e2aeb9..8708736 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -949,6 +949,17 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +// How the copied picture is drawn: the same elements [`crate::demux`] reads +// back. `DisplayUnit` 4 spells the pair as the sample aspect ratio itself and +// 3 as a display aspect ratio; this writer says SAR (unit 4) because that is +// the ratio it was handed ([`crate::demux::PixelAspect`]) and the one a +// round-trip through this engine's own reader reproduces exactly. Square -- +// the default these elements are optional for -- writes none of them, which is +// what keeps every existing copy's header byte-identical. +const DISPLAY_WIDTH: u32 = 0x54B0; +const DISPLAY_HEIGHT: u32 = 0x54BA; +const DISPLAY_UNIT: u32 = 0x54B2; +const DISPLAY_UNIT_SAR: u64 = 4; // `Colour` and the four children this writes, all inside `Video`. Byte-verified // against what `demux` reads back and what ffprobe reports: the spec tables that // list Range as 0x55B3 are describing ChromaSubsamplingHorz. @@ -1044,6 +1055,12 @@ pub struct CopyParams<'a> { /// grading display. Upgrade path is a `Colour` element written from that /// same struct. pub colour: ColorDescription, + /// The ratio one of the copied samples' pixels is drawn at, written as the + /// track's `Display*` elements: the aspect is metadata about the samples, + /// which are the source's own, so it travels instead of being baked in -- + /// ffmpeg's own copy behaviour. [`PixelAspect::SQUARE`] writes nothing, + /// which is every square-pixel file's header exactly as it was. + pub pixel_aspect: crate::demux::PixelAspect, } /// The soft subtitle track a file carries beside the picture: text, timed, still @@ -1168,6 +1185,7 @@ impl MkvMuxer { b"V_AV1", &av1c, ColorDescription::output(video.height), + crate::demux::PixelAspect::SQUARE, audio, subs, ) @@ -1197,6 +1215,7 @@ impl MkvMuxer { b"V_MPEGH/ISO/HEVC", video.hvcc, ColorDescription::output(video.height), + crate::demux::PixelAspect::SQUARE, audio, subs, ) @@ -1229,6 +1248,7 @@ impl MkvMuxer { video.codec_id, video.codec_private, video.colour, + video.pixel_aspect, audio, subs, ) @@ -1243,6 +1263,7 @@ impl MkvMuxer { codec_id: &[u8], codec_private: &[u8], colour: ColorDescription, + pixel_aspect: crate::demux::PixelAspect, audio: Option<(&AudioParams, Vec)>, subs: Vec, ) -> crate::Result { @@ -1308,6 +1329,15 @@ impl MkvMuxer { let mut dims = Vec::new(); uint(&mut dims, PIXEL_WIDTH, u64::from(width)); uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); + // The copied samples' aspect, where it is not square: the same three + // elements this engine's own reader asks a Matroska track for, as a + // sample aspect ratio (unit 4). A square copy writes none of them -- + // exactly the header every square-pixel copy wrote before this. + if !pixel_aspect.is_square() { + uint(&mut dims, DISPLAY_WIDTH, u64::from(pixel_aspect.h)); + uint(&mut dims, DISPLAY_HEIGHT, u64::from(pixel_aspect.v)); + uint(&mut dims, DISPLAY_UNIT, DISPLAY_UNIT_SAR); + } // What the samples in those pixels mean. Written rather than left to a // reader's own 720-line guess -- the guess is right for an encoded file // (the export remaps every clip into exactly that space) but a remuxer diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index c505f44..338db52 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -729,6 +729,11 @@ impl PlaybackSession { // the default description is what it is drawn in. color: ColorDescription::default(), rotation: Rotation::None, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; let (audio, audio_disabled) = open_audio(path, stream); // Through `from_parts` rather than `Project::single`, which is the @@ -827,6 +832,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, + // No container said anything about these: the picture this engine + // decoded itself is square pixels at the size it was decoded at. + coded_width: still.width, + coded_height: still.height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; let clip = Clip { fade_in: 0, @@ -991,6 +1001,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } @@ -1009,6 +1024,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, + // No container said anything about these: the picture this + // engine decoded itself is square pixels at its own size. + coded_width: still.width, + coded_height: still.height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; let stream = DecodeSession::open_still( &first.path, @@ -1051,6 +1071,11 @@ impl PlaybackSession { codec: Codec::H264, color: ColorDescription::default(), rotation: Rotation::None, + // No container said anything about these: the canvas this engine drew + // itself is square pixels at the size it was drawn at. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, }; (meta, DecodeSession::open_black(width, height, 1)) } diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index 85c72fb..6ae8b54 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -32,8 +32,8 @@ //! cancel a file export has ([`Job`]). use std::path::{Path, PathBuf}; -use std::sync::Arc; use std::sync::atomic::AtomicBool; +use std::sync::Arc; use std::time::UNIX_EPOCH; use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta}; @@ -127,7 +127,10 @@ pub fn path_for(source: &Path) -> Option { let meta = std::fs::metadata(source).ok()?; let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { Ok(d) => (d.as_secs() as i128, d.subsec_nanos()), - Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()), + Err(e) => ( + -(e.duration().as_secs() as i128), + e.duration().subsec_nanos(), + ), }; let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf()); let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec(); @@ -542,7 +545,10 @@ fn started( // it: sweeping to the bare cap left the finished ones filling it and // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that // is over by a whole film's worth by construction ([`reserve`]). - sweep(dir, CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count))); + sweep( + dir, + CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)), + ); } // What a killed editor left behind: the export worker deletes its own part // file when it is cancelled or fails, but nothing can delete it for a @@ -579,8 +585,7 @@ fn started( Vec::new(), Vec::new(), )?; - let bitrate = - (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64; + let bitrate = (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64; let handle = crate::export::start( project, VideoMeta { @@ -632,6 +637,11 @@ mod tests { codec, color: ColorDescription::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no + // container wrote, so nothing was read to disagree with it. + coded_width: width, + coded_height: height, + pixel_aspect: crate::demux::PixelAspect::SQUARE, } } @@ -714,10 +724,17 @@ mod tests { // order of their own, and the order is what is under test. `atime` // is what `sweep` reads and `set_times` is the one door to it // without a dependency. - let file = std::fs::File::options().write(true).open(&path).expect("open"); + let file = std::fs::File::options() + .write(true) + .open(&path) + .expect("open"); let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago); - file.set_times(std::fs::FileTimes::new().set_accessed(when).set_modified(when)) - .expect("stamp"); + file.set_times( + std::fs::FileTimes::new() + .set_accessed(when) + .set_modified(when), + ) + .expect("stamp"); path }; let old = write("old.mp4", 400, 300); @@ -732,7 +749,10 @@ mod tests { assert!(!old.exists(), "the oldest stand-in survived the sweep"); assert!(!middle.exists(), "the next oldest survived it"); assert!(fresh.exists(), "the freshest was taken"); - assert!(part.exists(), "a half-written proxy was deleted under its writer"); + assert!( + part.exists(), + "a half-written proxy was deleted under its writer" + ); assert_eq!(left, 800, "what is left is the fresh one and the part file"); // Under the cap, nothing is touched at all. @@ -897,7 +917,10 @@ mod tests { // is a stand-in still on the disk, and it is answered as one. let answer = delete(&file); assert!(answer.is_err(), "a refused unlink reported as a delete"); - assert!(proxy.is_dir(), "and what could not be deleted is still there"); + assert!( + proxy.is_dir(), + "and what could not be deleted is still there" + ); std::fs::remove_dir(&proxy).expect("clean up"); // ...against the honest no-op, which *is* an off switch: nothing there. assert_eq!(delete(&file).ok(), Some(false), "nothing to take"); @@ -952,7 +975,9 @@ mod tests { let cancel = Arc::new(AtomicBool::new(true)); let answer = generate_if_wanted(&file, &cancel); - let err = answer.err().expect("a pre-cancelled ask must not hand back a job"); + let err = answer + .err() + .expect("a pre-cancelled ask must not hand back a job"); assert!( crate::demux::is_cancelled(&err), "not the cancelled answer: {err}" diff --git a/crates/engine/tests/anamorphic.rs b/crates/engine/tests/anamorphic.rs new file mode 100644 index 0000000..a83b6f6 --- /dev/null +++ b/crates/engine/tests/anamorphic.rs @@ -0,0 +1,484 @@ +//! The sample aspect ratio: a file whose pixels are not square is drawn +//! wider than they are stored, and every rendition this engine makes -- +//! the probe, the preview and the export -- is the drawn one. +//! +//! `test_anamorphic.mp4` and `test_anamorphic.mkv` (`scripts/gen_fixtures.sh`) +//! are one 1440x1080 source with `setsar=4/3` asked of it: the classic +//! anamorphic 16:9 frame on a 4:3 raster, the way a DVD rip says "widen me". +//! The engine's answer is ffmpeg's own: the decode keeps the coded pixels, +//! the container's ratio is read as metadata, and the stretch is applied +//! exactly once, at the conversion to the square-pixel raster -- so the +//! preview shows 1920x1080 and the corners of it are picture, not bars. +//! +//! The copy door is the other half of ffmpeg's behaviour: a copied file +//! keeps the coded pixels and carries the ratio beside them (Matroska's +//! `Display*` elements), and where the container cannot state it -- an mp4 +//! has no `pasp` in this writer -- a copy refuses by name rather than +//! writing a header that lies about its own shape. +//! +//! ```text +//! cargo test -p engine --release --test anamorphic -- --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::demux::Demuxer; +use engine::export::{ExportSettings, Format}; +use engine::scratch::Scratch; +use engine::PlaybackSession; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Which seat an export takes is decided by *process-wide* environment +/// variables, so a test binary that shares the machine has to borrow them +/// rather than assume: this pins both decode and encode to software, which is +/// the seat every machine has, and holds the borrow for the whole test binary. +static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +type Shared = std::sync::RwLockReadGuard<'static, ()>; + +#[must_use = "the seat pin holds only while its guard is alive"] +fn pin_software() -> Shared { + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); + borrowed +} + +fn wait(handle: &engine::ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// The coded and displayed shapes every anamorphic test here agrees on: +/// 1440x1080 stored, 4/3 drawn, 1920x1080 shown. +const CODED: (u32, u32) = (1440, 1080); +const DISPLAY: (u32, u32) = (1920, 1080); + +/// The reduced form of `h/v`, so a ratio stated unreduced (a DAR pair like +/// ffmpeg's 17280/12960) compares equal to its simplest spelling. +fn gcd(mut a: u32, mut b: u32) -> u32 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +/// The header says what the samples are and what they are drawn at, and both +/// doors say the same thing about the same picture. +#[test] +fn the_container_aspect_is_probed_off_both_doors() { + for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { + let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture"); + assert_eq!( + (meta.coded_width, meta.coded_height), + CODED, + "{file}: the samples are stored at the coded size" + ); + assert_eq!( + (meta.width, meta.height), + DISPLAY, + "{file}: 4/3 over 1440x1080 is drawn 1920x1080" + ); + // The mkv door reads ffmpeg's DAR spelling (16/9) and the mp4 door the + // SAR itself (4/3); both name the same drawn picture, so the test + // compares the reduced ratio, not the spelling. + let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v); + let g = gcd(h, v); + assert_eq!( + (h / g, v / g), + (4, 3), + "{file}: the ratio one coded pixel is drawn at" + ); + assert!(!meta.pixel_aspect.is_square(), "{file}: it is not square"); + assert_eq!( + meta.rotation, + engine::Rotation::None, + "{file}: no turn was asked of it" + ); + } + // A square-pixel file states none of it, and both doors answer square: + // the default that makes the whole feature invisible to the ordinary + // library. + for file in ["test_baseline.mp4", "test_rotation90.mp4"] { + let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture"); + assert!( + meta.pixel_aspect.is_square(), + "{file}: no container said an aspect, so the pixels are square" + ); + // Drawn one to one: the displayed pair is the coded pair, swapped + // where the file's matrix turns it and never widened. + let (dw, dh) = match meta.rotation.swaps_axes() { + true => (meta.coded_height, meta.coded_width), + false => (meta.coded_width, meta.coded_height), + }; + assert_eq!( + (meta.width, meta.height), + (dw, dh), + "{file}: drawn one to one, swapped only by the turn" + ); + } + // The rotation still swaps on an anamorphic file whose *matrix* asks for + // 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"); + 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(&turned) + .status() + .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); + } +} + +/// The preview: the composed picture is the displayed shape, filled to the +/// corners -- no letterbox, no squeeze, no coded-shaped picture drawn into a +/// wider window. The corner gate is numeric: a picture that left bars would +/// sample black. +#[test] +fn the_preview_shows_the_drawn_picture() { + let _seat = pin_software(); + for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { + let (_, frames, _) = + engine::DecodeSession::open_at(&asset(file), 0).expect("open for a frame"); + let frame = frames.recv().expect("a first frame"); + assert_eq!( + (frame.width, frame.height), + DISPLAY, + "{file}: the composed picture is the drawn shape" + ); + let (w, h) = (frame.width as usize, frame.height as usize); + let at = |x: usize, y: usize| { + let i = (y * w + x) * 4; + let (b, g, r) = (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2]); + (u32::from(r), u32::from(g), u32::from(b)) + }; + 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(|(r, g, b)| *r + *g + *b > 48), + "{file}: the corners are picture, not black: {corners:?}" + ); + let dar = w as f64 / h as f64; + assert!( + (dar - 16.0 / 9.0).abs() < 0.01, + "{file}: the measured display aspect is 16:9, measured {dar:.4}" + ); + } +} + +/// The export: the drawn shape is what the file says, and the pixels are the +/// ones the preview showed -- re-encoded, so the new file is square-pixel at +/// the displayed size and states no aspect of its own. +#[test] +fn an_export_of_an_anamorphic_file_is_drawn_and_square() { + let _seat = pin_software(); + let source = asset("test_anamorphic.mkv"); + let mut session = PlaybackSession::open(&source).expect("open the fixture"); + session.pause(); + let preview = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + std::thread::sleep(Duration::from_millis(10)); + }; + let out = Scratch::file("ve_anamorphic_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), + DISPLAY, + "the re-encoded file is coded at the displayed shape" + ); + assert!( + meta.pixel_aspect.is_square(), + "the aspect was applied, not carried: the export states none" + ); + // Preview vs export, same clip: the drawn picture to the byte. + 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), + DISPLAY, + "the export plays at the drawn shape" + ); + // Encode is lossy, so the picture is measured, not diffed: a wrong shape + // or a squeezed picture would move far more than a rounding code. + 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 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 +/// coded blocks and carries the aspect beside them -- read back as the same +/// 4/3 off the same elements the probe reads. +#[test] +fn a_matroska_copy_keeps_the_pixel_aspect() { + // The copy itself decodes nothing, but opening the HEVC source and + // reopening the copy do -- there is no software HEVC decoder, so both + // need the plugin. A machine without it skips, exactly as + // `video_copy`'s decode-back test does. + let Ok(session) = PlaybackSession::open(asset("test_anamorphic_hevc.mkv")) else { + println!("no VA-API plugin: skipping the copy-keeps-aspect test"); + return; + }; + let out = Scratch::file("ve_anamorphic_copy", "mkv"); + let handle = session.export_to_with( + &out, + &ExportSettings { + format: Format::Hevc, + ..Default::default() + }, + ); + while !handle.is_finished() { + std::thread::sleep(Duration::from_millis(20)); + } + let encoders = handle.encoders().unwrap_or_default(); + handle.result().expect("an outcome").expect("copy export"); + assert!( + encoders.contains("copy"), + "an untouched anamorphic timeline copies: {encoders}" + ); + let (meta, _) = Demuxer::open(&out).expect("reopen the copy"); + assert_eq!( + (meta.coded_width, meta.coded_height), + CODED, + "the copied track declares the coded shape" + ); + let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v); + let g = gcd(h, v); + assert_eq!( + (h / g, v / g), + (4, 3), + "the copied track states the aspect it was copied with" + ); + assert_eq!( + (meta.width, meta.height), + DISPLAY, + "and so reads back as the drawn shape" + ); +} + +/// The copy door, mp4 side: the sample entry this writer produces has no +/// `pasp` box, so an anamorphic source's Exact row refuses by name rather +/// than writing a header that lies about its own shape -- and the export +/// still re-encodes to the right shape when asked without Exact. +#[test] +fn an_mp4_copy_of_an_anamorphic_source_refuses_in_words() { + let _seat = pin_software(); + // The refusal is decided at the header read, but the session must open + // the HEVC source first -- plugin on this machine or skip, as above. + let Ok(session) = PlaybackSession::open(asset("test_anamorphic_hevc.mkv")) else { + println!("no VA-API plugin: skipping the mp4 exact refusal test"); + return; + }; + let out = Scratch::file("ve_anamorphic_exact_refused", "mp4"); + let settings = ExportSettings { + format: Format::Mp4, + exact: true, + ..Default::default() + }; + let handle = session.export_to_with(&out, &settings); + wait(&handle, Duration::from_secs(300)) + .expect_err("an mp4 cannot honour exact for an anamorphic source"); + let error = handle + .result() + .expect("a finished export has an outcome") + .expect_err("the export refused") + .to_string(); + assert!( + error.contains("pixel aspect"), + "the refusal names the aspect it would lose: {error}" + ); + assert!( + !out.exists() || std::fs::read(&out).is_err(), + "no lying header was written" + ); +} diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 2b44aec..b079dce 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -379,6 +379,11 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() { codec: engine::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: 640, + coded_height: 360, + pixel_aspect: engine::demux::PixelAspect::SQUARE, }; let out = out_path("still_song", "mp4"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); @@ -440,8 +445,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { ], Vec::new(), Vec::new(), - Vec::new(), - ) + Vec::new(), + ) .expect("one second on four audio tracks") }; let write = |project: Project, name: &str| { @@ -454,8 +459,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { format: Format::Wav, ..Default::default() }, - None, - ); + None, + ); wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}")); let (audio, samples) = decode(&out); let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs())); @@ -630,8 +635,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { audio_kbps: kbps, ..Default::default() }, - None, - ); + None, + ); wait(&handle, Duration::from_secs(120)).expect("mp3 export"); let got = mp3_declared_kbps(&out); println!("mp3 asked {kbps:?}, header says {got} kbps"); @@ -706,6 +711,11 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { codec: engine::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: 640, + coded_height: 360, + pixel_aspect: engine::demux::PixelAspect::SQUARE, }; for want in [128u32, 320] { let out = out_path(&format!("mp4_aac_{want}"), "mp4"); @@ -717,8 +727,8 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() { audio_kbps: Some(want), ..Default::default() }, - None, - ); + None, + ); wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); let got = mp4_aac_kbps(&out, f64::from(RATE)); println!("mp4 asked {want} kbps, the track measures {got:.1}"); @@ -859,7 +869,9 @@ fn a_51_ac3_source_round_trips_through_a_wav() { Vec::new(), ) .expect("a one-source AC-3 project"); - let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0; + let video = engine::demux::Demuxer::open(&source) + .expect("open the fixture") + .0; let out = out_path("ac3", "wav"); let handle = engine::export::start( @@ -881,11 +893,20 @@ fn a_51_ac3_source_round_trips_through_a_wav() { "the §7.8 downmix is what reaches the file" ); let secs = (samples.len() / 2) as f64 / 48_000.; - assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s"); - let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::() + assert!( + (0.9..1.1).contains(&secs), + "one second of clip, got {secs:.3}s" + ); + let energy = (samples + .iter() + .map(|s| f64::from(*s) * f64::from(*s)) + .sum::() / samples.len() as f64) .sqrt(); - assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}"); + assert!( + energy > 0.005, + "the exported AC-3 is silence: RMS {energy:.6}" + ); std::fs::remove_file(&out).unwrap(); } @@ -1004,6 +1025,11 @@ fn a_fade_in_reaches_the_exported_audio() { codec: engine::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: 640, + coded_height: 360, + pixel_aspect: engine::demux::PixelAspect::SQUARE, }; let out = out_path("fadein", "wav"); let handle = engine::export::start( @@ -1034,7 +1060,10 @@ fn a_fade_in_reaches_the_exported_audio() { start < body * 0.1, "the very start is quiet: {start:.4} vs body {body:.4}" ); - assert!(quarter < half, "the envelope rises: {quarter:.4} -> {half:.4}"); + assert!( + quarter < half, + "the envelope rises: {quarter:.4} -> {half:.4}" + ); assert!( half < near_end, "the envelope keeps rising into the ramp's end: {half:.4} -> {near_end:.4}" @@ -1080,10 +1109,7 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() { // exactly what `Project::split` leaves behind. let mut project = Project::from_parts( vec![Source::new(src.to_path_buf(), 0)], - vec![( - LaneKind::Audio, - vec![clip(0, 0, 45), clip(45, 45, 90)], - )], + vec![(LaneKind::Audio, vec![clip(0, 0, 45), clip(45, 45, 90)])], Vec::new(), Vec::new(), Vec::new(), @@ -1101,6 +1127,11 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() { codec: engine::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: 640, + coded_height: 360, + pixel_aspect: engine::demux::PixelAspect::SQUARE, }; let out = out_path("crossfade", "wav"); let handle = engine::export::start( diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 4c84fed..dd2ffa5 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -278,6 +278,11 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { codec: engine::Codec::H264, color: Default::default(), rotation: Rotation::None, + // Square pixels, coded where they are declared: a meta no container + // wrote, so nothing was read to disagree with it. + coded_width: 960, + coded_height: 720, + pixel_aspect: engine::demux::PixelAspect::SQUARE, }; let out = out_path("mixed"); let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 0df6b04..8552494 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -769,5 +769,36 @@ for ext in mp4 mkv; do done rm -f assets/.rotation_tall_src.mp4 +# The sample aspect ratio: `test_anamorphic.*` are one 1440x1080 source whose +# pixels are drawn 4/3 wide -- the classic anamorphic 16:9 frame stored on a +# 4:3 raster (`-vf setsar=4/3`), so the displayed picture is 1920x1080 and the +# stored one never is. This is how a DVD rip and a Blu-ray remux say "widen +# me": the pixels stay where the encoder put them and the container carries +# the ratio. +# +# What each muxer actually writes, byte-verified by walking the output rather +# than taken off a table: the Matroska muxer writes `DisplayWidth` 16, +# `DisplayHeight` 9 and `DisplayUnit` 3 -- a *display aspect ratio* pair, not +# a sample aspect ratio, and 4:3 SAR over 1440x1080 is exactly 16:9 DAR -- and +# a square-pixel file gets no `Display*` element at all. The mp4 muxer writes +# a `pasp` box (hSpacing 4, vSpacing 3) inside the `avc1` sample entry, and +# 1/1 for a square one. `tests/anamorphic.rs` reads both spellings through the +# engine and asserts the same displayed shape off either. +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=1" \ + -vf "setsar=4/3" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + assets/test_anamorphic.mp4 +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=1" \ + -vf "setsar=4/3" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + assets/test_anamorphic.mkv + +# ...and the anamorphic HEVC Matroska twin, for the copy path: `tests/`'s +# copy door only copies HEVC or AV1 Matroska (`tests/video_copy.rs`), so an +# anamorphic *copy* needs an anamorphic source in a codec that door takes. +# Same source as above through libx265; the SAR rides the stream. +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=2" \ + -vf "setsar=4/3" -c:v libx265 -pix_fmt yuv420p \ + -x265-params "log-level=error:keyint=30:min-keyint=30" \ + assets/test_anamorphic_hevc.mkv + echo "fixtures written to assets/" diff --git a/scripts/memguard-runner.sh b/scripts/memguard-runner.sh new file mode 100755 index 0000000..78161c6 --- /dev/null +++ b/scripts/memguard-runner.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Wraps a test/bin invocation in a transient user cgroup scope so a runaway +# allocation dies inside its own cgroup instead of triggering a machine-wide +# OOM kill. Used as the cargo target runner (see .cargo/config.toml) so every +# `cargo test`/`cargo run` invocation of this workspace is capped, from any +# checkout (main repo or worktree). +set -euo pipefail + +if [ "${EC_NOMEMGUARD:-0}" = "1" ]; then + echo "memguard-runner: EC_NOMEMGUARD=1, running without memory cap" >&2 + exec "$@" +fi + +if ! systemd-run --user --scope --quiet -p MemoryMax=10G true >/dev/null 2>&1; then + echo "memguard-runner: systemd-run --user --scope unavailable, running without memory cap" >&2 + exec "$@" +fi + +exec systemd-run --user --scope --quiet --same-dir \ + -p MemoryMax=10G -p MemorySwapMax=2G \ + -- "$@"