From 9fdee6f6ff1ad95333d6e5d479f22c2f6919d2d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 04:37:20 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine-hw):=20the=20hardware?= =?UTF-8?q?=20HEVC=20seat=20says=20what=20its=20samples=20mean?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin's HEVC encoder wrote no VUI at all, so libavcodec read the stream's colour as "unspecified" and rendered a 709 export through the 601 matrix -- the HEVC decoder takes the bitstream's answer and overwrites the container's with it, which is why the mp4's `colr` box and the Matroska's Colour element could not cover for it (`export_color::every_format_signals_its_space_in_the_bitstream`, both HEVC containers, whenever the plugin is on the path). The three H.273 code points and the range flag now go in at the open, from the same `ColorDescription::output` rule the software intra seat's VUI and both muxers' tags come from, through the vendored `SpsBuilder`'s own `video_signal_type`/`colour_description`. A symbol of its own, `vh_enc_hevc_open_colour`, rather than four more arguments under the old name: a plugin that predates it is then simply missing the seat and the export falls back to the software encoder, which has always written the VUI, instead of being called with a signature it does not have. --- crates/engine-hw/src/lib.rs | 44 +++++++++++++++++-- crates/engine/src/caps.rs | 3 +- crates/engine/src/export.rs | 15 +++++-- crates/engine/src/hw.rs | 34 ++++++++++++-- vendor/cros-codecs/src/encoder/h265.rs | 15 +++++++ .../src/encoder/stateless/h265/predictor.rs | 18 ++++++-- 6 files changed, 116 insertions(+), 13 deletions(-) diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 120c007..224211a 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -30,6 +30,7 @@ use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVi use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; use cros_codecs::encoder::av1::EncoderConfig as Av1Config; use cros_codecs::encoder::h264::EncoderConfig as H264Config; +use cros_codecs::encoder::h265::ColourDescription as H265Colour; use cros_codecs::encoder::h265::EncoderConfig as H265Config; use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder; use cros_codecs::encoder::stateless::h264::StatelessEncoder; @@ -1154,7 +1155,7 @@ impl EncSession { bitrate: u64, codec: EncCodec, ) -> Option { - Self::open_seat(width, height, fps_num, fps_den, bitrate, codec, false) + Self::open_seat(width, height, fps_num, fps_den, bitrate, codec, false, None) } #[allow(clippy::too_many_arguments)] @@ -1166,6 +1167,7 @@ impl EncSession { bitrate: u64, codec: EncCodec, intra_only: bool, + colour: Option, ) -> Option { // NV12 chroma is half resolution, so odd dimensions have no packing; // and radeonsi refuses encode contexts below 64x64 (measured). @@ -1295,6 +1297,14 @@ impl EncSession { framerate, ..Default::default() }, + // What the SPS tells a decoder the samples mean. Without it + // libavcodec reads this stream's colour as "unspecified" and + // renders it BT.601 whatever the container says -- the HEVC + // decoder takes the bitstream's answer and overwrites the + // container's with it, so an untagged 709 export is a + // visible shift (`engine::export::video_signal_type` writes + // the same three code points on the software seat). + colour, }; Box::new( HevcEncoder::new_vaapi( @@ -1625,6 +1635,7 @@ pub extern "C" fn vh_enc_open_intra( bitrate, EncCodec::H264, true, + None, ) { Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, None => std::ptr::null_mut(), @@ -1672,16 +1683,43 @@ pub extern "C" fn vh_enc_av1_open( /// The session it returns is fed, drained and closed through `vh_enc_frame`, /// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back /// out of them is Annex-B HEVC access units. +/// +/// The last four arguments are what the SPS says the samples mean -- the three +/// H.273 code points and the range flag -- and they are part of the *symbol* +/// rather than a later setter because the parameter sets are built when the +/// sequence starts. A seat that signalled nothing is read back as "unspecified" +/// and rendered BT.601, the container's own tag notwithstanding, which is why +/// this replaced the colourless `vh_enc_hevc_open`: an engine older than this +/// symbol finds none and takes the software intra seat, which has always +/// written the VUI. #[unsafe(no_mangle)] -pub extern "C" fn vh_enc_hevc_open( +pub extern "C" fn vh_enc_hevc_open_colour( width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64, + colour_primaries: u32, + transfer_characteristics: u32, + matrix_coeffs: u32, + full_range: i32, ) -> *mut c_void { catch_unwind(AssertUnwindSafe(|| { - match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Hevc) { + match EncSession::open_seat( + width, + height, + fps_num, + fps_den, + bitrate, + EncCodec::Hevc, + false, + Some(H265Colour { + colour_primaries, + transfer_characteristics, + matrix_coeffs, + full_range: full_range != 0, + }), + ) { Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, None => std::ptr::null_mut(), } diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index 858e16a..27c5862 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -106,7 +106,8 @@ mod tests { assert!(hw_line(Some(VhCaps::default())).starts_with("none —")); // This project's own GPU as `vainfo` lists it: H.264, HEVC and AV1 both // ways, VP9 decode only, and the 10-bit profiles on three of the four. - // HEVC is an encode seat here as of the plugin's `vh_enc_hevc_open` -- + // HEVC is an encode seat here as of the plugin's + // `vh_enc_hevc_open_colour` -- // the 10-bit note beside it stays a *decode* claim, that seat coding // 8-bit Main whatever the source was. let radeonsi = VhCaps { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 00f2974..6973b7e 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -549,9 +549,18 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { // (`hevc_export::a_1080p_hardware_export_leaves_a_decoder_with_nothing_to_say`). // `None` here is the plugin's own "no" -- no entrypoint, or a picture // under the driver's 384x384 floor -- and the software seat takes it. - format if format.is_hevc() => { - HwEncoder::open_hevc(meta.width, meta.height, fps_num, fps_den, bitrate) - } + // The colour goes in at the open, from the same [`ColorDescription::output`] + // rule the software seat's VUI and both containers' tags come from, so + // the file cannot say one thing in its bitstream and another in its + // header. + format if format.is_hevc() => HwEncoder::open_hevc( + meta.width, + meta.height, + fps_num, + fps_den, + bitrate, + ColorDescription::output(meta.height), + ), // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both // AV1 formats sit on it: the container is not the encoder's business. format if format.is_av1() && !forced("VE_HW_AV1") => None, diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 99a34fe..2c35bf7 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -22,6 +22,8 @@ use std::sync::OnceLock; use libloading::Library; +use crate::colorspace::ColorDescription; + const LIB_NAME: &str = "libengine_hw.so"; /// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]. @@ -443,7 +445,11 @@ struct EncPlugin { open_av1: Option *mut c_void>, /// The HEVC seat, missing from an older plugin for the same reason and at /// the same cost: an HEVC export then runs on the software intra encoder. - open_hevc: Option *mut c_void>, + /// Four arguments more than the others: what the SPS says the samples mean + /// ([`HwEncoder::open_hevc`]), which is why the symbol is named apart from + /// the colourless `vh_enc_hevc_open` it replaced rather than sharing its + /// name with another signature. + open_hevc: Option *mut c_void>, /// The **intra-only** H.264 seat, missing from an older plugin for the same /// reason and at the same cost: a proxy then runs on the software encoder, /// which codes one frame a GOP and so writes the same kind of file. @@ -480,7 +486,7 @@ fn load_enc() -> Option { Some(EncPlugin { open: *lib.get(b"vh_enc_open\0").ok()?, open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), - open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), + open_hevc: lib.get(b"vh_enc_hevc_open_colour\0").ok().map(|s| *s), open_intra: lib.get(b"vh_enc_open_intra\0").ok().map(|s| *s), frame: *lib.get(b"vh_enc_frame\0").ok()?, dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s), @@ -575,16 +581,38 @@ impl HwEncoder { /// too old to export the symbol, on a GPU with no HEVC encode entrypoint, /// and below 384x384 -- the driver's own floor, stated in the plugin. The /// caller then takes the software intra encoder without a word about it. + /// + /// `colour` is what the SPS will say the samples mean, and it is taken at + /// the open because the parameter sets are written when the sequence starts. + /// libavcodec's HEVC decoder overwrites a container's colour with the + /// bitstream's, so a seat that signalled nothing hands a player + /// "unspecified" -- BT.601 -- however the file is tagged. pub fn open_hevc( width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64, + colour: ColorDescription, ) -> Option { let plugin = enc_plugin()?; let open = plugin.open_hevc?; - Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) + let (primaries, transfer, matrix) = colour.codes(); + let handle = open( + width, + height, + fps_num, + fps_den, + bitrate, + u32::from(primaries), + u32::from(transfer), + u32::from(matrix), + i32::from(colour.full_range), + ); + if handle.is_null() { + return None; + } + Some(Self { plugin, handle }) } /// The null check both opens share, which is the plugin's whole way of diff --git a/vendor/cros-codecs/src/encoder/h265.rs b/vendor/cros-codecs/src/encoder/h265.rs index 3a21198..2e6cc03 100644 --- a/vendor/cros-codecs/src/encoder/h265.rs +++ b/vendor/cros-codecs/src/encoder/h265.rs @@ -10,6 +10,17 @@ use crate::Resolution; pub struct H265; +/// What the SPS says the coded samples mean, as H.273 code points, and whether +/// the luma codes cover the full range. Written into the VUI, which is the +/// answer a decoder takes before it looks at any container tag. +#[derive(Clone, Copy)] +pub struct ColourDescription { + pub colour_primaries: u32, + pub transfer_characteristics: u32, + pub matrix_coeffs: u32, + pub full_range: bool, +} + #[derive(Clone)] pub struct EncoderConfig { pub resolution: Resolution, @@ -18,6 +29,9 @@ pub struct EncoderConfig { pub pred_structure: PredictionStructure, /// Initial tunings values pub initial_tunings: Tunings, + /// What the VUI declares about the samples. `None` writes no video signal + /// type at all, and a stream that says nothing is read as "unspecified". + pub colour: Option, } impl Default for EncoderConfig { @@ -29,6 +43,7 @@ impl Default for EncoderConfig { level: Level::L4, pred_structure: PredictionStructure::LowDelay { limit: 2048 }, initial_tunings: Default::default(), + colour: None, } } } diff --git a/vendor/cros-codecs/src/encoder/stateless/h265/predictor.rs b/vendor/cros-codecs/src/encoder/stateless/h265/predictor.rs index f1a9c68..62d04a7 100644 --- a/vendor/cros-codecs/src/encoder/stateless/h265/predictor.rs +++ b/vendor/cros-codecs/src/encoder/stateless/h265/predictor.rs @@ -131,7 +131,7 @@ impl LowDelayH265 { // H.265 Table 6-1, the encoder only supports 4:2:0 subsampling. Must be set before // `resolution()`, which derives the conformance window from it. - let sps = SpsBuilder::new(Rc::clone(&vps)) + let mut sps = SpsBuilder::new(Rc::clone(&vps)) .seq_parameter_set_id(0) .chroma_format_idc(1) .resolution(coded_width, coded_height) @@ -150,8 +150,20 @@ impl LowDelayH265 { .max_latency_increase_plus1(0) .short_term_ref_pic_set(short_term_ref_pic_set) .long_term_ref_pics_present_flag(false) - .timing_info(1, self.tunings.framerate, false) - .build(); + .timing_info(1, self.tunings.framerate, false); + + // What the samples mean, where the caller declared it. `video_format` is + // 5, "unspecified": the field is the analogue system a picture came off + // and an encoded timeline came off none. + if let Some(colour) = config.colour { + sps = sps.video_signal_type(5, colour.full_range).colour_description( + colour.colour_primaries, + colour.transfer_characteristics, + colour.matrix_coeffs, + ); + } + + let sps = sps.build(); let min_qp = self.tunings.min_quality.max(MIN_QP as u32); let max_qp = self.tunings.max_quality.min(MAX_QP as u32);