🔀 merge(anamorphic): the pixel aspect off the container, stretched once at the single post-decode step
Browse files at this commit13 changed files +1177 -71
- crates/engine-hw/src/lib.rs +12 -0
- crates/engine/src/decode.rs +72 -2
- crates/engine/src/demux.rs +193 -10
- crates/engine/src/export.rs +194 -26
- crates/engine/src/hw.rs +26 -5
- crates/engine/src/mux.rs +30 -0
- crates/engine/src/playback.rs +25 -0
- crates/engine/src/proxy.rs +36 -11
- crates/engine/tests/anamorphic.rs +484 -0
- crates/engine/tests/audio_export.rs +48 -17
- crates/engine/tests/export.rs +5 -0
- scripts/gen_fixtures.sh +31 -0
- scripts/memguard-runner.sh +21 -0
crates/engine-hw/src/lib.rsmodified+12 -0
| @@ -403,6 +403,10 @@ impl Session { | |||
| 403 | height: meta.height, | 403 | height: meta.height, |
| 404 | frame_rate: meta.frame_rate, | 404 | frame_rate: meta.frame_rate, |
| 405 | frame_count: meta.frame_count, | 405 | frame_count: meta.frame_count, |
| 406 | + coded_width: meta.coded_width, | ||
| 407 | + coded_height: meta.coded_height, | ||
| 408 | + pixel_aspect_h: meta.pixel_aspect.h, | ||
| 409 | + pixel_aspect_v: meta.pixel_aspect.v, | ||
| 406 | }, | 410 | }, |
| 407 | ready: VecDeque::new(), | 411 | ready: VecDeque::new(), |
| 408 | pending: Vec::new(), | 412 | pending: Vec::new(), |
| @@ -935,6 +939,10 @@ impl VpxSession { | |||
| 935 | height: meta.height, | 939 | height: meta.height, |
| 936 | frame_rate: meta.frame_rate, | 940 | frame_rate: meta.frame_rate, |
| 937 | frame_count: meta.frame_count, | 941 | frame_count: meta.frame_count, |
| 942 | + coded_width: meta.coded_width, | ||
| 943 | + coded_height: meta.coded_height, | ||
| 944 | + pixel_aspect_h: meta.pixel_aspect.h, | ||
| 945 | + pixel_aspect_v: meta.pixel_aspect.v, | ||
| 938 | }, | 946 | }, |
| 939 | flushed: false, | 947 | flushed: false, |
| 940 | skip: 0, | 948 | skip: 0, |
| @@ -1110,6 +1118,10 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 | |||
| 1110 | (*out).height = meta.height; | 1118 | (*out).height = meta.height; |
| 1111 | (*out).frame_rate = meta.frame_rate; | 1119 | (*out).frame_rate = meta.frame_rate; |
| 1112 | (*out).frame_count = meta.frame_count; | 1120 | (*out).frame_count = meta.frame_count; |
| 1121 | + (*out).coded_width = meta.coded_width; | ||
| 1122 | + (*out).coded_height = meta.coded_height; | ||
| 1123 | + (*out).pixel_aspect_h = meta.pixel_aspect_h; | ||
| 1124 | + (*out).pixel_aspect_v = meta.pixel_aspect_v; | ||
| 1113 | } | 1125 | } |
| 1114 | 0 | 1126 | 0 |
| 1115 | })) | 1127 | })) |
crates/engine/src/decode.rsmodified+72 -2
| @@ -18,7 +18,7 @@ use ec_h264::H264Decoder; | |||
| 18 | use crate::color::ColorParams; | 18 | use crate::color::ColorParams; |
| 19 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; | 19 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 20 | use crate::convert::{i420_to_bgra, i420_to_bgra_with}; | 20 | use crate::convert::{i420_to_bgra, i420_to_bgra_with}; |
| 21 | -use crate::demux::{Codec, Demuxer, Rotation, VideoMeta}; | 21 | +use crate::demux::{Codec, Demuxer, PixelAspect, Rotation, VideoMeta}; |
| 22 | use crate::hw::HwSession; | 22 | use crate::hw::HwSession; |
| 23 | use crate::project::Speed; | 23 | use crate::project::Speed; |
| 24 | use crate::scale::Composer; | 24 | use crate::scale::Composer; |
| @@ -562,6 +562,8 @@ impl DecodeSession { | |||
| 562 | transform, | 562 | transform, |
| 563 | // A still has no display matrix: what the file holds is what it is. | 563 | // A still has no display matrix: what the file holds is what it is. |
| 564 | Rotation::None, | 564 | Rotation::None, |
| 565 | + // ...and no sample aspect either: a still is authored square. | ||
| 566 | + PixelAspect::SQUARE, | ||
| 565 | ColorDescription::default(), | 567 | ColorDescription::default(), |
| 566 | canvas, | 568 | canvas, |
| 567 | tonemap::Preset::default(), | 569 | tonemap::Preset::default(), |
| @@ -691,6 +693,9 @@ impl DecodeSession { | |||
| 691 | transform, | 693 | transform, |
| 692 | // Painted here, at the canvas's own size: nothing turned it. | 694 | // Painted here, at the canvas's own size: nothing turned it. |
| 693 | Rotation::None, | 695 | Rotation::None, |
| 696 | + // ...and nothing drew it anamorphic: it is square by | ||
| 697 | + // construction. | ||
| 698 | + PixelAspect::SQUARE, | ||
| 694 | ColorDescription::default(), | 699 | ColorDescription::default(), |
| 695 | canvas, | 700 | canvas, |
| 696 | tonemap::Preset::default(), | 701 | tonemap::Preset::default(), |
| @@ -1108,6 +1113,7 @@ fn run_span( | |||
| 1108 | color, | 1113 | color, |
| 1109 | transform, | 1114 | transform, |
| 1110 | opened.meta.rotation, | 1115 | opened.meta.rotation, |
| 1116 | + opened.meta.pixel_aspect, | ||
| 1111 | opened.meta.color, | 1117 | opened.meta.color, |
| 1112 | canvas, | 1118 | canvas, |
| 1113 | tone, | 1119 | tone, |
| @@ -1197,6 +1203,12 @@ struct Render { | |||
| 1197 | /// every file that states no turn, which is the whole of an ordinary | 1203 | /// every file that states no turn, which is the whole of an ordinary |
| 1198 | /// library. | 1204 | /// library. |
| 1199 | rotation: Rotation, | 1205 | rotation: Rotation, |
| 1206 | + /// The ratio one coded pixel is drawn at ([`crate::demux::PixelAspect`]): | ||
| 1207 | + /// the file's sample aspect ratio, applied exactly once, at this one | ||
| 1208 | + /// conversion to the square-pixel raster -- the same place ffmpeg's swscale | ||
| 1209 | + /// applies it, and nowhere else. Square for every file that states no | ||
| 1210 | + /// aspect, which takes the branch by a bool and touches no byte. | ||
| 1211 | + pixel_aspect: PixelAspect, | ||
| 1200 | /// What the source's samples mean -- the stream's own matrix and range, | 1212 | /// What the source's samples mean -- the stream's own matrix and range, |
| 1201 | /// which is what the conversion below is done in rather than the BT.601 it | 1213 | /// which is what the conversion below is done in rather than the BT.601 it |
| 1202 | /// used to assume of every file. | 1214 | /// used to assume of every file. |
| @@ -1215,6 +1227,10 @@ struct Render { | |||
| 1215 | /// asks for none, and resized once for one that does -- a steady-state | 1227 | /// asks for none, and resized once for one that does -- a steady-state |
| 1216 | /// buffer rather than three plane allocations per decoded frame. | 1228 | /// buffer rather than three plane allocations per decoded frame. |
| 1217 | turned: (Vec<u8>, Vec<u8>, Vec<u8>), | 1229 | turned: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1230 | + /// The same, for the pixel-aspect stretch: the coded picture widened to | ||
| 1231 | + /// the displayed width, empty for every square-pixel file and sized once | ||
| 1232 | + /// for one that is not. | ||
| 1233 | + stretched: (Vec<u8>, Vec<u8>, Vec<u8>), | ||
| 1218 | /// Where [`Composer::place_transformed`]'s owned picture lands, so a | 1234 | /// Where [`Composer::place_transformed`]'s owned picture lands, so a |
| 1219 | /// transformed frame's planes live as long as `self` -- matching what | 1235 | /// transformed frame's planes live as long as `self` -- matching what |
| 1220 | /// [`Composer::place`] already hands back by borrowing `self.canvas`. | 1236 | /// [`Composer::place`] already hands back by borrowing `self.canvas`. |
| @@ -1238,6 +1254,7 @@ impl Render { | |||
| 1238 | color: ColorParams, | 1254 | color: ColorParams, |
| 1239 | transform: TransformParams, | 1255 | transform: TransformParams, |
| 1240 | rotation: Rotation, | 1256 | rotation: Rotation, |
| 1257 | + pixel_aspect: PixelAspect, | ||
| 1241 | desc: ColorDescription, | 1258 | desc: ColorDescription, |
| 1242 | canvas: Composer, | 1259 | canvas: Composer, |
| 1243 | preset: tonemap::Preset, | 1260 | preset: tonemap::Preset, |
| @@ -1247,6 +1264,7 @@ impl Render { | |||
| 1247 | color, | 1264 | color, |
| 1248 | transform, | 1265 | transform, |
| 1249 | rotation, | 1266 | rotation, |
| 1267 | + pixel_aspect, | ||
| 1250 | desc, | 1268 | desc, |
| 1251 | canvas, | 1269 | canvas, |
| 1252 | // corner-cut: the ceiling is that the map reads limited-range codes | 1270 | // corner-cut: the ceiling is that the map reads limited-range codes |
| @@ -1261,6 +1279,7 @@ impl Render { | |||
| 1261 | }, | 1279 | }, |
| 1262 | graded: (Vec::new(), Vec::new(), Vec::new()), | 1280 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 1263 | turned: (Vec::new(), Vec::new(), Vec::new()), | 1281 | turned: (Vec::new(), Vec::new(), Vec::new()), |
| 1282 | + stretched: (Vec::new(), Vec::new(), Vec::new()), | ||
| 1264 | placed: (Vec::new(), Vec::new(), Vec::new()), | 1283 | placed: (Vec::new(), Vec::new(), Vec::new()), |
| 1265 | } | 1284 | } |
| 1266 | } | 1285 | } |
| @@ -1274,7 +1293,58 @@ impl Render { | |||
| 1274 | width: u32, | 1293 | width: u32, |
| 1275 | height: u32, | 1294 | height: u32, |
| 1276 | ) -> Frame { | 1295 | ) -> Frame { |
| 1277 | - // The file's own turn, before anything else: a phone's portrait video | 1296 | + // The pixel aspect, applied exactly once -- the single conversion to |
| 1297 | + // the square-pixel raster this engine makes, where ffmpeg's swscale | ||
| 1298 | + // makes its own -- *before* the display-matrix turn. The ratio belongs | ||
| 1299 | + // to the axis that was horizontal before the turn: the coded width is | ||
| 1300 | + // stretched by h/v and the turn then swaps the stretched pair, which | ||
| 1301 | + // is the composition the probe declares (a 1440x1080 SAR-4/3 file | ||
| 1302 | + // turned 90° displays 1080x1920, DAR 9:16). Stretching after the turn | ||
| 1303 | + // instead lands the ratio on the coded height and renders a | ||
| 1304 | + // 1440x1440 square into a 9:16 canvas -- letterboxed, and the bars | ||
| 1305 | + // baked into any export. Only a file whose samples are not square | ||
| 1306 | + // reaches the resample: a square one takes the branch by a bool and | ||
| 1307 | + // not one byte is touched, which is what keeps every existing picture | ||
| 1308 | + // identical to the day before anamorphic sources existed. | ||
| 1309 | + let (y, u, v, width, height) = if self.pixel_aspect.is_square() { | ||
| 1310 | + (y, u, v, width, height) | ||
| 1311 | + } else { | ||
| 1312 | + // The aspect widens the *width*, always: 4:3 SAR over 1440x1080 | ||
| 1313 | + // shows 1920x1080. `width_factor` lands on the even grid 4:2:0 | ||
| 1314 | + // composes on, and a height is never touched by it. | ||
| 1315 | + let display_width = self.pixel_aspect.width_factor(width); | ||
| 1316 | + let (sy, su, sv) = &mut self.stretched; | ||
| 1317 | + // Sized for `scale_i420`'s exact-planes assertion, once for the | ||
| 1318 | + // worker's whole range: steady-state buffers, not per-frame | ||
| 1319 | + // allocations ([`turned`]'s reason). | ||
| 1320 | + let (dcw, dch) = ( | ||
| 1321 | + display_width.div_ceil(2) as usize, | ||
| 1322 | + height.div_ceil(2) as usize, | ||
| 1323 | + ); | ||
| 1324 | + sy.resize(display_width as usize * height as usize, 0); | ||
| 1325 | + su.resize(dcw * dch, 0); | ||
| 1326 | + sv.resize(dcw * dch, 0); | ||
| 1327 | + crate::scale::scale_i420( | ||
| 1328 | + y, | ||
| 1329 | + u, | ||
| 1330 | + v, | ||
| 1331 | + width as usize, | ||
| 1332 | + height as usize, | ||
| 1333 | + sy, | ||
| 1334 | + su, | ||
| 1335 | + sv, | ||
| 1336 | + display_width as usize, | ||
| 1337 | + height as usize, | ||
| 1338 | + ); | ||
| 1339 | + ( | ||
| 1340 | + &sy[..display_width as usize * height as usize], | ||
| 1341 | + &su[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], | ||
| 1342 | + &sv[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], | ||
| 1343 | + display_width, | ||
| 1344 | + height, | ||
| 1345 | + ) | ||
| 1346 | + }; | ||
| 1347 | + // The file's own turn, after the stretch: a phone's portrait video | ||
| 1278 | // arrives as landscape planes, and the grade, the canvas and the | 1348 | // arrives as landscape planes, and the grade, the canvas and the |
| 1279 | // conversion below all have to see the picture the way it is meant to | 1349 | // conversion below all have to see the picture the way it is meant to |
| 1280 | // be seen. Nothing here at all for the ordinary file that states no | 1350 | // be seen. Nothing here at all for the ordinary file that states no |
crates/engine/src/demux.rsmodified+193 -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 display | 404 | /// 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,30 @@ impl MkvDemuxer { | |||
| 1313 | } | 1384 | } |
| 1314 | } | 1385 | } |
| 1315 | }; | 1386 | }; |
| 1316 | - // The coded size, swapped where the turn is a quarter one: a portrait | 1387 | + // The displayed shape, in the order the two facts compose -- the same |
| 1317 | - // `.mkv` stores a landscape picture plus the turn, so the displayed | 1388 | + // order the render applies them in |
| 1318 | - // shape is the coded one turned -- the same two numbers the mp4 door | 1389 | + // ([`crate::decode::Render::frame`]): the aspect widens the *coded* |
| 1319 | - // swaps, off the same kind of turn. | 1390 | + // frame (180x320 at SAR 4/3 is drawn 240x320 -- ffprobe's own |
| 1391 | + // `display_aspect_ratio` of such a file, measured), then the quarter | ||
| 1392 | + // turn swaps that stretched pair the way it swaps the coded one. The | ||
| 1393 | + // other order is a different picture: 320x180 then widened by 4/3 | ||
| 1394 | + // lands at 426x180, and a rotated anamorphic file rendered that way | ||
| 1395 | + // lands a square raster in the 9:16 canvas its probe declares -- | ||
| 1396 | + // letterboxed in the preview and in the export both. The SAR only | ||
| 1397 | + // ever widens a width, never a height; the displayed height is the | ||
| 1398 | + // coded one without a turn and the stretched coded width with one. | ||
| 1399 | + // The coded pair stays what the decoder hands back, and carries on to | ||
| 1400 | + // [`VideoMeta::coded_width`]/[`VideoMeta::coded_height`]. | ||
| 1320 | let (width, height) = match video.rotation.swaps_axes() { | 1401 | let (width, height) = match video.rotation.swaps_axes() { |
| 1321 | - true => (video.height, video.width), | 1402 | + true => (video.height, video.pixel_aspect.width_factor(video.width)), |
| 1322 | - false => (video.width, video.height), | 1403 | + false => (video.pixel_aspect.width_factor(video.width), video.height), |
| 1323 | }; | 1404 | }; |
| 1324 | let meta = VideoMeta { | 1405 | let meta = VideoMeta { |
| 1325 | width, | 1406 | width, |
| 1326 | height, | 1407 | height, |
| 1408 | + coded_width: video.width, | ||
| 1409 | + coded_height: video.height, | ||
| 1410 | + pixel_aspect: video.pixel_aspect, | ||
| 1327 | frame_rate, | 1411 | frame_rate, |
| 1328 | frame_count: mkv.frames as u32, | 1412 | frame_count: mkv.frames as u32, |
| 1329 | codec: video.codec, | 1413 | codec: video.codec, |
| @@ -2014,6 +2098,10 @@ struct MkvVideo { | |||
| 2014 | number: u64, | 2098 | number: u64, |
| 2015 | width: u32, | 2099 | width: u32, |
| 2016 | height: u32, | 2100 | height: u32, |
| 2101 | + /// The sample aspect ratio the track's `Display*` elements state, square | ||
| 2102 | + /// where they state none ([`PixelAspect::SQUARE`]) -- the same reading | ||
| 2103 | + /// every Matroska reader makes of their absence. | ||
| 2104 | + pixel_aspect: PixelAspect, | ||
| 2017 | /// The quarter turn the track's `Projection` asks for; | 2105 | /// The quarter turn the track's `Projection` asks for; |
| 2018 | /// [`Rotation::None`] where it states none. | 2106 | /// [`Rotation::None`] where it states none. |
| 2019 | rotation: Rotation, | 2107 | rotation: Rotation, |
| @@ -2164,6 +2252,14 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 2164 | const VIDEO: u32 = 0xE0; | 2252 | const VIDEO: u32 = 0xE0; |
| 2165 | const PIXEL_WIDTH: u32 = 0xB0; | 2253 | const PIXEL_WIDTH: u32 = 0xB0; |
| 2166 | const PIXEL_HEIGHT: u32 = 0xBA; | 2254 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 2255 | +// How the picture is drawn: Matroska carries the aspect as a `Display*` pair | ||
| 2256 | +// in *display units* (0x54B2) -- 0 pixels, 1 centimetres, 2 inches, 3 a display | ||
| 2257 | +// aspect ratio, 4 the sample aspect ratio itself. Absent, the pixels are the | ||
| 2258 | +// coded ones: every square-pixel file states none of these, which is what makes | ||
| 2259 | +// their absence the square answer rather than an error. | ||
| 2260 | +const DISPLAY_WIDTH: u32 = 0x54B0; | ||
| 2261 | +const DISPLAY_HEIGHT: u32 = 0x54BA; | ||
| 2262 | +const DISPLAY_UNIT: u32 = 0x54B2; | ||
| 2167 | // The track's projection: how the flat picture sits in space. A roll on the | 2263 | // 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 mp4 | 2264 | // rectangular projection (type 0) is how a Matroska muxer states what an mp4 |
| 2169 | // states with its `tkhd` matrix -- mkvmerge has translated display matrices | 2265 | // states with its `tkhd` matrix -- mkvmerge has translated display matrices |
| @@ -2428,6 +2524,9 @@ fn mkv_track_entry( | |||
| 2428 | ) -> crate::Result<MkvEntry> { | 2524 | ) -> crate::Result<MkvEntry> { |
| 2429 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); | 2525 | 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()); | 2526 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); |
| 2527 | + // The `Display*` elements: unstated for the square-pixel file, which is | ||
| 2528 | + // most of them. | ||
| 2529 | + let (mut display_width, mut display_height, mut display_unit) = (0u64, 0u64, 0u64); | ||
| 2431 | let mut rotation = Rotation::None; | 2530 | let mut rotation = Rotation::None; |
| 2432 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); | 2531 | let (mut language, mut name, mut bcp47) = (String::new(), String::new(), String::new()); |
| 2433 | let mut tags = Tags::default(); | 2532 | let mut tags = Tags::default(); |
| @@ -2455,6 +2554,9 @@ fn mkv_track_entry( | |||
| 2455 | match e.0 { | 2554 | match e.0 { |
| 2456 | PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32, | 2555 | 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, | 2556 | PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32, |
| 2557 | + DISPLAY_WIDTH => display_width = ebml_uint(file, e.1, e.2)?, | ||
| 2558 | + DISPLAY_HEIGHT => display_height = ebml_uint(file, e.1, e.2)?, | ||
| 2559 | + DISPLAY_UNIT => display_unit = ebml_uint(file, e.1, e.2)?, | ||
| 2458 | PROJECTION => { | 2560 | PROJECTION => { |
| 2459 | let (mut kind, mut yaw, mut pitch, mut roll) = | 2561 | let (mut kind, mut yaw, mut pitch, mut roll) = |
| 2460 | (0u64, 0.0f64, 0.0f64, 0.0f64); | 2562 | (0u64, 0.0f64, 0.0f64, 0.0f64); |
| @@ -2599,6 +2701,13 @@ fn mkv_track_entry( | |||
| 2599 | number, | 2701 | number, |
| 2600 | width, | 2702 | width, |
| 2601 | height, | 2703 | height, |
| 2704 | + pixel_aspect: pixel_aspect_of( | ||
| 2705 | + display_width, | ||
| 2706 | + display_height, | ||
| 2707 | + display_unit, | ||
| 2708 | + width, | ||
| 2709 | + height, | ||
| 2710 | + ), | ||
| 2602 | rotation, | 2711 | rotation, |
| 2603 | tags, | 2712 | tags, |
| 2604 | light, | 2713 | light, |
| @@ -2795,6 +2904,53 @@ fn rotation_of_roll(degrees: f64) -> crate::Result<Rotation> { | |||
| 2795 | /// quarter turn here can make -- the same missing capability the mp4 door | 2904 | /// 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 a | 2905 | /// refuses a 45-degree matrix for, so it gets the same refusal rather than a |
| 2797 | /// sideways picture. | 2906 | /// sideways picture. |
| 2907 | + | ||
| 2908 | +/// The sample aspect ratio a Matroska `TrackEntry`'s `Video` element states, | ||
| 2909 | +/// from its `DisplayWidth`/`DisplayHeight`/`DisplayUnit` children and the coded | ||
| 2910 | +/// size beside them. | ||
| 2911 | +/// | ||
| 2912 | +/// The units decide what the pair *is*: 3 spells a display aspect ratio (16 and | ||
| 2913 | +/// 9 over 1440x1080 is what ffmpeg writes for a `setsar=4/3` source, measured), | ||
| 2914 | +/// 4 spells the sample aspect ratio itself, and 0/absent spells pixels -- where | ||
| 2915 | +/// a pair beside the coded one at all means a crop, not an aspect. 1 and 2 | ||
| 2916 | +/// (centimetres, inches) are physical sizes a picture this engine shows cannot | ||
| 2917 | +/// mean anything by, and read as square rather than guessed. Every unstated or | ||
| 2918 | +/// unusable shape is [`PixelAspect::SQUARE`], which is also the answer the spec's | ||
| 2919 | +/// own default gives: DisplayWidth and DisplayHeight "SHOULD be set to the | ||
| 2920 | +/// PixelWidth and PixelHeight" when they mean the same thing, so a file that | ||
| 2921 | +/// means square most often says nothing at all. | ||
| 2922 | +fn pixel_aspect_of( | ||
| 2923 | + display_width: u64, | ||
| 2924 | + display_height: u64, | ||
| 2925 | + display_unit: u64, | ||
| 2926 | + coded_width: u32, | ||
| 2927 | + coded_height: u32, | ||
| 2928 | +) -> PixelAspect { | ||
| 2929 | + // A zero pair (unstated, or a header that lies about it) and a zero coded | ||
| 2930 | + // size are all square: there is nothing to divide by and nothing to stretch. | ||
| 2931 | + if display_width == 0 || display_height == 0 || coded_width == 0 || coded_height == 0 { | ||
| 2932 | + return PixelAspect::SQUARE; | ||
| 2933 | + } | ||
| 2934 | + match display_unit { | ||
| 2935 | + // 4: the pair *is* the sample aspect ratio. | ||
| 2936 | + 4 => PixelAspect { | ||
| 2937 | + h: display_width.min(u32::MAX as u64) as u32, | ||
| 2938 | + v: display_height.min(u32::MAX as u64) as u32, | ||
| 2939 | + }, | ||
| 2940 | + // 3: the pair is the display aspect ratio -- display_w / display_h -- | ||
| 2941 | + // which the SAR is that against the coded one: sar = dar * h / w. | ||
| 2942 | + // 16/9 over 1440x1080 lands on 4/3. | ||
| 2943 | + 3 => PixelAspect { | ||
| 2944 | + h: ((display_width * u64::from(coded_height)) | ||
| 2945 | + .min(u32::MAX as u64 * u64::from(coded_width))) as u32, | ||
| 2946 | + v: ((display_height * u64::from(coded_width)) | ||
| 2947 | + .min(u32::MAX as u64 * u64::from(coded_height))) as u32, | ||
| 2948 | + }, | ||
| 2949 | + // Pixels (0) or a physical unit this engine cannot interpret: square. | ||
| 2950 | + _ => PixelAspect::SQUARE, | ||
| 2951 | + } | ||
| 2952 | +} | ||
| 2953 | + | ||
| 2798 | fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> { | 2954 | fn projection_rotation(kind: u64, yaw: f64, pitch: f64, roll: f64) -> crate::Result<Rotation> { |
| 2799 | if kind != 0 { | 2955 | if kind != 0 { |
| 2800 | return Ok(Rotation::None); | 2956 | return Ok(Rotation::None); |
| @@ -3993,6 +4149,33 @@ fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> { | |||
| 3993 | Some(Tags::from_codes(code(8)?, code(6)?, range)) | 4149 | Some(Tags::from_codes(code(8)?, code(6)?, range)) |
| 3994 | } | 4150 | } |
| 3995 | 4151 | ||
| 4152 | +/// The `pasp` box of `track_id`'s sample entry (ISO/IEC 14496-12 §6.2.3, the | ||
| 4153 | +/// pixel aspect ratio box a visual sample entry may carry): two 32-bit | ||
| 4154 | +/// big-endian integers, hSpacing then vSpacing, the ratio one coded pixel is | ||
| 4155 | +/// drawn at. ffmpeg writes it for a `setsar=4/3` source and writes 1/1 for a | ||
| 4156 | +/// square one (both measured); a box absent -- most mp4s there are -- is square | ||
| 4157 | +/// pixels, the same answer Matroska's absent `Display*` elements give. | ||
| 4158 | +/// | ||
| 4159 | +/// [`None`] rather than an error for a file with no such box, which is most of | ||
| 4160 | +/// them -- an untagged mp4 is not a broken one. | ||
| 4161 | +fn pasp_of(path: &Path, track_id: u32) -> PixelAspect { | ||
| 4162 | + let Ok((_, entry)) = sample_entry(path, track_id) else { | ||
| 4163 | + return PixelAspect::SQUARE; | ||
| 4164 | + }; | ||
| 4165 | + // The same fixed 78-byte VisualSampleEntry header `colr` and `hvcC` sit | ||
| 4166 | + // behind; `pasp` is one of their siblings. | ||
| 4167 | + let Some(pasp) = child(entry.get(78..).unwrap_or_default(), b"pasp") else { | ||
| 4168 | + return PixelAspect::SQUARE; | ||
| 4169 | + }; | ||
| 4170 | + let (Some(h), Some(v)) = ( | ||
| 4171 | + pasp.get(..4).map(|b| u32::from_be_bytes(b.try_into().unwrap())), | ||
| 4172 | + pasp.get(4..8).map(|b| u32::from_be_bytes(b.try_into().unwrap())), | ||
| 4173 | + ) else { | ||
| 4174 | + return PixelAspect::SQUARE; | ||
| 4175 | + }; | ||
| 4176 | + PixelAspect { h, v } | ||
| 4177 | +} | ||
| 4178 | + | ||
| 3996 | /// The `clli` and `mdcv` boxes of `track_id`'s sample entry: what an mp4 says | 4179 | /// 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 their | 4180 | /// 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 SEI | 4181 | /// numbers mean. Neither is a FullBox -- their payloads are the HEVC SEI |
crates/engine/src/export.rsmodified+194 -26
| @@ -1229,10 +1229,16 @@ struct Dissolve<'a> { | |||
| 1229 | /// B's own file's display-matrix turn, [`place_picture`]'s first stage; | 1229 | /// B's own file's display-matrix turn, [`place_picture`]'s first stage; |
| 1230 | /// B is a different file and may be turned differently from A. | 1230 | /// B is a different file and may be turned differently from A. |
| 1231 | rotation: Rotation, | 1231 | rotation: Rotation, |
| 1232 | + /// B's own file's sample aspect, [`place_picture`]'s second stage, for | ||
| 1233 | + /// the same reason the turn is per file. | ||
| 1234 | + pixel_aspect: crate::demux::PixelAspect, | ||
| 1232 | canvas: Composer, | 1235 | canvas: Composer, |
| 1233 | /// The turn's, the grade's and the transform's scratch, exactly as A's | 1236 | /// The turn's, the grade's and the transform's scratch, exactly as A's |
| 1234 | /// span keeps them: refilled per picture, allocated once. | 1237 | /// span keeps them: refilled per picture, allocated once. |
| 1235 | rotated: (Vec<u8>, Vec<u8>, Vec<u8>), | 1238 | rotated: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1239 | + /// The stretch's own scratch, [`place_picture`]'s second stage -- the | ||
| 1240 | + /// pixel aspect's, beside the turn's. | ||
| 1241 | + stretched: (Vec<u8>, Vec<u8>, Vec<u8>), | ||
| 1236 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), | 1242 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1237 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), | 1243 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 1238 | } | 1244 | } |
| @@ -1737,8 +1743,15 @@ struct CopyPlan { | |||
| 1737 | /// copy. | 1743 | /// copy. |
| 1738 | private: Vec<u8>, | 1744 | private: Vec<u8>, |
| 1739 | colour: ColorDescription, | 1745 | colour: ColorDescription, |
| 1746 | + /// The coded shape the copied track declares: the samples under it are the | ||
| 1747 | + /// source's own, so the header names what they are stored at -- not the | ||
| 1748 | + /// shape they are drawn at. | ||
| 1740 | width: u32, | 1749 | width: u32, |
| 1741 | height: u32, | 1750 | height: u32, |
| 1751 | + /// The aspect the copied samples are drawn at, written into the file as | ||
| 1752 | + /// display metadata ([`CopyParams::pixel_aspect`]): square for every | ||
| 1753 | + /// ordinary source, so the header gains nothing. | ||
| 1754 | + pixel_aspect: crate::demux::PixelAspect, | ||
| 1742 | } | 1755 | } |
| 1743 | 1756 | ||
| 1744 | /// A run of source blocks copied in one piece: what a cut leaves behind, and | 1757 | /// A run of source blocks copied in one piece: what a cut leaves behind, and |
| @@ -1772,6 +1785,30 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti | |||
| 1772 | if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { | 1785 | if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { |
| 1773 | return None; | 1786 | return None; |
| 1774 | } | 1787 | } |
| 1788 | + // An anamorphic source asked of a format that cannot state the aspect: the | ||
| 1789 | + // blocks would copy, but the sample entry this writer produces has no | ||
| 1790 | + // `pasp` box to carry it in, and a header that declares the coded pair | ||
| 1791 | + // while the pixels are drawn 4/3 wide is a file that lies about its own | ||
| 1792 | + // shape. Refused by name -- the sentence a reader is owed -- before the | ||
| 1793 | + // container's codec question, because this is the *nearer* reason: a | ||
| 1794 | + // Matroska copy needs no refusal at all (its track carries the aspect | ||
| 1795 | + // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own | ||
| 1796 | + // copy behaviour), so an anamorphic source's Exact row only ever dies on | ||
| 1797 | + // this for an mp4. | ||
| 1798 | + if !settings.format.is_mkv() { | ||
| 1799 | + let anamorphic = project.sources().iter().any(|source| { | ||
| 1800 | + Demuxer::open(&source.path) | ||
| 1801 | + .ok() | ||
| 1802 | + .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square()) | ||
| 1803 | + }); | ||
| 1804 | + if anamorphic { | ||
| 1805 | + return Some( | ||
| 1806 | + "a copy would lose the pixel aspect — this format cannot state it beside the \ | ||
| 1807 | + coded picture, so the export re-encodes it into the square pixels it is drawn at" | ||
| 1808 | + .to_string(), | ||
| 1809 | + ); | ||
| 1810 | + } | ||
| 1811 | + } | ||
| 1775 | let codec = match settings.format { | 1812 | let codec = match settings.format { |
| 1776 | Format::Hevc => Codec::Hevc, | 1813 | Format::Hevc => Codec::Hevc, |
| 1777 | Format::Av1 => Codec::Av1, | 1814 | Format::Av1 => Codec::Av1, |
| @@ -1782,6 +1819,12 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti | |||
| 1782 | )); | 1819 | )); |
| 1783 | } | 1820 | } |
| 1784 | }; | 1821 | }; |
| 1822 | + // The turn-baking corner-cut (a copied packet is the source's own coded | ||
| 1823 | + // picture; this export bakes a display-matrix turn into the pixels) and | ||
| 1824 | + // the rest of the reasons a copy says something other than what the | ||
| 1825 | + // timeline says are [`CopyPlan::of`]'s own gates, so the container and | ||
| 1826 | + // edit sentences below are checked the same way rather than duplicated | ||
| 1827 | + // with different words. | ||
| 1785 | let carries = project.sources().iter().all(|source| { | 1828 | let carries = project.sources().iter().all(|source| { |
| 1786 | crate::demux::is_matroska(&source.path) | 1829 | crate::demux::is_matroska(&source.path) |
| 1787 | && Demuxer::open(&source.path) | 1830 | && Demuxer::open(&source.path) |
| @@ -1811,7 +1854,7 @@ impl CopyPlan { | |||
| 1811 | }; | 1854 | }; |
| 1812 | let entries = project.sources(); | 1855 | let entries = project.sources(); |
| 1813 | let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect(); | 1856 | let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect(); |
| 1814 | - let mut declared: Option<(Vec<u8>, ColorDescription)> = None; | 1857 | + let mut declared: Option<(Vec<u8>, ColorDescription, crate::demux::PixelAspect)> = None; |
| 1815 | let mut regions: Vec<CopyRegion> = Vec::new(); | 1858 | let mut regions: Vec<CopyRegion> = Vec::new(); |
| 1816 | let r_start = settings.range.map_or(0, |(s, _)| s); | 1859 | let r_start = settings.range.map_or(0, |(s, _)| s); |
| 1817 | for span in export_spans(project, settings.range) { | 1860 | for span in export_spans(project, settings.range) { |
| @@ -1869,20 +1912,42 @@ impl CopyPlan { | |||
| 1869 | // this export bakes the turn into the pixels -- so a copy would | 1912 | // this export bakes the turn into the pixels -- so a copy would |
| 1870 | // ship the file sideways. Re-encoding is the only honest | 1913 | // ship the file sideways. Re-encoding is the only honest |
| 1871 | // answer here. | 1914 | // answer here. |
| 1915 | + // | ||
| 1916 | + // The size the copy declares is the source's *coded* pair, so | ||
| 1917 | + // that is what the comparison asks: coded to coded. A display | ||
| 1918 | + // comparison would refuse every anamorphic source that happens | ||
| 1919 | + // to sit at the project's displayed shape and then write a | ||
| 1920 | + // track that lies about its own samples -- and a square | ||
| 1921 | + // source's coded pair is its display pair, so this asks nothing | ||
| 1922 | + // new of the ordinary file. | ||
| 1923 | + // | ||
| 1924 | + // A source whose samples are not square is the *other* kind of | ||
| 1925 | + // picture a copy cannot carry here: the blocks are its own | ||
| 1926 | + // coded pixels and this engine's Matroska writer can now state | ||
| 1927 | + // the aspect beside them -- but only this engine's | ||
| 1928 | + // ([`MkvMuxer::create_copy`] writes the `Display*` elements), | ||
| 1929 | + // and the copy's declared shape must stay the coded one. The | ||
| 1930 | + // aspect travels with the track instead of being baked in, | ||
| 1931 | + // which is ffmpeg's own copy behaviour, so an anamorphic | ||
| 1932 | + // source is copyable *into Matroska* and nowhere else. | ||
| 1872 | if !source_meta.rotation.is_none() | 1933 | if !source_meta.rotation.is_none() |
| 1873 | || source_meta.codec != codec | 1934 | || source_meta.codec != codec |
| 1874 | - || source_meta.width != meta.width | 1935 | + || source_meta.coded_width != meta.coded_width |
| 1875 | - || source_meta.height != meta.height | 1936 | + || source_meta.coded_height != meta.coded_height |
| 1876 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? | 1937 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? |
| 1877 | != Rate::REAL_TIME | 1938 | != Rate::REAL_TIME |
| 1878 | || !demuxer.plain_blocks() | 1939 | || !demuxer.plain_blocks() |
| 1879 | { | 1940 | { |
| 1880 | return None; | 1941 | return None; |
| 1881 | } | 1942 | } |
| 1882 | - // One track, one configuration record and one `Colour`: two | 1943 | + // Two sources that disagree about their pixel aspect are two |
| 1883 | - // sources that disagree about either are two streams, and this | 1944 | + // displayed pictures under one track; the copy declares one |
| 1884 | - // writes one. | 1945 | + // aspect or none. |
| 1885 | - let declares = (demuxer.codec_private().to_vec(), source_meta.color); | 1946 | + let declares = ( |
| 1947 | + demuxer.codec_private().to_vec(), | ||
| 1948 | + source_meta.color, | ||
| 1949 | + source_meta.pixel_aspect, | ||
| 1950 | + ); | ||
| 1886 | if declared.get_or_insert(declares.clone()) != &declares { | 1951 | if declared.get_or_insert(declares.clone()) != &declares { |
| 1887 | return None; | 1952 | return None; |
| 1888 | } | 1953 | } |
| @@ -1920,15 +1985,19 @@ impl CopyPlan { | |||
| 1920 | }), | 1985 | }), |
| 1921 | } | 1986 | } |
| 1922 | } | 1987 | } |
| 1923 | - let (private, colour) = declared?; | 1988 | + let (private, colour, pixel_aspect) = declared?; |
| 1924 | Some(Self { | 1989 | Some(Self { |
| 1925 | sources, | 1990 | sources, |
| 1926 | regions, | 1991 | regions, |
| 1927 | codec_id, | 1992 | codec_id, |
| 1928 | private, | 1993 | private, |
| 1929 | colour, | 1994 | colour, |
| 1930 | - width: meta.width, | 1995 | + // The track the copy declares is the source's coded shape -- the |
| 1931 | - height: meta.height, | 1996 | + // samples under it are the source's own -- with the aspect beside |
| 1997 | + // it as the display metadata ([`CopyParams::pixel_aspect`]). | ||
| 1998 | + width: meta.coded_width, | ||
| 1999 | + height: meta.coded_height, | ||
| 2000 | + pixel_aspect, | ||
| 1932 | }) | 2001 | }) |
| 1933 | } | 2002 | } |
| 1934 | 2003 | ||
| @@ -1952,6 +2021,7 @@ impl CopyPlan { | |||
| 1952 | codec_id: self.codec_id, | 2021 | codec_id: self.codec_id, |
| 1953 | codec_private: &self.private, | 2022 | codec_private: &self.private, |
| 1954 | colour: self.colour, | 2023 | colour: self.colour, |
| 2024 | + pixel_aspect: self.pixel_aspect, | ||
| 1955 | }, | 2025 | }, |
| 1956 | audio, | 2026 | audio, |
| 1957 | subs, | 2027 | subs, |
| @@ -2721,7 +2791,13 @@ fn run( | |||
| 2721 | // samples *mean* ([`ColorDescription`]), which is what decides whether they | 2791 | // samples *mean* ([`ColorDescription`]), which is what decides whether they |
| 2722 | // are remapped on the way in. Real time for a still, a song and a | 2792 | // are remapped on the way in. Real time for a still, a song and a |
| 2723 | // single-rate project, where every conversion below is the identity. | 2793 | // single-rate project, where every conversion below is the identity. |
| 2724 | - let rates: Vec<(Rate, ColorDescription, Option<f32>, Rotation)> = sources | 2794 | + let rates: Vec<( |
| 2795 | + Rate, | ||
| 2796 | + ColorDescription, | ||
| 2797 | + Option<f32>, | ||
| 2798 | + Rotation, | ||
| 2799 | + crate::demux::PixelAspect, | ||
| 2800 | + )> = sources | ||
| 2725 | .iter() | 2801 | .iter() |
| 2726 | .map(|source| source_rate(&source.path, meta.frame_rate)) | 2802 | .map(|source| source_rate(&source.path, meta.frame_rate)) |
| 2727 | .collect(); | 2803 | .collect(); |
| @@ -2740,7 +2816,7 @@ fn run( | |||
| 2740 | let preset = project.tone(); | 2816 | let preset = project.tone(); |
| 2741 | let tone: Vec<Option<ToneMapper>> = rates | 2817 | let tone: Vec<Option<ToneMapper>> = rates |
| 2742 | .iter() | 2818 | .iter() |
| 2743 | - .map(|(_, color, peak, _)| match color.transfer { | 2819 | + .map(|(_, color, peak, _, _)| match color.transfer { |
| 2744 | // A preview file keeps the film's own curve and is tone-mapped when | 2820 | // A preview file keeps the film's own curve and is tone-mapped when |
| 2745 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is | 2821 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is |
| 2746 | // both cheaper and the only way the preset can still be changed | 2822 | // both cheaper and the only way the preset can still be changed |
| @@ -2806,12 +2882,14 @@ fn run( | |||
| 2806 | // A's pixels on the CPU, so a dissolving span never asks for a GPU | 2882 | // A's pixels on the CPU, so a dissolving span never asks for a GPU |
| 2807 | // buffer, not even outside its own window. | 2883 | // buffer, not even outside its own window. |
| 2808 | let dissolve = dissolve_window(project, &span); | 2884 | let dissolve = dissolve_window(project, &span); |
| 2809 | - let (mut pictures, rate, in_frame, color, mapper, rotation) = match span.from { | 2885 | + let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = |
| 2886 | + match span.from | ||
| 2887 | + { | ||
| 2810 | Some((source, in_frame)) => { | 2888 | Some((source, in_frame)) => { |
| 2811 | let entry = sources | 2889 | let entry = sources |
| 2812 | .get(source) | 2890 | .get(source) |
| 2813 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; | 2891 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 2814 | - let (rate, color, _peak, rotation) = rates[source]; | 2892 | + let (rate, color, _peak, rotation, pixel_aspect) = rates[source]; |
| 2815 | let mapper = tone[source].as_ref(); | 2893 | let mapper = tone[source].as_ref(); |
| 2816 | // Nothing on the way from this span's decoder to the encoder | 2894 | // Nothing on the way from this span's decoder to the encoder |
| 2817 | // touches a sample: no tone map, no matrix remap, no grade -- | 2895 | // touches a sample: no tone map, no matrix remap, no grade -- |
| @@ -2831,8 +2909,12 @@ fn run( | |||
| 2831 | // A file whose display matrix asks for a turn is *not* | 2909 | // A file whose display matrix asks for a turn is *not* |
| 2832 | // untouched, whatever else the timeline says: its pictures | 2910 | // untouched, whatever else the timeline says: its pictures |
| 2833 | // have to be turned, which is a read-back no GPU buffer | 2911 | // have to be turned, which is a read-back no GPU buffer |
| 2834 | - // survives. | 2912 | + // survives. The sample aspect is the same refusal one |
| 2913 | + // stage later: its pictures have to be stretched to the | ||
| 2914 | + // square-pixel raster before an encoder sees them, which | ||
| 2915 | + // is the same kind of touch. | ||
| 2835 | && rotation.is_none() | 2916 | && rotation.is_none() |
| 2917 | + && pixel_aspect.is_square() | ||
| 2836 | && dissolve.is_none(); | 2918 | && dissolve.is_none(); |
| 2837 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); | 2919 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); |
| 2838 | // Opened at the file's own frame, which is the only place the | 2920 | // Opened at the file's own frame, which is the only place the |
| @@ -2852,13 +2934,21 @@ fn run( | |||
| 2852 | } else { | 2934 | } else { |
| 2853 | ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? | 2935 | ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? |
| 2854 | }; | 2936 | }; |
| 2855 | - (Some(pictures), rate, in_frame, Some(color), mapper, rotation) | 2937 | + (Some(pictures), rate, in_frame, Some(color), mapper, rotation, pixel_aspect) |
| 2856 | } | 2938 | } |
| 2857 | // A gap's black is 16/128/128, which is black in every matrix here | 2939 | // A gap's black is 16/128/128, which is black in every matrix here |
| 2858 | // and on every curve: nothing to remap and nothing to tone-map, | 2940 | // and on every curve: nothing to remap and nothing to tone-map, |
| 2859 | // which is what `None` says. A gap is no file either, so nothing | 2941 | // which is what `None` says. A gap is no file either, so nothing |
| 2860 | // turns it. | 2942 | // turns it. |
| 2861 | - None => (None, Rate::REAL_TIME, 0, None, None, Rotation::None), | 2943 | + None => ( |
| 2944 | + None, | ||
| 2945 | + Rate::REAL_TIME, | ||
| 2946 | + 0, | ||
| 2947 | + None, | ||
| 2948 | + None, | ||
| 2949 | + Rotation::None, | ||
| 2950 | + crate::demux::PixelAspect::SQUARE, | ||
| 2951 | + ), | ||
| 2862 | }; | 2952 | }; |
| 2863 | // Mixed spaces on one timeline: a clip coded against another matrix than | 2953 | // Mixed spaces on one timeline: a clip coded against another matrix than |
| 2864 | // the one this file declares is rewritten into it, *after* the grade -- | 2954 | // the one this file declares is rewritten into it, *after* the grade -- |
| @@ -2885,8 +2975,10 @@ fn run( | |||
| 2885 | let mut transformed = (Vec::new(), Vec::new(), Vec::new()); | 2975 | let mut transformed = (Vec::new(), Vec::new(), Vec::new()); |
| 2886 | // ...and one more for the file's own display-matrix turn, which happens | 2976 | // ...and one more for the file's own display-matrix turn, which happens |
| 2887 | // before all of those (see [`place_picture`]): empty for every source | 2977 | // before all of those (see [`place_picture`]): empty for every source |
| 2888 | - // that states no turn. | 2978 | + // that states no turn. `stretched` is its twin for the pixel aspect, |
| 2979 | + // which happens right after it. | ||
| 2889 | let mut rotated = (Vec::new(), Vec::new(), Vec::new()); | 2980 | let mut rotated = (Vec::new(), Vec::new(), Vec::new()); |
| 2981 | + let mut stretched = (Vec::new(), Vec::new(), Vec::new()); | ||
| 2890 | // ...and the canvas it is placed on, which is where a source of another | 2982 | // ...and the canvas it is placed on, which is where a source of another |
| 2891 | // resolution becomes a picture at the project's. The same `Composer` | 2983 | // resolution becomes a picture at the project's. The same `Composer` |
| 2892 | // playback composes with, given the same policy, so an export is what | 2984 | // playback composes with, given the same policy, so an export is what |
| @@ -2905,7 +2997,7 @@ fn run( | |||
| 2905 | let entry = sources.get(b_source).ok_or_else(|| { | 2997 | let entry = sources.get(b_source).ok_or_else(|| { |
| 2906 | format!("clip names source {b_source} of {}", sources.len()) | 2998 | format!("clip names source {b_source} of {}", sources.len()) |
| 2907 | })?; | 2999 | })?; |
| 2908 | - let (b_rate, b_color, _peak, b_rotation) = rates[b_source]; | 3000 | + let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; |
| 2909 | let b_mapper = tone[b_source].as_ref(); | 3001 | let b_mapper = tone[b_source].as_ref(); |
| 2910 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); | 3002 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); |
| 2911 | Ok(Dissolve { | 3003 | Ok(Dissolve { |
| @@ -2935,12 +3027,14 @@ fn run( | |||
| 2935 | .copied() | 3027 | .copied() |
| 2936 | .unwrap_or_default(), | 3028 | .unwrap_or_default(), |
| 2937 | rotation: b_rotation, | 3029 | rotation: b_rotation, |
| 3030 | + pixel_aspect: b_pixel_aspect, | ||
| 2938 | canvas: Composer::new( | 3031 | canvas: Composer::new( |
| 2939 | meta.width, | 3032 | meta.width, |
| 2940 | meta.height, | 3033 | meta.height, |
| 2941 | project.composite_fit_at(b_start), | 3034 | project.composite_fit_at(b_start), |
| 2942 | ), | 3035 | ), |
| 2943 | rotated: (Vec::new(), Vec::new(), Vec::new()), | 3036 | rotated: (Vec::new(), Vec::new(), Vec::new()), |
| 3037 | + stretched: (Vec::new(), Vec::new(), Vec::new()), | ||
| 2944 | graded: (Vec::new(), Vec::new(), Vec::new()), | 3038 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 2945 | transformed: (Vec::new(), Vec::new(), Vec::new()), | 3039 | transformed: (Vec::new(), Vec::new(), Vec::new()), |
| 2946 | }) | 3040 | }) |
| @@ -3045,11 +3139,13 @@ fn run( | |||
| 3045 | width, | 3139 | width, |
| 3046 | height, | 3140 | height, |
| 3047 | rotation, | 3141 | rotation, |
| 3142 | + pixel_aspect, | ||
| 3048 | grade, | 3143 | grade, |
| 3049 | transform, | 3144 | transform, |
| 3050 | remap, | 3145 | remap, |
| 3051 | mapper, | 3146 | mapper, |
| 3052 | &mut rotated, | 3147 | &mut rotated, |
| 3148 | + &mut stretched, | ||
| 3053 | &mut graded, | 3149 | &mut graded, |
| 3054 | &mut transformed, | 3150 | &mut transformed, |
| 3055 | &mut canvas, | 3151 | &mut canvas, |
| @@ -3079,9 +3175,10 @@ fn run( | |||
| 3079 | } | 3175 | } |
| 3080 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { | 3176 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { |
| 3081 | let (by, bu, bv, _, _) = place_picture( | 3177 | let (by, bu, bv, _, _) = place_picture( |
| 3082 | - by, bu, bv, bw, bh, d.rotation, d.grade, d.transform, | 3178 | + by, bu, bv, bw, bh, d.rotation, d.pixel_aspect, d.grade, |
| 3083 | - d.remap, d.mapper, &mut d.rotated, &mut d.graded, | 3179 | + d.transform, d.remap, d.mapper, &mut d.rotated, |
| 3084 | - &mut d.transformed, &mut d.canvas, | 3180 | + &mut d.stretched, &mut d.graded, &mut d.transformed, |
| 3181 | + &mut d.canvas, | ||
| 3085 | ); | 3182 | ); |
| 3086 | let idx_in_window = done_here + r - d.tail_start; | 3183 | let idx_in_window = done_here + r - d.tail_start; |
| 3087 | let t = dissolve_weight(idx_in_window, d.window); | 3184 | let t = dissolve_weight(idx_in_window, d.window); |
| @@ -3236,15 +3333,54 @@ fn place_picture<'a>( | |||
| 3236 | width: u32, | 3333 | width: u32, |
| 3237 | height: u32, | 3334 | height: u32, |
| 3238 | rotation: Rotation, | 3335 | rotation: Rotation, |
| 3336 | + pixel_aspect: crate::demux::PixelAspect, | ||
| 3239 | grade: Option<crate::color::ColorParams>, | 3337 | grade: Option<crate::color::ColorParams>, |
| 3240 | transform: TransformParams, | 3338 | transform: TransformParams, |
| 3241 | remap: Option<(Matrix, Matrix)>, | 3339 | remap: Option<(Matrix, Matrix)>, |
| 3242 | mapper: Option<&ToneMapper>, | 3340 | mapper: Option<&ToneMapper>, |
| 3243 | turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | 3341 | turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3342 | + stretched: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | ||
| 3244 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | 3343 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3245 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | 3344 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3246 | canvas: &'a mut Composer, | 3345 | canvas: &'a mut Composer, |
| 3247 | ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { | 3346 | ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { |
| 3347 | + // The pixel aspect, applied exactly once -- the same single conversion to | ||
| 3348 | + // the square-pixel raster the decode funnel makes, in the same order | ||
| 3349 | + // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s | ||
| 3350 | + // comment carries the 1440x1440 failure the other order produces). A | ||
| 3351 | + // square-pixel file -- every file whose samples are one to one -- borrows | ||
| 3352 | + // the planes through. | ||
| 3353 | + let (y, u, v, width, height) = if pixel_aspect.is_square() { | ||
| 3354 | + (y, u, v, width, height) | ||
| 3355 | + } else { | ||
| 3356 | + let display_width = pixel_aspect.width_factor(width); | ||
| 3357 | + let (dcw, dch) = ( | ||
| 3358 | + display_width.div_ceil(2) as usize, | ||
| 3359 | + height.div_ceil(2) as usize, | ||
| 3360 | + ); | ||
| 3361 | + stretched.0.resize(display_width as usize * height as usize, 0); | ||
| 3362 | + stretched.1.resize(dcw * dch, 0); | ||
| 3363 | + stretched.2.resize(dcw * dch, 0); | ||
| 3364 | + crate::scale::scale_i420( | ||
| 3365 | + y, | ||
| 3366 | + u, | ||
| 3367 | + v, | ||
| 3368 | + width as usize, | ||
| 3369 | + height as usize, | ||
| 3370 | + &mut stretched.0, | ||
| 3371 | + &mut stretched.1, | ||
| 3372 | + &mut stretched.2, | ||
| 3373 | + display_width as usize, | ||
| 3374 | + height as usize, | ||
| 3375 | + ); | ||
| 3376 | + ( | ||
| 3377 | + &stretched.0[..], | ||
| 3378 | + &stretched.1[..], | ||
| 3379 | + &stretched.2[..], | ||
| 3380 | + display_width, | ||
| 3381 | + height, | ||
| 3382 | + ) | ||
| 3383 | + }; | ||
| 3248 | // The file's own turn, taken exactly as playback's decode funnel takes it | 3384 | // The file's own turn, taken exactly as playback's decode funnel takes it |
| 3249 | // ([`crate::decode`]): a phone's portrait video is landscape in the file, | 3385 | // ([`crate::decode`]): a phone's portrait video is landscape in the file, |
| 3250 | // and the encoder must be fed what the preview showed. A file that states | 3386 | // and the encoder must be fed what the preview showed. A file that states |
| @@ -3334,13 +3470,26 @@ fn remap_into( | |||
| 3334 | fn source_rate( | 3470 | fn source_rate( |
| 3335 | path: &Path, | 3471 | path: &Path, |
| 3336 | timeline_fps: f64, | 3472 | timeline_fps: f64, |
| 3337 | -) -> (Rate, ColorDescription, Option<f32>, Rotation) { | 3473 | +) -> ( |
| 3474 | + Rate, | ||
| 3475 | + ColorDescription, | ||
| 3476 | + Option<f32>, | ||
| 3477 | + Rotation, | ||
| 3478 | + crate::demux::PixelAspect, | ||
| 3479 | +) { | ||
| 3338 | if crate::is_image(path) || crate::is_audio(path) { | 3480 | if crate::is_image(path) || crate::is_audio(path) { |
| 3339 | // A still is BT.601 by construction whatever it was authored as: | 3481 | // A still is BT.601 by construction whatever it was authored as: |
| 3340 | // `decode::rgb_to_i420` is the one matrix that turns its pixels into | 3482 | // `decode::rgb_to_i420` is the one matrix that turns its pixels into |
| 3341 | // planes. A song has no picture and the answer is never read. Neither | 3483 | // planes. A song has no picture and the answer is never read. Neither |
| 3342 | - // has a display matrix to be turned by. | 3484 | + // has a display matrix to be turned by, nor an aspect to be widened |
| 3343 | - return (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None); | 3485 | + // by: both are authored square. |
| 3486 | + return ( | ||
| 3487 | + Rate::REAL_TIME, | ||
| 3488 | + ColorDescription::default(), | ||
| 3489 | + None, | ||
| 3490 | + Rotation::None, | ||
| 3491 | + crate::demux::PixelAspect::SQUARE, | ||
| 3492 | + ); | ||
| 3344 | } | 3493 | } |
| 3345 | match Demuxer::open(path) { | 3494 | match Demuxer::open(path) { |
| 3346 | // ...and one whose rate cannot be named against the timeline's, which | 3495 | // ...and one whose rate cannot be named against the timeline's, which |
| @@ -3357,10 +3506,19 @@ fn source_rate( | |||
| 3357 | // The file's own turn, so the encoder is fed the picture the | 3506 | // The file's own turn, so the encoder is fed the picture the |
| 3358 | // preview shows: the same header read, one more answer. | 3507 | // preview shows: the same header read, one more answer. |
| 3359 | meta.rotation, | 3508 | meta.rotation, |
| 3509 | + // ...and its own sample aspect, for the same reason on the same | ||
| 3510 | + // read: the encoder is fed the shape the preview showed. | ||
| 3511 | + meta.pixel_aspect, | ||
| 3360 | ), | 3512 | ), |
| 3361 | // Unreadable here means unreadable below too, where the span dies with a | 3513 | // Unreadable here means unreadable below too, where the span dies with a |
| 3362 | // real message; the file's own space is the least of that. | 3514 | // real message; the file's own space is the least of that. |
| 3363 | - Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None, Rotation::None), | 3515 | + Err(_) => ( |
| 3516 | + Rate::REAL_TIME, | ||
| 3517 | + ColorDescription::default(), | ||
| 3518 | + None, | ||
| 3519 | + Rotation::None, | ||
| 3520 | + crate::demux::PixelAspect::SQUARE, | ||
| 3521 | + ), | ||
| 3364 | } | 3522 | } |
| 3365 | } | 3523 | } |
| 3366 | 3524 | ||
| @@ -5488,6 +5646,11 @@ mod tests { | |||
| 5488 | codec: crate::demux::Codec::H264, | 5646 | codec: crate::demux::Codec::H264, |
| 5489 | color: Default::default(), | 5647 | color: Default::default(), |
| 5490 | rotation: Rotation::None, | 5648 | rotation: Rotation::None, |
| 5649 | + // Square pixels, coded where they are declared: a meta no container | ||
| 5650 | + // wrote, so nothing was read to disagree with it. | ||
| 5651 | + coded_width: width, | ||
| 5652 | + coded_height: height, | ||
| 5653 | + pixel_aspect: crate::demux::PixelAspect::SQUARE, | ||
| 5491 | }; | 5654 | }; |
| 5492 | // 1280 * 720 * 30 * 0.1 | 5655 | // 1280 * 720 * 30 * 0.1 |
| 5493 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); | 5656 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); |
| @@ -5540,6 +5703,11 @@ mod tests { | |||
| 5540 | codec: crate::demux::Codec::H264, | 5703 | codec: crate::demux::Codec::H264, |
| 5541 | color: Default::default(), | 5704 | color: Default::default(), |
| 5542 | rotation: Rotation::None, | 5705 | rotation: Rotation::None, |
| 5706 | + // Square pixels, coded where they are declared: a meta no | ||
| 5707 | + // container wrote, so nothing was read to disagree with it. | ||
| 5708 | + coded_width: width, | ||
| 5709 | + coded_height: height, | ||
| 5710 | + pixel_aspect: crate::demux::PixelAspect::SQUARE, | ||
| 5543 | } | 5711 | } |
| 5544 | } | 5712 | } |
| 5545 | 5713 | ||
crates/engine/src/hw.rsmodified+26 -5
| @@ -15,7 +15,7 @@ | |||
| 15 | //! path -- the same "no" it gives for an unsupported profile, and the caller's | 15 | //! path -- the same "no" it gives for an unsupported profile, and the caller's |
| 16 | //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. | 16 | //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. |
| 17 | 17 | ||
| 18 | -use std::ffi::{CString, c_char, c_void}; | 18 | +use std::ffi::{c_char, c_void, CString}; |
| 19 | use std::os::fd::FromRawFd; | 19 | use std::os::fd::FromRawFd; |
| 20 | use std::path::{Path, PathBuf}; | 20 | use std::path::{Path, PathBuf}; |
| 21 | use std::sync::OnceLock; | 21 | use std::sync::OnceLock; |
| @@ -26,7 +26,18 @@ use crate::colorspace::ColorDescription; | |||
| 26 | 26 | ||
| 27 | const LIB_NAME: &str = "libengine_hw.so"; | 27 | const LIB_NAME: &str = "libengine_hw.so"; |
| 28 | 28 | ||
| 29 | -/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]. | 29 | +/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]'s picture half -- |
| 30 | +/// the four fields a session was opened with, plus the coded pair and the | ||
| 31 | +/// sample aspect a display size can now differ from the coded one by. | ||
| 32 | +/// | ||
| 33 | +/// `width`/`height` are the *displayed* shape, exactly as [`crate::VideoMeta`] | ||
| 34 | +/// promises: a plugin opened on a rotated file has always been handed a | ||
| 35 | +/// swapped pair here, and the pictures it hands back are sized by its own | ||
| 36 | +/// decoder's output, which is the coded pair. `coded_width`/`coded_height` | ||
| 37 | +/// name that pair explicitly, and `pixel_aspect_h`/`_v` carry the ratio one | ||
| 38 | +/// coded pixel is drawn at, so a caller that needs the stored shape (a copy | ||
| 39 | +/// declaring a track, an encoder agreeing on a surface) asks the coded one and | ||
| 40 | +/// a caller that draws asks the display one -- both answered, neither derived. | ||
| 30 | #[repr(C)] | 41 | #[repr(C)] |
| 31 | #[derive(Default)] | 42 | #[derive(Default)] |
| 32 | pub struct VhMeta { | 43 | pub struct VhMeta { |
| @@ -34,6 +45,13 @@ pub struct VhMeta { | |||
| 34 | pub height: u32, | 45 | pub height: u32, |
| 35 | pub frame_rate: f64, | 46 | pub frame_rate: f64, |
| 36 | pub frame_count: u32, | 47 | pub frame_count: u32, |
| 48 | + /// What the samples are stored at, before any turn or stretch. | ||
| 49 | + pub coded_width: u32, | ||
| 50 | + pub coded_height: u32, | ||
| 51 | + /// The sample aspect ratio, h over v, square as 1 and 1 -- or 0 and 0, | ||
| 52 | + /// which is `Default` and reads square ([`crate::demux::PixelAspect`]). | ||
| 53 | + pub pixel_aspect_h: u32, | ||
| 54 | + pub pixel_aspect_v: u32, | ||
| 37 | } | 55 | } |
| 38 | 56 | ||
| 39 | /// One decoded picture as planar I420. Pointers belong to the plugin and stay | 57 | /// One decoded picture as planar I420. Pointers belong to the plugin and stay |
| @@ -371,7 +389,9 @@ impl HwSession { | |||
| 371 | /// for a few pictures only: encode it before asking this for a few more. | 389 | /// for a few pictures only: encode it before asking this for a few more. |
| 372 | pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> { | 390 | pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> { |
| 373 | let Some(next_dma) = self.plugin.next_frame_dma else { | 391 | let Some(next_dma) = self.plugin.next_frame_dma else { |
| 374 | - return Ok(self.next_frame()?.map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); | 392 | + return Ok(self |
| 393 | + .next_frame()? | ||
| 394 | + .map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); | ||
| 375 | }; | 395 | }; |
| 376 | let mut frame = VhFrame::default(); | 396 | let mut frame = VhFrame::default(); |
| 377 | let mut dma = VhDma::default(); | 397 | let mut dma = VhDma::default(); |
| @@ -482,8 +502,9 @@ struct EncPlugin { | |||
| 482 | /// neither and every picture reaches it as bytes, which is what it always | 502 | /// neither and every picture reaches it as bytes, which is what it always |
| 483 | /// did. | 503 | /// did. |
| 484 | dma_geometry: Option<unsafe extern "C" fn(*mut c_void, *mut u32, *mut u32) -> i32>, | 504 | dma_geometry: Option<unsafe extern "C" fn(*mut c_void, *mut u32, *mut u32) -> i32>, |
| 485 | - frame_dma: | 505 | + frame_dma: Option< |
| 486 | - Option<unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32>, | 506 | + unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32, |
| 507 | + >, | ||
| 487 | drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, | 508 | drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, |
| 488 | close: unsafe extern "C" fn(*mut c_void), | 509 | close: unsafe extern "C" fn(*mut c_void), |
| 489 | // Never dropped (lives in a static), so the fn pointers above stay valid. | 510 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
crates/engine/src/mux.rsmodified+30 -0
| @@ -949,6 +949,17 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 949 | const VIDEO: u32 = 0xE0; | 949 | const VIDEO: u32 = 0xE0; |
| 950 | const PIXEL_WIDTH: u32 = 0xB0; | 950 | const PIXEL_WIDTH: u32 = 0xB0; |
| 951 | const PIXEL_HEIGHT: u32 = 0xBA; | 951 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 952 | +// How the copied picture is drawn: the same elements [`crate::demux`] reads | ||
| 953 | +// back. `DisplayUnit` 4 spells the pair as the sample aspect ratio itself and | ||
| 954 | +// 3 as a display aspect ratio; this writer says SAR (unit 4) because that is | ||
| 955 | +// the ratio it was handed ([`crate::demux::PixelAspect`]) and the one a | ||
| 956 | +// round-trip through this engine's own reader reproduces exactly. Square -- | ||
| 957 | +// the default these elements are optional for -- writes none of them, which is | ||
| 958 | +// what keeps every existing copy's header byte-identical. | ||
| 959 | +const DISPLAY_WIDTH: u32 = 0x54B0; | ||
| 960 | +const DISPLAY_HEIGHT: u32 = 0x54BA; | ||
| 961 | +const DISPLAY_UNIT: u32 = 0x54B2; | ||
| 962 | +const DISPLAY_UNIT_SAR: u64 = 4; | ||
| 952 | // `Colour` and the four children this writes, all inside `Video`. Byte-verified | 963 | // `Colour` and the four children this writes, all inside `Video`. Byte-verified |
| 953 | // against what `demux` reads back and what ffprobe reports: the spec tables that | 964 | // against what `demux` reads back and what ffprobe reports: the spec tables that |
| 954 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. | 965 | // list Range as 0x55B3 are describing ChromaSubsamplingHorz. |
| @@ -1044,6 +1055,12 @@ pub struct CopyParams<'a> { | |||
| 1044 | /// grading display. Upgrade path is a `Colour` element written from that | 1055 | /// grading display. Upgrade path is a `Colour` element written from that |
| 1045 | /// same struct. | 1056 | /// same struct. |
| 1046 | pub colour: ColorDescription, | 1057 | pub colour: ColorDescription, |
| 1058 | + /// The ratio one of the copied samples' pixels is drawn at, written as the | ||
| 1059 | + /// track's `Display*` elements: the aspect is metadata about the samples, | ||
| 1060 | + /// which are the source's own, so it travels instead of being baked in -- | ||
| 1061 | + /// ffmpeg's own copy behaviour. [`PixelAspect::SQUARE`] writes nothing, | ||
| 1062 | + /// which is every square-pixel file's header exactly as it was. | ||
| 1063 | + pub pixel_aspect: crate::demux::PixelAspect, | ||
| 1047 | } | 1064 | } |
| 1048 | 1065 | ||
| 1049 | /// The soft subtitle track a file carries beside the picture: text, timed, still | 1066 | /// The soft subtitle track a file carries beside the picture: text, timed, still |
| @@ -1168,6 +1185,7 @@ impl MkvMuxer { | |||
| 1168 | b"V_AV1", | 1185 | b"V_AV1", |
| 1169 | &av1c, | 1186 | &av1c, |
| 1170 | ColorDescription::output(video.height), | 1187 | ColorDescription::output(video.height), |
| 1188 | + crate::demux::PixelAspect::SQUARE, | ||
| 1171 | audio, | 1189 | audio, |
| 1172 | subs, | 1190 | subs, |
| 1173 | ) | 1191 | ) |
| @@ -1197,6 +1215,7 @@ impl MkvMuxer { | |||
| 1197 | b"V_MPEGH/ISO/HEVC", | 1215 | b"V_MPEGH/ISO/HEVC", |
| 1198 | video.hvcc, | 1216 | video.hvcc, |
| 1199 | ColorDescription::output(video.height), | 1217 | ColorDescription::output(video.height), |
| 1218 | + crate::demux::PixelAspect::SQUARE, | ||
| 1200 | audio, | 1219 | audio, |
| 1201 | subs, | 1220 | subs, |
| 1202 | ) | 1221 | ) |
| @@ -1229,6 +1248,7 @@ impl MkvMuxer { | |||
| 1229 | video.codec_id, | 1248 | video.codec_id, |
| 1230 | video.codec_private, | 1249 | video.codec_private, |
| 1231 | video.colour, | 1250 | video.colour, |
| 1251 | + video.pixel_aspect, | ||
| 1232 | audio, | 1252 | audio, |
| 1233 | subs, | 1253 | subs, |
| 1234 | ) | 1254 | ) |
| @@ -1243,6 +1263,7 @@ impl MkvMuxer { | |||
| 1243 | codec_id: &[u8], | 1263 | codec_id: &[u8], |
| 1244 | codec_private: &[u8], | 1264 | codec_private: &[u8], |
| 1245 | colour: ColorDescription, | 1265 | colour: ColorDescription, |
| 1266 | + pixel_aspect: crate::demux::PixelAspect, | ||
| 1246 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 1267 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 1247 | subs: Vec<SubParams>, | 1268 | subs: Vec<SubParams>, |
| 1248 | ) -> crate::Result<Self> { | 1269 | ) -> crate::Result<Self> { |
| @@ -1308,6 +1329,15 @@ impl MkvMuxer { | |||
| 1308 | let mut dims = Vec::new(); | 1329 | let mut dims = Vec::new(); |
| 1309 | uint(&mut dims, PIXEL_WIDTH, u64::from(width)); | 1330 | uint(&mut dims, PIXEL_WIDTH, u64::from(width)); |
| 1310 | uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); | 1331 | uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); |
| 1332 | + // The copied samples' aspect, where it is not square: the same three | ||
| 1333 | + // elements this engine's own reader asks a Matroska track for, as a | ||
| 1334 | + // sample aspect ratio (unit 4). A square copy writes none of them -- | ||
| 1335 | + // exactly the header every square-pixel copy wrote before this. | ||
| 1336 | + if !pixel_aspect.is_square() { | ||
| 1337 | + uint(&mut dims, DISPLAY_WIDTH, u64::from(pixel_aspect.h)); | ||
| 1338 | + uint(&mut dims, DISPLAY_HEIGHT, u64::from(pixel_aspect.v)); | ||
| 1339 | + uint(&mut dims, DISPLAY_UNIT, DISPLAY_UNIT_SAR); | ||
| 1340 | + } | ||
| 1311 | // What the samples in those pixels mean. Written rather than left to a | 1341 | // What the samples in those pixels mean. Written rather than left to a |
| 1312 | // reader's own 720-line guess -- the guess is right for an encoded file | 1342 | // reader's own 720-line guess -- the guess is right for an encoded file |
| 1313 | // (the export remaps every clip into exactly that space) but a remuxer | 1343 | // (the export remaps every clip into exactly that space) but a remuxer |
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 the | 739 | // 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 and | 545 | // 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 that | 546 | // 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 part | 553 | // 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 a | 554 | // 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 it | 725 | // 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 | path | 738 | 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/anamorphic.rsadded+484 -0
| @@ -0,0 +1,484 @@ | |||
| 1 | +//! The sample aspect ratio: a file whose pixels are not square is drawn | ||
| 2 | +//! wider than they are stored, and every rendition this engine makes -- | ||
| 3 | +//! the probe, the preview and the export -- is the drawn one. | ||
| 4 | +//! | ||
| 5 | +//! `test_anamorphic.mp4` and `test_anamorphic.mkv` (`scripts/gen_fixtures.sh`) | ||
| 6 | +//! are one 1440x1080 source with `setsar=4/3` asked of it: the classic | ||
| 7 | +//! anamorphic 16:9 frame on a 4:3 raster, the way a DVD rip says "widen me". | ||
| 8 | +//! The engine's answer is ffmpeg's own: the decode keeps the coded pixels, | ||
| 9 | +//! the container's ratio is read as metadata, and the stretch is applied | ||
| 10 | +//! exactly once, at the conversion to the square-pixel raster -- so the | ||
| 11 | +//! preview shows 1920x1080 and the corners of it are picture, not bars. | ||
| 12 | +//! | ||
| 13 | +//! The copy door is the other half of ffmpeg's behaviour: a copied file | ||
| 14 | +//! keeps the coded pixels and carries the ratio beside them (Matroska's | ||
| 15 | +//! `Display*` elements), and where the container cannot state it -- an mp4 | ||
| 16 | +//! has no `pasp` in this writer -- a copy refuses by name rather than | ||
| 17 | +//! writing a header that lies about its own shape. | ||
| 18 | +//! | ||
| 19 | +//! ```text | ||
| 20 | +//! cargo test -p engine --release --test anamorphic -- --test-threads=1 | ||
| 21 | +//! ``` | ||
| 22 | + | ||
| 23 | +use std::path::PathBuf; | ||
| 24 | +use std::sync::Once; | ||
| 25 | +use std::time::{Duration, Instant}; | ||
| 26 | + | ||
| 27 | +use engine::demux::Demuxer; | ||
| 28 | +use engine::export::{ExportSettings, Format}; | ||
| 29 | +use engine::scratch::Scratch; | ||
| 30 | +use engine::PlaybackSession; | ||
| 31 | + | ||
| 32 | +fn asset(name: &str) -> PathBuf { | ||
| 33 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 34 | + .join("../../assets") | ||
| 35 | + .join(name) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Which seat an export takes is decided by *process-wide* environment | ||
| 39 | +/// variables, so a test binary that shares the machine has to borrow them | ||
| 40 | +/// rather than assume: this pins both decode and encode to software, which is | ||
| 41 | +/// the seat every machine has, and holds the borrow for the whole test binary. | ||
| 42 | +static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); | ||
| 43 | + | ||
| 44 | +type Shared = std::sync::RwLockReadGuard<'static, ()>; | ||
| 45 | + | ||
| 46 | +#[must_use = "the seat pin holds only while its guard is alive"] | ||
| 47 | +fn pin_software() -> Shared { | ||
| 48 | + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); | ||
| 49 | + static PIN: Once = Once::new(); | ||
| 50 | + PIN.call_once(|| unsafe { | ||
| 51 | + std::env::set_var("VE_SW", "1"); | ||
| 52 | + std::env::set_var("VE_SW_ENC", "1"); | ||
| 53 | + }); | ||
| 54 | + borrowed | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +fn wait(handle: &engine::ExportHandle, limit: Duration) -> engine::Result<()> { | ||
| 58 | + let started = Instant::now(); | ||
| 59 | + while !handle.is_finished() { | ||
| 60 | + assert!( | ||
| 61 | + started.elapsed() < limit, | ||
| 62 | + "export did not finish in {limit:?}" | ||
| 63 | + ); | ||
| 64 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 65 | + } | ||
| 66 | + handle.result().expect("a finished export has an outcome") | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// The coded and displayed shapes every anamorphic test here agrees on: | ||
| 70 | +/// 1440x1080 stored, 4/3 drawn, 1920x1080 shown. | ||
| 71 | +const CODED: (u32, u32) = (1440, 1080); | ||
| 72 | +const DISPLAY: (u32, u32) = (1920, 1080); | ||
| 73 | + | ||
| 74 | +/// The reduced form of `h/v`, so a ratio stated unreduced (a DAR pair like | ||
| 75 | +/// ffmpeg's 17280/12960) compares equal to its simplest spelling. | ||
| 76 | +fn gcd(mut a: u32, mut b: u32) -> u32 { | ||
| 77 | + while b != 0 { | ||
| 78 | + (a, b) = (b, a % b); | ||
| 79 | + } | ||
| 80 | + a.max(1) | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// The header says what the samples are and what they are drawn at, and both | ||
| 84 | +/// doors say the same thing about the same picture. | ||
| 85 | +#[test] | ||
| 86 | +fn the_container_aspect_is_probed_off_both_doors() { | ||
| 87 | + for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { | ||
| 88 | + let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture"); | ||
| 89 | + assert_eq!( | ||
| 90 | + (meta.coded_width, meta.coded_height), | ||
| 91 | + CODED, | ||
| 92 | + "{file}: the samples are stored at the coded size" | ||
| 93 | + ); | ||
| 94 | + assert_eq!( | ||
| 95 | + (meta.width, meta.height), | ||
| 96 | + DISPLAY, | ||
| 97 | + "{file}: 4/3 over 1440x1080 is drawn 1920x1080" | ||
| 98 | + ); | ||
| 99 | + // The mkv door reads ffmpeg's DAR spelling (16/9) and the mp4 door the | ||
| 100 | + // SAR itself (4/3); both name the same drawn picture, so the test | ||
| 101 | + // compares the reduced ratio, not the spelling. | ||
| 102 | + let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v); | ||
| 103 | + let g = gcd(h, v); | ||
| 104 | + assert_eq!( | ||
| 105 | + (h / g, v / g), | ||
| 106 | + (4, 3), | ||
| 107 | + "{file}: the ratio one coded pixel is drawn at" | ||
| 108 | + ); | ||
| 109 | + assert!(!meta.pixel_aspect.is_square(), "{file}: it is not square"); | ||
| 110 | + assert_eq!( | ||
| 111 | + meta.rotation, | ||
| 112 | + engine::Rotation::None, | ||
| 113 | + "{file}: no turn was asked of it" | ||
| 114 | + ); | ||
| 115 | + } | ||
| 116 | + // A square-pixel file states none of it, and both doors answer square: | ||
| 117 | + // the default that makes the whole feature invisible to the ordinary | ||
| 118 | + // library. | ||
| 119 | + for file in ["test_baseline.mp4", "test_rotation90.mp4"] { | ||
| 120 | + let (meta, _) = Demuxer::open(&asset(file)).expect("open a fixture"); | ||
| 121 | + assert!( | ||
| 122 | + meta.pixel_aspect.is_square(), | ||
| 123 | + "{file}: no container said an aspect, so the pixels are square" | ||
| 124 | + ); | ||
| 125 | + // Drawn one to one: the displayed pair is the coded pair, swapped | ||
| 126 | + // where the file's matrix turns it and never widened. | ||
| 127 | + let (dw, dh) = match meta.rotation.swaps_axes() { | ||
| 128 | + true => (meta.coded_height, meta.coded_width), | ||
| 129 | + false => (meta.coded_width, meta.coded_height), | ||
| 130 | + }; | ||
| 131 | + assert_eq!( | ||
| 132 | + (meta.width, meta.height), | ||
| 133 | + (dw, dh), | ||
| 134 | + "{file}: drawn one to one, swapped only by the turn" | ||
| 135 | + ); | ||
| 136 | + } | ||
| 137 | + // The rotation still swaps on an anamorphic file whose *matrix* asks for | ||
| 138 | + // a turn: the composition is stretch the coded width, then swap -- the | ||
| 139 | + // order the render applies ([`crate::decode::Render::frame`]). The | ||
| 140 | + // fixture carries a REAL display matrix (a `-display_rotation 90` remux, | ||
| 141 | + // the gen_fixtures pattern), because a `setsar`-only file asserts nothing | ||
| 142 | + // about the turn -- the case this whole block exists for. | ||
| 143 | + let turned = asset(".anamorphic_turned.mp4"); | ||
| 144 | + let made = std::process::Command::new("ffmpeg") | ||
| 145 | + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) | ||
| 146 | + .arg("testsrc2=size=1440x1080:rate=30:duration=1") | ||
| 147 | + .args([ | ||
| 148 | + "-vf", | ||
| 149 | + "setsar=4/3", | ||
| 150 | + "-c:v", | ||
| 151 | + "libx264", | ||
| 152 | + "-profile:v", | ||
| 153 | + "baseline", | ||
| 154 | + "-pix_fmt", | ||
| 155 | + "yuv420p", | ||
| 156 | + ]) | ||
| 157 | + .arg(&turned) | ||
| 158 | + .status() | ||
| 159 | + .is_ok_and(|s| s.success()); | ||
| 160 | + if made { | ||
| 161 | + // The same file with a 90-degree display matrix asked of it. | ||
| 162 | + let matrix_on = asset(".anamorphic_turned90.mp4"); | ||
| 163 | + let remuxed = std::process::Command::new("ffmpeg") | ||
| 164 | + .args(["-y", "-v", "error", "-display_rotation", "90", "-i"]) | ||
| 165 | + .arg(&turned) | ||
| 166 | + .args(["-c", "copy"]) | ||
| 167 | + .arg(&matrix_on) | ||
| 168 | + .status() | ||
| 169 | + .is_ok_and(|s| s.success()); | ||
| 170 | + if remuxed { | ||
| 171 | + let (meta, _) = Demuxer::open(&matrix_on).expect("open the turned fixture"); | ||
| 172 | + // The probe: coded 1440x1080 stays; the SAR-4/3 widen of the | ||
| 173 | + // coded width (1920) is what the turn swaps into the height, so | ||
| 174 | + // the displayed pair is 1080x1920 -- DAR 9:16, the ratio ffprobe | ||
| 175 | + // reports for the same file turned. A turn-then-stretch probe | ||
| 176 | + // would declare 1440x1440 here; a stretch-on-the-wrong-axis | ||
| 177 | + // render paints exactly that square into this 9:16 canvas. | ||
| 178 | + assert_eq!( | ||
| 179 | + (meta.coded_width, meta.coded_height), | ||
| 180 | + (1440, 1080), | ||
| 181 | + "the turned fixture's samples" | ||
| 182 | + ); | ||
| 183 | + assert_eq!( | ||
| 184 | + meta.rotation, | ||
| 185 | + engine::Rotation::Cw270, | ||
| 186 | + "the matrix was read as a quarter turn" | ||
| 187 | + ); | ||
| 188 | + assert_eq!( | ||
| 189 | + (meta.width, meta.height), | ||
| 190 | + (1080, 1920), | ||
| 191 | + "the aspect widens the coded width; the turn swaps the stretched pair" | ||
| 192 | + ); | ||
| 193 | + // ...and the render agrees with the probe: the composed picture | ||
| 194 | + // is handed out at the displayed pair, filled to the corners -- | ||
| 195 | + // the 1440x1440 failure the other order produces would fail both | ||
| 196 | + // assertions. | ||
| 197 | + let (_, frames, _) = | ||
| 198 | + engine::DecodeSession::open_at(&matrix_on, 0).expect("open for a frame"); | ||
| 199 | + let frame = frames.recv().expect("a first frame"); | ||
| 200 | + assert_eq!( | ||
| 201 | + (frame.width, frame.height), | ||
| 202 | + (1080, 1920), | ||
| 203 | + "the rendered picture is the displayed pair" | ||
| 204 | + ); | ||
| 205 | + let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 206 | + let at = |x: usize, y: usize| { | ||
| 207 | + let i = (y * w + x) * 4; | ||
| 208 | + (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2]) | ||
| 209 | + }; | ||
| 210 | + let m = w / 10; | ||
| 211 | + let corners = [ | ||
| 212 | + at(m, m), | ||
| 213 | + at(w - 1 - m, m), | ||
| 214 | + at(w - 1 - m, h - 1 - m), | ||
| 215 | + at(m, h - 1 - m), | ||
| 216 | + ]; | ||
| 217 | + assert!( | ||
| 218 | + corners | ||
| 219 | + .iter() | ||
| 220 | + .all(|&(b, g, r)| u32::from(r) + u32::from(g) + u32::from(b) > 48), | ||
| 221 | + "the corners are picture, not black: {corners:?}" | ||
| 222 | + ); | ||
| 223 | + } | ||
| 224 | + let _ = std::fs::remove_file(&turned); | ||
| 225 | + let _ = std::fs::remove_file(&matrix_on); | ||
| 226 | + } | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/// The preview: the composed picture is the displayed shape, filled to the | ||
| 230 | +/// corners -- no letterbox, no squeeze, no coded-shaped picture drawn into a | ||
| 231 | +/// wider window. The corner gate is numeric: a picture that left bars would | ||
| 232 | +/// sample black. | ||
| 233 | +#[test] | ||
| 234 | +fn the_preview_shows_the_drawn_picture() { | ||
| 235 | + let _seat = pin_software(); | ||
| 236 | + for file in ["test_anamorphic.mp4", "test_anamorphic.mkv"] { | ||
| 237 | + let (_, frames, _) = | ||
| 238 | + engine::DecodeSession::open_at(&asset(file), 0).expect("open for a frame"); | ||
| 239 | + let frame = frames.recv().expect("a first frame"); | ||
| 240 | + assert_eq!( | ||
| 241 | + (frame.width, frame.height), | ||
| 242 | + DISPLAY, | ||
| 243 | + "{file}: the composed picture is the drawn shape" | ||
| 244 | + ); | ||
| 245 | + let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 246 | + let at = |x: usize, y: usize| { | ||
| 247 | + let i = (y * w + x) * 4; | ||
| 248 | + let (b, g, r) = (frame.bgra[i], frame.bgra[i + 1], frame.bgra[i + 2]); | ||
| 249 | + (u32::from(r), u32::from(g), u32::from(b)) | ||
| 250 | + }; | ||
| 251 | + let m = w / 10; | ||
| 252 | + let corners = [ | ||
| 253 | + at(m, m), | ||
| 254 | + at(w - 1 - m, m), | ||
| 255 | + at(w - 1 - m, h - 1 - m), | ||
| 256 | + at(m, h - 1 - m), | ||
| 257 | + ]; | ||
| 258 | + assert!( | ||
| 259 | + corners.iter().all(|(r, g, b)| *r + *g + *b > 48), | ||
| 260 | + "{file}: the corners are picture, not black: {corners:?}" | ||
| 261 | + ); | ||
| 262 | + let dar = w as f64 / h as f64; | ||
| 263 | + assert!( | ||
| 264 | + (dar - 16.0 / 9.0).abs() < 0.01, | ||
| 265 | + "{file}: the measured display aspect is 16:9, measured {dar:.4}" | ||
| 266 | + ); | ||
| 267 | + } | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// The export: the drawn shape is what the file says, and the pixels are the | ||
| 271 | +/// ones the preview showed -- re-encoded, so the new file is square-pixel at | ||
| 272 | +/// the displayed size and states no aspect of its own. | ||
| 273 | +#[test] | ||
| 274 | +fn an_export_of_an_anamorphic_file_is_drawn_and_square() { | ||
| 275 | + let _seat = pin_software(); | ||
| 276 | + let source = asset("test_anamorphic.mkv"); | ||
| 277 | + let mut session = PlaybackSession::open(&source).expect("open the fixture"); | ||
| 278 | + session.pause(); | ||
| 279 | + let preview = loop { | ||
| 280 | + if let Some(frame) = session.try_frame() { | ||
| 281 | + break frame; | ||
| 282 | + } | ||
| 283 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 284 | + }; | ||
| 285 | + let out = Scratch::file("ve_anamorphic_export", "mp4"); | ||
| 286 | + let handle = session.export_to_with(&out, &ExportSettings::default()); | ||
| 287 | + wait(&handle, Duration::from_secs(120)).expect("export"); | ||
| 288 | + | ||
| 289 | + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 290 | + assert_eq!( | ||
| 291 | + (meta.coded_width, meta.coded_height), | ||
| 292 | + DISPLAY, | ||
| 293 | + "the re-encoded file is coded at the displayed shape" | ||
| 294 | + ); | ||
| 295 | + assert!( | ||
| 296 | + meta.pixel_aspect.is_square(), | ||
| 297 | + "the aspect was applied, not carried: the export states none" | ||
| 298 | + ); | ||
| 299 | + // Preview vs export, same clip: the drawn picture to the byte. | ||
| 300 | + let mut reopened = PlaybackSession::open(&out).expect("reopen the export"); | ||
| 301 | + let exported = loop { | ||
| 302 | + if let Some(frame) = reopened.try_frame() { | ||
| 303 | + break frame; | ||
| 304 | + } | ||
| 305 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 306 | + }; | ||
| 307 | + assert_eq!( | ||
| 308 | + (exported.width, exported.height), | ||
| 309 | + DISPLAY, | ||
| 310 | + "the export plays at the drawn shape" | ||
| 311 | + ); | ||
| 312 | + // Encode is lossy, so the picture is measured, not diffed: a wrong shape | ||
| 313 | + // or a squeezed picture would move far more than a rounding code. | ||
| 314 | + let moved = preview | ||
| 315 | + .bgra | ||
| 316 | + .iter() | ||
| 317 | + .zip(&exported.bgra) | ||
| 318 | + .map(|(a, b)| u32::from(a.abs_diff(*b))) | ||
| 319 | + .sum::<u32>(); | ||
| 320 | + let mean = moved as f64 / preview.bgra.len() as f64; | ||
| 321 | + assert!( | ||
| 322 | + mean < 2.0, | ||
| 323 | + "the export is {mean:.2} mean codes from the preview -- not the same picture" | ||
| 324 | + ); | ||
| 325 | + | ||
| 326 | + // The same contract for a ROTATED anamorphic source: the fixture carries a | ||
| 327 | + // real display matrix, the probe declares 1080x1920, and the export must | ||
| 328 | + // be that shape with the picture the preview showed -- the case a | ||
| 329 | + // turn-then-stretch render filled with 1440x1440 and baked bars into. | ||
| 330 | + let plain = asset(".anamorphic_export_src.mp4"); | ||
| 331 | + let matrix_on = asset(".anamorphic_export_rot.mp4"); | ||
| 332 | + let made = std::process::Command::new("ffmpeg") | ||
| 333 | + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) | ||
| 334 | + .arg("testsrc2=size=1440x1080:rate=30:duration=1") | ||
| 335 | + .args([ | ||
| 336 | + "-vf", | ||
| 337 | + "setsar=4/3", | ||
| 338 | + "-c:v", | ||
| 339 | + "libx264", | ||
| 340 | + "-profile:v", | ||
| 341 | + "baseline", | ||
| 342 | + "-pix_fmt", | ||
| 343 | + "yuv420p", | ||
| 344 | + ]) | ||
| 345 | + .arg(&plain) | ||
| 346 | + .status() | ||
| 347 | + .is_ok_and(|s| s.success()) | ||
| 348 | + && std::process::Command::new("ffmpeg") | ||
| 349 | + .args(["-y", "-v", "error", "-display_rotation", "90", "-i"]) | ||
| 350 | + .arg(&plain) | ||
| 351 | + .args(["-c", "copy"]) | ||
| 352 | + .arg(&matrix_on) | ||
| 353 | + .status() | ||
| 354 | + .is_ok_and(|s| s.success()); | ||
| 355 | + if made { | ||
| 356 | + let mut session = PlaybackSession::open(&matrix_on).expect("open the turned fixture"); | ||
| 357 | + session.pause(); | ||
| 358 | + let preview = loop { | ||
| 359 | + if let Some(frame) = session.try_frame() { | ||
| 360 | + break frame; | ||
| 361 | + } | ||
| 362 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 363 | + }; | ||
| 364 | + assert_eq!((preview.width, preview.height), (1080, 1920)); | ||
| 365 | + let out = Scratch::file("ve_anamorphic_rot_export", "mp4"); | ||
| 366 | + let handle = session.export_to_with(&out, &ExportSettings::default()); | ||
| 367 | + wait(&handle, Duration::from_secs(120)).expect("export"); | ||
| 368 | + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 369 | + assert_eq!( | ||
| 370 | + (meta.coded_width, meta.coded_height), | ||
| 371 | + (1080, 1920), | ||
| 372 | + "the rotated export is coded at the displayed shape" | ||
| 373 | + ); | ||
| 374 | + assert!(meta.pixel_aspect.is_square(), "no aspect left to state"); | ||
| 375 | + let mut reopened = PlaybackSession::open(&out).expect("reopen the export"); | ||
| 376 | + let exported = loop { | ||
| 377 | + if let Some(frame) = reopened.try_frame() { | ||
| 378 | + break frame; | ||
| 379 | + } | ||
| 380 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 381 | + }; | ||
| 382 | + assert_eq!((exported.width, exported.height), (1080, 1920)); | ||
| 383 | + let moved = preview | ||
| 384 | + .bgra | ||
| 385 | + .iter() | ||
| 386 | + .zip(&exported.bgra) | ||
| 387 | + .map(|(a, b)| u32::from(a.abs_diff(*b))) | ||
| 388 | + .sum::<u32>(); | ||
| 389 | + let mean = moved as f64 / preview.bgra.len() as f64; | ||
| 390 | + assert!( | ||
| 391 | + mean < 2.0, | ||
| 392 | + "the rotated export is {mean:.2} mean codes from the preview" | ||
| 393 | + ); | ||
| 394 | + let _ = std::fs::remove_file(&plain); | ||
| 395 | + let _ = std::fs::remove_file(&matrix_on); | ||
| 396 | + } | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +/// The copy door, Matroska side: an anamorphic source's Exact row copies the | ||
| 400 | +/// coded blocks and carries the aspect beside them -- read back as the same | ||
| 401 | +/// 4/3 off the same elements the probe reads. | ||
| 402 | +#[test] | ||
| 403 | +fn a_matroska_copy_keeps_the_pixel_aspect() { | ||
| 404 | + // The copy itself decodes nothing, but opening the HEVC source and | ||
| 405 | + // reopening the copy do -- there is no software HEVC decoder, so both | ||
| 406 | + // need the plugin. A machine without it skips, exactly as | ||
| 407 | + // `video_copy`'s decode-back test does. | ||
| 408 | + let Ok(session) = PlaybackSession::open(asset("test_anamorphic_hevc.mkv")) else { | ||
| 409 | + println!("no VA-API plugin: skipping the copy-keeps-aspect test"); | ||
| 410 | + return; | ||
| 411 | + }; | ||
| 412 | + let out = Scratch::file("ve_anamorphic_copy", "mkv"); | ||
| 413 | + let handle = session.export_to_with( | ||
| 414 | + &out, | ||
| 415 | + &ExportSettings { | ||
| 416 | + format: Format::Hevc, | ||
| 417 | + ..Default::default() | ||
| 418 | + }, | ||
| 419 | + ); | ||
| 420 | + while !handle.is_finished() { | ||
| 421 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 422 | + } | ||
| 423 | + let encoders = handle.encoders().unwrap_or_default(); | ||
| 424 | + handle.result().expect("an outcome").expect("copy export"); | ||
| 425 | + assert!( | ||
| 426 | + encoders.contains("copy"), | ||
| 427 | + "an untouched anamorphic timeline copies: {encoders}" | ||
| 428 | + ); | ||
| 429 | + let (meta, _) = Demuxer::open(&out).expect("reopen the copy"); | ||
| 430 | + assert_eq!( | ||
| 431 | + (meta.coded_width, meta.coded_height), | ||
| 432 | + CODED, | ||
| 433 | + "the copied track declares the coded shape" | ||
| 434 | + ); | ||
| 435 | + let (h, v) = (meta.pixel_aspect.h, meta.pixel_aspect.v); | ||
| 436 | + let g = gcd(h, v); | ||
| 437 | + assert_eq!( | ||
| 438 | + (h / g, v / g), | ||
| 439 | + (4, 3), | ||
| 440 | + "the copied track states the aspect it was copied with" | ||
| 441 | + ); | ||
| 442 | + assert_eq!( | ||
| 443 | + (meta.width, meta.height), | ||
| 444 | + DISPLAY, | ||
| 445 | + "and so reads back as the drawn shape" | ||
| 446 | + ); | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +/// The copy door, mp4 side: the sample entry this writer produces has no | ||
| 450 | +/// `pasp` box, so an anamorphic source's Exact row refuses by name rather | ||
| 451 | +/// than writing a header that lies about its own shape -- and the export | ||
| 452 | +/// still re-encodes to the right shape when asked without Exact. | ||
| 453 | +#[test] | ||
| 454 | +fn an_mp4_copy_of_an_anamorphic_source_refuses_in_words() { | ||
| 455 | + let _seat = pin_software(); | ||
| 456 | + // The refusal is decided at the header read, but the session must open | ||
| 457 | + // the HEVC source first -- plugin on this machine or skip, as above. | ||
| 458 | + let Ok(session) = PlaybackSession::open(asset("test_anamorphic_hevc.mkv")) else { | ||
| 459 | + println!("no VA-API plugin: skipping the mp4 exact refusal test"); | ||
| 460 | + return; | ||
| 461 | + }; | ||
| 462 | + let out = Scratch::file("ve_anamorphic_exact_refused", "mp4"); | ||
| 463 | + let settings = ExportSettings { | ||
| 464 | + format: Format::Mp4, | ||
| 465 | + exact: true, | ||
| 466 | + ..Default::default() | ||
| 467 | + }; | ||
| 468 | + let handle = session.export_to_with(&out, &settings); | ||
| 469 | + wait(&handle, Duration::from_secs(300)) | ||
| 470 | + .expect_err("an mp4 cannot honour exact for an anamorphic source"); | ||
| 471 | + let error = handle | ||
| 472 | + .result() | ||
| 473 | + .expect("a finished export has an outcome") | ||
| 474 | + .expect_err("the export refused") | ||
| 475 | + .to_string(); | ||
| 476 | + assert!( | ||
| 477 | + error.contains("pixel aspect"), | ||
| 478 | + "the refusal names the aspect it would lose: {error}" | ||
| 479 | + ); | ||
| 480 | + assert!( | ||
| 481 | + !out.exists() || std::fs::read(&out).is_err(), | ||
| 482 | + "no lying header was written" | ||
| 483 | + ); | ||
| 484 | +} | ||
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/gen_fixtures.shmodified+31 -0
| @@ -769,5 +769,36 @@ for ext in mp4 mkv; do | |||
| 769 | done | 769 | done |
| 770 | rm -f assets/.rotation_tall_src.mp4 | 770 | rm -f assets/.rotation_tall_src.mp4 |
| 771 | 771 | ||
| 772 | +# The sample aspect ratio: `test_anamorphic.*` are one 1440x1080 source whose | ||
| 773 | +# pixels are drawn 4/3 wide -- the classic anamorphic 16:9 frame stored on a | ||
| 774 | +# 4:3 raster (`-vf setsar=4/3`), so the displayed picture is 1920x1080 and the | ||
| 775 | +# stored one never is. This is how a DVD rip and a Blu-ray remux say "widen | ||
| 776 | +# me": the pixels stay where the encoder put them and the container carries | ||
| 777 | +# the ratio. | ||
| 778 | +# | ||
| 779 | +# What each muxer actually writes, byte-verified by walking the output rather | ||
| 780 | +# than taken off a table: the Matroska muxer writes `DisplayWidth` 16, | ||
| 781 | +# `DisplayHeight` 9 and `DisplayUnit` 3 -- a *display aspect ratio* pair, not | ||
| 782 | +# a sample aspect ratio, and 4:3 SAR over 1440x1080 is exactly 16:9 DAR -- and | ||
| 783 | +# a square-pixel file gets no `Display*` element at all. The mp4 muxer writes | ||
| 784 | +# a `pasp` box (hSpacing 4, vSpacing 3) inside the `avc1` sample entry, and | ||
| 785 | +# 1/1 for a square one. `tests/anamorphic.rs` reads both spellings through the | ||
| 786 | +# engine and asserts the same displayed shape off either. | ||
| 787 | +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=1" \ | ||
| 788 | + -vf "setsar=4/3" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 789 | + assets/test_anamorphic.mp4 | ||
| 790 | +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=1" \ | ||
| 791 | + -vf "setsar=4/3" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 792 | + assets/test_anamorphic.mkv | ||
| 793 | + | ||
| 794 | +# ...and the anamorphic HEVC Matroska twin, for the copy path: `tests/`'s | ||
| 795 | +# copy door only copies HEVC or AV1 Matroska (`tests/video_copy.rs`), so an | ||
| 796 | +# anamorphic *copy* needs an anamorphic source in a codec that door takes. | ||
| 797 | +# Same source as above through libx265; the SAR rides the stream. | ||
| 798 | +ffmpeg -y -f lavfi -i "testsrc2=size=1440x1080:rate=30:duration=2" \ | ||
| 799 | + -vf "setsar=4/3" -c:v libx265 -pix_fmt yuv420p \ | ||
| 800 | + -x265-params "log-level=error:keyint=30:min-keyint=30" \ | ||
| 801 | + assets/test_anamorphic_hevc.mkv | ||
| 802 | + | ||
| 772 | 803 | ||
| 773 | echo "fixtures written to assets/" | 804 | echo "fixtures written to assets/" |
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 | + -- "$@" | ||