forge
Explore
Log in

Don't you dare go Hollow

Zero-copy decode-to-encode surface path, VUI colour description

Browse files at this commit

fc705c7f95f473563b03591c7b88de50b385a2caAhmet Kaan GümüşParent: 6f27127
  • feat
    • zero-copy decode-to-encode surface path, VUI colour description
Show full message
feat(ec-hw): zero-copy decode-to-encode surface path, VUI colour description

Encoder::encode_frame submits a Frame's decoded VA surface directly as the
encoder's source picture, with no to_i420 CPU read-back and no re-upload —
what the consumer's previous backend did for a decode-then-encode pipeline.
Refuses a cross-Display frame, a 10-bit (P010) source (no Main10 profile is
built here), or a coded-size mismatch with a typed Error.

EncoderConfig::colour(primaries, transfer, matrix, full_range) reaches the
VUI of both the H.264 and HEVC packed SPS writers
(video_signal_type_present_flag / colour_description_present_flag), so an
HDR or BT.709 export stops reading back as "unspecified".

Live-GPU tests in gpu.rs cover both: encode_frame vs the CPU-path baseline
on the same decoded frames (PSNR compared, further: they came back byte
identical on this driver), and ffprobe reading BT.2020/PQ/BT.2020nc back off
a written stream while the no-colour-set case stays deterministic.
crates/ec-hw/src/enc/h264.rsmodified+1 -0
@@ -134,6 +134,7 @@ pub(super) fn parameters(
134134 num_units_in_tick: seq.num_units_in_tick,
135135 time_scale: seq.time_scale,
136136 pic_init_qp: pic.pic_init_qp,
137+ colour: config.colour,
137138 };
138139 if keyframe {
139140 encoder.push_packed(&headers::h264_sps(&header_params), out)?;
crates/ec-hw/src/enc/headers.rsmodified+24 -2
@@ -12,6 +12,7 @@
1212
1313 use ec_core::BitWriter;
1414
15+use super::Colour;
1516 use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
1617
1718 /// A header ready to submit: escaped bytes plus its exact length in bits.
@@ -49,6 +50,7 @@ pub(super) struct H264Params {
4950 pub(super) num_units_in_tick: u32,
5051 pub(super) time_scale: u32,
5152 pub(super) pic_init_qp: u8,
53+ pub(super) colour: Option<Colour>,
5254 }
5355
5456 /// `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 {
8789 w.write_bit(true); // vui_parameters_present_flag
8890 w.write_bit(false); // aspect_ratio_info_present_flag
8991 w.write_bit(false); // overscan_info_present_flag
90- w.write_bit(false); // video_signal_type_present_flag
92+ w.write_bit(p.colour.is_some()); // video_signal_type_present_flag
93+ if let Some(colour) = p.colour {
94+ w.write_bits(5, 3); // video_format: unspecified
95+ w.write_bit(colour.full_range);
96+ w.write_bit(true); // colour_description_present_flag
97+ w.write_bits(u32::from(colour.primaries), 8);
98+ w.write_bits(u32::from(colour.transfer), 8);
99+ w.write_bits(u32::from(colour.matrix), 8);
100+ }
91101 w.write_bit(false); // chroma_loc_info_present_flag
92102 w.write_bit(true); // timing_info_present_flag
93103 w.write_bits(p.num_units_in_tick, 32);
@@ -185,7 +195,7 @@ pub(super) mod hevc {
185195 SliceHeader, SliceType, Sps, Vps,
186196 };
187197
188- use super::{Packed, nal};
198+ use super::{Colour, Packed, nal};
189199 use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
190200
191201 /// Geometry and timing for the parameter sets.
@@ -198,6 +208,7 @@ pub(super) mod hevc {
198208 pub(in crate::enc) num_units_in_tick: u32,
199209 pub(in crate::enc) time_scale: u32,
200210 pub(in crate::enc) init_qp: u8,
211+ pub(in crate::enc) colour: Option<Colour>,
201212 }
202213
203214 /// The VPS, SPS and PPS, in that order.
@@ -254,6 +265,17 @@ pub(super) mod hevc {
254265 ptl,
255266 vui: Some(ec_h265_syntax::vui::VuiParameters {
256267 timing: Some((p.num_units_in_tick, p.time_scale)),
268+ video_signal_type: p.colour.map(|colour| {
269+ ec_h265_syntax::vui::VideoSignalType {
270+ video_format: 5, // unspecified
271+ video_full_range_flag: colour.full_range,
272+ colour_description: Some(ec_h265_syntax::vui::ColourDescription {
273+ colour_primaries: colour.primaries,
274+ transfer_characteristics: colour.transfer,
275+ matrix_coeffs: colour.matrix,
276+ }),
277+ }
278+ }),
257279 ..ec_h265_syntax::vui::VuiParameters::default()
258280 }),
259281 };
crates/ec-hw/src/enc/hevc.rsmodified+1 -0
@@ -146,6 +146,7 @@ pub(super) fn parameters(
146146 num_units_in_tick: seq.vui_num_units_in_tick,
147147 time_scale: seq.vui_time_scale,
148148 init_qp: pic.pic_init_qp,
149+ colour: config.colour,
149150 };
150151 let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params);
151152 if keyframe {
crates/ec-hw/src/enc/mod.rsmodified+88 -5
@@ -97,6 +97,27 @@ pub struct EncoderConfig {
9797 pub quality: u32,
9898 /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused.
9999 pub allow_av1: bool,
100+ /// The colour description to write into the VUI, or `None` to leave it
101+ /// unsignalled (`video_signal_type_present_flag = 0`) as before.
102+ pub colour: Option<Colour>,
103+}
104+
105+/// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI.
106+///
107+/// Carried verbatim into `colour_primaries`, `transfer_characteristics` and
108+/// `matrix_coeffs` — this crate does not interpret them, so a caller wanting
109+/// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273
110+/// tables 2/3/4).
111+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112+pub struct Colour {
113+ /// `colour_primaries`.
114+ pub primaries: u8,
115+ /// `transfer_characteristics`.
116+ pub transfer: u8,
117+ /// `matrix_coeffs`.
118+ pub matrix: u8,
119+ /// `video_full_range_flag`.
120+ pub full_range: bool,
100121 }
101122
102123 impl EncoderConfig {
@@ -112,8 +133,20 @@ impl EncoderConfig {
112133 rate_control: RateControlMode::ConstantBitrate,
113134 quality: 0,
114135 allow_av1: false,
136+ colour: None,
115137 }
116138 }
139+
140+ /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points.
141+ pub fn colour(mut self, primaries: u8, transfer: u8, matrix: u8, full_range: bool) -> EncoderConfig {
142+ self.colour = Some(Colour {
143+ primaries,
144+ transfer,
145+ matrix,
146+ full_range,
147+ });
148+ self
149+ }
117150 }
118151
119152 /// One coded picture.
@@ -269,15 +302,65 @@ impl Encoder {
269302 self.config.width, self.config.height, frame.width, frame.height
270303 )));
271304 }
272- let keyframe = meta.force_keyframe
273- || self.reference.is_none()
274- || self.gop_position >= self.config.gop_size.max(1);
275-
276305 let input = self
277306 .pool
278307 .acquire()
279308 .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
280309 self.upload(frame, &input)?;
310+ self.encode_surface(Arc::clone(input.surface()), meta)
311+ }
312+
313+ /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back,
314+ /// no re-upload, just the decoder's picture handed straight to the
315+ /// encoder as its source. This is the path a decode-then-encode pipeline
316+ /// (e.g. a transcode) wants — the alternative is a full frame through
317+ /// system memory and back for no reason.
318+ ///
319+ /// Refused, rather than silently working around, when:
320+ /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id
321+ /// only means anything on the display that created it.
322+ /// - `frame` is 10-bit (P010): every profile this crate encodes
323+ /// (`H264High`, `HEVCMain`) is 8-bit, so there is no lossless
324+ /// destination for the extra two bits — call [`Frame::to_i420`] and
325+ /// [`Encoder::encode`] if the truncation is acceptable.
326+ /// - `frame`'s coded size does not match this encoder's: the surface
327+ /// formats have to agree for the driver to read one as the other with
328+ /// no VPP conversion pass, and this crate does not carry a VPP-free
329+ /// fallback for a mismatched size.
330+ pub fn encode_frame(
331+ &mut self,
332+ frame: &crate::frame::Frame,
333+ meta: FrameMetadata,
334+ ) -> Result<CodedFrame> {
335+ if frame.bit_depth != 8 {
336+ return Err(Error::unsupported(
337+ format!("encode_frame of a {}-bit source", frame.bit_depth),
338+ "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit; \
339+ decode to I420 with Frame::to_i420 and call Encoder::encode instead",
340+ ));
341+ }
342+ if !Arc::ptr_eq(frame.surface().display(), self.context.display()) {
343+ return Err(Error::config(
344+ "encode_frame: the frame was decoded on a different Display than this encoder",
345+ ));
346+ }
347+ if frame.coded_size != self.coded_size {
348+ return Err(Error::config(format!(
349+ "encode_frame: encoder surfaces are {}x{}, the frame's are {}x{}",
350+ self.coded_size.0, self.coded_size.1, frame.coded_size.0, frame.coded_size.1
351+ )));
352+ }
353+ self.encode_surface(Arc::clone(frame.surface()), meta)
354+ }
355+
356+ /// Shared submission path for [`Encoder::encode`] and
357+ /// [`Encoder::encode_frame`]: everything after the source surface is
358+ /// settled.
359+ fn encode_surface(&mut self, source: Arc<Surface>, meta: FrameMetadata) -> Result<CodedFrame> {
360+ let keyframe = meta.force_keyframe
361+ || self.reference.is_none()
362+ || self.gop_position >= self.config.gop_size.max(1);
363+
281364 let recon = self
282365 .pool
283366 .acquire()
@@ -298,7 +381,7 @@ impl Encoder {
298381 buffers.extend(self.rate_control_buffers()?);
299382 buffers.push(coded_buf);
300383
301- let mut picture = Picture::new(&self.context, Arc::clone(input.surface()))
384+ let mut picture = Picture::new(&self.context, source)
302385 .begin()?
303386 .render_all(buffers)?
304387 .end()?
crates/ec-hw/tests/gpu.rsmodified+160 -0
@@ -657,6 +657,166 @@ fn our_encoder_and_our_decoder_agree() {
657657 }
658658 }
659659
660+/// A decoded surface goes straight into an encoder with no `to_i420`
661+/// read-back, and what comes out is not measurably different from the
662+/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames.
663+///
664+/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block
665+/// rounding both land on the same 1920x1088 coded size for it, so the
666+/// decoder's surfaces satisfy `encode_frame`'s coded-size check against
667+/// either target codec without a second fixture.
668+#[test]
669+fn encode_frame_zero_copy_matches_the_cpu_path() {
670+ let Some(display) = display() else { return };
671+ let (width, height) = (1920u32, 1080u32);
672+ let Some(path) = fixtures(".264")
673+ .into_iter()
674+ .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("h264-1080p-23.976-8bit.264"))
675+ else {
676+ eprintln!("skipped: no h264-1080p fixture — run scripts/gen-bitstream-fixtures.sh");
677+ return;
678+ };
679+ let data = std::fs::read(&path).expect("fixture is readable");
680+ let frames = 10usize;
681+
682+ for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
683+ let mut cfg = EncoderConfig::new(target, width, height);
684+ cfg.gop_size = 30;
685+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
686+ let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens");
687+ let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens");
688+ let mut zc_stream = Vec::new();
689+ let mut cpu_stream = Vec::new();
690+ let mut count = 0i64;
691+
692+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
693+ decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| {
694+ let meta = FrameMetadata {
695+ timestamp: count,
696+ force_keyframe: false,
697+ };
698+ // The zero-copy path never reads the surface back to the CPU: the
699+ // only `to_i420` call in this loop is the CPU-path baseline's.
700+ let zc = zero_copy
701+ .encode_frame(&frame, meta)
702+ .expect("encode_frame (zero copy)");
703+ zc_stream.extend_from_slice(&zc.data);
704+ let i420 = frame.to_i420().expect("readback for the CPU-path baseline");
705+ let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)");
706+ cpu_stream.extend_from_slice(&cpu.data);
707+ count += 1;
708+ })
709+ .expect("decode");
710+ assert_eq!(count as usize, frames, "{target:?}: decoded {count} of {frames}");
711+
712+ let ext = match target {
713+ EncCodec::H264 => "264",
714+ EncCodec::H265 => "265",
715+ EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"),
716+ };
717+ let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy");
718+ std::fs::create_dir_all(&dir).expect("temp dir");
719+ for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] {
720+ std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream");
721+ }
722+
723+ let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens");
724+ let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens");
725+ let mut zc_frames = Vec::new();
726+ let mut cpu_frames = Vec::new();
727+ decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| {
728+ zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))
729+ })
730+ .expect("decode zero-copy stream");
731+ decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| {
732+ cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback")))
733+ })
734+ .expect("decode CPU-path stream");
735+ assert_eq!(zc_frames.len(), frames, "{target:?}: zero-copy stream frame count");
736+ assert_eq!(cpu_frames.len(), frames, "{target:?}: CPU-path stream frame count");
737+
738+ let worst = zc_frames
739+ .iter()
740+ .zip(&cpu_frames)
741+ .map(|(a, b)| psnr(a, b))
742+ .fold(f64::INFINITY, f64::min);
743+ println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB");
744+ assert!(worst >= 35.0, "{target:?}: worst {worst:.1} dB vs the CPU path");
745+ }
746+}
747+
748+/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an
749+/// export with a colour description survives ffprobe reading it back, and
750+/// leaving it unset keeps today's behaviour (no `video_signal_type`,
751+/// deterministically — two encodes of the same picture with no colour set
752+/// come back byte for byte identical).
753+#[test]
754+fn colour_description_reaches_the_vui() {
755+ let Some(display) = display() else { return };
756+ let (width, height) = (640u32, 480u32);
757+ let dir = std::env::temp_dir().join("ec-hw-colour-vui");
758+ std::fs::create_dir_all(&dir).expect("temp dir");
759+
760+ let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) {
761+ let mut cfg = EncoderConfig::new(EncCodec::H265, width, height);
762+ cfg.rate_control = RateControlMode::ConstantQp { qp: 26 };
763+ if let Some((primaries, transfer, matrix, full_range)) = colour {
764+ cfg = cfg.colour(primaries, transfer, matrix, full_range);
765+ }
766+ let mut enc = Encoder::new(&display, cfg).expect("encoder opens");
767+ let coded = enc
768+ .encode(
769+ &source_frame(width, height, 0),
770+ FrameMetadata {
771+ timestamp: 0,
772+ force_keyframe: true,
773+ },
774+ )
775+ .expect("encode");
776+ let path = dir.join(name);
777+ std::fs::write(&path, &coded.data).expect("write bitstream");
778+ (path, coded.data)
779+ };
780+ let probe = |path: &Path| -> String {
781+ let out = Command::new("ffprobe")
782+ .args([
783+ "-v",
784+ "error",
785+ "-select_streams",
786+ "v:0",
787+ "-show_entries",
788+ "stream=color_primaries,color_transfer,color_space",
789+ "-of",
790+ "csv=p=0",
791+ ])
792+ .arg(path)
793+ .output()
794+ .expect("ffprobe runs");
795+ String::from_utf8_lossy(&out.stdout).trim().to_string()
796+ };
797+
798+ // Pinned default case: no colour set, twice, must match exactly.
799+ let (default_path, default_bytes) = encode_one(None, "default-a.265");
800+ let (_, default_bytes2) = encode_one(None, "default-b.265");
801+ assert_eq!(
802+ default_bytes, default_bytes2,
803+ "no colour set: two encodes of the same picture must be byte-identical"
804+ );
805+ let default_probe = probe(&default_path);
806+ println!("no colour set: ffprobe sees `{default_probe}`");
807+ assert!(
808+ !default_probe.contains("bt2020"),
809+ "no colour set should not read back as BT.2020: `{default_probe}`"
810+ );
811+
812+ // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9).
813+ let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265");
814+ // ffprobe's csv reorders these as color_space,color_transfer,color_primaries
815+ // regardless of the -show_entries order given above.
816+ let got = probe(&bt2020_path);
817+ assert_eq!(got, "bt2020nc,smpte2084,bt2020", "ffprobe on the BT.2020 stream");
818+}
819+
660820 /// AV1 encoding is opt-in, and this test does not turn it on.
661821 ///
662822 /// It was probed once, live, at the driver's own minimum encode size