forge
Explore
Log in

Don't you dare go Hollow

copy(exact): the copy door keeps the pixel aspect, and an mp4 copy refuses it

Browse files at this commit

312b13e13dea73da6a4788a07bfd31e669c51845Ahmet Kaan GümüşParent: c3f9e0a
ffmpeg's own copy behaviour: the blocks are the source's coded pixels
and the aspect travels with them as container metadata. The Matroska
copy door now does that: CopyPlan compares CODED to CODED (the display
comparison would refuse every anamorphic source and then lie about the
track it wrote), declares the source's coded pair, and writes the
source's aspect as Display* elements -- unit 4, the SAR itself, the
ratio this engine's reader reproduces exactly. A square copy writes no
Display* at all, so every existing copy's header is byte-identical.

The mp4 copy cannot carry it: the sample entry this writer produces has
no pasp box, and a header that declares the coded pair while the pixels
are drawn 4/3 wide lies about its own shape. Refused by name -- 'a copy
would lose the pixel aspect' -- before the container's codec sentence,
so the export re-encodes into the square pixels the picture is drawn at
(mp4 export measured: 1920x1080, square).
crates/engine/src/export.rsmodified+74 -10
@@ -1743,8 +1743,15 @@ struct CopyPlan {
1743 /// copy.1743 /// copy.
1744 private: Vec<u8>,1744 private: Vec<u8>,
1745 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.
1746 width: u32,1749 width: u32,
1747 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,
1748 }1755 }
1749 1756
1750 /// A run of source blocks copied in one piece: what a cut leaves behind, and1757 /// A run of source blocks copied in one piece: what a cut leaves behind, and
@@ -1778,6 +1785,30 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti
1778 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {1785 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {
1779 return None;1786 return None;
1780 }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+ }
1781 let codec = match settings.format {1812 let codec = match settings.format {
1782 Format::Hevc => Codec::Hevc,1813 Format::Hevc => Codec::Hevc,
1783 Format::Av1 => Codec::Av1,1814 Format::Av1 => Codec::Av1,
@@ -1788,6 +1819,12 @@ pub fn exact_refusal(project: &Project, meta: &VideoMeta, settings: &ExportSetti
1788 ));1819 ));
1789 }1820 }
1790 };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.
1791 let carries = project.sources().iter().all(|source| {1828 let carries = project.sources().iter().all(|source| {
1792 crate::demux::is_matroska(&source.path)1829 crate::demux::is_matroska(&source.path)
1793 && Demuxer::open(&source.path)1830 && Demuxer::open(&source.path)
@@ -1817,7 +1854,7 @@ impl CopyPlan {
1817 };1854 };
1818 let entries = project.sources();1855 let entries = project.sources();
1819 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();
1820- let mut declared: Option<(Vec<u8>, ColorDescription)> = None;1857+ let mut declared: Option<(Vec<u8>, ColorDescription, crate::demux::PixelAspect)> = None;
1821 let mut regions: Vec<CopyRegion> = Vec::new();1858 let mut regions: Vec<CopyRegion> = Vec::new();
1822 let r_start = settings.range.map_or(0, |(s, _)| s);1859 let r_start = settings.range.map_or(0, |(s, _)| s);
1823 for span in export_spans(project, settings.range) {1860 for span in export_spans(project, settings.range) {
@@ -1875,20 +1912,42 @@ impl CopyPlan {
1875 // this export bakes the turn into the pixels -- so a copy would1912 // this export bakes the turn into the pixels -- so a copy would
1876 // ship the file sideways. Re-encoding is the only honest1913 // ship the file sideways. Re-encoding is the only honest
1877 // 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.
1878 if !source_meta.rotation.is_none()1933 if !source_meta.rotation.is_none()
1879 || source_meta.codec != codec1934 || source_meta.codec != codec
1880- || source_meta.width != meta.width1935+ || source_meta.coded_width != meta.coded_width
1881- || source_meta.height != meta.height1936+ || source_meta.coded_height != meta.coded_height
1882 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?1937 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
1883 != Rate::REAL_TIME1938 != Rate::REAL_TIME
1884 || !demuxer.plain_blocks()1939 || !demuxer.plain_blocks()
1885 {1940 {
1886 return None;1941 return None;
1887 }1942 }
1888- // One track, one configuration record and one `Colour`: two1943+ // Two sources that disagree about their pixel aspect are two
1889- // sources that disagree about either are two streams, and this1944+ // displayed pictures under one track; the copy declares one
1890- // writes one.1945+ // aspect or none.
1891- 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+ );
1892 if declared.get_or_insert(declares.clone()) != &declares {1951 if declared.get_or_insert(declares.clone()) != &declares {
1893 return None;1952 return None;
1894 }1953 }
@@ -1926,15 +1985,19 @@ impl CopyPlan {
1926 }),1985 }),
1927 }1986 }
1928 }1987 }
1929- let (private, colour) = declared?;1988+ let (private, colour, pixel_aspect) = declared?;
1930 Some(Self {1989 Some(Self {
1931 sources,1990 sources,
1932 regions,1991 regions,
1933 codec_id,1992 codec_id,
1934 private,1993 private,
1935 colour,1994 colour,
1936- width: meta.width,1995+ // The track the copy declares is the source's coded shape -- the
1937- 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,
1938 })2001 })
1939 }2002 }
1940 2003
@@ -1958,6 +2021,7 @@ impl CopyPlan {
1958 codec_id: self.codec_id,2021 codec_id: self.codec_id,
1959 codec_private: &self.private,2022 codec_private: &self.private,
1960 colour: self.colour,2023 colour: self.colour,
2024+ pixel_aspect: self.pixel_aspect,
1961 },2025 },
1962 audio,2026 audio,
1963 subs,2027 subs,
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-verified963 // `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 that964 // 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 that1055 /// 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, still1066 /// 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 a1341 // 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 file1342 // 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 remuxer1343 // (the export remaps every clip into exactly that space) but a remuxer