From 907dfc5358a16fce099c9f50e6c805dbd2234ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 19:38:09 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(export):=20a=20file=20says=20w?= =?UTF-8?q?hich=20matrix=20its=20numbers=20are=20in,=20and=20its=20clips?= =?UTF-8?q?=20are=20all=20in=20that=20one?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exports carried no colour tags at all: the numbers went out as they came off the decoder and every reader downstream had to guess. A 601 clip beside a 709 one went out as two spaces in one file, and nothing said so. Now every export declares a space -- BT.709 at 720 lines and up, BT.601 below, the same rule a reader with no tags applies -- in the Matroska `Colour` element and the mp4 `colr` box, and a clip coded against the other matrix is rewritten into it before it is graded. Same-space clips take the path they always did and not a byte is touched. --- crates/engine/src/colorspace.rs | 228 ++++++++++++++++++++++++++- crates/engine/src/export.rs | 66 ++++++-- crates/engine/src/mux.rs | 107 +++++++++---- crates/engine/tests/export_color.rs | 232 ++++++++++++++++++++++++++++ 4 files changed, 586 insertions(+), 47 deletions(-) create mode 100644 crates/engine/tests/export_color.rs diff --git a/crates/engine/src/colorspace.rs b/crates/engine/src/colorspace.rs index 8c0defe..5a238ea 100644 --- a/crates/engine/src/colorspace.rs +++ b/crates/engine/src/colorspace.rs @@ -1,7 +1,8 @@ //! What the numbers in a decoded picture *mean*: which YUV->RGB matrix they //! were coded against, which transfer curve, and whether they span the full -//! byte or the limited 16..235 range. Everything here is read off the file; -//! nothing here converts anything yet. +//! byte or the limited 16..235 range. Everything but [`remap`] is read off the +//! file; that one is the other direction -- what an export does to a clip whose +//! matrix is not the one the file being written declares. //! //! Three tiers, in this order, per field: //! @@ -89,6 +90,88 @@ impl ColorDescription { full_range: tags.full_range.unwrap_or(false), } } + + /// What an export of a `height`-line canvas *declares itself to be*, and + /// therefore what every clip on it is remapped into: the same 720-line rule + /// [`resolve`](Self::resolve)'s heuristic reads, so a file written here is + /// read back as the space it was written in even by a reader that drops the + /// tags. Limited range because both encoders here are configured for it, and + /// SDR because nothing on this path tone-maps yet. + pub fn output(height: u32) -> Self { + Self { + matrix: if height >= 720 { + Matrix::Bt709 + } else { + Matrix::Bt601 + }, + transfer: Transfer::Sdr, + full_range: false, + } + } + + /// The H.273 code points a container writes this as: primaries, transfer + /// characteristics, matrix coefficients. The same table Matroska's `Colour` + /// and mp4's `colr` both index, so one answer serves both muxers. + pub fn codes(self) -> (u16, u16, u16) { + // Primaries and the SDR curve travel with the matrix: a 709 file is + // 1/1/1 and an SD one 6/6/6 (SMPTE 170M), which is what ffmpeg writes + // for each and what a player expects to see together. + let (primaries, sdr_transfer, matrix) = match self.matrix { + Matrix::Bt709 => (1, 1, 1), + Matrix::Bt601 => (6, 6, 6), + Matrix::Bt2020Ncl => (9, 14, 9), + }; + let transfer = match self.transfer { + Transfer::Sdr => sdr_transfer, + Transfer::Pq => 16, + Transfer::Hlg => 18, + }; + (primaries, transfer, matrix) + } +} + +/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded +/// against `to`, in place. Both spaces here are limited range with the same +/// primaries, so this is the matrix and nothing else: no gamut mapping, no range +/// scaling, and the 16/128/128 of black lands on itself either way -- which is +/// what makes a letterboxed bar and a gap's black frame cost nothing. +/// +/// Derived from the two matrices, not tabulated: with R,G,B eliminated between +/// them, luma picks up a chroma term and the two chroma planes mix only with +/// each other -- so chroma never needs the luma plane and is remapped at its own +/// resolution, while luma reads the co-sited chroma sample the way +/// [`crate::convert::i420_to_bgra`] does. 8.8 fixed point, the same as every +/// other matrix in this engine. +/// +/// A no-op when the two spaces are the same, so the caller may hand any pair. +pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) { + // BT.2020 is never an output here (see [`ColorDescription::output`]) and a + // 2020 source arrives on the tone-mapping path, not this one. + // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr, + // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values + // the luma row's chroma terms carry a further 219/224, the ratio of the two + // limited-range spans, while the chroma rows' do not (both sides are + // chroma). That is the whole difference between these numbers and the + // published ones. + let coeffs = match (from, to) { + (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262], + // ...and its inverse, which round-trips to within a code. + (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252], + _ => return, + }; + let [yb, yr, ub, ur, vb, vr] = coeffs; + let cw = width.div_ceil(2); + for (i, y) in y.iter_mut().enumerate() { + let (row, col) = (i / width, i % width); + let ci = (row / 2) * cw + col / 2; + let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128); + *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8; + } + for (u, v) in u.iter_mut().zip(v) { + let (d, e) = (*u as i32 - 128, *v as i32 - 128); + *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8; + *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8; + } } /// One tier's worth of colour tags: what that tier said, field by field, with @@ -1042,4 +1125,145 @@ mod tests { } ); } + + /// The rule an export declares itself by, and the reason it is the *same* + /// rule the heuristic reads: a file written here says out loud what a reader + /// with no tags would have assumed anyway. + #[test] + fn an_output_declares_the_space_its_height_implies() { + assert_eq!(ColorDescription::output(1080).matrix, Matrix::Bt709); + assert_eq!(ColorDescription::output(720).matrix, Matrix::Bt709); + assert_eq!(ColorDescription::output(576).matrix, Matrix::Bt601); + for height in [480, 1080] { + let out = ColorDescription::output(height); + assert_eq!(out.transfer, Transfer::Sdr); + assert!(!out.full_range, "both encoders here are limited range"); + } + // What the two containers write, in the one table both index. + assert_eq!(ColorDescription::output(1080).codes(), (1, 1, 1)); + assert_eq!(ColorDescription::output(480).codes(), (6, 6, 6)); + } + + /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way -- + /// what a correct encoder would have written. + fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) { + let (kr, kb) = weights(matrix); + let [r, g, b] = rgb.map(|c| c / 255.0); + let luma = kr * r + (1.0 - kr - kb) * g + kb * b; + let round = |x: f64| x.round().clamp(0.0, 255.0) as u8; + ( + round(16.0 + 219.0 * luma), + round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)), + round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)), + ) + } + + /// ...and back out of `matrix`, unrounded, which is what a player shows. + fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] { + let (kr, kb) = weights(matrix); + let luma = (f64::from(y) - 16.0) / 219.0; + let cb = (f64::from(u) - 128.0) / 224.0; + let cr = (f64::from(v) - 128.0) / 224.0; + let r = luma + 2.0 * (1.0 - kr) * cr; + let b = luma + 2.0 * (1.0 - kb) * cb; + let g = (luma - kr * r - kb * b) / (1.0 - kr - kb); + [r, g, b].map(|c| c * 255.0) + } + + fn weights(matrix: Matrix) -> (f64, f64) { + match matrix { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020Ncl => (0.2627, 0.0593), + } + } + + /// One colour as a 2x2 picture -- four luma samples over one chroma pair, + /// the smallest thing [`remap`] indexes the way it indexes a frame. + fn tile((y, u, v): (u8, u8, u8)) -> (Vec, Vec, Vec) { + (vec![y; 4], vec![u], vec![v]) + } + + /// The claim the whole reconcile rests on: samples coded against one matrix, + /// remapped, and then *decoded by the other matrix* are the colour that went + /// in -- not a second conversion of it. Within a code or two, which is what + /// 8-bit 8.8 fixed point can promise. + #[test] + fn a_remap_is_the_same_colour_read_by_the_other_matrix() { + let colours = [ + [255.0, 0.0, 0.0], + [0.0, 255.0, 0.0], + [0.0, 0.0, 255.0], + [255.0, 255.0, 0.0], + [18.0, 200.0, 140.0], + [128.0, 128.0, 128.0], + [235.0, 210.0, 30.0], + ]; + for (from, to) in [ + (Matrix::Bt601, Matrix::Bt709), + (Matrix::Bt709, Matrix::Bt601), + ] { + for rgb in colours { + let (mut y, mut u, mut v) = tile(encode(from, rgb)); + remap(from, to, &mut y, &mut u, &mut v, 2); + let out = decode(to, (y[0], u[0], v[0])); + for (want, got) in rgb.iter().zip(&out) { + assert!( + (want - got).abs() <= 2.0, + "{from:?}->{to:?} {rgb:?} came out {out:?}" + ); + } + } + } + } + + /// Black, white and neutral grey are the same samples in both matrices, and + /// a remap has to leave them alone: those are the letterbox bars, the gap + /// frames and every grey in the picture, and a shift there is visible as a + /// tint on nothing at all. + #[test] + fn a_remap_leaves_the_greys_where_they_are() { + for (from, to) in [ + (Matrix::Bt601, Matrix::Bt709), + (Matrix::Bt709, Matrix::Bt601), + ] { + for luma in [16u8, 128, 235] { + let (mut y, mut u, mut v) = tile((luma, 128, 128)); + remap(from, to, &mut y, &mut u, &mut v, 2); + assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}"); + } + } + } + + /// The export's zero-cost path, asserted where it is decided: a clip already + /// in the file's own space comes out byte for byte the samples it went in + /// as, so an ordinary single-space project is not touched by any of this. + #[test] + fn a_same_space_remap_touches_nothing() { + let mut y: Vec = (0..64 * 48).map(|i| (i % 256) as u8).collect(); + let mut u: Vec = (0..32 * 24).map(|i| (i % 256) as u8).collect(); + let mut v: Vec = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect(); + let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone()); + for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + remap(matrix, matrix, &mut y, &mut u, &mut v, 64); + } + assert_eq!((y, u, v), (before_y, before_u, before_v)); + } + + /// There and back is the picture again: the two directions are one matrix + /// and its inverse, not two independent approximations. + #[test] + fn a_remap_round_trips_within_a_code() { + let y: Vec = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect(); + let u: Vec = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect(); + let v: Vec = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect(); + let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone()); + remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64); + remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64); + let worst = + |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap(); + assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry)); + assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru)); + assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv)); + } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 641af38..857e543 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -64,6 +64,7 @@ use flacenc::error::Verify; use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; +use crate::colorspace::ColorDescription; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; @@ -953,13 +954,17 @@ fn run( // One header parse per source, before any of them is decoded: what rate // each file was shot at against the timeline's ([`Rate`]), which is how the - // clip's timeline frames below become frames of the file. Real time for a - // still, a song and a single-rate project, where every conversion below is - // the identity. - let rates: Vec = sources + // clip's timeline frames below become frames of the file, and what its + // samples *mean* ([`ColorDescription`]), which is what decides whether they + // are remapped on the way in. Real time for a still, a song and a + // single-rate project, where every conversion below is the identity. + let rates: Vec<(Rate, ColorDescription)> = sources .iter() .map(|source| source_rate(&source.path, meta.frame_rate)) .collect(); + // ...and the one space they are all written in, the same rule a reader with + // no tags to read would apply to this file's height. + let out_color = ColorDescription::output(meta.height); let mut encoder = Enc::open(meta, settings)?; // What this file is really being written by, for a progress line to name. @@ -985,19 +990,34 @@ fn run( // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. - let (mut pictures, rate, in_frame) = match span.from { + let (mut pictures, rate, in_frame, color) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - let rate = rates[source]; + let (rate, color) = rates[source]; // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; - (Some(pictures), rate, in_frame) + (Some(pictures), rate, in_frame, Some(color)) } - None => (None, Rate::REAL_TIME, 0), + // A gap's black is 16/128/128, which is black in every matrix here: + // nothing to remap, which is what `None` says. + None => (None, Rate::REAL_TIME, 0, None), }; + // Mixed spaces on one timeline: a clip coded against another matrix than + // the one this file declares is rewritten into it, before the grade, + // whose numbers the user set against what the canvas showed. Same-space + // clips -- the whole of an ordinary project -- take `None` and not a + // byte is touched. + // + // ponytail: an HDR source is composited with the matrix treatment alone + // and still looks washed out; the tonemap lands here, ahead of this, and + // is a sibling task's. + let remap = color + .map(|c| c.matrix) + .filter(|&m| m != out_color.matrix) + .map(|m| (m, out_color.matrix)); // What this span is graded by -- the same answer playback's decoder // carries, so the export is the picture that was watched. `None` for a // gap and for an ungraded clip, and that is the path where not a byte @@ -1069,8 +1089,10 @@ fn run( // hands the same slice as both u and v), so a grade cannot be // applied in place: it goes onto a copy, which the encoder then // reads instead. - let (y, u, v) = match grade.filter(|p| !p.is_identity()) { - Some(params) => { + let params = grade.filter(|p| !p.is_identity()); + let (y, u, v) = match (params, remap) { + (None, None) => (y, u, v), + (params, remap) => { let (gy, gu, gv) = &mut graded; gy.clear(); gy.extend_from_slice(y); @@ -1078,10 +1100,14 @@ fn run( gu.extend_from_slice(u); gv.clear(); gv.extend_from_slice(v); - crate::color::apply_yuv(¶ms, gy, gu, gv); + if let Some((from, to)) = remap { + crate::colorspace::remap(from, to, gy, gu, gv, width as usize); + } + if let Some(params) = params { + crate::color::apply_yuv(¶ms, gy, gu, gv); + } (&gy[..], &gu[..], &gv[..]) } - None => (y, u, v), }; // Grade first, place second: the grade is the clip's own pixels // and the bars around them are not the clip (see `scale::Composer`). @@ -1153,16 +1179,24 @@ fn run( /// -- a still, a song -- and for one that will not open here: the decoder is /// opened a few lines later and fails the export by name, which is a better /// error than this one could raise. -fn source_rate(path: &Path, timeline_fps: f64) -> Rate { +fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription) { if crate::is_image(path) || crate::is_audio(path) { - return Rate::REAL_TIME; + // A still is BT.601 by construction whatever it was authored as: + // `decode::rgb_to_i420` is the one matrix that turns its pixels into + // planes. A song has no picture and the answer is never read. + return (Rate::REAL_TIME, ColorDescription::default()); } match Demuxer::open(path) { // ...and one whose rate cannot be named against the timeline's, which // `matches_timeline` refuses at import, so nothing on a timeline is on // this arm either. - Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), - Err(_) => Rate::REAL_TIME, + Ok((meta, _)) => ( + Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), + meta.color, + ), + // Unreadable here means unreadable below too, where the span dies with a + // real message; the file's own space is the least of that. + Err(_) => (Rate::REAL_TIME, ColorDescription::default()), } } diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 332a856..9becbb0 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -22,6 +22,8 @@ use mp4::{ Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, }; +use crate::colorspace::ColorDescription; + /// 90 kHz is the H.264 convention, and it divides exactly at every *integer* /// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at /// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see @@ -71,11 +73,30 @@ pub struct Mp4Muxer { /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1). entry: Option<([u8; 4], [u8; 4], Vec)>, + /// The `colr` box that entry gets either way -- what the samples in it mean + /// ([`colr_nclx`]). `mp4 0.14` writes no `colr` of its own, so this is + /// patched in at [`finish`](Mp4Muxer::finish) beside the entry rewrite, + /// which is why an H.264 file is patched at all now. + colr: [u8; 11], /// Where the file is, for that patch: the writer owns the handle it wrote /// through and the patch reopens the finished file. path: PathBuf, } +/// A `ColourInformationBox` payload, ISO/IEC 14496-12 ยง12.1.5: the `nclx` tag +/// and the same three H.273 code points Matroska's `Colour` carries, plus the +/// range as the one-bit flag an mp4 says it with rather than Matroska's code. +fn colr_nclx(colour: ColorDescription) -> [u8; 11] { + let (primaries, transfer, matrix) = colour.codes(); + let mut out = [0u8; 11]; + out[..4].copy_from_slice(b"nclx"); + out[4..6].copy_from_slice(&primaries.to_be_bytes()); + out[6..8].copy_from_slice(&transfer.to_be_bytes()); + out[8..10].copy_from_slice(&matrix.to_be_bytes()); + out[10] = u8::from(colour.full_range) << 7; + out +} + const VIDEO_TRACK: u32 = 1; const AUDIO_TRACK: u32 = 2; @@ -247,6 +268,7 @@ impl Mp4Muxer { frame_duration, has_audio: audio.is_some(), entry, + colr: colr_nclx(ColorDescription::output(video.height)), path: path.to_path_buf(), }) } @@ -318,6 +340,7 @@ impl Mp4Muxer { let Self { writer, entry, + colr, path, .. } = self; @@ -325,17 +348,14 @@ impl Mp4Muxer { // patch below reads it back, and a `BufWriter` swallows the error of // flushing it on drop. writer.into_writer().flush()?; - match entry { - Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config), - None => Ok(()), - } + patch_entry(&path, entry.as_ref(), &colr) } } -/// Rewrites the finished file's one video sample entry from the `avc1` the crate -/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` + -/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file -/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened. +/// Rewrites the finished file's one video sample entry: `colr` appended to it +/// always (the crate writes none), and where `entry` says so the `avc1` header +/// itself replaced by the `av01` + `av1C` an AV1 track declares -- or the `hvc1` +/// + `hvcC` an HEVC one does. Called once, on a complete file. /// /// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only /// ever rewrites the tail of the file: no sample moves and no chunk offset in @@ -343,15 +363,13 @@ impl Mp4Muxer { /// is what keeps every ancestor's size right by construction. fn patch_entry( path: &Path, - kind: &[u8; 4], - config_kind: &[u8; 4], - config: &[u8], + entry: Option<&([u8; 4], [u8; 4], Vec)>, + colr: &[u8], ) -> crate::Result<()> { let mut file = OpenOptions::new().read(true).write(true).open(path)?; let end = file.metadata()?.len(); let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; - let patched = swap_entry(&payload, 0, kind, config_kind, config) - .ok_or("no avc1 sample entry to rewrite")?; + let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?; let mut out = Vec::with_capacity(patched.len() + 8); push_box(&mut out, b"moov", &patched); file.seek(SeekFrom::Start(at))?; @@ -393,38 +411,47 @@ fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result)>, + colr: &[u8], ) -> Option> { if depth == STSD_PATH.len() { // stsd is a FullBox (4) plus entry_count (4), then the sample entries. let mut out = payload.get(..8)?.to_vec(); - let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?; + let (kind, sample_entry) = crate::demux::boxes(payload.get(8..)?).next()?; if kind != b"avc1" { return None; } - // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all) - // before its codec box, and `av01` and `hvc1` carry exactly the same - // ones -- so the header is kept and only the configuration box is - // swapped. - let mut swapped = entry.get(..78)?.to_vec(); - push_box(&mut swapped, config_kind, config); - push_box(&mut out, want, &swapped); + let (name, mut swapped) = match entry { + // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and + // all) before its codec box, and `av01` and `hvc1` carry exactly the + // same ones -- so the header is kept and only the configuration box + // is swapped. + Some((want, config_kind, config)) => { + let mut swapped = sample_entry.get(..78)?.to_vec(); + push_box(&mut swapped, config_kind, config); + (want, swapped) + } + // H.264: the crate spelled the whole entry, `avcC` and all, and only + // the colour tag is missing from it. + None => (b"avc1", sample_entry.to_vec()), + }; + push_box(&mut swapped, b"colr", colr); + push_box(&mut out, name, &swapped); return Some(out); } let mut out = Vec::with_capacity(payload.len()); let mut done = false; for (kind, child) in crate::demux::boxes(payload) { let patched = match !done && kind == STSD_PATH[depth] { - true => swap_entry(child, depth + 1, want, config_kind, config), + true => swap_entry(child, depth + 1, entry, colr), false => None, }; match patched { @@ -475,6 +502,14 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +// `Colour` and the four children this writes, all inside `Video`. Byte-verified +// against what `demux` reads back and what ffprobe reports: the spec tables that +// list Range as 0x55B3 are describing ChromaSubsamplingHorz. +const COLOUR: u32 = 0x55B0; +const MATRIX_COEFFICIENTS: u32 = 0x55B1; +const RANGE: u32 = 0x55B9; +const TRANSFER_CHARACTERISTICS: u32 = 0x55BA; +const PRIMARIES: u32 = 0x55BB; const AUDIO: u32 = 0xE1; const SAMPLING_FREQUENCY: u32 = 0xB5; const CHANNELS: u32 = 0x9F; @@ -733,6 +768,20 @@ impl MkvMuxer { let mut dims = Vec::new(); uint(&mut dims, PIXEL_WIDTH, u64::from(width)); uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); + // What the samples in those pixels mean. Written rather than left to a + // reader's own 720-line guess -- the guess is right for this file (the + // export remaps every clip into exactly that space) but a remuxer or a + // scaler downstream has no reason to make it, and an untagged file is + // how a 601 source ends up displayed as 709. + let colour = ColorDescription::output(height); + let (primaries, transfer, matrix) = colour.codes(); + let mut tags = Vec::new(); + uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix)); + // Matroska says the range as a code, not a flag: 1 limited, 2 full. + uint(&mut tags, RANGE, 1 + u64::from(colour.full_range)); + uint(&mut tags, TRANSFER_CHARACTERISTICS, u64::from(transfer)); + uint(&mut tags, PRIMARIES, u64::from(primaries)); + elem(&mut dims, COLOUR, &tags); elem(&mut entry, VIDEO, &dims); let mut tracks = Vec::new(); elem(&mut tracks, TRACK_ENTRY, &entry); diff --git a/crates/engine/tests/export_color.rs b/crates/engine/tests/export_color.rs new file mode 100644 index 0000000..3f670c6 --- /dev/null +++ b/crates/engine/tests/export_color.rs @@ -0,0 +1,232 @@ +//! What an exported file says its numbers mean, and what it does to a clip that +//! disagreed: the writing half of `engine::colorspace`. +//! +//! Two claims, both measured with `ffmpeg`/`ffprobe` rather than with this +//! project's own reader alone -- an export is read by other software, and a tag +//! only this engine agrees with is not a tag: +//! +//! 1. every export declares a space (BT.709 at 720 lines and up, BT.601 below), +//! in the `Colour` element of a Matroska and the `colr` box of an mp4, and +//! 2. a clip coded against the *other* matrix is rewritten into the file's, so +//! reading the export by its own tags gives back the picture that went in -- +//! a reconcile, not a second conversion. +//! +//! ```text +//! cargo test -p engine --release --test export_color +//! ``` +//! +//! Release: the Matroska half goes through the intra HEVC encoder, which is +//! minutes a frame in debug. Without `ffmpeg` on the machine the external half +//! says so and passes, exactly as the hardware tests elsewhere here do. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +use engine::PlaybackSession; +use engine::colorspace::{ColorDescription, Matrix, Transfer, remap}; +use engine::demux::Demuxer; +use engine::export::{ExportSettings, Format}; +use engine::scratch::Scratch; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str, ext: &str) -> Scratch { + Scratch::file(&format!("ve_color_{name}"), ext) +} + +/// The first two frames of `source`, so what is measured is the colour path and +/// not how long an encoder takes. +fn two_frames(source: &Path) -> PlaybackSession { + let mut session = PlaybackSession::open(source).expect("open the fixture"); + assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front"); + assert!(session.delete_clip(engine::project::Lane::V1, 1)); + session +} + +fn export(session: &PlaybackSession, out: &Path, format: Format) { + let handle = session.export_to_with( + out, + &ExportSettings { + format, + ..Default::default() + }, + ); + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(300), + "the export did not finish in 300 s" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("an outcome").expect("the export"); +} + +/// What ffprobe says the stream declares: matrix, primaries, transfer, range. +/// `None` when ffprobe is not installed. +fn probed(path: &Path) -> Option> { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=color_space,color_primaries,color_transfer,color_range", + "-of", + "default=nw=1:nk=1", + ]) + .arg(path) + .output() + .ok()?; + Some( + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim().to_string()) + .collect(), + ) +} + +/// Frame 0 of `path` as planar 4:2:0 bytes, straight off the decoder with no +/// colour conversion at all -- the samples as they are in the file, which is +/// what a remap is measured on. `None` when ffmpeg is not installed. +fn raw_yuv(path: &Path) -> Option> { + let raw = Scratch::file("ve_color_raw", "yuv"); + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-i"]) + .arg(path) + .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .arg(&*raw) + .status() + .ok()?; + assert!(ok.success(), "ffmpeg could not read {}", path.display()); + Some(std::fs::read(&*raw).expect("the raw frame")) +} + +fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len(), "frame sizes differ"); + a.iter() + .zip(b) + .map(|(x, y)| f64::from(x.abs_diff(*y))) + .sum::() + / a.len() as f64 +} + +/// Every export says which space it is in, in the words its container spells +/// them and in the words ffprobe reads back. `test_bt601.mp4` is 1280x720 and +/// the export of it is therefore BT.709 whatever the source said; the 640x480 +/// fixture is below the line and comes out BT.601 whatever *its* bitstream said. +/// Both containers, because the two tags are written by different code. +#[test] +fn an_export_declares_the_space_it_was_written_in() { + for (fixture, matrix, probe) in [ + ("test_bt601.mp4", Matrix::Bt709, "bt709"), + ("test_vui_h264.mp4", Matrix::Bt601, "smpte170m"), + ] { + for (format, ext) in [(Format::Mp4, "mp4"), (Format::Hevc, "mkv")] { + let session = two_frames(&asset(fixture)); + let out = out_path(&format!("tags_{ext}"), ext); + export(&session, &out, format); + + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + meta.color, + ColorDescription { + matrix, + transfer: Transfer::Sdr, + full_range: false, + }, + "{fixture} -> {ext}: what the file says about itself" + ); + match probed(&out) { + Some(tags) => { + eprintln!("{fixture} -> {ext}: ffprobe {tags:?}"); + // ffprobe prints these in its own field order, range first, + // whatever order they were asked for in. + let want: Vec = ["tv", probe, probe, probe] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!( + tags, want, + "{fixture} -> {ext}: range, matrix, primaries, transfer" + ); + } + None => eprintln!("no ffprobe: skipping the external read of {ext}"), + } + std::fs::remove_file(&out).unwrap(); + } + } +} + +/// The reconcile itself, on the samples: a BT.601 clip on a 720-line canvas is +/// written as BT.709, and the numbers in the file are the source's *remapped* -- +/// within what the encoder rounds off. The second measurement is the one that +/// makes the first mean something: the untouched source is far further away +/// than the remapped one, so this cannot pass by doing nothing. +#[test] +fn a_clip_in_another_space_is_remapped_into_the_files() { + let source = asset("test_bt601.mp4"); + let Some(src) = raw_yuv(&source) else { + eprintln!("no ffmpeg: skipping the sample-level remap check"); + return; + }; + let session = two_frames(&source); + let out = out_path("remap", "mp4"); + export(&session, &out, Format::Mp4); + let got = raw_yuv(&out).expect("ffmpeg read the export"); + + let (width, height) = (1280usize, 720usize); + let mut planes = src.clone(); + let (y, chroma) = planes.split_at_mut(width * height); + let (u, v) = chroma.split_at_mut(width * height / 4); + remap(Matrix::Bt601, Matrix::Bt709, y, u, v, width); + + let remapped = mean_abs_diff(&got, &planes); + let untouched = mean_abs_diff(&got, &src); + eprintln!( + "601 clip on a 709 canvas: {remapped:.2} off the remapped source, {untouched:.2} off the raw one" + ); + assert!( + remapped < 3.0, + "the export is {remapped:.2} away from the remapped source" + ); + assert!( + untouched > 3.0 * remapped, + "remapped {remapped:.2} vs untouched {untouched:.2}: nothing was reconciled" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// ...and the other half of that claim, which is the regression one: a clip +/// already in the file's space is not remapped at all, so an ordinary +/// single-space project comes out exactly as it did before any of this existed. +/// `test_baseline.mp4` is 1280x720 and untagged, which resolves to BT.709 -- +/// the very space its export declares. +#[test] +fn a_same_space_clip_is_left_alone() { + let source = asset("test_baseline.mp4"); + let Some(src) = raw_yuv(&source) else { + eprintln!("no ffmpeg: skipping the same-space regression check"); + return; + }; + let (meta, _) = Demuxer::open(&source).expect("open the fixture"); + assert_eq!(meta.color.matrix, Matrix::Bt709, "the fixture's own space"); + let session = two_frames(&source); + let out = out_path("same_space", "mp4"); + export(&session, &out, Format::Mp4); + let got = raw_yuv(&out).expect("ffmpeg read the export"); + + let diff = mean_abs_diff(&got, &src); + eprintln!("same-space export: {diff:.2} off the source samples"); + assert!( + diff < 3.0, + "a same-space export moved the samples by {diff:.2}" + ); + std::fs::remove_file(&out).unwrap(); +}