From 66a1c405140f4b42a93d97dd87152c87cee31b09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 24 Sep 2026 19:17:06 +0300 Subject: [PATCH] probe(demux): sample aspect ratio off the container, coded dims beside the display pair ffmpeg's model: the decoder keeps coded pixels and carries the SAR as metadata. VideoMeta carries the pair now: coded_width/coded_height are what the samples are stored at, pixel_aspect is the ratio one coded pixel is drawn at (PixelAspect, square when nothing is stated), and width/height stay the displayed shape their docs always promised -- stretched by the aspect, then swapped by the turn, in that order. mkv: DisplayWidth/DisplayHeight/DisplayUnit read off the Video element (units 3 DAR and 4 SAR; absent, or units 0/1/2, square -- measured against ffmpeg 8.1.2, which writes a 16/9 DAR pair with unit 3 for a setsar=4/3 source and nothing at all for a square one). mp4: pasp (hSpacing/vSpacing) out of the visual sample entry, behind the same fixed 78-byte header colr and hvcC sit behind, absent = square -- measured: ffmpeg writes pasp 4/3 for setsar=4/3 and 1/1 otherwise. VhMeta's twin fields ride along so the plugin ABI can carry the same answer once a display size differs from the coded one. --- crates/engine/src/demux.rs | 200 ++++++++++++++++++++++++++-- crates/engine/src/export.rs | 10 ++ crates/engine/src/playback.rs | 25 ++++ crates/engine/src/proxy.rs | 47 +++++-- crates/engine/tests/audio_export.rs | 65 ++++++--- crates/engine/tests/export.rs | 5 + scripts/memguard-runner.sh | 21 +++ 7 files changed, 335 insertions(+), 38 deletions(-) create mode 100755 scripts/memguard-runner.sh diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 6329f57..420b97a 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,27 @@ 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 aspect + // widens the *coded* frame (180x320 at SAR 4/3 is drawn 240x320 -- + // ffprobe's own `display_aspect_ratio` of such a file, measured), then + // the quarter turn swaps that stretched pair the way it swaps the + // coded one. The other order is a different picture: 320x180 then + // widened by 4/3 lands at 426x180, and a pixel's drawn shape turns + // with the picture it belongs to. The SAR only ever widens a width, + // never a height; the displayed height is the coded one without a + // turn and the stretched coded width with one. The coded pair stays + // what the decoder hands back, and carries on to + // [`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 +2095,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 +2249,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 +2521,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 +2551,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 +2698,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 +2901,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 +4146,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..fbad59d 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -5488,6 +5488,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 +5545,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/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/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/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 \ + -- "$@"