From 2b83b5058d7d9d126a44f6306dedfaa810ce7f2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:38:53 +0300 Subject: [PATCH] U16: remove VA encoder submit_prime, encode_frame, encode_surface and the VPP pipeline they alone used, Encoder::profile, Frame::display; drop their gpu.rs tests --- crates/ec-hw/src/enc/mod.rs | 237 +------------------------------- crates/ec-hw/src/frame.rs | 5 - crates/ec-hw/tests/gpu.rs | 264 ------------------------------------ 3 files changed, 2 insertions(+), 504 deletions(-) diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 8f39a94b..c1306f20 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -48,10 +48,10 @@ use ec_va::va::{ VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage, }; -use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; +use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec}; use crate::error::{Error, Result}; -use crate::frame::{Frame, I420, I420_16}; +use crate::frame::{I420, I420_16}; use crate::pool::{PooledSurface, SurfacePool}; use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms}; @@ -128,17 +128,6 @@ pub struct Encoder { /// Set when the rate control parameters have to be resent. tunings_dirty: bool, rc: RateFeedback, - profile: Profile, - /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] - /// on a source that is not the encoder's own format or size; built lazily, - /// since most encoders never see one. - vpp: Option, - /// The small pool [`Encoder::vpp`] converts into, round-robined rather - /// than pool-acquired: each conversion is fully synced before this - /// encoder's own picture submission returns, so two surfaces are enough - /// to never hand out one still in flight. - vpp_surfaces: Vec>, - vpp_next: usize, /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back. pending: VecDeque>, } @@ -263,10 +252,6 @@ impl Encoder { idr_count: 0, tunings_dirty: true, rc: RateFeedback::default(), - profile, - vpp: None, - vpp_surfaces: Vec::new(), - vpp_next: 0, pending: VecDeque::new(), }) } @@ -368,36 +353,6 @@ impl Encoder { } } - /// Pipelined encode of an imported surface: a GPU copy into a pool surface - /// whose padding is then zeroed, matching the CPU upload path. A surface of - /// the coded size is copied whole; any other size is scaled to the - /// configured width x height, so one capture can feed several layers. - pub fn submit_prime( - &mut self, - surface: Rc>, - meta: FrameMetadata, - ) -> Result> { - let input = self - .pool - .acquire() - .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; - let dest = if surface.size() == self.coded_size { - (0, 0, 0, 0) - } else { - (0, 0, self.config.width, self.config.height) - }; - self.vpp()? - .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?; - zero_padding( - self.context.display(), - input.surface(), - self.config.bit_depth, - (self.config.width, self.config.height), - self.coded_size, - )?; - self.push_pipelined(input, meta) - } - fn retire_oldest(&mut self) -> Result> { match self.pending.pop_front() { Some(f) => self.finish(f).map(Some), @@ -430,72 +385,6 @@ impl Encoder { self.encode_settled(Rc::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. - /// - /// A source whose size differs from the encoder's coded size, or whose - /// depth differs from the encoder's, goes through the GPU video-processing - /// pipeline into an NV12 surface of the encoder's size first. - /// - /// 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`'s bit depth is neither 8 nor 10. - pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result { - if !self.pending.is_empty() { - return Err(Error::config( - "encode_frame: pipelined frames pending; call flush first", - )); - } - if frame.bit_depth != 8 && frame.bit_depth != 10 { - return Err(Error::unsupported( - format!("encode_frame of a {}-bit source", frame.bit_depth), - "the VPP conversion this crate builds reads 8-bit NV12 and 10-bit P010 only", - )); - } - if !Rc::ptr_eq(frame.display(), self.context.display()) { - return Err(Error::config( - "encode_frame: the frame was decoded on a different Display than this encoder", - )); - } - let source = - if frame.bit_depth != self.config.bit_depth || frame.coded_size != self.coded_size { - self.vpp_into_pool(frame.surface(), frame.display_size)? - } else { - Rc::clone(frame.surface()) - }; - self.encode_settled(source, meta) - } - - /// Encode a surface imported with [`ec_va::Surface::import_prime`] or - /// decoded elsewhere on this encoder's display: read by the GPU in place. - /// - /// The surface must be NV12, since H.264 is 8-bit only. A surface of another - /// size goes through the same GPU conversion as [`Encoder::encode_frame`]; - /// `display_size` is the picture's visible size (its cropped size, when the - /// surface is padded to the codec's block size). - pub fn encode_surface( - &mut self, - surface: &Rc>, - display_size: (u32, u32), - meta: FrameMetadata, - ) -> Result { - if !self.pending.is_empty() { - return Err(Error::config( - "encode_surface: pipelined frames pending; call flush first", - )); - } - if surface.size() != self.coded_size { - let converted = self.vpp_into_pool(surface, display_size)?; - self.encode_settled(converted, meta) - } else { - self.encode_settled(Rc::clone(surface), meta) - } - } - fn check_size(&self, width: u32, height: u32) -> Result<()> { if width != self.config.width || height != self.config.height { return Err(Error::config(format!( @@ -506,50 +395,6 @@ impl Encoder { Ok(()) } - /// Place a source surface's visible rect into this encoder's coded size, - /// in NV12, on the GPU: a whole-surface convert when the source is - /// already the encoder's coded size, a region copy/convert otherwise. - /// Builds the VPP pipeline and its two-surface pool on first use, painting - /// the pool black so any padding beyond `display_size` a region copy never - /// touches is deterministic. - fn vpp(&mut self) -> Result<&Vpp> { - if self.vpp.is_none() { - let spec = surface_spec(self.config.bit_depth, self.coded_size); - let display = Rc::clone(self.context.display()); - let surfaces = ec_va::create_pool(&display, &spec, 2)?; - for s in &surfaces { - fill_black(&display, s, self.coded_size, self.config.bit_depth)?; - } - let vpp = Vpp::new( - &display, - VA_RT_FORMAT_YUV420 | VA_RT_FORMAT_YUV420_10, - self.coded_size.0, - self.coded_size.1, - )?; - self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect(); - self.vpp = Some(vpp); - } - Ok(self.vpp.as_ref().expect("just built above if it was None")) - } - - fn vpp_into_pool( - &mut self, - source: &ec_va::va::Surface, - display_size: (u32, u32), - ) -> Result> { - self.vpp()?; - let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]); - self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); - let whole = display_size == self.coded_size; - let vpp = self.vpp()?; - if whole { - Ok(vpp.convert(source, dest)?) - } else { - let rect = (0, 0, display_size.0, display_size.1); - Ok(vpp.convert_region(source, rect, dest, rect)?) - } - } - /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`] /// and [`Encoder::encode_surface`]: submit, then read back at once. fn encode_settled( @@ -780,10 +625,6 @@ impl Encoder { self.idr_count } - /// The VA profile this encoder was configured with. - pub fn profile(&self) -> Profile { - self.profile - } } /// The surface format an encoder of `bit_depth` works in. @@ -864,86 +705,12 @@ fn upload(context: &Rc, frame: &I420, surface: &Surface, coded: (u32, u }) } -/// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the -/// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a -/// region copy's untouched padding reads the same deterministic value on -/// every driver instead of whatever the fresh allocation contained. -fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { - write_surface(display, surface, fourcc(bit_depth), size, |layout, data| { - // P010 carries the sample in the top ten bits, so black is the 8-bit - // value shifted up by six, little endian. - let samples = |eight: u8| -> Vec { - if bit_depth == 8 { - vec![eight] - } else { - (u16::from(eight) << 6).to_le_bytes().to_vec() - } - }; - for (plane, value, rows) in [ - (0usize, 16u8, size.1 as usize), - (1, 128, size.1 as usize / 2), - ] { - let pitch = layout.pitches[plane] as usize; - let base = layout.offsets[plane] as usize; - let unit = samples(value); - let width = size.0 as usize * unit.len(); - for row in 0..rows { - let start = base + row * pitch; - if let Some(line) = data.get_mut(start..start + width) { - for px in line.chunks_exact_mut(unit.len()) { - px.copy_from_slice(&unit); - } - } - } - } - }) -} - fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { write_surface(display, surface, fourcc(bit_depth), size, |_, data| { data.fill(0) }) } -fn zero_padding( - display: &Display, - surface: &ec_va::va::Surface, - bit_depth: u8, - (w, h): (u32, u32), - coded: (u32, u32), -) -> Result<()> { - if (w, h) == coded { - return Ok(()); - } - let (fourcc, px) = if bit_depth > 8 { - (VA_FOURCC_P010, 2) - } else { - (VA_FOURCC_NV12, 1) - }; - let (w, h, cw, ch) = ( - w as usize * px, - h as usize, - coded.0 as usize * px, - coded.1 as usize, - ); - write_surface(display, surface, fourcc, coded, |layout, data| { - for (plane, rows, last, start) in [ - (0, h, ch, w), - (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)), - ] { - let pitch = layout.pitches[plane] as usize; - let base = layout.offsets[plane] as usize; - for row in 0..last { - let from = if row < rows { start } else { 0 }; - if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw) - { - dst.fill(0); - } - } - } - }) -} - /// Upload one 10-bit frame into a surface as P010: samples move from the low /// ten bits of the caller's `u16` into P010's top ten. fn upload_16( diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 94f173b2..d2ba392b 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -72,11 +72,6 @@ impl Frame { &self.surface } - /// The display the surface was created on. - pub(crate) fn display(&self) -> &Rc { - &self.display - } - /// This frame's colour metadata, when the codec's decoder resolves one. pub fn colour(&self) -> Option { self.colour diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 63ae3da1..da5d467c 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -761,94 +761,6 @@ fn our_encoder_and_our_decoder_agree() { /// 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 path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - 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`, @@ -2617,93 +2529,8 @@ fn cbr_lands_within_five_percent_of_the_request() { assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); } -fn imported_nv12( - display: &Rc, - frame: &I420, -) -> Rc> { - use ec_va::SurfaceExt; - - let (w, h) = (frame.width, frame.height); - let mut pool = - ec_va::create_pool(display, &ec_va::SurfaceSpec::nv12(w, h), 1).expect("surface"); - let surface = pool.pop().expect("one surface"); - { - let format = - ec_va::surface::image_format(display, ec_va::va::VA_FOURCC_NV12).expect("format"); - let mut image = - ec_va::surface::create_image(&surface, format, (w, h), (w, h)).expect("image"); - let layout = *image.image(); - let data = AsMut::<[u8]>::as_mut(&mut image); - let (wu, hu) = (w as usize, h as usize); - let (cw, ch) = (wu.div_ceil(2), hu.div_ceil(2)); - for row in 0..hu { - let d = layout.offsets[0] as usize + row * layout.pitches[0] as usize; - data[d..d + wu].copy_from_slice(&frame.y[row * wu..row * wu + wu]); - } - for row in 0..ch { - let d = layout.offsets[1] as usize + row * layout.pitches[1] as usize; - for col in 0..cw { - data[d + col * 2] = frame.u[row * cw + col]; - data[d + col * 2 + 1] = frame.v[row * cw + col]; - } - } - } - let prime = surface.export().expect("export"); - let objects: Vec = prime - .objects - .iter() - .map(|o| ec_va::RawPrimeObject { - fd: std::os::fd::AsRawFd::as_raw_fd(&o.fd), - size: o.size, - modifier: o.modifier, - }) - .collect(); - let imported = ec_va::import_prime_raw( - display, - prime.fourcc, - (prime.width, prime.height), - &objects, - &prime.layers, - ) - .expect("import"); - drop(prime); - Rc::new(imported) -} - /// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the /// same pixels: the import is only a different way of handing over the source. -#[test] -fn encode_surface_of_an_imported_dma_buf_matches_the_cpu_path() { - let Some(display) = display() else { return }; - let (w, h) = (640u32, 480u32); - for codec in [EncCodec::H264, EncCodec::H265] { - let mut config = EncoderConfig::new(codec, w, h); - config.gop_size = 3; - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut cpu = Encoder::new(&display, config).expect("cpu encoder"); - let mut dma = Encoder::new(&display, config).expect("dma encoder"); - for t in 0..4u32 { - let frame = source_frame(w, h, t); - let meta = FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }; - let want = cpu.encode(&frame, meta).expect("cpu encode"); - let surface = imported_nv12(&display, &frame); - let got = dma - .encode_surface(&surface, (w, h), meta) - .expect("encode_surface"); - assert_eq!(got.is_keyframe, want.is_keyframe, "{codec:?} frame {t}"); - assert_eq!( - got.data.len(), - want.data.len(), - "{codec:?} frame {t}: imported source coded to a different size" - ); - assert!(got.data == want.data, "{codec:?} frame {t}: bytes differ"); - } - } -} - // --------------------------------------------------------------------------- // Broken streams: an inter picture whose references were never decoded // --------------------------------------------------------------------------- @@ -2840,54 +2667,6 @@ fn a_broken_gop_is_refused_on_every_codec() { } } -#[test] -fn ten_bit_prime_submit_matches_the_cpu_path() { - let file = ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); - let Some(display) = display() else { return }; - let data = elementary(&file, Codec::H265, 1).expect("elementary stream"); - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut size = (0, 0); - decode_stream(&mut decoder, Codec::H265, &data, 1, |f| { - size = f.display_size - }) - .expect("decode"); - let mut cfg = EncoderConfig::new(EncCodec::H265, size.0, size.1).ten_bit(); - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - let mut zc = Encoder::new(&display, cfg).expect("encoder"); - let mut cpu = Encoder::new(&display, cfg).expect("encoder"); - let (mut a, mut b) = (Vec::new(), Vec::new()); - let mut t = 0; - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - decode_stream(&mut decoder, Codec::H265, &data, 8, |frame| { - let meta = FrameMetadata { - timestamp: t, - force_keyframe: false, - }; - t += 1; - let prime = frame.export_prime().expect("export"); - let imported = Rc::new(ec_va::import_prime(&display, &prime).expect("import")); - if let Some(c) = zc.submit_prime(imported, meta).expect("submit_prime") { - a.extend(c.data); - } - if let Some(c) = cpu - .submit_16(&frame.to_i420_16().expect("readback"), meta) - .expect("submit_16") - { - b.extend(c.data); - } - }) - .expect("decode"); - a.extend(zc.flush().expect("flush").into_iter().flat_map(|c| c.data)); - b.extend(cpu.flush().expect("flush").into_iter().flat_map(|c| c.data)); - assert!(!a.is_empty()); - assert!( - a == b, - "zero-copy and CPU 10-bit streams differ ({} vs {} bytes)", - a.len(), - b.len() - ); -} - #[test] fn h264_encode_decodes_with_no_reorder_delay() { let Some(display) = display() else { return }; @@ -2909,46 +2688,3 @@ fn h264_encode_decodes_with_no_reorder_delay() { assert!(decoder.next_frame().is_some(), "frame {t} held back"); } } - -#[test] -fn imported_dma_buf_scales_and_crops_through_vpp() { - let Some(display) = display() else { return }; - let mean = |y: &[u8]| y.iter().map(|&v| f64::from(v)).sum::() / y.len() as f64; - let meta = FrameMetadata { - timestamp: 0, - force_keyframe: false, - }; - for (source_w, source_h, scale) in [(1280, 720, true), (640, 360, false)] { - let source = source_frame(source_w, source_h, 0); - let mut config = EncoderConfig::new(EncCodec::H264, 640, 360); - config.rate_control = RateControlMode::ConstantQp { qp: 22 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let surface = imported_nv12(&display, &source); - let data = if scale { - let mut data = Vec::new(); - if let Some(c) = encoder.submit_prime(surface, meta).expect("submit_prime") { - data.extend(c.data); - } - data.extend( - encoder - .flush() - .expect("flush") - .into_iter() - .flat_map(|c| c.data), - ); - data - } else { - encoder - .encode_surface(&surface, (640, 360), meta) - .expect("encode_surface") - .data - }; - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); - decoder.decode(&data, 0).expect("decode"); - decoder.flush().expect("flush"); - let frame = decoder.next_frame().expect("a picture"); - assert_eq!(frame.display_size, (640, 360)); - let got = frame.to_i420().expect("readback"); - assert!((mean(&got.y) - mean(&source.y)).abs() < 3.0); - } -}