diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 5f4d2cf..8033455 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..3de12cb 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, @@ -2212,6 +2221,23 @@ fn run( "export audio: waited for after {:.1} s of picture", picture_started.elapsed().as_secs_f64() ); + // ...and the line on screen finished with it. The loop above + // publishes the measured codec the moment the pass lands + // under the picture, but a picture that outran the mix never + // reaches that branch -- and "working out the sound…" would + // then be the last thing the card ever said about a track it + // had long since written. + publish_seats( + shared, + seat, + project, + settings, + track.as_ref().map(|track| track.copied), + track + .as_ref() + .is_some_and(|track| track.opus_pre_skip.is_some()), + false, + ); track } None => late, 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/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs index 0e1e513..4239fb8 100644 --- a/crates/engine/tests/backends.rs +++ b/crates/engine/tests/backends.rs @@ -123,22 +123,7 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { ); let out = out_path("planned", ext); let handle = session.export_to_with(&out, &settings); - let started = Instant::now(); - let opened = loop { - if let Some(line) = handle.encoders() { - break line; - } - assert!( - !handle.is_finished(), - "the export settled before it opened an encoder: {:?}", - handle.result().map(|r| r.err()) - ); - assert!( - started.elapsed() < Duration::from_secs(60), - "no encoder was published" - ); - std::thread::sleep(Duration::from_millis(10)); - }; + let opened = published_encoders(&handle, ext); // Nothing here wants the file, only the seat it was going to be written // with: cancelling deletes the `.part` the worker had started. handle.cancel(); @@ -201,22 +186,7 @@ fn the_planned_seat_follows_the_size_and_the_pin() { } let out = out_path("seat", ext); let handle = session.export_to_with(&out, &settings); - let started = Instant::now(); - let opened = loop { - if let Some(line) = handle.encoders() { - break line; - } - assert!( - !handle.is_finished(), - "{ext} {width}x{height}: settled before an encoder opened: {:?}", - handle.result().map(|r| r.err()) - ); - assert!( - started.elapsed() < Duration::from_secs(60), - "no encoder was published" - ); - std::thread::sleep(Duration::from_millis(10)); - }; + let opened = published_encoders(&handle, &format!("{ext} {width}x{height}")); handle.cancel(); wind_down(&handle); assert!( @@ -313,28 +283,64 @@ fn a_mixed_timeline_says_it_re_encodes_and_then_does() { ..ExportSettings::default() }, ); + let opened = published_encoders(&handle, "a mixed timeline"); + assert!( + opened.ends_with(&planned), + "{opened} does not end in {planned}" + ); + // ...and it is the line the job *settles* on, which is why this one runs to + // the end instead of cancelling: an mp4 mixes its sound beside the picture, + // and a hardware picture is through first, so the measured codec reaches the + // line where the pass is collected under the muxer rather than in the frame + // loop. A card left saying "working out the sound…" over a written file is + // the same lie as one naming a codec that never ran. let started = Instant::now(); - let opened = loop { - if let Some(line) = handle.encoders() { - break line; + 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(10)); + } + handle.result().expect("an outcome").expect("the export"); + let settled = handle.encoders().expect("a finished job still names its seats"); + assert!( + settled.ends_with(&planned), + "the export settled on {settled}, which does not end in {planned}" + ); +} + +/// The half-line an export shows while its sound is still being mixed on the +/// thread beside the picture (`engine::export::publish_seats`). An mp4 job +/// overlaps the two passes, so this is what the *first* line out of one says +/// about a codec that has not run yet. +const MIXING: &str = "working out the sound…"; + +/// The encoders line a running job settles on: published as soon as the picture +/// seat is open, and completed once the sound has been measured. Waiting for the +/// second half is what makes this the line a card shows rather than a snapshot +/// of an export mid-decision -- and, because a job that ends without ever +/// completing it fails here, it is also the pin on that completion happening at +/// all, whichever of the two passes finishes first. +fn published_encoders(handle: &ExportHandle, what: &str) -> String { + let started = Instant::now(); + loop { + match handle.encoders() { + Some(line) if !line.ends_with(MIXING) => return line, + _ => {} } assert!( !handle.is_finished(), - "the export settled before it opened an encoder: {:?}", + "{what}: the export settled without naming its encoders ({:?}): {:?}", + handle.encoders(), handle.result().map(|r| r.err()) ); assert!( started.elapsed() < Duration::from_secs(60), - "no encoder was published" + "{what}: no encoder was published" ); std::thread::sleep(Duration::from_millis(10)); - }; - handle.cancel(); - wind_down(&handle); - assert!( - opened.ends_with(&planned), - "{opened} does not end in {planned}" - ); + } } /// Waits for a cancelled job to settle, so its `.part` is gone before the test 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);