diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs index 70a7cd5e..5c142b1d 100644 --- a/crates/ec-hw/src/enc/h264.rs +++ b/crates/ec-hw/src/enc/h264.rs @@ -134,6 +134,7 @@ pub(super) fn parameters( num_units_in_tick: seq.num_units_in_tick, time_scale: seq.time_scale, pic_init_qp: pic.pic_init_qp, + colour: config.colour, }; if keyframe { encoder.push_packed(&headers::h264_sps(&header_params), out)?; diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs index 2563ae81..0083a77a 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -12,6 +12,7 @@ use ec_core::BitWriter; +use super::Colour; use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; /// A header ready to submit: escaped bytes plus its exact length in bits. @@ -49,6 +50,7 @@ pub(super) struct H264Params { pub(super) num_units_in_tick: u32, pub(super) time_scale: u32, pub(super) pic_init_qp: u8, + pub(super) colour: Option, } /// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`. @@ -87,7 +89,15 @@ pub(super) fn h264_sps(p: &H264Params) -> Packed { w.write_bit(true); // vui_parameters_present_flag w.write_bit(false); // aspect_ratio_info_present_flag w.write_bit(false); // overscan_info_present_flag - w.write_bit(false); // video_signal_type_present_flag + w.write_bit(p.colour.is_some()); // video_signal_type_present_flag + if let Some(colour) = p.colour { + w.write_bits(5, 3); // video_format: unspecified + w.write_bit(colour.full_range); + w.write_bit(true); // colour_description_present_flag + w.write_bits(u32::from(colour.primaries), 8); + w.write_bits(u32::from(colour.transfer), 8); + w.write_bits(u32::from(colour.matrix), 8); + } w.write_bit(false); // chroma_loc_info_present_flag w.write_bit(true); // timing_info_present_flag w.write_bits(p.num_units_in_tick, 32); @@ -185,7 +195,7 @@ pub(super) mod hevc { SliceHeader, SliceType, Sps, Vps, }; - use super::{Packed, nal}; + use super::{Colour, Packed, nal}; use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; /// Geometry and timing for the parameter sets. @@ -198,6 +208,7 @@ pub(super) mod hevc { pub(in crate::enc) num_units_in_tick: u32, pub(in crate::enc) time_scale: u32, pub(in crate::enc) init_qp: u8, + pub(in crate::enc) colour: Option, } /// The VPS, SPS and PPS, in that order. @@ -254,6 +265,17 @@ pub(super) mod hevc { ptl, vui: Some(ec_h265_syntax::vui::VuiParameters { timing: Some((p.num_units_in_tick, p.time_scale)), + video_signal_type: p.colour.map(|colour| { + ec_h265_syntax::vui::VideoSignalType { + video_format: 5, // unspecified + video_full_range_flag: colour.full_range, + colour_description: Some(ec_h265_syntax::vui::ColourDescription { + colour_primaries: colour.primaries, + transfer_characteristics: colour.transfer, + matrix_coeffs: colour.matrix, + }), + } + }), ..ec_h265_syntax::vui::VuiParameters::default() }), }; diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index a139afd9..bfe5485e 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -146,6 +146,7 @@ pub(super) fn parameters( num_units_in_tick: seq.vui_num_units_in_tick, time_scale: seq.vui_time_scale, init_qp: pic.pic_init_qp, + colour: config.colour, }; let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params); if keyframe { diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 0de67604..98b7c1b7 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -97,6 +97,27 @@ pub struct EncoderConfig { pub quality: u32, /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused. pub allow_av1: bool, + /// The colour description to write into the VUI, or `None` to leave it + /// unsignalled (`video_signal_type_present_flag = 0`) as before. + pub colour: Option, +} + +/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. +/// +/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and +/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting +/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273 +/// tables 2/3/4). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Colour { + /// `colour_primaries`. + pub primaries: u8, + /// `transfer_characteristics`. + pub transfer: u8, + /// `matrix_coeffs`. + pub matrix: u8, + /// `video_full_range_flag`. + pub full_range: bool, } impl EncoderConfig { @@ -112,8 +133,20 @@ impl EncoderConfig { rate_control: RateControlMode::ConstantBitrate, quality: 0, allow_av1: false, + colour: None, } } + + /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. + pub fn colour(mut self, primaries: u8, transfer: u8, matrix: u8, full_range: bool) -> EncoderConfig { + self.colour = Some(Colour { + primaries, + transfer, + matrix, + full_range, + }); + self + } } /// One coded picture. @@ -269,15 +302,65 @@ impl Encoder { self.config.width, self.config.height, frame.width, frame.height ))); } - let keyframe = meta.force_keyframe - || self.reference.is_none() - || self.gop_position >= self.config.gop_size.max(1); - let input = self .pool .acquire() .ok_or_else(|| Error::config("encode: every surface is still in use"))?; self.upload(frame, &input)?; + self.encode_surface(Arc::clone(input.surface()), meta) + } + + /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, + /// no re-upload, just the decoder's picture handed straight to the + /// encoder as its source. This is the path a decode-then-encode pipeline + /// (e.g. a transcode) wants — the alternative is a full frame through + /// system memory and back for no reason. + /// + /// Refused, rather than silently working around, when: + /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id + /// only means anything on the display that created it. + /// - `frame` is 10-bit (P010): every profile this crate encodes + /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless + /// destination for the extra two bits — call [`Frame::to_i420`] and + /// [`Encoder::encode`] if the truncation is acceptable. + /// - `frame`'s coded size does not match this encoder's: the surface + /// formats have to agree for the driver to read one as the other with + /// no VPP conversion pass, and this crate does not carry a VPP-free + /// fallback for a mismatched size. + pub fn encode_frame( + &mut self, + frame: &crate::frame::Frame, + meta: FrameMetadata, + ) -> Result { + if frame.bit_depth != 8 { + return Err(Error::unsupported( + format!("encode_frame of a {}-bit source", frame.bit_depth), + "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \ + decode to I420 with Frame::to_i420 and call Encoder::encode instead", + )); + } + if !Arc::ptr_eq(frame.surface().display(), self.context.display()) { + return Err(Error::config( + "encode_frame: the frame was decoded on a different Display than this encoder", + )); + } + if frame.coded_size != self.coded_size { + return Err(Error::config(format!( + "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}", + self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1 + ))); + } + self.encode_surface(Arc::clone(frame.surface()), meta) + } + + /// Shared submission path for [`Encoder::encode`] and + /// [`Encoder::encode_frame`]: everything after the source surface is + /// settled. + fn encode_surface(&mut self, source: Arc, meta: FrameMetadata) -> Result { + let keyframe = meta.force_keyframe + || self.reference.is_none() + || self.gop_position >= self.config.gop_size.max(1); + let recon = self .pool .acquire() @@ -298,7 +381,7 @@ impl Encoder { buffers.extend(self.rate_control_buffers()?); buffers.push(coded_buf); - let mut picture = Picture::new(&self.context, Arc::clone(input.surface())) + let mut picture = Picture::new(&self.context, source) .begin()? .render_all(buffers)? .end()? diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 6f0f5ea9..5d19d4f5 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -657,6 +657,166 @@ fn our_encoder_and_our_decoder_agree() { } } +/// A decoded surface goes straight into an encoder with no `to_i420` +/// read-back, and what comes out is not measurably different from the +/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. +/// +/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block +/// rounding both land on the same 1920x1088 coded size for it, so the +/// decoder's surfaces satisfy `encode_frame`'s coded-size check against +/// either target codec without a second fixture. +#[test] +fn encode_frame_zero_copy_matches_the_cpu_path() { + let Some(display) = display() else { return }; + let (width, height) = (1920u32, 1080u32); + let Some(path) = fixtures(".264") + .into_iter() + .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264")) + else { + eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh"); + return; + }; + let data = std::fs::read(&path).expect("fixture is readable"); + let frames = 10usize; + + for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { + let mut cfg = EncoderConfig::new(target, width, height); + cfg.gop_size = 30; + cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; + let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); + let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); + let mut zc_stream = Vec::new(); + let mut cpu_stream = Vec::new(); + let mut count = 0i64; + + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { + let meta = FrameMetadata { + timestamp: count, + force_keyframe: false, + }; + // The zero-copy path never reads the surface back to the CPU: the + // only `to_i420` call in this loop is the CPU-path baseline's. + let zc = zero_copy + .encode_frame(&frame, meta) + .expect("encode_frame (zero copy)"); + zc_stream.extend_from_slice(&zc.data); + let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); + let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); + cpu_stream.extend_from_slice(&cpu.data); + count += 1; + }) + .expect("decode"); + assert_eq!(count as usize, frames, "{target:?}: decoded {count} of {frames}"); + + let ext = match target { + EncCodec::H264 => "264", + EncCodec::H265 => "265", + EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), + }; + let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); + std::fs::create_dir_all(&dir).expect("temp dir"); + for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { + std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); + } + + let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); + let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); + let mut zc_frames = Vec::new(); + let mut cpu_frames = Vec::new(); + decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { + zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) + }) + .expect("decode zero-copy stream"); + decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { + cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) + }) + .expect("decode CPU-path stream"); + assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy stream frame count"); + assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path stream frame count"); + + let worst = zc_frames + .iter() + .zip(&cpu_frames) + .map(|(a, b)| psnr(a, b)) + .fold(f64::INFINITY, f64::min); + println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); + assert!(worst >= 35.0, "{target:?}: worst {worst:.1} dB vs the CPU path"); + } +} + +/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an +/// export with a colour description survives ffprobe reading it back, and +/// leaving it unset keeps today's behaviour (no `video_signal_type`, +/// deterministically — two encodes of the same picture with no colour set +/// come back byte for byte identical). +#[test] +fn colour_description_reaches_the_vui() { + let Some(display) = display() else { return }; + let (width, height) = (640u32, 480u32); + let dir = std::env::temp_dir().join("ec-hw-colour-vui"); + std::fs::create_dir_all(&dir).expect("temp dir"); + + let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec) { + let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); + cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; + if let Some((primaries, transfer, matrix, full_range)) = colour { + cfg = cfg.colour(primaries, transfer, matrix, full_range); + } + let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); + let coded = enc + .encode( + &source_frame(width, height, 0), + FrameMetadata { + timestamp: 0, + force_keyframe: true, + }, + ) + .expect("encode"); + let path = dir.join(name); + std::fs::write(&path, &coded.data).expect("write bitstream"); + (path, coded.data) + }; + let probe = |path: &Path| -> String { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=color_primaries,color_transfer,color_space", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .expect("ffprobe runs"); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + + // Pinned default case: no colour set, twice, must match exactly. + let (default_path, default_bytes) = encode_one(None, "default-a.265"); + let (_, default_bytes2) = encode_one(None, "default-b.265"); + assert_eq!( + default_bytes, default_bytes2, + "no colour set: two encodes of the same picture must be byte-identical" + ); + let default_probe = probe(&default_path); + println!("no colour set: ffprobe sees `{default_probe}`"); + assert!( + !default_probe.contains("bt2020"), + "no colour set should not read back as BT.2020: `{default_probe}`" + ); + + // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). + let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); + // ffprobe's csv reorders these as color_space,color_transfer,color_primaries + // regardless of the -show_entries order given above. + let got = probe(&bt2020_path); + assert_eq!(got, "bt2020nc,smpte2084,bt2020", "ffprobe on the BT.2020 stream"); +} + /// AV1 encoding is opt-in, and this test does not turn it on. /// /// It was probed once, live, at the driver's own minimum encode size