From f390c37c7f0cd1aacbdb462c52a1cd9bacb00ac2 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 20:38:59 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(export):=20an=20HDR=20source?= =?UTF-8?q?=20is=20tone-mapped=20into=20the=20file's=20SDR,=20once,=20befo?= =?UTF-8?q?re=20the=20grade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The export path read a PQ or HLG source's tags, wrote an SDR file and left the pixels on their HDR curve: a washed-out, flat picture in a file that says BT.709. `engine::tonemap` existed and nothing called it. One `ToneMapper` per source stream -- the 9 537-node table is built beside the per-source rate and colour, not per span -- and one call per frame, into the grade scratch the path already owns, ahead of `apply_yuv`. That order is playback's: the grade is a decision made against the SDR picture on the canvas, so applying it to HDR codes would export a picture nobody saw. The matrix remap that used to be the whole of the answer now asks `remap_into`, which knows the tone map hands back BT.709 whatever the source was coded as: an HDR clip is never *also* given the 2020 matrix treatment, and one on a canvas below 720 lines still takes its 709 -> 601 step. An SDR project is byte-identical: no table is built, no branch is taken. --- crates/engine/src/colorspace.rs | 3 +- crates/engine/src/export.rs | 119 ++++++++++++--- crates/engine/tests/export_color.rs | 219 +++++++++++++++++++++++++++- 3 files changed, 320 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/colorspace.rs b/crates/engine/src/colorspace.rs index 5a238ea..f257a47 100644 --- a/crates/engine/src/colorspace.rs +++ b/crates/engine/src/colorspace.rs @@ -96,7 +96,8 @@ impl ColorDescription { /// [`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. + /// SDR always: an HDR source is *tone-mapped* into this on the way out + /// ([`crate::tonemap`]), never carried through and re-tagged. pub fn output(height: u32) -> Self { Self { matrix: if height >= 720 { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 512d7d6..304e281 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -64,13 +64,14 @@ use flacenc::error::Verify; use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; -use crate::colorspace::{ColorDescription, Matrix}; +use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; use crate::subtitle::{Cue, SubtitleTrack}; +use crate::tonemap::{self, ToneMapper}; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -962,6 +963,20 @@ fn run( .iter() .map(|source| source_rate(&source.path, meta.frame_rate)) .collect(); + // ...and, for a source on an HDR curve, the tone map that brings its samples + // down to the SDR this file is written in ([`crate::tonemap`]). Once per + // source stream: the table costs a couple of milliseconds to build and a + // span reopens its file, so building it here rather than in the loop below + // is the difference between paying that once and paying it per cut. An SDR + // source -- the whole of an ordinary project -- builds no table at all. + let tone: Vec> = rates + .iter() + .map(|(_, color)| match color.transfer { + Transfer::Sdr => None, + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)), + }) + .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); @@ -990,7 +1005,7 @@ 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, color) = match span.from { + let (mut pictures, rate, in_frame, color, mapper) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) @@ -999,11 +1014,18 @@ fn run( // 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(color)) + ( + Some(pictures), + rate, + in_frame, + Some(color), + tone[source].as_ref(), + ) } - // 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), + // A gap's black is 16/128/128, which is black in every matrix here + // and on every curve: nothing to remap and nothing to tone-map, + // which is what `None` says. + None => (None, Rate::REAL_TIME, 0, None, None), }; // Mixed spaces on one timeline: a clip coded against another matrix than // the one this file declares is rewritten into it, *after* the grade -- @@ -1013,13 +1035,9 @@ fn run( // 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)); + // ...and what the samples mean when that remap sees them is not always + // what the file said, which is [`remap_into`]'s whole question. + let remap = remap_into(color, mapper.is_some(), 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 @@ -1092,9 +1110,9 @@ fn run( // applied in place: it goes onto a copy, which the encoder then // reads instead. let params = grade.filter(|p| !p.is_identity()); - let (y, u, v) = match (params, remap) { - (None, None) => (y, u, v), - (params, remap) => { + let (y, u, v) = match (params, remap, mapper) { + (None, None, None) => (y, u, v), + (params, remap, mapper) => { let (gy, gu, gv) = &mut graded; gy.clear(); gy.extend_from_slice(y); @@ -1102,9 +1120,13 @@ fn run( gu.extend_from_slice(u); gv.clear(); gv.extend_from_slice(v); - // Grade in the source's space, then remap the graded - // result: the order playback's `Decoded::frame` renders in, - // and the only order in which preview and export agree. + // Tone-map first, so the grade is applied to the SDR picture + // the canvas showed and not to HDR codes; then remap the + // graded result. The order playback renders in, and the + // only order in which preview and export agree. + if let Some(mapper) = mapper { + mapper.map(gy, gu, gv, width as usize, height as usize); + } if let Some(params) = params { crate::color::apply_yuv(¶ms, gy, gu, gv); } @@ -1179,6 +1201,27 @@ fn run( Ok(()) } +/// Which matrix pair a span's samples are rewritten by on the way into a file +/// whose own matrix is `out` -- `None` when they are already coded against it, +/// and for a gap, whose 16/128/128 black is black in every matrix here. +/// +/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever +/// the source was coded as, so an HDR clip is never *also* given the matrix +/// treatment its BT.2020 tag would ask for -- one conversion or the other, never +/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines +/// still takes its 709 -> 601 step. +fn remap_into( + color: Option, + toned: bool, + out: Matrix, +) -> Option<(Matrix, Matrix)> { + let from = match toned { + true => Matrix::Bt709, + false => color?.matrix, + }; + (from != out).then_some((from, out)) +} + /// What rate `path` was shot at against a timeline at `timeline_fps` /// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own /// -- a still, a song -- and for one that will not open here: the decoder is @@ -2418,6 +2461,44 @@ impl SwDecoder { mod tests { use super::*; + /// The one rule that keeps a picture from being converted twice: a frame the + /// tone map has already brought to BT.709 is never handed the 2020 matrix as + /// well, on either canvas -- and everything else about the remap is + /// unchanged by the tone map existing. + #[test] + fn a_tone_mapped_span_is_never_matrix_remapped_too() { + let hdr = ColorDescription { + matrix: Matrix::Bt2020Ncl, + transfer: Transfer::Pq, + full_range: false, + }; + let sdr = ColorDescription::default(); // BT.601 + for out in [Matrix::Bt709, Matrix::Bt601] { + let toned = remap_into(Some(hdr), true, out); + assert!( + toned.is_none_or(|(from, _)| from == Matrix::Bt709), + "tone-mapped onto a {out:?} canvas asked for {toned:?}" + ); + // Untouched by any of this: the 2020 clip that was *not* tone-mapped + // (an unreachable state today, and still the matrix answer), the + // ordinary 601-on-709 reconcile, and a gap. + assert_eq!( + remap_into(Some(hdr), false, out), + (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out)) + ); + assert_eq!( + remap_into(Some(sdr), false, out), + (out != Matrix::Bt601).then_some((Matrix::Bt601, out)) + ); + assert_eq!(remap_into(None, false, out), None); + } + assert_eq!( + remap_into(Some(hdr), true, Matrix::Bt601), + Some((Matrix::Bt709, Matrix::Bt601)), + "a tone-mapped clip below 720 lines still takes its 709 -> 601 step" + ); + } + /// A track of three cues, in whichever clock `track` says: `Some(n)` is a /// track of the media file, `None` a `.srt` beside it. fn subtitles(path: &str, track: Option) -> SubtitleTrack { diff --git a/crates/engine/tests/export_color.rs b/crates/engine/tests/export_color.rs index 7c1c2c8..65a7d56 100644 --- a/crates/engine/tests/export_color.rs +++ b/crates/engine/tests/export_color.rs @@ -12,7 +12,10 @@ //! reading the export by its own tags gives back the picture that went in -- //! a reconcile, not a second conversion; and //! 3. a graded clip comes out of the export the way the preview showed it, -//! which is what makes a grade a decision and not a guess. +//! which is what makes a grade a decision and not a guess; and +//! 4. an HDR source is *tone-mapped* into that space rather than tagged into it +//! ([`engine::tonemap`]) -- once, before the grade, and never on top of a +//! matrix conversion of the same frame. //! //! ```text //! cargo test -p engine --release --test export_color @@ -31,6 +34,7 @@ use engine::colorspace::{ColorDescription, Matrix, Transfer, remap}; use engine::demux::Demuxer; use engine::export::{ExportSettings, Format}; use engine::scratch::Scratch; +use engine::tonemap::{self, ToneMapper}; fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -157,6 +161,40 @@ fn raw_yuv(path: &Path) -> Option> { Some(std::fs::read(&*raw).expect("the raw frame")) } +/// A one-second 720p fixture whose samples are ordinary 8-bit BT.709 pictures +/// but whose *tags* say BT.2020 PQ -- which is all the colour path reads, so it +/// exercises the tone map without an HDR encoder anywhere near the test. The +/// codes therefore mean something far brighter than they were drawn as, which is +/// the point: an HDR file handed to an SDR display is exactly that mistake. +/// +/// The tags go in through `-x264-params`, not ffmpeg's own `-color_trc`: the +/// latter writes the mp4's `colr` box alone here (measured: ffprobe reads the +/// transfer back as "unknown"), and the bitstream is the answer any reader takes +/// first. `None` where ffmpeg is not installed. +fn pq_fixture() -> Option { + let path = out_path("pq_source", "mp4"); + let made = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "testsrc2=size=1280x720:rate=30:duration=1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-x264-params", + "colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc", + ]) + .arg(&*path) + .output() + .ok()?; + made.status.success().then_some(path) +} + fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { assert_eq!(a.len(), b.len(), "frame sizes differ"); a.iter() @@ -312,6 +350,185 @@ fn every_format_signals_its_space_in_the_bitstream() { } } +/// An HDR source comes out as an SDR file that *says* it is one, in the +/// container and in the bitstream both. The tags are the half a player reads +/// before it reads a pixel: a file of tone-mapped samples still labelled PQ is +/// shown through a second, inverse curve and is worse than either honest answer. +#[test] +fn an_hdr_source_exports_as_a_tagged_sdr_file() { + let Some(source) = pq_fixture() else { + eprintln!("no ffmpeg: skipping the HDR export tags"); + return; + }; + let (meta, _) = Demuxer::open(&source).expect("open the PQ fixture"); + assert_eq!(meta.color.transfer, Transfer::Pq, "the fixture's own curve"); + assert_eq!(meta.color.matrix, Matrix::Bt2020Ncl, "...and its matrix"); + + let session = two_frames(&source); + let out = out_path("hdr_tags", "mp4"); + export(&session, &out, Format::Mp4); + + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + meta.color, + ColorDescription { + matrix: Matrix::Bt709, + transfer: Transfer::Sdr, + full_range: false, + }, + "what the export says about itself" + ); + match probed(&out) { + Some(tags) => { + eprintln!("PQ source -> mp4: ffprobe {tags:?}"); + let want: Vec = ["tv", "bt709", "bt709", "bt709"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(tags, want, "range, matrix, transfer, primaries"); + assert_eq!( + probed_frame(&out).expect("ffprobe is installed"), + "bt709", + "what a decoder makes of the coded frame" + ); + } + None => eprintln!("no ffprobe: skipping the external read"), + } + std::fs::remove_file(&out).unwrap(); +} + +/// The order, measured on the samples: tone-map first, grade the SDR picture +/// that comes out. Playback renders in that order, so an export that graded the +/// *HDR* codes and tone-mapped afterwards would be a different picture than the +/// canvas showed -- and with a brightness lift on a curve this steep, a very +/// different one, which is what the swapped-order control here measures. +/// +/// It is also where "converted once" is checked: the reference below is the tone +/// map and the grade and nothing else, no matrix step, so an export that also +/// ran the BT.2020 matrix over those samples could not land on it. +#[test] +fn an_hdr_clip_is_tone_mapped_before_it_is_graded() { + let Some(source) = pq_fixture() else { + eprintln!("no ffmpeg: skipping the tone-map order check"); + return; + }; + let Some(src) = raw_yuv(&source) else { + eprintln!("no ffmpeg: skipping the tone-map order check"); + return; + }; + // A lift, because the curve it is composed with is steepest where the codes + // are: swap the two and the picture is visibly elsewhere. + let grade = engine::color::ColorParams { + brightness: 0.25, + ..Default::default() + }; + let mut session = two_frames(&source); + assert!( + session.set_color(engine::project::Lane::V1, 0, Some(grade)), + "the grade went on the clip" + ); + let out = out_path("hdr_order", "mp4"); + export(&session, &out, Format::Mp4); + let got = raw_yuv(&out).expect("ffmpeg read the export"); + + let (width, height) = (1280usize, 720usize); + let mapper = ToneMapper::new(tonemap::Transfer::Pq); + // The same bytes twice, through the two orders. Whichever way MASTER_NITS is + // set, both sides move with it -- what is asserted is which of them the + // export sits on, not where either lands. + let both = [true, false].map(|tone_first| { + let mut planes = src.clone(); + let (y, chroma) = planes.split_at_mut(width * height); + let (u, v) = chroma.split_at_mut(width * height / 4); + if tone_first { + mapper.map(y, u, v, width, height); + engine::color::apply_yuv(&grade, y, u, v); + } else { + engine::color::apply_yuv(&grade, y, u, v); + mapper.map(y, u, v, width, height); + } + planes + }); + let [ordered, swapped] = both.map(|planes| mean_abs_diff(&got, &planes)); + eprintln!( + "HDR export: {ordered:.2} off tone-map-then-grade, {swapped:.2} off the swapped order" + ); + assert!( + ordered < 3.0, + "the export is {ordered:.2} codes from tone-map-then-grade" + ); + assert!( + swapped > 3.0 * ordered, + "ordered {ordered:.2} vs swapped {swapped:.2}: the two orders are not far enough apart to have measured anything" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// The real thing, where this machine has it: five seconds of a 4K HDR10 film, +/// ten minutes in (the opening two are black and would measure nothing), +/// decoded by the VA-API plugin -- 10-bit HEVC has no software decoder here -- +/// and exported. Skipped, loudly, on a machine without the film. +/// +/// What is asserted is what the synthetic fixture cannot be: that the tone map +/// survives a real grade of real HDR10 pixels. A picture that came out grey +/// (chroma collapsed onto 128) or crushed to black is what a mistuned or +/// double-applied conversion produces, and both are one mean away. +#[test] +fn a_real_hdr_film_exports_as_a_picture() { + let film = Path::new( + "/path/to/a-real-4k-hdr10-film.mkv", + ); + if !film.exists() { + eprintln!("skipped: {} is not on this machine", film.display()); + return; + } + let mut session = PlaybackSession::open(film).expect("open the film"); + assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR10 film"); + // A five-second window out of the middle: cut both ends, drop them, and the + // delete closes the gap ahead of what is left, so the export is those five + // seconds and no leading black. + assert!(session.cut_at(605.0), "the tail cut"); + assert!(session.cut_at(600.0), "the head cut"); + assert!(session.delete_clip(engine::project::Lane::V1, 2), "the tail"); + assert!(session.delete_clip(engine::project::Lane::V1, 0), "the head"); + let out = out_path("hdr_film", "mp4"); + export(&session, &out, Format::Mp4); + + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!( + meta.color, + ColorDescription { + matrix: Matrix::Bt709, + transfer: Transfer::Sdr, + full_range: false, + }, + "a 4K HDR film exported as tagged SDR" + ); + let Some(frame) = raw_yuv(&out) else { + eprintln!("no ffmpeg: skipping the pixel half of the film check"); + return; + }; + let (width, height) = (meta.width as usize, meta.height as usize); + let (y, chroma) = frame.split_at(width * height); + let luma = y.iter().map(|s| f64::from(*s)).sum::() / y.len() as f64; + let colour = chroma + .iter() + .map(|s| f64::from(s.abs_diff(128))) + .sum::() + / chroma.len() as f64; + eprintln!("5 s of the film at 600 s: mean luma {luma:.1}, mean chroma distance {colour:.1}"); + // Ranges, not anchors: the exposure the tone map is tuned to is a constant + // in that module and may move. What may not move is that the picture is + // still a picture -- neither crushed to black nor washed to white, and in + // colour. + assert!( + (25.0..200.0).contains(&luma), + "mean luma {luma:.1}: that is not a picture" + ); + assert!(colour > 4.0, "mean chroma distance {colour:.1}: grey"); + std::fs::remove_file(&out).unwrap(); +} + /// Preview and export are the same picture, on the one path where they used to /// differ: a graded clip whose own space is not the file's. Playback grades in /// the source's space and converts for the screen, so an export that remapped