diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 857e543..512d7d6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -64,7 +64,7 @@ use flacenc::error::Verify; use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; -use crate::colorspace::ColorDescription; +use crate::colorspace::{ColorDescription, Matrix}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; @@ -1006,10 +1006,12 @@ fn run( 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. + // the one this file declares is rewritten into it, *after* the grade -- + // playback grades in the source's own space and converts for the screen + // ([`crate::decode`]), so a grade applied to remapped samples is a + // different picture than the one 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 @@ -1100,12 +1102,15 @@ fn run( gu.extend_from_slice(u); gv.clear(); gv.extend_from_slice(v); - if let Some((from, to)) = remap { - crate::colorspace::remap(from, to, gy, gu, gv, width as usize); - } + // 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. if let Some(params) = params { 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); + } (&gy[..], &gu[..], &gv[..]) } }; @@ -1827,6 +1832,11 @@ struct HevcEnc { crop: (usize, usize), qp: i32, lanes: usize, + /// What the SPS says the samples mean. A decoder reads the bitstream before + /// it reads the container, so an HEVC stream without this renders BT.601 in + /// libavcodec however the file is tagged -- the container's `Colour` element + /// and `colr` box are not enough on their own. + signal: oxideav_h265::vui::VideoSignalType, } impl Enc { @@ -1929,6 +1939,25 @@ impl Enc { // progress the whole way, which is what makes that bearable rather than // hidden. cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED); + // What the sequence header says the samples mean, for the reason + // [`video_signal_type`] gives: a container tag is the second answer a + // decoder looks at, not the first. Written as rav1e's own enums rather + // than the H.273 numbers -- the crate has no `from` for the code points, + // and the output rule only ever picks one of these two spaces. + let out = ColorDescription::output(meta.height); + cfg.pixel_range = rav1e::prelude::PixelRange::Limited; + cfg.color_description = Some(match out.matrix { + Matrix::Bt709 => rav1e::prelude::ColorDescription { + color_primaries: rav1e::prelude::ColorPrimaries::BT709, + transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709, + matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709, + }, + _ => rav1e::prelude::ColorDescription { + color_primaries: rav1e::prelude::ColorPrimaries::BT601, + transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601, + matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601, + }, + }); let config = rav1e::Config::new() .with_encoder_config(cfg) .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get())); @@ -1987,6 +2016,7 @@ impl Enc { crop: (width - meta.width as usize, height - meta.height as usize), qp: hevc_qp(meta, settings), lanes: lanes.min(HEVC_LANES), + signal: video_signal_type(meta.height), })) } @@ -2122,6 +2152,7 @@ impl HevcEnc { /// as an error rather than unwinding the export thread. fn code_batch(&mut self) -> crate::Result<()> { let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop); + let signal = self.signal; let coded: Vec>> = std::thread::scope(|scope| { let lanes: Vec<_> = self .pending @@ -2129,7 +2160,15 @@ impl HevcEnc { .map(|(y, cb, cr)| { scope.spawn(move || { oxideav_h265::encoder::intra::encode_idr_intra_au_cropped( - y, cb, cr, width, height, qp, crop.0, crop.1, + y, + cb, + cr, + width, + height, + qp, + crop.0, + crop.1, + Some(signal), ) .map(|coded| coded.au) .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}"))) @@ -2212,6 +2251,31 @@ fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) } +/// What the *bitstream* says the samples mean, in the words a sequence header +/// spells them -- the same H.273 code points [`crate::mux`] writes into the +/// container, from the same [`ColorDescription::output`] rule, so the two halves +/// of a file cannot drift apart. +/// +/// This exists because a container tag is not enough: libavcodec takes the +/// bitstream's answer first, and a stream that says nothing is "unspecified", +/// which renders BT.601 -- a visible shift on a 709 export that a player reads +/// from the wrong matrix. Every export is limited range, which is what +/// `video_full_range_flag = false` says here. +fn video_signal_type(height: u32) -> oxideav_h265::vui::VideoSignalType { + let (primaries, transfer, matrix) = ColorDescription::output(height).codes(); + oxideav_h265::vui::VideoSignalType { + // "Unspecified", which is what every encoder here writes: the field is + // the analogue system a picture came off, and none of these did. + video_format: 5, + video_full_range_flag: false, + colour_description: Some(oxideav_h265::vui::ColourDescription { + colour_primaries: primaries as u8, + transfer_characteristics: transfer as u8, + matrix_coeffs: matrix as u8, + }), + } +} + /// Every temporal unit `rav1e` has finished, moved into the queue in display /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is /// through) are the two ways it says there is nothing more; `Encoded` means a diff --git a/crates/engine/tests/export_color.rs b/crates/engine/tests/export_color.rs index 3f670c6..7c1c2c8 100644 --- a/crates/engine/tests/export_color.rs +++ b/crates/engine/tests/export_color.rs @@ -6,10 +6,13 @@ //! 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 +//! in the `Colour` element of a Matroska and the `colr` box of an mp4, *and* +//! in the coded bitstream, which is the answer a decoder takes first; //! 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. +//! 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. //! //! ```text //! cargo test -p engine --release --test export_color @@ -92,6 +95,52 @@ fn probed(path: &Path) -> Option> { ) } +/// What ffprobe says the first *coded frame* is, which is the stream's own +/// answer and not the container's: libavcodec fills a frame's colour in from the +/// bitstream, so a codec that signalled nothing reads back "unknown" here even +/// where the file is tagged. `None` when ffprobe is not installed. +fn probed_frame(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_frames", + "-read_intervals", + "%+#1", + "-show_entries", + "frame=color_space", + "-of", + "default=nw=1:nk=1", + ]) + .arg(path) + .output() + .ok()?; + Some( + String::from_utf8_lossy(&out.stdout) + .lines() + .next() + .unwrap_or_default() + .trim() + .to_string(), + ) +} + +/// The session's first frame as BGRA, through this engine's own decode path -- +/// the very path the preview draws with, so a preview frame and a re-imported +/// export frame are two measurements of one picture and nothing else. +fn frame0_bgra(session: &mut PlaybackSession) -> Vec { + let deadline = Instant::now() + Duration::from_secs(180); + loop { + if let Some(frame) = session.try_frame() { + return frame.bgra; + } + assert!(Instant::now() < deadline, "no frame in 180 s"); + std::thread::sleep(Duration::from_millis(5)); + } +} + /// 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. @@ -230,3 +279,82 @@ fn a_same_space_clip_is_left_alone() { ); std::fs::remove_file(&out).unwrap(); } + +/// The tag a *decoder* reads, on every format there is. A container's colour +/// element is the second answer libavcodec looks at and the bitstream's is the +/// first, so a stream that signals nothing is rendered BT.601 whatever the file +/// says about itself -- which is a visible shift on a 709 export and was +/// measured as one (9.78 mean codes off the right render against 2.27 off the +/// wrong one, HEVC before its SPS carried a VUI). +/// +/// All five video formats, because the gap was per-codec and a container-level +/// check could not see it: the mp4 and Matroska tags were right the whole time. +#[test] +fn every_format_signals_its_space_in_the_bitstream() { + if probed_frame(&asset("test_bt601.mp4")).is_none() { + eprintln!("no ffprobe: skipping the frame-level colour check"); + return; + } + for (format, ext, name) in [ + (Format::Mp4, "mp4", "h264-mp4"), + (Format::Hevc, "mkv", "hevc-mkv"), + (Format::HevcMp4, "mp4", "hevc-mp4"), + (Format::Av1, "mkv", "av1-mkv"), + (Format::Av1Mp4, "mp4", "av1-mp4"), + ] { + let session = two_frames(&asset("test_bt601.mp4")); + let out = out_path(&format!("frametag_{name}"), ext); + export(&session, &out, format); + let got = probed_frame(&out).expect("ffprobe is installed"); + eprintln!("{name}: frame colour_space {got}"); + assert_eq!(got, "bt709", "{name}: what a decoder makes of the frame"); + 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 +/// *first* graded different numbers and came out 21.04 mean codes away from what +/// the canvas had shown -- a saturation the user set against one picture, +/// applied to another. +/// +/// Measured through this engine's own decode of its own export, because that is +/// the comparison the invariant is about; the ungraded control is what says the +/// number belongs to the grade and not to the encoder. +#[test] +fn a_graded_clip_exports_the_picture_the_preview_showed() { + for (grade, label, ceiling) in [ + ( + Some(engine::color::ColorParams { + brightness: 0.0, + contrast: 1.0, + saturation: 0.0, + tint: 0.0, + }), + "saturation 0", + 2.0, + ), + (None, "ungraded control", 2.0), + ] { + let mut session = two_frames(&asset("test_bt601.mp4")); + assert!( + session.set_color(engine::project::Lane::V1, 0, grade), + "{label}: the grade went on the clip" + ); + let preview = frame0_bgra(&mut session); + let out = out_path("preview_vs_export", "mp4"); + export(&session, &out, Format::Mp4); + + let mut reopened = PlaybackSession::open(&*out).expect("reopen the export"); + let exported = frame0_bgra(&mut reopened); + let diff = mean_abs_diff(&preview, &exported); + eprintln!("{label}: preview vs export {diff:.2} mean codes"); + assert!( + diff <= ceiling, + "{label}: the export is {diff:.2} codes from what the preview showed" + ); + drop(reopened); + std::fs::remove_file(&out).unwrap(); + } +} diff --git a/vendor/oxideav-h265/src/encoder/inter.rs b/vendor/oxideav-h265/src/encoder/inter.rs index d032a39..c11442c 100644 --- a/vendor/oxideav-h265/src/encoder/inter.rs +++ b/vendor/oxideav-h265/src/encoder/inter.rs @@ -364,7 +364,9 @@ impl LowDelayPEncoder { max_num_reorder_pics: 0, min_cb_log2: if self.amp { 3 } else { 4 }, amp: self.amp, - conf_win: (0, 0), // edith patch: no crop on the inter paths + // edith patch: no crop and no VUI on the inter paths + conf_win: (0, 0), + signal: None, }, &self.filters, )?; diff --git a/vendor/oxideav-h265/src/encoder/intra.rs b/vendor/oxideav-h265/src/encoder/intra.rs index 1db110b..22edcbd 100644 --- a/vendor/oxideav-h265/src/encoder/intra.rs +++ b/vendor/oxideav-h265/src/encoder/intra.rs @@ -54,6 +54,8 @@ use crate::encoder::loopfilter::{ encode_sao_ctb, filter_frame, CtbShape, FilterInput, LoopFilterCfg, }; use crate::encoder::nal::{annexb, nal_unit}; +// --- edith patch: the SPS's colour signalling reuses the parser's types --- +use crate::vui::VideoSignalType; use crate::encoder::pcm::{level_idc_for, write_pps_lf, write_ptl, write_vps, write_vps_cfg}; use crate::encoder::residual::encode_residual_coding; use crate::intra_mode_field::{IntraModeField, Neighbour}; @@ -157,6 +159,12 @@ pub(crate) struct SpsCfg { /// `conformance_window_flag = 0`, which is what upstream always /// wrote. pub conf_win: (u32, u32), + /// §E.2.1 `video_signal_type_present_flag` block, written into a + /// VUI of its own. `None` writes `vui_parameters_present_flag = 0`, + /// which is what upstream always wrote — and which makes a decoder + /// infer "unspecified" and render the picture BT.601 whatever the + /// container said. + pub signal: Option, // --- end edith patch --- } @@ -170,6 +178,7 @@ impl SpsCfg { min_cb_log2: CTB_LOG2, amp: false, conf_win: (0, 0), + signal: None, } } } @@ -233,7 +242,37 @@ pub(crate) fn write_sps_cfg( w.put_bit(0); // long_term_ref_pics_present_flag w.put_bit(0); // sps_temporal_mvp_enabled_flag w.put_bit(0); // strong_intra_smoothing_enabled_flag - w.put_bit(0); // vui_parameters_present_flag + // --- edith patch: §E.2.1 VUI, colour signalling only (upstream + // always wrote 0). Everything else in the VUI stays absent, which + // §E.3.1 infers to exactly the values upstream's silence did. + match cfg.signal { + None => w.put_bit(0), // vui_parameters_present_flag + Some(signal) => { + w.put_bit(1); // vui_parameters_present_flag + w.put_bit(0); // aspect_ratio_info_present_flag + w.put_bit(0); // overscan_info_present_flag + w.put_bit(1); // video_signal_type_present_flag + w.put_bits(u32::from(signal.video_format), 3); + w.put_bit(u8::from(signal.video_full_range_flag)); + match signal.colour_description { + None => w.put_bit(0), // colour_description_present_flag + Some(colour) => { + w.put_bit(1); // colour_description_present_flag + w.put_bits(u32::from(colour.colour_primaries), 8); + w.put_bits(u32::from(colour.transfer_characteristics), 8); + w.put_bits(u32::from(colour.matrix_coeffs), 8); + } + } + w.put_bit(0); // chroma_loc_info_present_flag + w.put_bit(0); // neutral_chroma_indication_flag + w.put_bit(0); // field_seq_flag + w.put_bit(0); // frame_field_info_present_flag + w.put_bit(0); // default_display_window_flag + w.put_bit(0); // vui_timing_info_present_flag + w.put_bit(0); // bitstream_restriction_flag + } + } + // --- end edith patch --- w.put_bit(0); // sps_extension_present_flag w.rbsp_trailing_bits(); w.finish() @@ -524,6 +563,10 @@ pub fn encode_idr_intra_au( /// size. Both crops must be even (4:2:0 addresses the window in chroma /// units) and smaller than 16. /// +/// `signal` is the §E.2.1 colour signalling the SPS carries: a decoder +/// reads the bitstream before it reads the container, so `None` renders +/// as "unspecified" — BT.601 in libavcodec — however the file is tagged. +/// /// # Errors /// [`IntraEncodeError`] as [`encode_idr_intra_au`], plus /// [`IntraEncodeError::BadDimensions`] for an odd or oversized crop. @@ -536,6 +579,7 @@ pub fn encode_idr_intra_au_cropped( qp: i32, crop_right: usize, crop_bottom: usize, + signal: Option, ) -> Result { if crop_right % 2 != 0 || crop_bottom % 2 != 0 || crop_right >= CTB || crop_bottom >= CTB { return Err(IntraEncodeError::BadDimensions { @@ -545,6 +589,7 @@ pub fn encode_idr_intra_au_cropped( } let mut cfg = SpsCfg::legacy(1); cfg.conf_win = ((crop_right / 2) as u32, (crop_bottom / 2) as u32); + cfg.signal = signal; encode_idr_intra_au_full(y, cb, cr, width, height, qp, &cfg, &LoopFilterCfg::off()) } // --- end edith patch --- diff --git a/vendor/oxideav-h265/src/encoder/pyramid.rs b/vendor/oxideav-h265/src/encoder/pyramid.rs index e97fd1b..95e6d3c 100644 --- a/vendor/oxideav-h265/src/encoder/pyramid.rs +++ b/vendor/oxideav-h265/src/encoder/pyramid.rs @@ -230,7 +230,9 @@ impl PyramidEncoder { max_num_reorder_pics: self.depth(), min_cb_log2: if self.amp { 3 } else { 4 }, amp: self.amp, - conf_win: (0, 0), // edith patch: no crop on the inter paths + // edith patch: no crop and no VUI on the inter paths + conf_win: (0, 0), + signal: None, } }