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 {
357 }357 }
358 }358 }
359 359
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+
360 #[derive(Debug, Clone, Copy, PartialEq)]402 #[derive(Debug, Clone, Copy, PartialEq)]
361 pub struct VideoMeta {403 pub struct VideoMeta {
362 /// The displayed width: the coded one, swapped where the file's display404 /// 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`].
364 pub width: u32,410 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.
366 pub height: u32,414 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,
367 pub frame_rate: f64,428 pub frame_rate: f64,
368 pub frame_count: u32,429 pub frame_count: u32,
369 pub codec: Codec,430 pub codec: Codec,
@@ -856,13 +917,23 @@ impl Mp4Demuxer {
856 None => Rotation::None,917 None => Rotation::None,
857 };918 };
858 let (coded_w, coded_h) = (u32::from(track.width()), u32::from(track.height()));919 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.
859 let (width, height) = match rotation.swaps_axes() {927 let (width, height) = match rotation.swaps_axes() {
860- true => (coded_h, coded_w),928+ true => (coded_h, pixel_aspect.width_factor(coded_w)),
861- false => (coded_w, coded_h),929+ false => (pixel_aspect.width_factor(coded_w), coded_h),
862 };930 };
863 let meta = VideoMeta {931 let meta = VideoMeta {
864 width,932 width,
865 height,933 height,
934+ coded_width: coded_w,
935+ coded_height: coded_h,
936+ pixel_aspect,
866 frame_rate: frame_rate(track),937 frame_rate: frame_rate(track),
867 frame_count: 0,938 frame_count: 0,
868 codec,939 codec,
@@ -1313,17 +1384,27 @@ impl MkvDemuxer {
1313 }1384 }
1314 }1385 }
1315 };1386 };
1316- // The coded size, swapped where the turn is a quarter one: a portrait1387+ // The displayed shape, in the order the two facts compose: the aspect
1317- // `.mkv` stores a landscape picture plus the turn, so the displayed1388+ // widens the *coded* frame (180x320 at SAR 4/3 is drawn 240x320 --
1318- // shape is the coded one turned -- the same two numbers the mp4 door1389+ // ffprobe's own `display_aspect_ratio` of such a file, measured), then
1319- // swaps, off the same kind of turn.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`].
1320 let (width, height) = match video.rotation.swaps_axes() {1398 let (width, height) = match video.rotation.swaps_axes() {
1321- true => (video.height, video.width),1399+ true => (video.height, video.pixel_aspect.width_factor(video.width)),
1322- false => (video.width, video.height),1400+ false => (video.pixel_aspect.width_factor(video.width), video.height),
1323 };1401 };
1324 let meta = VideoMeta {1402 let meta = VideoMeta {
1325 width,1403 width,
1326 height,1404 height,
1405+ coded_width: video.width,
1406+ coded_height: video.height,
1407+ pixel_aspect: video.pixel_aspect,
1327 frame_rate,1408 frame_rate,
1328 frame_count: mkv.frames as u32,1409 frame_count: mkv.frames as u32,
1329 codec: video.codec,1410 codec: video.codec,
@@ -2014,6 +2095,10 @@ struct MkvVideo {
2014 number: u64,2095 number: u64,
2015 width: u32,2096 width: u32,
2016 height: u32,2097 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,
2017 /// The quarter turn the track's `Projection` asks for;2102 /// The quarter turn the track's `Projection` asks for;
2018 /// [`Rotation::None`] where it states none.2103 /// [`Rotation::None`] where it states none.
2019 rotation: Rotation,2104 rotation: Rotation,
@@ -2164,6 +2249,14 @@ const DEFAULT_DURATION: u32 = 0x23E383;
2164 const VIDEO: u32 = 0xE0;2249 const VIDEO: u32 = 0xE0;
2165 const PIXEL_WIDTH: u32 = 0xB0;2250 const PIXEL_WIDTH: u32 = 0xB0;
2166 const PIXEL_HEIGHT: u32 = 0xBA;2251 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;
2167 // The track's projection: how the flat picture sits in space. A roll on the2260 // The track's projection: how the flat picture sits in space. A roll on the
2168 // rectangular projection (type 0) is how a Matroska muxer states what an mp42261 // rectangular projection (type 0) is how a Matroska muxer states what an mp4
2169 // states with its `tkhd` matrix -- mkvmerge has translated display matrices2262 // states with its `tkhd` matrix -- mkvmerge has translated display matrices
@@ -2428,6 +2521,9 @@ fn mkv_track_entry(
2428 ) -> crate::Result<MkvEntry> {2521 ) -> crate::Result<MkvEntry> {
2429 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);2522 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
2430 let (mut width, mut height, mut config) = (0, 0, Vec::new());2523 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);
2431 let mut rotation = Rotation::None;2527 let mut rotation = Rotation::None;
2432 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());2528 let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new());
2433 let mut tags = Tags::default();2529 let mut tags = Tags::default();
@@ -2455,6 +2551,9 @@ fn mkv_track_entry(
2455 match e.0 {2551 match e.0 {
2456 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,2552 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
2457 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,2553 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)?,
2458 PROJECTION => {2557 PROJECTION => {
2459 let (mut kind, mut yaw, mut pitch, mut roll) =2558 let (mut kind, mut yaw, mut pitch, mut roll) =
2460 (0u64, 0.0f64, 0.0f64, 0.0f64);2559 (0u64, 0.0f64, 0.0f64, 0.0f64);
@@ -2599,6 +2698,13 @@ fn mkv_track_entry(
2599 number,2698 number,
2600 width,2699 width,
2601 height,2700 height,
2701+ pixel_aspect: pixel_aspect_of(
2702+ display_width,
2703+ display_height,
2704+ display_unit,
2705+ width,
2706+ height,
2707+ ),
2602 rotation,2708 rotation,
2603 tags,2709 tags,
2604 light,2710 light,
@@ -2795,6 +2901,53 @@ fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> {
2795 /// quarter turn here can make -- the same missing capability the mp4 door2901 /// quarter turn here can make -- the same missing capability the mp4 door
2796 /// refuses a 45-degree matrix for, so it gets the same refusal rather than a2902 /// refuses a 45-degree matrix for, so it gets the same refusal rather than a
2797 /// sideways picture.2903 /// 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+
2798 fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> {2951 fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> {
2799 if kind != 0 {2952 if kind != 0 {
2800 return Ok(Rotation::None);2953 return Ok(Rotation::None);
@@ -3993,6 +4146,33 @@ fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
3993 Some(Tags::from_codes(code(8)?, code(6)?, range))4146 Some(Tags::from_codes(code(8)?, code(6)?, range))
3994 }4147 }
3995 4148
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+
3996 /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says4176 /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says
3997 /// about how bright its pictures get, beside the `colr` that says what their4177 /// about how bright its pictures get, beside the `colr` that says what their
3998 /// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI4178 /// 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 {
5488 codec: crate::demux::Codec::H264,5488 codec: crate::demux::Codec::H264,
5489 color: Default::default(),5489 color: Default::default(),
5490 rotation: Rotation::None,5490 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,
5491 };5496 };
5492 // 1280 * 720 * 30 * 0.15497 // 1280 * 720 * 30 * 0.1
5493 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);5498 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
@@ -5540,6 +5545,11 @@ mod tests {
5540 codec: crate::demux::Codec::H264,5545 codec: crate::demux::Codec::H264,
5541 color: Default::default(),5546 color: Default::default(),
5542 rotation: Rotation::None,5547 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,
5543 }5553 }
5544 }5554 }
5545 5555
crates/engine/src/playback.rsmodified+25 -0
@@ -729,6 +729,11 @@ impl PlaybackSession {
729 // the default description is what it is drawn in.729 // the default description is what it is drawn in.
730 color: ColorDescription::default(),730 color: ColorDescription::default(),
731 rotation: Rotation::None,731 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,
732 };737 };
733 let (audio, audio_disabled) = open_audio(path, stream);738 let (audio, audio_disabled) = open_audio(path, stream);
734 // Through `from_parts` rather than `Project::single`, which is the739 // Through `from_parts` rather than `Project::single`, which is the
@@ -827,6 +832,11 @@ impl PlaybackSession {
827 codec: Codec::H264,832 codec: Codec::H264,
828 color: ColorDescription::default(),833 color: ColorDescription::default(),
829 rotation: Rotation::None,834 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,
830 };840 };
831 let clip = Clip {841 let clip = Clip {
832 fade_in: 0,842 fade_in: 0,
@@ -991,6 +1001,11 @@ impl PlaybackSession {
991 codec: Codec::H264,1001 codec: Codec::H264,
992 color: ColorDescription::default(),1002 color: ColorDescription::default(),
993 rotation: Rotation::None,1003 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,
994 };1009 };
995 (meta, DecodeSession::open_black(width, height, 1))1010 (meta, DecodeSession::open_black(width, height, 1))
996 }1011 }
@@ -1009,6 +1024,11 @@ impl PlaybackSession {
1009 codec: Codec::H264,1024 codec: Codec::H264,
1010 color: ColorDescription::default(),1025 color: ColorDescription::default(),
1011 rotation: Rotation::None,1026 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,
1012 };1032 };
1013 let stream = DecodeSession::open_still(1033 let stream = DecodeSession::open_still(
1014 &first.path,1034 &first.path,
@@ -1051,6 +1071,11 @@ impl PlaybackSession {
1051 codec: Codec::H264,1071 codec: Codec::H264,
1052 color: ColorDescription::default(),1072 color: ColorDescription::default(),
1053 rotation: Rotation::None,1073 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,
1054 };1079 };
1055 (meta, DecodeSession::open_black(width, height, 1))1080 (meta, DecodeSession::open_black(width, height, 1))
1056 }1081 }
crates/engine/src/proxy.rsmodified+36 -11
@@ -32,8 +32,8 @@
32 //! cancel a file export has ([`Job`]).32 //! cancel a file export has ([`Job`]).
33 33
34 use std::path::{Path, PathBuf};34 use std::path::{Path, PathBuf};
35-use std::sync::Arc;
36 use std::sync::atomic::AtomicBool;35 use std::sync::atomic::AtomicBool;
36+use std::sync::Arc;
37 use std::time::UNIX_EPOCH;37 use std::time::UNIX_EPOCH;
38 38
39 use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};39 use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
@@ -127,7 +127,10 @@ pub fn path_for(source: &Path) -> Option<PathBuf> {
127 let meta = std::fs::metadata(source).ok()?;127 let meta = std::fs::metadata(source).ok()?;
128 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {128 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
129 Ok(d) => (d.as_secs() as i128, d.subsec_nanos()),129 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+ ),
131 };134 };
132 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());135 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
133 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();136 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
@@ -542,7 +545,10 @@ fn started(
542 // it: sweeping to the bare cap left the finished ones filling it and545 // it: sweeping to the bare cap left the finished ones filling it and
543 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that546 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that
544 // is over by a whole film's worth by construction ([`reserve`]).547 // 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+ );
546 }552 }
547 // What a killed editor left behind: the export worker deletes its own part553 // What a killed editor left behind: the export worker deletes its own part
548 // file when it is cancelled or fails, but nothing can delete it for a554 // file when it is cancelled or fails, but nothing can delete it for a
@@ -579,8 +585,7 @@ fn started(
579 Vec::new(),585 Vec::new(),
580 Vec::new(),586 Vec::new(),
581 )?;587 )?;
582- let bitrate =588+ let bitrate = (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
583- (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
584 let handle = crate::export::start(589 let handle = crate::export::start(
585 project,590 project,
586 VideoMeta {591 VideoMeta {
@@ -632,6 +637,11 @@ mod tests {
632 codec,637 codec,
633 color: ColorDescription::default(),638 color: ColorDescription::default(),
634 rotation: Rotation::None,639 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,
635 }645 }
636 }646 }
637 647
@@ -714,10 +724,17 @@ mod tests {
714 // order of their own, and the order is what is under test. `atime`724 // order of their own, and the order is what is under test. `atime`
715 // is what `sweep` reads and `set_times` is the one door to it725 // is what `sweep` reads and `set_times` is the one door to it
716 // without a dependency.726 // 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");
718 let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago);731 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))732+ file.set_times(
720- .expect("stamp");733+ std::fs::FileTimes::new()
734+ .set_accessed(when)
735+ .set_modified(when),
736+ )
737+ .expect("stamp");
721 path738 path
722 };739 };
723 let old = write("old.mp4", 400, 300);740 let old = write("old.mp4", 400, 300);
@@ -732,7 +749,10 @@ mod tests {
732 assert!(!old.exists(), "the oldest stand-in survived the sweep");749 assert!(!old.exists(), "the oldest stand-in survived the sweep");
733 assert!(!middle.exists(), "the next oldest survived it");750 assert!(!middle.exists(), "the next oldest survived it");
734 assert!(fresh.exists(), "the freshest was taken");751 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+ );
736 assert_eq!(left, 800, "what is left is the fresh one and the part file");756 assert_eq!(left, 800, "what is left is the fresh one and the part file");
737 757
738 // Under the cap, nothing is touched at all.758 // Under the cap, nothing is touched at all.
@@ -897,7 +917,10 @@ mod tests {
897 // is a stand-in still on the disk, and it is answered as one.917 // is a stand-in still on the disk, and it is answered as one.
898 let answer = delete(&file);918 let answer = delete(&file);
899 assert!(answer.is_err(), "a refused unlink reported as a delete");919 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+ );
901 std::fs::remove_dir(&proxy).expect("clean up");924 std::fs::remove_dir(&proxy).expect("clean up");
902 // ...against the honest no-op, which *is* an off switch: nothing there.925 // ...against the honest no-op, which *is* an off switch: nothing there.
903 assert_eq!(delete(&file).ok(), Some(false), "nothing to take");926 assert_eq!(delete(&file).ok(), Some(false), "nothing to take");
@@ -952,7 +975,9 @@ mod tests {
952 let cancel = Arc::new(AtomicBool::new(true));975 let cancel = Arc::new(AtomicBool::new(true));
953 976
954 let answer = generate_if_wanted(&file, &cancel);977 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");
956 assert!(981 assert!(
957 crate::demux::is_cancelled(&err),982 crate::demux::is_cancelled(&err),
958 "not the cancelled answer: {err}"983 "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() {
379 codec: engine::Codec::H264,379 codec: engine::Codec::H264,
380 color: Default::default(),380 color: Default::default(),
381 rotation: Rotation::None,381 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,
382 };387 };
383 let out = out_path("still_song", "mp4");388 let out = out_path("still_song", "mp4");
384 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);389 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() {
440 ],445 ],
441 Vec::new(),446 Vec::new(),
442 Vec::new(),447 Vec::new(),
443- Vec::new(),448+ Vec::new(),
444- )449+ )
445 .expect("one second on four audio tracks")450 .expect("one second on four audio tracks")
446 };451 };
447 let write = |project: Project, name: &str| {452 let write = |project: Project, name: &str| {
@@ -454,8 +459,8 @@ fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() {
454 format: Format::Wav,459 format: Format::Wav,
455 ..Default::default()460 ..Default::default()
456 },461 },
457- None,462+ None,
458- );463+ );
459 wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));464 wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));
460 let (audio, samples) = decode(&out);465 let (audio, samples) = decode(&out);
461 let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));466 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() {
630 audio_kbps: kbps,635 audio_kbps: kbps,
631 ..Default::default()636 ..Default::default()
632 },637 },
633- None,638+ None,
634- );639+ );
635 wait(&handle, Duration::from_secs(120)).expect("mp3 export");640 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
636 let got = mp3_declared_kbps(&out);641 let got = mp3_declared_kbps(&out);
637 println!("mp3 asked {kbps:?}, header says {got} kbps");642 println!("mp3 asked {kbps:?}, header says {got} kbps");
@@ -706,6 +711,11 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() {
706 codec: engine::Codec::H264,711 codec: engine::Codec::H264,
707 color: Default::default(),712 color: Default::default(),
708 rotation: Rotation::None,713 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,
709 };719 };
710 for want in [128u32, 320] {720 for want in [128u32, 320] {
711 let out = out_path(&format!("mp4_aac_{want}"), "mp4");721 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() {
717 audio_kbps: Some(want),727 audio_kbps: Some(want),
718 ..Default::default()728 ..Default::default()
719 },729 },
720- None,730+ None,
721- );731+ );
722 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");732 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
723 let got = mp4_aac_kbps(&out, f64::from(RATE));733 let got = mp4_aac_kbps(&out, f64::from(RATE));
724 println!("mp4 asked {want} kbps, the track measures {got:.1}");734 println!("mp4 asked {want} kbps, the track measures {got:.1}");
@@ -859,7 +869,9 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
859 Vec::new(),869 Vec::new(),
860 )870 )
861 .expect("a one-source AC-3 project");871 .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;
863 875
864 let out = out_path("ac3", "wav");876 let out = out_path("ac3", "wav");
865 let handle = engine::export::start(877 let handle = engine::export::start(
@@ -881,11 +893,20 @@ fn a_51_ac3_source_round_trips_through_a_wav() {
881 "the §7.8 downmix is what reaches the file"893 "the §7.8 downmix is what reaches the file"
882 );894 );
883 let secs = (samples.len() / 2) as f64 / 48_000.;895 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");896+ assert!(
885- let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()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>()
886 / samples.len() as f64)904 / samples.len() as f64)
887 .sqrt();905 .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+ );
889 std::fs::remove_file(&out).unwrap();910 std::fs::remove_file(&out).unwrap();
890 }911 }
891 912
@@ -1004,6 +1025,11 @@ fn a_fade_in_reaches_the_exported_audio() {
1004 codec: engine::Codec::H264,1025 codec: engine::Codec::H264,
1005 color: Default::default(),1026 color: Default::default(),
1006 rotation: Rotation::None,1027 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,
1007 };1033 };
1008 let out = out_path("fadein", "wav");1034 let out = out_path("fadein", "wav");
1009 let handle = engine::export::start(1035 let handle = engine::export::start(
@@ -1034,7 +1060,10 @@ fn a_fade_in_reaches_the_exported_audio() {
1034 start < body * 0.1,1060 start < body * 0.1,
1035 "the very start is quiet: {start:.4} vs body {body:.4}"1061 "the very start is quiet: {start:.4} vs body {body:.4}"
1036 );1062 );
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+ );
1038 assert!(1067 assert!(
1039 half < near_end,1068 half < near_end,
1040 "the envelope keeps rising into the ramp's end: {half:.4} -> {near_end:.4}"1069 "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() {
1080 // exactly what `Project::split` leaves behind.1109 // exactly what `Project::split` leaves behind.
1081 let mut project = Project::from_parts(1110 let mut project = Project::from_parts(
1082 vec![Source::new(src.to_path_buf(), 0)],1111 vec![Source::new(src.to_path_buf(), 0)],
1083- vec![(1112+ vec![(LaneKind::Audio, vec![clip(0, 0, 45), clip(45, 45, 90)])],
1084- LaneKind::Audio,
1085- vec![clip(0, 0, 45), clip(45, 45, 90)],
1086- )],
1087 Vec::new(),1113 Vec::new(),
1088 Vec::new(),1114 Vec::new(),
1089 Vec::new(),1115 Vec::new(),
@@ -1101,6 +1127,11 @@ fn a_split_and_crossfaded_clip_has_no_muted_interior() {
1101 codec: engine::Codec::H264,1127 codec: engine::Codec::H264,
1102 color: Default::default(),1128 color: Default::default(),
1103 rotation: Rotation::None,1129 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,
1104 };1135 };
1105 let out = out_path("crossfade", "wav");1136 let out = out_path("crossfade", "wav");
1106 let handle = engine::export::start(1137 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() {
278 codec: engine::Codec::H264,278 codec: engine::Codec::H264,
279 color: Default::default(),279 color: Default::default(),
280 rotation: Rotation::None,280 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,
281 };286 };
282 let out = out_path("mixed");287 let out = out_path("mixed");
283 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);288 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+ -- "$@"