forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-af2cf156c2af6618f'

Browse files at this commit

cc667e6819d96fdfa32fc2debfcf76352e10da4cAhmet Kaan GümüşParent: 958e3d6907dfc5
crates/engine/src/colorspace.rsmodified+226 -2
@@ -1,7 +1,8 @@
11 //! What the numbers in a decoded picture *mean*: which YUV->RGB matrix they
22 //! were coded against, which transfer curve, and whether they span the full
3-//! byte or the limited 16..235 range. Everything here is read off the file;
4-//! nothing here converts anything yet.
3+//! byte or the limited 16..235 range. Everything but [`remap`] is read off the
4+//! file; that one is the other direction -- what an export does to a clip whose
5+//! matrix is not the one the file being written declares.
56 //!
67 //! Three tiers, in this order, per field:
78 //!
@@ -89,6 +90,88 @@ impl ColorDescription {
8990 full_range: tags.full_range.unwrap_or(false),
9091 }
9192 }
93+
94+ /// What an export of a `height`-line canvas *declares itself to be*, and
95+ /// therefore what every clip on it is remapped into: the same 720-line rule
96+ /// [`resolve`](Self::resolve)'s heuristic reads, so a file written here is
97+ /// read back as the space it was written in even by a reader that drops the
98+ /// tags. Limited range because both encoders here are configured for it, and
99+ /// SDR because nothing on this path tone-maps yet.
100+ pub fn output(height: u32) -> Self {
101+ Self {
102+ matrix: if height >= 720 {
103+ Matrix::Bt709
104+ } else {
105+ Matrix::Bt601
106+ },
107+ transfer: Transfer::Sdr,
108+ full_range: false,
109+ }
110+ }
111+
112+ /// The H.273 code points a container writes this as: primaries, transfer
113+ /// characteristics, matrix coefficients. The same table Matroska's `Colour`
114+ /// and mp4's `colr` both index, so one answer serves both muxers.
115+ pub fn codes(self) -> (u16, u16, u16) {
116+ // Primaries and the SDR curve travel with the matrix: a 709 file is
117+ // 1/1/1 and an SD one 6/6/6 (SMPTE 170M), which is what ffmpeg writes
118+ // for each and what a player expects to see together.
119+ let (primaries, sdr_transfer, matrix) = match self.matrix {
120+ Matrix::Bt709 => (1, 1, 1),
121+ Matrix::Bt601 => (6, 6, 6),
122+ Matrix::Bt2020Ncl => (9, 14, 9),
123+ };
124+ let transfer = match self.transfer {
125+ Transfer::Sdr => sdr_transfer,
126+ Transfer::Pq => 16,
127+ Transfer::Hlg => 18,
128+ };
129+ (primaries, transfer, matrix)
130+ }
131+}
132+
133+/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
134+/// against `to`, in place. Both spaces here are limited range with the same
135+/// primaries, so this is the matrix and nothing else: no gamut mapping, no range
136+/// scaling, and the 16/128/128 of black lands on itself either way -- which is
137+/// what makes a letterboxed bar and a gap's black frame cost nothing.
138+///
139+/// Derived from the two matrices, not tabulated: with R,G,B eliminated between
140+/// them, luma picks up a chroma term and the two chroma planes mix only with
141+/// each other -- so chroma never needs the luma plane and is remapped at its own
142+/// resolution, while luma reads the co-sited chroma sample the way
143+/// [`crate::convert::i420_to_bgra`] does. 8.8 fixed point, the same as every
144+/// other matrix in this engine.
145+///
146+/// A no-op when the two spaces are the same, so the caller may hand any pair.
147+pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) {
148+ // BT.2020 is never an output here (see [`ColorDescription::output`]) and a
149+ // 2020 source arrives on the tone-mapping path, not this one.
150+ // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr,
151+ // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values
152+ // the luma row's chroma terms carry a further 219/224, the ratio of the two
153+ // limited-range spans, while the chroma rows' do not (both sides are
154+ // chroma). That is the whole difference between these numbers and the
155+ // published ones.
156+ let coeffs = match (from, to) {
157+ (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262],
158+ // ...and its inverse, which round-trips to within a code.
159+ (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252],
160+ _ => return,
161+ };
162+ let [yb, yr, ub, ur, vb, vr] = coeffs;
163+ let cw = width.div_ceil(2);
164+ for (i, y) in y.iter_mut().enumerate() {
165+ let (row, col) = (i / width, i % width);
166+ let ci = (row / 2) * cw + col / 2;
167+ let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128);
168+ *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8;
169+ }
170+ for (u, v) in u.iter_mut().zip(v) {
171+ let (d, e) = (*u as i32 - 128, *v as i32 - 128);
172+ *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8;
173+ *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8;
174+ }
92175 }
93176
94177 /// One tier's worth of colour tags: what that tier said, field by field, with
@@ -1042,4 +1125,145 @@ mod tests {
10421125 }
10431126 );
10441127 }
1128+
1129+ /// The rule an export declares itself by, and the reason it is the *same*
1130+ /// rule the heuristic reads: a file written here says out loud what a reader
1131+ /// with no tags would have assumed anyway.
1132+ #[test]
1133+ fn an_output_declares_the_space_its_height_implies() {
1134+ assert_eq!(ColorDescription::output(1080).matrix, Matrix::Bt709);
1135+ assert_eq!(ColorDescription::output(720).matrix, Matrix::Bt709);
1136+ assert_eq!(ColorDescription::output(576).matrix, Matrix::Bt601);
1137+ for height in [480, 1080] {
1138+ let out = ColorDescription::output(height);
1139+ assert_eq!(out.transfer, Transfer::Sdr);
1140+ assert!(!out.full_range, "both encoders here are limited range");
1141+ }
1142+ // What the two containers write, in the one table both index.
1143+ assert_eq!(ColorDescription::output(1080).codes(), (1, 1, 1));
1144+ assert_eq!(ColorDescription::output(480).codes(), (6, 6, 6));
1145+ }
1146+
1147+ /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way --
1148+ /// what a correct encoder would have written.
1149+ fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) {
1150+ let (kr, kb) = weights(matrix);
1151+ let [r, g, b] = rgb.map(|c| c / 255.0);
1152+ let luma = kr * r + (1.0 - kr - kb) * g + kb * b;
1153+ let round = |x: f64| x.round().clamp(0.0, 255.0) as u8;
1154+ (
1155+ round(16.0 + 219.0 * luma),
1156+ round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)),
1157+ round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)),
1158+ )
1159+ }
1160+
1161+ /// ...and back out of `matrix`, unrounded, which is what a player shows.
1162+ fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] {
1163+ let (kr, kb) = weights(matrix);
1164+ let luma = (f64::from(y) - 16.0) / 219.0;
1165+ let cb = (f64::from(u) - 128.0) / 224.0;
1166+ let cr = (f64::from(v) - 128.0) / 224.0;
1167+ let r = luma + 2.0 * (1.0 - kr) * cr;
1168+ let b = luma + 2.0 * (1.0 - kb) * cb;
1169+ let g = (luma - kr * r - kb * b) / (1.0 - kr - kb);
1170+ [r, g, b].map(|c| c * 255.0)
1171+ }
1172+
1173+ fn weights(matrix: Matrix) -> (f64, f64) {
1174+ match matrix {
1175+ Matrix::Bt601 => (0.299, 0.114),
1176+ Matrix::Bt709 => (0.2126, 0.0722),
1177+ Matrix::Bt2020Ncl => (0.2627, 0.0593),
1178+ }
1179+ }
1180+
1181+ /// One colour as a 2x2 picture -- four luma samples over one chroma pair,
1182+ /// the smallest thing [`remap`] indexes the way it indexes a frame.
1183+ fn tile((y, u, v): (u8, u8, u8)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1184+ (vec![y; 4], vec![u], vec![v])
1185+ }
1186+
1187+ /// The claim the whole reconcile rests on: samples coded against one matrix,
1188+ /// remapped, and then *decoded by the other matrix* are the colour that went
1189+ /// in -- not a second conversion of it. Within a code or two, which is what
1190+ /// 8-bit 8.8 fixed point can promise.
1191+ #[test]
1192+ fn a_remap_is_the_same_colour_read_by_the_other_matrix() {
1193+ let colours = [
1194+ [255.0, 0.0, 0.0],
1195+ [0.0, 255.0, 0.0],
1196+ [0.0, 0.0, 255.0],
1197+ [255.0, 255.0, 0.0],
1198+ [18.0, 200.0, 140.0],
1199+ [128.0, 128.0, 128.0],
1200+ [235.0, 210.0, 30.0],
1201+ ];
1202+ for (from, to) in [
1203+ (Matrix::Bt601, Matrix::Bt709),
1204+ (Matrix::Bt709, Matrix::Bt601),
1205+ ] {
1206+ for rgb in colours {
1207+ let (mut y, mut u, mut v) = tile(encode(from, rgb));
1208+ remap(from, to, &mut y, &mut u, &mut v, 2);
1209+ let out = decode(to, (y[0], u[0], v[0]));
1210+ for (want, got) in rgb.iter().zip(&out) {
1211+ assert!(
1212+ (want - got).abs() <= 2.0,
1213+ "{from:?}->{to:?} {rgb:?} came out {out:?}"
1214+ );
1215+ }
1216+ }
1217+ }
1218+ }
1219+
1220+ /// Black, white and neutral grey are the same samples in both matrices, and
1221+ /// a remap has to leave them alone: those are the letterbox bars, the gap
1222+ /// frames and every grey in the picture, and a shift there is visible as a
1223+ /// tint on nothing at all.
1224+ #[test]
1225+ fn a_remap_leaves_the_greys_where_they_are() {
1226+ for (from, to) in [
1227+ (Matrix::Bt601, Matrix::Bt709),
1228+ (Matrix::Bt709, Matrix::Bt601),
1229+ ] {
1230+ for luma in [16u8, 128, 235] {
1231+ let (mut y, mut u, mut v) = tile((luma, 128, 128));
1232+ remap(from, to, &mut y, &mut u, &mut v, 2);
1233+ assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}");
1234+ }
1235+ }
1236+ }
1237+
1238+ /// The export's zero-cost path, asserted where it is decided: a clip already
1239+ /// in the file's own space comes out byte for byte the samples it went in
1240+ /// as, so an ordinary single-space project is not touched by any of this.
1241+ #[test]
1242+ fn a_same_space_remap_touches_nothing() {
1243+ let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
1244+ let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
1245+ let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
1246+ let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone());
1247+ for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
1248+ remap(matrix, matrix, &mut y, &mut u, &mut v, 64);
1249+ }
1250+ assert_eq!((y, u, v), (before_y, before_u, before_v));
1251+ }
1252+
1253+ /// There and back is the picture again: the two directions are one matrix
1254+ /// and its inverse, not two independent approximations.
1255+ #[test]
1256+ fn a_remap_round_trips_within_a_code() {
1257+ let y: Vec<u8> = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect();
1258+ let u: Vec<u8> = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect();
1259+ let v: Vec<u8> = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect();
1260+ let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone());
1261+ remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64);
1262+ remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64);
1263+ let worst =
1264+ |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
1265+ assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry));
1266+ assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
1267+ assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
1268+ }
10451269 }
crates/engine/src/export.rsmodified+50 -16
@@ -64,6 +64,7 @@ use flacenc::error::Verify;
6464 use oxideav_core::Muxer as _;
6565
6666 use crate::audio::{AudioMeta, AudioSession};
67+use crate::colorspace::ColorDescription;
6768 use crate::demux::{Demuxer, VideoMeta};
6869 use crate::hw::{HwEncoder, HwSession};
6970 use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams};
@@ -953,13 +954,17 @@ fn run(
953954
954955 // One header parse per source, before any of them is decoded: what rate
955956 // each file was shot at against the timeline's ([`Rate`]), which is how the
956- // clip's timeline frames below become frames of the file. Real time for a
957- // still, a song and a single-rate project, where every conversion below is
958- // the identity.
959- let rates: Vec<Rate> = sources
957+ // clip's timeline frames below become frames of the file, and what its
958+ // samples *mean* ([`ColorDescription`]), which is what decides whether they
959+ // are remapped on the way in. Real time for a still, a song and a
960+ // single-rate project, where every conversion below is the identity.
961+ let rates: Vec<(Rate, ColorDescription)> = sources
960962 .iter()
961963 .map(|source| source_rate(&source.path, meta.frame_rate))
962964 .collect();
965+ // ...and the one space they are all written in, the same rule a reader with
966+ // no tags to read would apply to this file's height.
967+ let out_color = ColorDescription::output(meta.height);
963968
964969 let mut encoder = Enc::open(meta, settings)?;
965970 // What this file is really being written by, for a progress line to name.
@@ -985,19 +990,34 @@ fn run(
985990 // encoder is *not* reopened, so the export is one continuous stream
986991 // whose GOP boundaries need not line up with the cuts -- nor with the
987992 // file boundaries, which are just cuts that change the path.
988- let (mut pictures, rate, in_frame) = match span.from {
993+ let (mut pictures, rate, in_frame, color) = match span.from {
989994 Some((source, in_frame)) => {
990995 let entry = sources
991996 .get(source)
992997 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
993- let rate = rates[source];
998+ let (rate, color) = rates[source];
994999 // Opened at the file's own frame, which is the only place the
9951000 // file's numbering is used -- the span's are the timeline's.
9961001 let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
997- (Some(pictures), rate, in_frame)
1002+ (Some(pictures), rate, in_frame, Some(color))
9981003 }
999- None => (None, Rate::REAL_TIME, 0),
1004+ // A gap's black is 16/128/128, which is black in every matrix here:
1005+ // nothing to remap, which is what `None` says.
1006+ None => (None, Rate::REAL_TIME, 0, None),
10001007 };
1008+ // Mixed spaces on one timeline: a clip coded against another matrix than
1009+ // the one this file declares is rewritten into it, before the grade,
1010+ // whose numbers the user set against what the canvas showed. Same-space
1011+ // clips -- the whole of an ordinary project -- take `None` and not a
1012+ // byte is touched.
1013+ //
1014+ // ponytail: an HDR source is composited with the matrix treatment alone
1015+ // and still looks washed out; the tonemap lands here, ahead of this, and
1016+ // is a sibling task's.
1017+ let remap = color
1018+ .map(|c| c.matrix)
1019+ .filter(|&m| m != out_color.matrix)
1020+ .map(|m| (m, out_color.matrix));
10011021 // What this span is graded by -- the same answer playback's decoder
10021022 // carries, so the export is the picture that was watched. `None` for a
10031023 // gap and for an ungraded clip, and that is the path where not a byte
@@ -1069,8 +1089,10 @@ fn run(
10691089 // hands the same slice as both u and v), so a grade cannot be
10701090 // applied in place: it goes onto a copy, which the encoder then
10711091 // reads instead.
1072- let (y, u, v) = match grade.filter(|p| !p.is_identity()) {
1073- Some(params) => {
1092+ let params = grade.filter(|p| !p.is_identity());
1093+ let (y, u, v) = match (params, remap) {
1094+ (None, None) => (y, u, v),
1095+ (params, remap) => {
10741096 let (gy, gu, gv) = &mut graded;
10751097 gy.clear();
10761098 gy.extend_from_slice(y);
@@ -1078,10 +1100,14 @@ fn run(
10781100 gu.extend_from_slice(u);
10791101 gv.clear();
10801102 gv.extend_from_slice(v);
1081- crate::color::apply_yuv(&params, gy, gu, gv);
1103+ if let Some((from, to)) = remap {
1104+ crate::colorspace::remap(from, to, gy, gu, gv, width as usize);
1105+ }
1106+ if let Some(params) = params {
1107+ crate::color::apply_yuv(&params, gy, gu, gv);
1108+ }
10821109 (&gy[..], &gu[..], &gv[..])
10831110 }
1084- None => (y, u, v),
10851111 };
10861112 // Grade first, place second: the grade is the clip's own pixels
10871113 // and the bars around them are not the clip (see `scale::Composer`).
@@ -1153,16 +1179,24 @@ fn run(
11531179 /// -- a still, a song -- and for one that will not open here: the decoder is
11541180 /// opened a few lines later and fails the export by name, which is a better
11551181 /// error than this one could raise.
1156-fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
1182+fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription) {
11571183 if crate::is_image(path) || crate::is_audio(path) {
1158- return Rate::REAL_TIME;
1184+ // A still is BT.601 by construction whatever it was authored as:
1185+ // `decode::rgb_to_i420` is the one matrix that turns its pixels into
1186+ // planes. A song has no picture and the answer is never read.
1187+ return (Rate::REAL_TIME, ColorDescription::default());
11591188 }
11601189 match Demuxer::open(path) {
11611190 // ...and one whose rate cannot be named against the timeline's, which
11621191 // `matches_timeline` refuses at import, so nothing on a timeline is on
11631192 // this arm either.
1164- Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
1165- Err(_) => Rate::REAL_TIME,
1193+ Ok((meta, _)) => (
1194+ Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
1195+ meta.color,
1196+ ),
1197+ // Unreadable here means unreadable below too, where the span dies with a
1198+ // real message; the file's own space is the least of that.
1199+ Err(_) => (Rate::REAL_TIME, ColorDescription::default()),
11661200 }
11671201 }
11681202
crates/engine/src/mux.rsmodified+78 -29
@@ -22,6 +22,8 @@ use mp4::{
2222 Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType,
2323 };
2424
25+use crate::colorspace::ColorDescription;
26+
2527 /// 90 kHz is the H.264 convention, and it divides exactly at every *integer*
2628 /// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at
2729 /// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see
@@ -71,11 +73,30 @@ pub struct Mp4Muxer {
7173 /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the
7274 /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1).
7375 entry: Option<([u8; 4], [u8; 4], Vec<u8>)>,
76+ /// The `colr` box that entry gets either way -- what the samples in it mean
77+ /// ([`colr_nclx`]). `mp4 0.14` writes no `colr` of its own, so this is
78+ /// patched in at [`finish`](Mp4Muxer::finish) beside the entry rewrite,
79+ /// which is why an H.264 file is patched at all now.
80+ colr: [u8; 11],
7481 /// Where the file is, for that patch: the writer owns the handle it wrote
7582 /// through and the patch reopens the finished file.
7683 path: PathBuf,
7784 }
7885
86+/// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag
87+/// and the same three H.273 code points Matroska's `Colour` carries, plus the
88+/// range as the one-bit flag an mp4 says it with rather than Matroska's code.
89+fn colr_nclx(colour: ColorDescription) -> [u8; 11] {
90+ let (primaries, transfer, matrix) = colour.codes();
91+ let mut out = [0u8; 11];
92+ out[..4].copy_from_slice(b"nclx");
93+ out[4..6].copy_from_slice(&primaries.to_be_bytes());
94+ out[6..8].copy_from_slice(&transfer.to_be_bytes());
95+ out[8..10].copy_from_slice(&matrix.to_be_bytes());
96+ out[10] = u8::from(colour.full_range) << 7;
97+ out
98+}
99+
79100 const VIDEO_TRACK: u32 = 1;
80101 const AUDIO_TRACK: u32 = 2;
81102
@@ -247,6 +268,7 @@ impl Mp4Muxer {
247268 frame_duration,
248269 has_audio: audio.is_some(),
249270 entry,
271+ colr: colr_nclx(ColorDescription::output(video.height)),
250272 path: path.to_path_buf(),
251273 })
252274 }
@@ -318,6 +340,7 @@ impl Mp4Muxer {
318340 let Self {
319341 writer,
320342 entry,
343+ colr,
321344 path,
322345 ..
323346 } = self;
@@ -325,17 +348,14 @@ impl Mp4Muxer {
325348 // patch below reads it back, and a `BufWriter` swallows the error of
326349 // flushing it on drop.
327350 writer.into_writer().flush()?;
328- match entry {
329- Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config),
330- None => Ok(()),
331- }
351+ patch_entry(&path, entry.as_ref(), &colr)
332352 }
333353 }
334354
335-/// Rewrites the finished file's one video sample entry from the `avc1` the crate
336-/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` +
337-/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file
338-/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened.
355+/// Rewrites the finished file's one video sample entry: `colr` appended to it
356+/// always (the crate writes none), and where `entry` says so the `avc1` header
357+/// itself replaced by the `av01` + `av1C` an AV1 track declares -- or the `hvc1`
358+/// + `hvcC` an HEVC one does. Called once, on a complete file.
339359 ///
340360 /// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only
341361 /// ever rewrites the tail of the file: no sample moves and no chunk offset in
@@ -343,15 +363,13 @@ impl Mp4Muxer {
343363 /// is what keeps every ancestor's size right by construction.
344364 fn patch_entry(
345365 path: &Path,
346- kind: &[u8; 4],
347- config_kind: &[u8; 4],
348- config: &[u8],
366+ entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,
367+ colr: &[u8],
349368 ) -> crate::Result<()> {
350369 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
351370 let end = file.metadata()?.len();
352371 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
353- let patched = swap_entry(&payload, 0, kind, config_kind, config)
354- .ok_or("no avc1 sample entry to rewrite")?;
372+ let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?;
355373 let mut out = Vec::with_capacity(patched.len() + 8);
356374 push_box(&mut out, b"moov", &patched);
357375 file.seek(SeekFrom::Start(at))?;
@@ -393,38 +411,47 @@ fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result<Option<
393411 /// `moov` down to the sample descriptions, which is where the entry lives.
394412 const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"];
395413
396-/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry replaced.
397-/// `None` where this branch holds no such entry -- an audio `trak` is walked
398-/// into and comes back untouched, which is how the *video* track is found
399-/// without being told which id it has.
414+/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry given a
415+/// `colr` box and, where `entry` says so, another four-character name and
416+/// configuration box. `None` where this branch holds no such entry -- an audio
417+/// `trak` is walked into and comes back untouched, which is how the *video*
418+/// track is found without being told which id it has.
400419 fn swap_entry(
401420 payload: &[u8],
402421 depth: usize,
403- want: &[u8; 4],
404- config_kind: &[u8; 4],
405- config: &[u8],
422+ entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,
423+ colr: &[u8],
406424 ) -> Option<Vec<u8>> {
407425 if depth == STSD_PATH.len() {
408426 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
409427 let mut out = payload.get(..8)?.to_vec();
410- let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?;
428+ let (kind, sample_entry) = crate::demux::boxes(payload.get(8..)?).next()?;
411429 if kind != b"avc1" {
412430 return None;
413431 }
414- // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all)
415- // before its codec box, and `av01` and `hvc1` carry exactly the same
416- // ones -- so the header is kept and only the configuration box is
417- // swapped.
418- let mut swapped = entry.get(..78)?.to_vec();
419- push_box(&mut swapped, config_kind, config);
420- push_box(&mut out, want, &swapped);
432+ let (name, mut swapped) = match entry {
433+ // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and
434+ // all) before its codec box, and `av01` and `hvc1` carry exactly the
435+ // same ones -- so the header is kept and only the configuration box
436+ // is swapped.
437+ Some((want, config_kind, config)) => {
438+ let mut swapped = sample_entry.get(..78)?.to_vec();
439+ push_box(&mut swapped, config_kind, config);
440+ (want, swapped)
441+ }
442+ // H.264: the crate spelled the whole entry, `avcC` and all, and only
443+ // the colour tag is missing from it.
444+ None => (b"avc1", sample_entry.to_vec()),
445+ };
446+ push_box(&mut swapped, b"colr", colr);
447+ push_box(&mut out, name, &swapped);
421448 return Some(out);
422449 }
423450 let mut out = Vec::with_capacity(payload.len());
424451 let mut done = false;
425452 for (kind, child) in crate::demux::boxes(payload) {
426453 let patched = match !done && kind == STSD_PATH[depth] {
427- true => swap_entry(child, depth + 1, want, config_kind, config),
454+ true => swap_entry(child, depth + 1, entry, colr),
428455 false => None,
429456 };
430457 match patched {
@@ -475,6 +502,14 @@ const DEFAULT_DURATION: u32 = 0x23E383;
475502 const VIDEO: u32 = 0xE0;
476503 const PIXEL_WIDTH: u32 = 0xB0;
477504 const PIXEL_HEIGHT: u32 = 0xBA;
505+// `Colour` and the four children this writes, all inside `Video`. Byte-verified
506+// against what `demux` reads back and what ffprobe reports: the spec tables that
507+// list Range as 0x55B3 are describing ChromaSubsamplingHorz.
508+const COLOUR: u32 = 0x55B0;
509+const MATRIX_COEFFICIENTS: u32 = 0x55B1;
510+const RANGE: u32 = 0x55B9;
511+const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
512+const PRIMARIES: u32 = 0x55BB;
478513 const AUDIO: u32 = 0xE1;
479514 const SAMPLING_FREQUENCY: u32 = 0xB5;
480515 const CHANNELS: u32 = 0x9F;
@@ -733,6 +768,20 @@ impl MkvMuxer {
733768 let mut dims = Vec::new();
734769 uint(&mut dims, PIXEL_WIDTH, u64::from(width));
735770 uint(&mut dims, PIXEL_HEIGHT, u64::from(height));
771+ // What the samples in those pixels mean. Written rather than left to a
772+ // reader's own 720-line guess -- the guess is right for this file (the
773+ // export remaps every clip into exactly that space) but a remuxer or a
774+ // scaler downstream has no reason to make it, and an untagged file is
775+ // how a 601 source ends up displayed as 709.
776+ let colour = ColorDescription::output(height);
777+ let (primaries, transfer, matrix) = colour.codes();
778+ let mut tags = Vec::new();
779+ uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix));
780+ // Matroska says the range as a code, not a flag: 1 limited, 2 full.
781+ uint(&mut tags, RANGE, 1 + u64::from(colour.full_range));
782+ uint(&mut tags, TRANSFER_CHARACTERISTICS, u64::from(transfer));
783+ uint(&mut tags, PRIMARIES, u64::from(primaries));
784+ elem(&mut dims, COLOUR, &tags);
736785 elem(&mut entry, VIDEO, &dims);
737786 let mut tracks = Vec::new();
738787 elem(&mut tracks, TRACK_ENTRY, &entry);
crates/engine/tests/export_color.rsadded+232 -0
@@ -0,0 +1,232 @@
1+//! What an exported file says its numbers mean, and what it does to a clip that
2+//! disagreed: the writing half of `engine::colorspace`.
3+//!
4+//! Two claims, both measured with `ffmpeg`/`ffprobe` rather than with this
5+//! project's own reader alone -- an export is read by other software, and a tag
6+//! only this engine agrees with is not a tag:
7+//!
8+//! 1. every export declares a space (BT.709 at 720 lines and up, BT.601 below),
9+//! in the `Colour` element of a Matroska and the `colr` box of an mp4, and
10+//! 2. a clip coded against the *other* matrix is rewritten into the file's, so
11+//! reading the export by its own tags gives back the picture that went in --
12+//! a reconcile, not a second conversion.
13+//!
14+//! ```text
15+//! cargo test -p engine --release --test export_color
16+//! ```
17+//!
18+//! Release: the Matroska half goes through the intra HEVC encoder, which is
19+//! minutes a frame in debug. Without `ffmpeg` on the machine the external half
20+//! says so and passes, exactly as the hardware tests elsewhere here do.
21+
22+use std::path::{Path, PathBuf};
23+use std::process::Command;
24+use std::time::{Duration, Instant};
25+
26+use engine::PlaybackSession;
27+use engine::colorspace::{ColorDescription, Matrix, Transfer, remap};
28+use engine::demux::Demuxer;
29+use engine::export::{ExportSettings, Format};
30+use engine::scratch::Scratch;
31+
32+fn asset(name: &str) -> PathBuf {
33+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
34+ .join("../../assets")
35+ .join(name)
36+}
37+
38+fn out_path(name: &str, ext: &str) -> Scratch {
39+ Scratch::file(&format!("ve_color_{name}"), ext)
40+}
41+
42+/// The first two frames of `source`, so what is measured is the colour path and
43+/// not how long an encoder takes.
44+fn two_frames(source: &Path) -> PlaybackSession {
45+ let mut session = PlaybackSession::open(source).expect("open the fixture");
46+ assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front");
47+ assert!(session.delete_clip(engine::project::Lane::V1, 1));
48+ session
49+}
50+
51+fn export(session: &PlaybackSession, out: &Path, format: Format) {
52+ let handle = session.export_to_with(
53+ out,
54+ &ExportSettings {
55+ format,
56+ ..Default::default()
57+ },
58+ );
59+ let started = Instant::now();
60+ while !handle.is_finished() {
61+ assert!(
62+ started.elapsed() < Duration::from_secs(300),
63+ "the export did not finish in 300 s"
64+ );
65+ std::thread::sleep(Duration::from_millis(20));
66+ }
67+ handle.result().expect("an outcome").expect("the export");
68+}
69+
70+/// What ffprobe says the stream declares: matrix, primaries, transfer, range.
71+/// `None` when ffprobe is not installed.
72+fn probed(path: &Path) -> Option<Vec<String>> {
73+ let out = Command::new("ffprobe")
74+ .args([
75+ "-v",
76+ "error",
77+ "-select_streams",
78+ "v:0",
79+ "-show_entries",
80+ "stream=color_space,color_primaries,color_transfer,color_range",
81+ "-of",
82+ "default=nw=1:nk=1",
83+ ])
84+ .arg(path)
85+ .output()
86+ .ok()?;
87+ Some(
88+ String::from_utf8_lossy(&out.stdout)
89+ .lines()
90+ .map(|l| l.trim().to_string())
91+ .collect(),
92+ )
93+}
94+
95+/// Frame 0 of `path` as planar 4:2:0 bytes, straight off the decoder with no
96+/// colour conversion at all -- the samples as they are in the file, which is
97+/// what a remap is measured on. `None` when ffmpeg is not installed.
98+fn raw_yuv(path: &Path) -> Option<Vec<u8>> {
99+ let raw = Scratch::file("ve_color_raw", "yuv");
100+ let ok = Command::new("ffmpeg")
101+ .args(["-v", "error", "-y", "-i"])
102+ .arg(path)
103+ .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
104+ .arg(&*raw)
105+ .status()
106+ .ok()?;
107+ assert!(ok.success(), "ffmpeg could not read {}", path.display());
108+ Some(std::fs::read(&*raw).expect("the raw frame"))
109+}
110+
111+fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
112+ assert_eq!(a.len(), b.len(), "frame sizes differ");
113+ a.iter()
114+ .zip(b)
115+ .map(|(x, y)| f64::from(x.abs_diff(*y)))
116+ .sum::<f64>()
117+ / a.len() as f64
118+}
119+
120+/// Every export says which space it is in, in the words its container spells
121+/// them and in the words ffprobe reads back. `test_bt601.mp4` is 1280x720 and
122+/// the export of it is therefore BT.709 whatever the source said; the 640x480
123+/// fixture is below the line and comes out BT.601 whatever *its* bitstream said.
124+/// Both containers, because the two tags are written by different code.
125+#[test]
126+fn an_export_declares_the_space_it_was_written_in() {
127+ for (fixture, matrix, probe) in [
128+ ("test_bt601.mp4", Matrix::Bt709, "bt709"),
129+ ("test_vui_h264.mp4", Matrix::Bt601, "smpte170m"),
130+ ] {
131+ for (format, ext) in [(Format::Mp4, "mp4"), (Format::Hevc, "mkv")] {
132+ let session = two_frames(&asset(fixture));
133+ let out = out_path(&format!("tags_{ext}"), ext);
134+ export(&session, &out, format);
135+
136+ let (meta, _) = Demuxer::open(&out).expect("reopen the export");
137+ assert_eq!(
138+ meta.color,
139+ ColorDescription {
140+ matrix,
141+ transfer: Transfer::Sdr,
142+ full_range: false,
143+ },
144+ "{fixture} -> {ext}: what the file says about itself"
145+ );
146+ match probed(&out) {
147+ Some(tags) => {
148+ eprintln!("{fixture} -> {ext}: ffprobe {tags:?}");
149+ // ffprobe prints these in its own field order, range first,
150+ // whatever order they were asked for in.
151+ let want: Vec<String> = ["tv", probe, probe, probe]
152+ .iter()
153+ .map(|s| s.to_string())
154+ .collect();
155+ assert_eq!(
156+ tags, want,
157+ "{fixture} -> {ext}: range, matrix, primaries, transfer"
158+ );
159+ }
160+ None => eprintln!("no ffprobe: skipping the external read of {ext}"),
161+ }
162+ std::fs::remove_file(&out).unwrap();
163+ }
164+ }
165+}
166+
167+/// The reconcile itself, on the samples: a BT.601 clip on a 720-line canvas is
168+/// written as BT.709, and the numbers in the file are the source's *remapped* --
169+/// within what the encoder rounds off. The second measurement is the one that
170+/// makes the first mean something: the untouched source is far further away
171+/// than the remapped one, so this cannot pass by doing nothing.
172+#[test]
173+fn a_clip_in_another_space_is_remapped_into_the_files() {
174+ let source = asset("test_bt601.mp4");
175+ let Some(src) = raw_yuv(&source) else {
176+ eprintln!("no ffmpeg: skipping the sample-level remap check");
177+ return;
178+ };
179+ let session = two_frames(&source);
180+ let out = out_path("remap", "mp4");
181+ export(&session, &out, Format::Mp4);
182+ let got = raw_yuv(&out).expect("ffmpeg read the export");
183+
184+ let (width, height) = (1280usize, 720usize);
185+ let mut planes = src.clone();
186+ let (y, chroma) = planes.split_at_mut(width * height);
187+ let (u, v) = chroma.split_at_mut(width * height / 4);
188+ remap(Matrix::Bt601, Matrix::Bt709, y, u, v, width);
189+
190+ let remapped = mean_abs_diff(&got, &planes);
191+ let untouched = mean_abs_diff(&got, &src);
192+ eprintln!(
193+ "601 clip on a 709 canvas: {remapped:.2} off the remapped source, {untouched:.2} off the raw one"
194+ );
195+ assert!(
196+ remapped < 3.0,
197+ "the export is {remapped:.2} away from the remapped source"
198+ );
199+ assert!(
200+ untouched > 3.0 * remapped,
201+ "remapped {remapped:.2} vs untouched {untouched:.2}: nothing was reconciled"
202+ );
203+ std::fs::remove_file(&out).unwrap();
204+}
205+
206+/// ...and the other half of that claim, which is the regression one: a clip
207+/// already in the file's space is not remapped at all, so an ordinary
208+/// single-space project comes out exactly as it did before any of this existed.
209+/// `test_baseline.mp4` is 1280x720 and untagged, which resolves to BT.709 --
210+/// the very space its export declares.
211+#[test]
212+fn a_same_space_clip_is_left_alone() {
213+ let source = asset("test_baseline.mp4");
214+ let Some(src) = raw_yuv(&source) else {
215+ eprintln!("no ffmpeg: skipping the same-space regression check");
216+ return;
217+ };
218+ let (meta, _) = Demuxer::open(&source).expect("open the fixture");
219+ assert_eq!(meta.color.matrix, Matrix::Bt709, "the fixture's own space");
220+ let session = two_frames(&source);
221+ let out = out_path("same_space", "mp4");
222+ export(&session, &out, Format::Mp4);
223+ let got = raw_yuv(&out).expect("ffmpeg read the export");
224+
225+ let diff = mean_abs_diff(&got, &src);
226+ eprintln!("same-space export: {diff:.2} off the source samples");
227+ assert!(
228+ diff < 3.0,
229+ "a same-space export moved the samples by {diff:.2}"
230+ );
231+ std::fs::remove_file(&out).unwrap();
232+}