forge
Explore
Log in

Don't you dare go Hollow

probe(demux): sample aspect ratio off the container, coded dims beside the display pair

Browse files at this commit

66a1c405140f4b42a93d97dd87152c87cee31b09Ahmet Kaan GümüşParent: e5b5971
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.rsmodified+190 -10
@@ -357,13 +357,74 @@ impl UnsupportedRotation {
357357 }
358358 }
359359
360+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
361+pub struct PixelAspect {
362+ /// Horizontal sample size: the width a coded pixel is drawn at, relative to
363+ /// [`PixelAspect::v`]. 1 and 1 together are square pixels, which is every
364+ /// file that states no aspect anywhere in its container.
365+ pub h: u32,
366+ /// The vertical half of the same ratio; zero means the container said
367+ /// nothing usable and the pixels are square.
368+ pub v: u32,
369+}
370+
371+impl PixelAspect {
372+ /// The square pixels everything before anamorphic sources was.
373+ pub const SQUARE: Self = Self { h: 1, v: 1 };
374+
375+ /// Whether the displayed picture is the coded one, drawn one to one.
376+ pub fn is_square(self) -> bool {
377+ // An unstated ratio (0) and a stated 1:1 are the same pixels, and a
378+ // degenerate one a crafted header claimed is square rather than a
379+ // division by zero.
380+ self.v == 0 || self.h == self.v
381+ }
382+
383+ /// How many coded columns one displayed column is worth: the factor the
384+ /// width is stretched by, exactly as swscale takes it. 1 for square.
385+ ///
386+ /// Rounded to the even grid 4:2:0 composes on, so a ratio that is not a
387+ /// whole number of columns still lands on a picture the chroma planes
388+ /// cover -- the same rounding swscale applies, and the same one that keeps
389+ /// the stretch a whole-sample operation rather than a smear.
390+ pub fn width_factor(self, coded_width: u32) -> u32 {
391+ if self.is_square() {
392+ return coded_width;
393+ }
394+ // (coded * h / v), rounded up to even: 1440 at 4:3 gives 1920 exactly,
395+ // and a ratio that does not divide evenly is widened to the nearest
396+ // even column count rather than shown cropped or squeezed.
397+ let wide = u64::from(coded_width) * u64::from(self.h);
398+ (((wide + u64::from(self.v) - 1) / u64::from(self.v)) as u32 | 1) & !1
399+ }
400+}
401+
360402 #[derive(Debug, Clone, Copy, PartialEq)]
361403 pub struct VideoMeta {
362404 /// The displayed width: the coded one, swapped where the file's display
363- /// matrix is a 90- or 270-degree turn (see [`Rotation`]).
405+ /// matrix is a 90- or 270-degree turn (see [`Rotation`]) *and* stretched
406+ /// where the file's pixel aspect is not square (see [`PixelAspect`]) -- the
407+ /// size a player draws the picture at, which is what a timeline is cut in.
408+ /// The picture as stored is [`VideoMeta::coded_width`] by
409+ /// [`VideoMeta::coded_height`].
364410 pub width: u32,
365- /// The displayed height; see [`VideoMeta::width`].
411+ /// The displayed height; see [`VideoMeta::width`]. The aspect never touches
412+ /// it: a non-square pixel stretches the width, always -- 4:3 SAR over
413+ /// 1440x1080 displays 1920x1080, and the height is the coded one either way.
366414 pub height: u32,
415+ /// The size the samples are stored at, before the display-matrix turn and
416+ /// the pixel stretch: what a decoder hands back, what a copy carries, and
417+ /// the shape every container header of a *copied* file has to declare. The
418+ /// displayed pair above is derived; this one is read.
419+ pub coded_width: u32,
420+ /// The stored height; see [`VideoMeta::coded_width`].
421+ pub coded_height: u32,
422+ /// The sample aspect ratio the container states, square where it states
423+ /// none. Metadata about the pixels, like [`VideoMeta::rotation`] is about
424+ /// their orientation: the decode keeps the coded pixels and everything
425+ /// downstream is told the ratio, which is what applies it exactly once --
426+ /// at the conversion to the square-pixel raster.
427+ pub pixel_aspect: PixelAspect,
367428 pub frame_rate: f64,
368429 pub frame_count: u32,
369430 pub codec: Codec,
@@ -856,13 +917,23 @@ impl Mp4Demuxer {
856917 None => Rotation::None,
857918 };
858919 let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height()));
920+ // The ratio one coded pixel is drawn at, off the sample entry's `pasp`
921+ // box: absent for the square-pixel file, which is the common case.
922+ let pixel_aspect = pasp_of(path, track_id);
923+ // The aspect widens the *coded* frame, then the turn swaps that
924+ // stretched pair the way it swaps the coded one (`pixel_aspect_of`'s
925+ // twin comment in the Matroska door carries the measured proof). The
926+ // SAR only ever widens a width, never a height.
859927 let (width, height) = match rotation.swaps_axes() {
860- true => (coded_h, coded_w),
861- false => (coded_w, coded_h),
928+ true => (coded_h, pixel_aspect.width_factor(coded_w)),
929+ false => (pixel_aspect.width_factor(coded_w), coded_h),
862930 };
863931 let meta = VideoMeta {
864932 width,
865933 height,
934+ coded_width: coded_w,
935+ coded_height: coded_h,
936+ pixel_aspect,
866937 frame_rate: frame_rate(track),
867938 frame_count: 0,
868939 codec,
@@ -1313,17 +1384,27 @@ impl MkvDemuxer {
13131384 }
13141385 }
13151386 };
1316- // The coded size, swapped where the turn is a quarter one: a portrait
1317- // `.mkv` stores a landscape picture plus the turn, so the displayed
1318- // shape is the coded one turned -- the same two numbers the mp4 door
1319- // swaps, off the same kind of turn.
1387+ // The displayed shape, in the order the two facts compose: the aspect
1388+ // widens the *coded* frame (180x320 at SAR 4/3 is drawn 240x320 --
1389+ // ffprobe's own `display_aspect_ratio` of such a file, measured), then
1390+ // the quarter turn swaps that stretched pair the way it swaps the
1391+ // coded one. The other order is a different picture: 320x180 then
1392+ // widened by 4/3 lands at 426x180, and a pixel's drawn shape turns
1393+ // with the picture it belongs to. The SAR only ever widens a width,
1394+ // never a height; the displayed height is the coded one without a
1395+ // turn and the stretched coded width with one. The coded pair stays
1396+ // what the decoder hands back, and carries on to
1397+ // [`VideoMeta::coded_width`]/[`VideoMeta::coded_height`].
13201398 let (width, height) = match video.rotation.swaps_axes() {
1321- true => (video.height, video.width),
1322- false => (video.width, video.height),
1399+ true => (video.height, video.pixel_aspect.width_factor(video.width)),
1400+ false => (video.pixel_aspect.width_factor(video.width), video.height),
13231401 };
13241402 let meta = VideoMeta {
13251403 width,
13261404 height,
1405+ coded_width: video.width,
1406+ coded_height: video.height,
1407+ pixel_aspect: video.pixel_aspect,
13271408 frame_rate,
13281409 frame_count: mkv.frames as u32,
13291410 codec: video.codec,
@@ -2014,6 +2095,10 @@ struct MkvVideo {
20142095 number: u64,
20152096 width: u32,
20162097 height: u32,
2098+ /// The sample aspect ratio the track's `Display*` elements state, square
2099+ /// where they state none ([`PixelAspect::SQUARE`]) -- the same reading
2100+ /// every Matroska reader makes of their absence.
2101+ pixel_aspect: PixelAspect,
20172102 /// The quarter turn the track's `Projection` asks for;
20182103 /// [`Rotation::None`] where it states none.
20192104 rotation: Rotation,
@@ -2164,6 +2249,14 @@ const DEFAULT_DURATION: u32 = 0x23E383;
21642249 const VIDEO: u32 = 0xE0;
21652250 const PIXEL_WIDTH: u32 = 0xB0;
21662251 const PIXEL_HEIGHT: u32 = 0xBA;
2252+// How the picture is drawn: Matroska carries the aspect as a `Display*` pair
2253+// in *display units* (0x54B2) -- 0 pixels, 1 centimetres, 2 inches, 3 a display
2254+// aspect ratio, 4 the sample aspect ratio itself. Absent, the pixels are the
2255+// coded ones: every square-pixel file states none of these, which is what makes
2256+// their absence the square answer rather than an error.
2257+const DISPLAY_WIDTH: u32 = 0x54B0;
2258+const DISPLAY_HEIGHT: u32 = 0x54BA;
2259+const DISPLAY_UNIT: u32 = 0x54B2;
21672260 // The track's projection: how the flat picture sits in space. A roll on the
21682261 // rectangular projection (type 0) is how a Matroska muxer states what an mp4
21692262 // states with its `tkhd` matrix -- mkvmerge has translated display matrices
@@ -2428,6 +2521,9 @@ fn mkv_track_entry(
24282521 ) -> crate::Result<MkvEntry> {
24292522 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
24302523 let (mut width, mut height, mut config) = (0, 0, Vec::new());
2524+ // The `Display*` elements: unstated for the square-pixel file, which is
2525+ // most of them.
2526+ let (mut display_width, mut display_height, mut display_unit) = (0u64, 0u64, 0u64);
24312527 let mut rotation = Rotation::None;
24322528 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
24332529 let mut tags = Tags::default();
@@ -2455,6 +2551,9 @@ fn mkv_track_entry(
24552551 match e.0 {
24562552 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
24572553 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,
2554+ DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?,
2555+ DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?,
2556+ DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?,
24582557 PROJECTION => {
24592558 let (mut kind, mut yaw, mut pitch, mut roll) =
24602559 (0u64, 0.0f64, 0.0f64, 0.0f64);
@@ -2599,6 +2698,13 @@ fn mkv_track_entry(
25992698 number,
26002699 width,
26012700 height,
2701+ pixel_aspect: pixel_aspect_of(
2702+ display_width,
2703+ display_height,
2704+ display_unit,
2705+ width,
2706+ height,
2707+ ),
26022708 rotation,
26032709 tags,
26042710 light,
@@ -2795,6 +2901,53 @@ fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> {
27952901 /// quarter turn here can make -- the same missing capability the mp4 door
27962902 /// refuses a 45-degree matrix for, so it gets the same refusal rather than a
27972903 /// sideways picture.
2904+
2905+/// The sample aspect ratio a Matroska `TrackEntry`'s `Video` element states,
2906+/// from its `DisplayWidth`/`DisplayHeight`/`DisplayUnit` children and the coded
2907+/// size beside them.
2908+///
2909+/// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and
2910+/// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured),
2911+/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where
2912+/// a pair beside the coded one at all means a crop, not an aspect. 1 and 2
2913+/// (centimetres, inches) are physical sizes a picture this engine shows cannot
2914+/// mean anything by, and read as square rather than guessed. Every unstated or
2915+/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's
2916+/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the
2917+/// PixelWidth and PixelHeight" when they mean the same thing, so a file that
2918+/// means square most often says nothing at all.
2919+fn pixel_aspect_of(
2920+ display_width: u64,
2921+ display_height: u64,
2922+ display_unit: u64,
2923+ coded_width: u32,
2924+ coded_height: u32,
2925+) -> PixelAspect {
2926+ // A zero pair (unstated, or a header that lies about it) and a zero coded
2927+ // size are all square: there is nothing to divide by and nothing to stretch.
2928+ if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 {
2929+ return PixelAspect::SQUARE;
2930+ }
2931+ match display_unit {
2932+ // 4: the pair *is* the sample aspect ratio.
2933+ 4 => PixelAspect {
2934+ h: display_width.min(u32::MAX as u64) as u32,
2935+ v: display_height.min(u32::MAX as u64) as u32,
2936+ },
2937+ // 3: the pair is the display aspect ratio -- display_w / display_h --
2938+ // which the SAR is that against the coded one: sar = dar * h / w.
2939+ // 16/9 over 1440x1080 lands on 4/3.
2940+ 3 => PixelAspect {
2941+ h: ((display_width * u64::from(coded_height))
2942+ .min(u32::MAX as u64 * u64::from(coded_width))) as u32,
2943+ v: ((display_height * u64::from(coded_width))
2944+ .min(u32::MAX as u64 * u64::from(coded_height))) as u32,
2945+ },
2946+ // Pixels (0) or a physical unit this engine cannot interpret: square.
2947+ _ => PixelAspect::SQUARE,
2948+ }
2949+}
2950+
27982951 fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> {
27992952 if kind != 0 {
28002953 return Ok(Rotation::None);
@@ -3993,6 +4146,33 @@ fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
39934146 Some(Tags::from_codes(code(8)?, code(6)?, range))
39944147 }
39954148
4149+/// The `pasp` box of `track_id`'s sample entry (ISO/IEC 14496-12 §6.2.3, the
4150+/// pixel aspect ratio box a visual sample entry may carry): two 32-bit
4151+/// big-endian integers, hSpacing then vSpacing, the ratio one coded pixel is
4152+/// drawn at. ffmpeg writes it for a `setsar=4/3` source and writes 1/1 for a
4153+/// square one (both measured); a box absent -- most mp4s there are -- is square
4154+/// pixels, the same answer Matroska's absent `Display*` elements give.
4155+///
4156+/// [`None`] rather than an error for a file with no such box, which is most of
4157+/// them -- an untagged mp4 is not a broken one.
4158+fn pasp_of(path: &Path, track_id: u32) -> PixelAspect {
4159+ let Ok((_, entry)) = sample_entry(path, track_id) else {
4160+ return PixelAspect::SQUARE;
4161+ };
4162+ // The same fixed 78-byte VisualSampleEntry header `colr` and `hvcC` sit
4163+ // behind; `pasp` is one of their siblings.
4164+ let Some(pasp) = child(entry.get(78..).unwrap_or_default(), b"pasp") else {
4165+ return PixelAspect::SQUARE;
4166+ };
4167+ let (Some(h), Some(v)) = (
4168+ pasp.get(..4).map(|b| u32::from_be_bytes(b.try_into().unwrap())),
4169+ pasp.get(4..8).map(|b| u32::from_be_bytes(b.try_into().unwrap())),
4170+ ) else {
4171+ return PixelAspect::SQUARE;
4172+ };
4173+ PixelAspect { h, v }
4174+}
4175+
39964176 /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
39974177 /// about how bright its pictures get, beside the `colr` that says what their
39984178 /// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI
crates/engine/src/export.rsmodified+10 -0
@@ -5488,6 +5488,11 @@ mod tests {
54885488 codec: crate::demux::Codec::H264,
54895489 color: Default::default(),
54905490 rotation: Rotation::None,
5491+ // Square pixels, coded where they are declared: a meta no container
5492+ // wrote, so nothing was read to disagree with it.
5493+ coded_width: width,
5494+ coded_height: height,
5495+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
54915496 };
54925497 // 1280 * 720 * 30 * 0.1
54935498 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
@@ -5540,6 +5545,11 @@ mod tests {
55405545 codec: crate::demux::Codec::H264,
55415546 color: Default::default(),
55425547 rotation: Rotation::None,
5548+ // Square pixels, coded where they are declared: a meta no
5549+ // container wrote, so nothing was read to disagree with it.
5550+ coded_width: width,
5551+ coded_height: height,
5552+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
55435553 }
55445554 }
55455555
crates/engine/src/playback.rsmodified+25 -0
@@ -729,6 +729,11 @@ impl PlaybackSession {
729729 // the default description is what it is drawn in.
730730 color: ColorDescription::default(),
731731 rotation: Rotation::None,
732+ // No container said anything about these: the canvas this engine drew
733+ // itself is square pixels at the size it was drawn at.
734+ coded_width: width,
735+ coded_height: height,
736+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
732737 };
733738 let (audio, audio_disabled) = open_audio(path, stream);
734739 // Through `from_parts` rather than `Project::single`, which is the
@@ -827,6 +832,11 @@ impl PlaybackSession {
827832 codec: Codec::H264,
828833 color: ColorDescription::default(),
829834 rotation: Rotation::None,
835+ // No container said anything about these: the picture this engine
836+ // decoded itself is square pixels at the size it was decoded at.
837+ coded_width: still.width,
838+ coded_height: still.height,
839+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
830840 };
831841 let clip = Clip {
832842 fade_in: 0,
@@ -991,6 +1001,11 @@ impl PlaybackSession {
9911001 codec: Codec::H264,
9921002 color: ColorDescription::default(),
9931003 rotation: Rotation::None,
1004+ // No container said anything about these: the canvas this engine drew
1005+ // itself is square pixels at the size it was drawn at.
1006+ coded_width: width,
1007+ coded_height: height,
1008+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
9941009 };
9951010 (meta, DecodeSession::open_black(width, height, 1))
9961011 }
@@ -1009,6 +1024,11 @@ impl PlaybackSession {
10091024 codec: Codec::H264,
10101025 color: ColorDescription::default(),
10111026 rotation: Rotation::None,
1027+ // No container said anything about these: the picture this
1028+ // engine decoded itself is square pixels at its own size.
1029+ coded_width: still.width,
1030+ coded_height: still.height,
1031+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
10121032 };
10131033 let stream = DecodeSession::open_still(
10141034 &first.path,
@@ -1051,6 +1071,11 @@ impl PlaybackSession {
10511071 codec: Codec::H264,
10521072 color: ColorDescription::default(),
10531073 rotation: Rotation::None,
1074+ // No container said anything about these: the canvas this engine drew
1075+ // itself is square pixels at the size it was drawn at.
1076+ coded_width: width,
1077+ coded_height: height,
1078+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
10541079 };
10551080 (meta, DecodeSession::open_black(width, height, 1))
10561081 }
crates/engine/src/proxy.rsmodified+36 -11
@@ -32,8 +32,8 @@
3232 //! cancel a file export has ([`Job`]).
3333
3434 use std::path::{Path, PathBuf};
35-use std::sync::Arc;
3635 use std::sync::atomic::AtomicBool;
36+use std::sync::Arc;
3737 use std::time::UNIX_EPOCH;
3838
3939 use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
@@ -127,7 +127,10 @@ pub fn path_for(source: &Path) -> Option<PathBuf> {
127127 let meta = std::fs::metadata(source).ok()?;
128128 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
129129 Ok(d) => (d.as_secs() as i128, d.subsec_nanos()),
130- Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()),
130+ Err(e) => (
131+ -(e.duration().as_secs() as i128),
132+ e.duration().subsec_nanos(),
133+ ),
131134 };
132135 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
133136 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
@@ -542,7 +545,10 @@ fn started(
542545 // it: sweeping to the bare cap left the finished ones filling it and
543546 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that
544547 // is over by a whole film's worth by construction ([`reserve`]).
545- sweep(dir, CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)));
548+ sweep(
549+ dir,
550+ CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)),
551+ );
546552 }
547553 // What a killed editor left behind: the export worker deletes its own part
548554 // file when it is cancelled or fails, but nothing can delete it for a
@@ -579,8 +585,7 @@ fn started(
579585 Vec::new(),
580586 Vec::new(),
581587 )?;
582- let bitrate =
583- (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
588+ let bitrate = (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
584589 let handle = crate::export::start(
585590 project,
586591 VideoMeta {
@@ -632,6 +637,11 @@ mod tests {
632637 codec,
633638 color: ColorDescription::default(),
634639 rotation: Rotation::None,
640+ // Square pixels, coded where they are declared: a meta no
641+ // container wrote, so nothing was read to disagree with it.
642+ coded_width: width,
643+ coded_height: height,
644+ pixel_aspect: crate::demux::PixelAspect::SQUARE,
635645 }
636646 }
637647
@@ -714,10 +724,17 @@ mod tests {
714724 // order of their own, and the order is what is under test. `atime`
715725 // is what `sweep` reads and `set_times` is the one door to it
716726 // without a dependency.
717- let file = std::fs::File::options().write(true).open(&path).expect("open");
727+ let file = std::fs::File::options()
728+ .write(true)
729+ .open(&path)
730+ .expect("open");
718731 let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago);
719- file.set_times(std::fs::FileTimes::new().set_accessed(when).set_modified(when))
720- .expect("stamp");
732+ file.set_times(
733+ std::fs::FileTimes::new()
734+ .set_accessed(when)
735+ .set_modified(when),
736+ )
737+ .expect("stamp");
721738 path
722739 };
723740 let old = write("old.mp4", 400, 300);
@@ -732,7 +749,10 @@ mod tests {
732749 assert!(!old.exists(), "the oldest stand-in survived the sweep");
733750 assert!(!middle.exists(), "the next oldest survived it");
734751 assert!(fresh.exists(), "the freshest was taken");
735- assert!(part.exists(), "a half-written proxy was deleted under its writer");
752+ assert!(
753+ part.exists(),
754+ "a half-written proxy was deleted under its writer"
755+ );
736756 assert_eq!(left, 800, "what is left is the fresh one and the part file");
737757
738758 // Under the cap, nothing is touched at all.
@@ -897,7 +917,10 @@ mod tests {
897917 // is a stand-in still on the disk, and it is answered as one.
898918 let answer = delete(&file);
899919 assert!(answer.is_err(), "a refused unlink reported as a delete");
900- assert!(proxy.is_dir(), "and what could not be deleted is still there");
920+ assert!(
921+ proxy.is_dir(),
922+ "and what could not be deleted is still there"
923+ );
901924 std::fs::remove_dir(&proxy).expect("clean up");
902925 // ...against the honest no-op, which *is* an off switch: nothing there.
903926 assert_eq!(delete(&file).ok(), Some(false), "nothing to take");
@@ -952,7 +975,9 @@ mod tests {
952975 let cancel = Arc::new(AtomicBool::new(true));
953976
954977 let answer = generate_if_wanted(&file, &cancel);
955- let err = answer.err().expect("a pre-cancelled ask must not hand back a job");
978+ let err = answer
979+ .err()
980+ .expect("a pre-cancelled ask must not hand back a job");
956981 assert!(
957982 crate::demux::is_cancelled(&err),
958983 "not the cancelled answer: {err}"
crates/engine/tests/audio_export.rsmodified+48 -17
@@ -379,6 +379,11 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() {
379379 codec: engine::Codec::H264,
380380 color: Default::default(),
381381 rotation: Rotation::None,
382+ // Square pixels, coded where they are declared: a meta no container
383+ // wrote, so nothing was read to disagree with it.
384+ coded_width: 640,
385+ coded_height: 360,
386+ pixel_aspect: engine::demux::PixelAspect::SQUARE,
382387 };
383388 let out = out_path("still_song", "mp4");
384389 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() {
440445 ],
441446 Vec::new(),
442447 Vec::new(),
443- Vec::new(),
444- )
448+ Vec::new(),
449+ )
445450 .expect("one second on four audio tracks")
446451 };
447452 let write = |project: Project, name: &str| {
@@ -454,8 +459,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() {
454459 format: Format::Wav,
455460 ..Default::default()
456461 },
457- None,
458- );
462+ None,
463+ );
459464 wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));
460465 let (audio, samples) = decode(&out);
461466 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() {
630635 audio_kbps: kbps,
631636 ..Default::default()
632637 },
633- None,
634- );
638+ None,
639+ );
635640 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
636641 let got = mp3_declared_kbps(&out);
637642 println!("mp3 asked {kbps:?}, header says {got} kbps");
@@ -706,6 +711,11 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() {
706711 codec: engine::Codec::H264,
707712 color: Default::default(),
708713 rotation: Rotation::None,
714+ // Square pixels, coded where they are declared: a meta no container
715+ // wrote, so nothing was read to disagree with it.
716+ coded_width: 640,
717+ coded_height: 360,
718+ pixel_aspect: engine::demux::PixelAspect::SQUARE,
709719 };
710720 for want in [128u32, 320] {
711721 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() {
717727 audio_kbps: Some(want),
718728 ..Default::default()
719729 },
720- None,
721- );
730+ None,
731+ );
722732 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
723733 let got = mp4_aac_kbps(&out, f64::from(RATE));
724734 println!("mp4 asked {want} kbps, the track measures {got:.1}");
@@ -859,7 +869,9 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
859869 Vec::new(),
860870 )
861871 .expect("a one-source AC-3 project");
862- let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0;
872+ let video = engine::demux::Demuxer::open(&source)
873+ .expect("open the fixture")
874+ .0;
863875
864876 let out = out_path("ac3", "wav");
865877 let handle = engine::export::start(
@@ -881,11 +893,20 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
881893 "the §7.8 downmix is what reaches the file"
882894 );
883895 let secs = (samples.len() / 2) as f64 / 48_000.;
884- assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s");
885- let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
896+ assert!(
897+ (0.9..1.1).contains(&secs),
898+ "one second of clip, got {secs:.3}s"
899+ );
900+ let energy = (samples
901+ .iter()
902+ .map(|s| f64::from(*s) * f64::from(*s))
903+ .sum::<f64>()
886904 / samples.len() as f64)
887905 .sqrt();
888- assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}");
906+ assert!(
907+ energy > 0.005,
908+ "the exported AC-3 is silence: RMS {energy:.6}"
909+ );
889910 std::fs::remove_file(&out).unwrap();
890911 }
891912
@@ -1004,6 +1025,11 @@ fn a_fade_in_reaches_the_exported_audio() {
10041025 codec: engine::Codec::H264,
10051026 color: Default::default(),
10061027 rotation: Rotation::None,
1028+ // Square pixels, coded where they are declared: a meta no container
1029+ // wrote, so nothing was read to disagree with it.
1030+ coded_width: 640,
1031+ coded_height: 360,
1032+ pixel_aspect: engine::demux::PixelAspect::SQUARE,
10071033 };
10081034 let out = out_path("fadein", "wav");
10091035 let handle = engine::export::start(
@@ -1034,7 +1060,10 @@ fn a_fade_in_reaches_the_exported_audio() {
10341060 start < body * 0.1,
10351061 "the very start is quiet: {start:.4} vs body {body:.4}"
10361062 );
1037- assert!(quarter < half, "the envelope rises: {quarter:.4} -> {half:.4}");
1063+ assert!(
1064+ quarter < half,
1065+ "the envelope rises: {quarter:.4} -> {half:.4}"
1066+ );
10381067 assert!(
10391068 half < near_end,
10401069 "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() {
10801109 // exactly what `Project::split` leaves behind.
10811110 let mut project = Project::from_parts(
10821111 vec![Source::new(src.to_path_buf(), 0)],
1083- vec![(
1084- LaneKind::Audio,
1085- vec![clip(0, 0, 45), clip(45, 45, 90)],
1086- )],
1112+ vec![(LaneKind::Audio, vec![clip(0, 0, 45), clip(45, 45, 90)])],
10871113 Vec::new(),
10881114 Vec::new(),
10891115 Vec::new(),
@@ -1101,6 +1127,11 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() {
11011127 codec: engine::Codec::H264,
11021128 color: Default::default(),
11031129 rotation: Rotation::None,
1130+ // Square pixels, coded where they are declared: a meta no container
1131+ // wrote, so nothing was read to disagree with it.
1132+ coded_width: 640,
1133+ coded_height: 360,
1134+ pixel_aspect: engine::demux::PixelAspect::SQUARE,
11041135 };
11051136 let out = out_path("crossfade", "wav");
11061137 let handle = engine::export::start(
crates/engine/tests/export.rsmodified+5 -0
@@ -278,6 +278,11 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() {
278278 codec: engine::Codec::H264,
279279 color: Default::default(),
280280 rotation: Rotation::None,
281+ // Square pixels, coded where they are declared: a meta no container
282+ // wrote, so nothing was read to disagree with it.
283+ coded_width: 960,
284+ coded_height: 720,
285+ pixel_aspect: engine::demux::PixelAspect::SQUARE,
281286 };
282287 let out = out_path("mixed");
283288 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
scripts/memguard-runner.shadded+21 -0
@@ -0,0 +1,21 @@
1+#!/usr/bin/env bash
2+# Wraps a test/bin invocation in a transient user cgroup scope so a runaway
3+# allocation dies inside its own cgroup instead of triggering a machine-wide
4+# OOM kill. Used as the cargo target runner (see .cargo/config.toml) so every
5+# `cargo test`/`cargo run` invocation of this workspace is capped, from any
6+# checkout (main repo or worktree).
7+set -euo pipefail
8+
9+if [ "${EC_NOMEMGUARD:-0}" = "1" ]; then
10+ echo "memguard-runner: EC_NOMEMGUARD=1, running without memory cap" >&2
11+ exec "$@"
12+fi
13+
14+if ! systemd-run --user --scope --quiet -p MemoryMax=10G true >/dev/null 2>&1; then
15+ echo "memguard-runner: systemd-run --user --scope unavailable, running without memory cap" >&2
16+ exec "$@"
17+fi
18+
19+exec systemd-run --user --scope --quiet --same-dir \
20+ -p MemoryMax=10G -p MemorySwapMax=2G \
21+ -- "$@"