diff --git a/Cargo.lock b/Cargo.lock index 634c54e6..d91fca38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -746,17 +746,6 @@ dependencies = [ "ec-core", ] -[[package]] -name = "edith-sink" -version = "0.1.0" -dependencies = [ - "ec-core", - "ec-dsp", - "ec-hw", - "ec-mp4", - "ec-va", -] - [[package]] name = "either" version = "1.17.0" diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs index 6894fcdf..aa92f9b0 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -229,11 +229,16 @@ pub(super) mod hevc { pub(in crate::enc) time_scale: u32, pub(in crate::enc) init_qp: u8, pub(in crate::enc) colour: Option, + pub(in crate::enc) bit_depth: u8, } /// The VPS, SPS and PPS, in that order. pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) { - let ptl = ProfileTierLevel::main(p.level_idc); + let ptl = if p.bit_depth == 10 { + ProfileTierLevel::main10(p.level_idc) + } else { + ProfileTierLevel::main(p.level_idc) + }; let vps = Vps { id: 0, ptl, @@ -255,8 +260,8 @@ pub(super) mod hevc { top: 0, bottom: (p.coded_height - p.height) / 2, }, - bit_depth_luma_minus8: 0, - bit_depth_chroma_minus8: 0, + bit_depth_luma_minus8: u32::from(p.bit_depth - 8), + bit_depth_chroma_minus8: u32::from(p.bit_depth - 8), log2_max_poc_lsb_minus4: 8, max_dec_pic_buffering_minus1: 1, max_num_reorder_pics: 0, diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index dc71f8cf..b14c1e46 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -57,8 +57,9 @@ pub(super) fn parameters( let vui_num_units_in_tick = config.framerate.1.max(1); let vui_time_scale = config.framerate.0.max(1); - // chroma_format_idc 1, bit depths 8, strong intra smoothing, AMP, SAO. - let seq_fields = HEVCEncSeqFields::new(1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0); + let depth_minus8 = u32::from(config.bit_depth - 8); + let seq_fields = + HEVCEncSeqFields::new(1, 0, depth_minus8, depth_minus8, 0, 1, 1, 1, 0, 0, 0, 0, 0); // vui_timing_info_present_flag. let vui = HevcEncVuiFields::new(0, 0, 0, 1, 0, 0, 0, 0, 0, 0); let scc = HevcEncSeqSccFields::new(0); @@ -67,7 +68,7 @@ pub(super) fn parameters( // parameters say, and `num_ctu_in_slice` below has to count the same // blocks the hardware does. let seq = EncSequenceParameterBufferHEVC::new( - 1, + if config.bit_depth == 10 { 2 } else { 1 }, general_level_idc, 0, intra_period, @@ -98,7 +99,9 @@ pub(super) fn parameters( 0, &scc, ); - out.push(BufferType::EncSequenceParameter(EncSequenceParameter::HEVC(seq))); + out.push(BufferType::EncSequenceParameter( + EncSequenceParameter::HEVC(seq), + )); let pic_init_qp = match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, @@ -166,7 +169,9 @@ pub(super) fn parameters( 0, &pic_scc, ); - out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC(pic))); + out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC( + pic, + ))); // CTBs are 64x64 by the sequence parameters above. let ctbs = coded_w.div_ceil(64) * coded_h.div_ceil(64); @@ -177,20 +182,8 @@ pub(super) fn parameters( } // last_slice_of_pic_flag, slice_sao_luma/chroma, and the reference override // on P pictures. The loop filter across slices stays off, matching the PPS. - let slice_fields = HevcEncSliceFields::new( - 1, - 0, - 0, - 0, - 1, - 1, - u32::from(!keyframe), - 0, - 0, - 0, - 0, - 0, - ); + let slice_fields = + HevcEncSliceFields::new(1, 0, 0, 0, 1, 1, u32::from(!keyframe), 0, 0, 0, 0, 0); let slice = EncSliceParameterBufferHEVC::new( 0, ctbs, @@ -231,6 +224,7 @@ pub(super) fn parameters( time_scale: vui_time_scale, init_qp: pic_init_qp, colour: config.colour, + bit_depth: config.bit_depth, }; let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params); if keyframe { @@ -243,7 +237,9 @@ pub(super) fn parameters( // only when a slice header accompanies them, so dropping it costs the // stream its VPS, SPS and PPS (measured 2026-08-14). encoder.push_packed(&hevc_headers::packed_slice(&sps, &pps, keyframe, poc), out)?; - out.push(BufferType::EncSliceParameter(EncSliceParameter::HEVC(slice))); + out.push(BufferType::EncSliceParameter(EncSliceParameter::HEVC( + slice, + ))); Ok(()) } diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 1a24c351..73fd0327 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -36,17 +36,18 @@ #![allow(dead_code)] // the header writers wait for the encoder port +use std::collections::VecDeque; use std::rc::Rc; use ec_va::caps::{Entrypoint, Profile}; +use ec_va::va::SurfaceMemoryDescriptor; use ec_va::va::{ BufferType, EncMiscParameter, EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType, RcFlags, - VAConfigAttribType, VAImage, VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, - VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, - VA_RT_FORMAT_YUV420_10, VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, + VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE, + 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::va::SurfaceMemoryDescriptor; use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; use crate::error::{Error, Result}; @@ -111,6 +112,9 @@ impl H264Profile { /// The rate window the request is spread over, in milliseconds (`window_size`). const RATE_WINDOW_MS: u32 = 1000; +/// Pictures the pipelined path keeps in flight before the oldest is read back. +const DEPTH: usize = 3; + /// The HRD buffer for a GOP of `gop_size` pictures, in milliseconds of the /// requested bitrate. /// @@ -136,6 +140,26 @@ fn hrd_buffer_ms(gop_size: u32) -> u32 { if gop_size < 10 { 20 } else { RATE_WINDOW_MS } } +/// Closed-loop correction of the driver's rate control, which lands off the ask +/// on detailed content (testsrc2: +12..19% on mesa 26.2.6, ffmpeg's VA-API +/// encoders too): once a second the bitrate sent is rescaled by the measured +/// bias, plus whatever was over- or under-spent so far. +#[derive(Debug, Clone, Copy)] +struct RateFeedback { + scale: f64, + spent: f64, + frames: u32, + window: f64, + window_frames: u32, + steered: bool, +} + +impl Default for RateFeedback { + fn default() -> Self { + RateFeedback { scale: 1.0, spent: 0.0, frames: 0, window: 0.0, window_frames: 0, steered: false } + } +} + /// How the driver should spend bits. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RateControlMode { @@ -264,7 +288,7 @@ impl EncoderConfig { } } - /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`]. + /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`]. pub fn ten_bit(mut self) -> EncoderConfig { self.bit_depth = 10; self @@ -306,6 +330,16 @@ pub struct CodedFrame { pub is_keyframe: bool, } +/// A picture submitted but not yet read back. +struct InFlight { + picture: ec_va::picture::Picture>>, + coded: ec_va::picture::EncCodedBuffer, + source: Rc>, + leases: Vec>, + timestamp: i64, + keyframe: bool, +} + /// A hardware encoder. /// A hardware encoder. pub struct Encoder { @@ -325,6 +359,7 @@ pub struct Encoder { tunings: Tunings, /// 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, @@ -336,6 +371,8 @@ pub struct Encoder { /// 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>, } impl Encoder { @@ -352,20 +389,19 @@ impl Encoder { } if config.bit_depth != 8 && config.bit_depth != 10 { return Err(Error::config(format!( - "encoder bit depth {} : this crate encodes 8-bit, or 10-bit AV1", + "encoder bit depth {} : this crate encodes 8-bit, or 10-bit H.265/AV1", config.bit_depth ))); } - if config.bit_depth == 10 && config.codec != EncCodec::Av1 { - // Not a driver refusal: H264High and HEVCMain are 8-bit profiles by - // definition, and this crate configures no other. + if config.bit_depth == 10 && config.codec == EncCodec::H264 { return Err(Error::config( - "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate \ + "10-bit encode is H.265 and AV1 only here: the H.264 profiles this crate \ configures are 8-bit", )); } let (profile, block) = match config.codec { EncCodec::H264 => (config.h264_profile.va_profile(), 16), + EncCodec::H265 if config.bit_depth == 10 => (Profile::HEVCMain10, 32), EncCodec::H265 => (Profile::HEVCMain, 32), EncCodec::Av1 => (Profile::AV1Profile0, 64), }; @@ -428,9 +464,12 @@ impl Encoder { ], )?; let spec = surface_spec(config.bit_depth, coded_size); - // Input, reconstruction, one reference, and slack for the driver to - // keep a submission in flight. - let surfaces = ec_va::create_pool(display, &spec, 8)?; + // Input, reconstruction, one reference, and slack for the pictures + // the pipelined path keeps in flight. + let surfaces = ec_va::create_pool(display, &spec, 12)?; + for s in &surfaces { + fill_zero(display, s, coded_size, config.bit_depth)?; + } let context = ec_va::picture::create_context( display, &config_id, @@ -455,10 +494,12 @@ impl Encoder { gop_position: 0, idr_count: 0, tunings_dirty: true, + rc: RateFeedback::default(), profile, vpp: None, vpp_surfaces: Vec::new(), vpp_next: 0, + pending: VecDeque::new(), }) } @@ -471,10 +512,16 @@ impl Encoder { pub fn tune(&mut self, tunings: Tunings) { self.tunings = tunings; self.tunings_dirty = true; + self.rc = RateFeedback::default(); } /// Encode one frame and return its coded bytes. pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + if !self.pending.is_empty() { + return Err(Error::config( + "encode: pipelined frames pending; call flush first", + )); + } if self.config.bit_depth != 8 { return Err(Error::config(format!( "encode: this encoder is configured for {} bits; call encode_16", @@ -490,11 +537,115 @@ impl Encoder { self.encode_settled(Rc::clone(input.surface()), meta) } + /// Submit one frame without waiting for it; the oldest pending frame comes back + /// once more than [`DEPTH`] are in flight. + pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result> { + if self.config.bit_depth != 8 { + return Err(Error::config(format!( + "submit: this encoder is configured for {} bits; call submit_16", + self.config.bit_depth + ))); + } + self.check_size(frame.width, frame.height)?; + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("submit: every surface is still in use"))?; + upload(&self.context, frame, input.surface(), self.coded_size)?; + self.push_pipelined(input, meta) + } + + /// The [`Encoder::submit`] of a 10-bit encoder. + pub fn submit_16( + &mut self, + frame: &I420_16, + meta: FrameMetadata, + ) -> Result> { + if self.config.bit_depth != 10 { + return Err(Error::config(format!( + "submit_16: this encoder is configured for {} bits; call submit", + self.config.bit_depth + ))); + } + self.check_size(frame.width, frame.height)?; + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?; + upload_16(&self.context, frame, input.surface(), self.coded_size)?; + self.push_pipelined(input, meta) + } + + /// Read back every pending frame, oldest first. + pub fn flush(&mut self) -> Result> { + let mut out = Vec::with_capacity(self.pending.len()); + while let Some(f) = self.pending.pop_front() { + out.push(self.finish(f)?); + } + Ok(out) + } + + fn push_pipelined( + &mut self, + input: Rc, + meta: FrameMetadata, + ) -> Result> { + let source = Rc::clone(input.surface()); + let in_flight = self.submit_settled(source, meta, vec![input])?; + self.pending.push_back(in_flight); + if self.pending.len() > DEPTH { + self.retire_oldest() + } else { + Ok(None) + } + } + + /// Pipelined encode of an imported surface of the encoder's coded size: a GPU copy + /// into a pool surface whose padding is then zeroed, matching the CPU upload path. + pub fn submit_prime( + &mut self, + surface: Rc>, + meta: FrameMetadata, + ) -> Result> { + if surface.size() != self.coded_size { + return Err(Error::config(format!( + "submit_prime: a {:?} surface for a {:?} encoder", + surface.size(), + self.coded_size + ))); + } + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; + self.vpp()?.convert(&surface, Rc::clone(input.surface()))?; + 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), + None => Ok(None), + } + } + /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder. /// /// Samples are 0..1023 in the low ten bits of each `u16`, shifted into - /// P010's top ten bits on upload. Only a 10-bit (AV1) encoder takes this path. + /// P010's top ten bits on upload. Only a 10-bit (H.265/AV1) encoder takes this path. pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + if !self.pending.is_empty() { + return Err(Error::config( + "encode_16: pipelined frames pending; call flush first", + )); + } if self.config.bit_depth != 10 { return Err(Error::config(format!( "encode_16: this encoder is configured for {} bits; call encode", @@ -525,6 +676,11 @@ impl Encoder { /// 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), @@ -558,6 +714,11 @@ impl Encoder { 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) @@ -582,11 +743,7 @@ impl Encoder { /// 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_into_pool( - &mut self, - source: &ec_va::va::Surface, - display_size: (u32, u32), - ) -> Result> { + 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()); @@ -603,10 +760,20 @@ impl Encoder { 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 vpp = self.vpp.as_ref().expect("just built above if it was None"); - if display_size == self.coded_size { + 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); @@ -614,14 +781,23 @@ impl Encoder { } } - /// Shared submission path for [`Encoder::encode`], [`Encoder::encode_frame`] - /// and [`Encoder::encode_surface`]: everything after the source surface is - /// settled. + /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`] + /// and [`Encoder::encode_surface`]: submit, then read back at once. fn encode_settled( &mut self, source: Rc>, meta: FrameMetadata, ) -> Result { + let in_flight = self.submit_settled(source, meta, Vec::new())?; + self.finish(in_flight) + } + + fn submit_settled( + &mut self, + source: Rc>, + meta: FrameMetadata, + mut leases: Vec>, + ) -> Result> { if crate::reset::gpu_reset_epoch() != self.born_epoch { return Err(Error::hw_reset( "the GPU was reset after this encoder was created; its context is lost", @@ -657,7 +833,33 @@ impl Encoder { } let picture = ec_va::picture::submit(&self.context, Rc::clone(&source), buffers)?; - crate::reset::sync_watched(&source)?; + if let Some(previous) = self.reference.replace(recon) { + leases.push(previous); + } + if keyframe { + self.idr_count = self.idr_count.wrapping_add(1); + } + self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; + Ok(InFlight { + picture, + coded, + source, + leases, + timestamp: meta.timestamp, + keyframe, + }) + } + + fn finish(&mut self, f: InFlight) -> Result { + crate::reset::sync_watched(&f.source)?; + let InFlight { + picture, + coded, + leases, + timestamp, + keyframe, + .. + } = f; drop(picture); let mut data = { @@ -674,6 +876,7 @@ impl Encoder { if data.is_empty() { return Err(Error::config("the encoder produced an empty coded buffer")); } + self.track_rate(data.len()); if self.config.codec == EncCodec::Av1 { // Every AV1 temporal unit begins with a temporal delimiter (5.6), // and this driver emits none: its coded buffer starts at the @@ -682,21 +885,52 @@ impl Encoder { // here rather than left to the caller. data.splice(0..0, [0x12u8, 0x00]); } - // The coded buffer is no longer read once it is copied out. drop(coded); - - self.reference = Some(recon); - if keyframe { - self.idr_count = self.idr_count.wrapping_add(1); - } - self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; + drop(leases); Ok(CodedFrame { data, - timestamp: meta.timestamp, + timestamp, is_keyframe: keyframe, }) } + fn steered_bitrate(&self) -> u32 { + (f64::from(self.tunings.bitrate) * self.rc.scale) as u32 + } + + fn track_rate(&mut self, bytes: usize) { + if !matches!( + self.config.rate_control, + RateControlMode::ConstantBitrate | RateControlMode::VariableBitrate + ) { + return; + } + let (num, den) = self.tunings.framerate; + let fps = f64::from(num.max(1)) / f64::from(den.max(1)); + let rate = f64::from(self.tunings.bitrate); + let per_frame = rate / fps; + let rc = &mut self.rc; + let bits = bytes as f64 * 8.0; + rc.spent += bits; + rc.frames += 1; + rc.window += bits; + rc.window_frames += 1; + if f64::from(rc.window_frames) < fps.round().max(1.0) { + return; + } + let asked = rc.scale * per_frame * f64::from(rc.window_frames); + let bias = rc.window / asked; + let debt = f64::from(rc.frames) * per_frame - rc.spent; + let scale = ((rate + debt) / rate / bias).clamp(0.5, 1.5); + rc.window = 0.0; + rc.window_frames = 0; + if (scale / rc.scale - 1.0).abs() > 0.02 { + rc.scale = scale; + rc.steered = true; + self.tunings_dirty = true; + } + } + /// The misc parameter buffers that carry rate control, resent when tuned. fn rate_control_buffers(&mut self) -> Result> { if !self.tunings_dirty { @@ -708,9 +942,9 @@ impl Encoder { // becomes a 1.5x ceiling at 66%. let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0), - RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate, 100, 0), + RateControlMode::ConstantBitrate => (0, 0, 0, self.steered_bitrate(), 100, 0), RateControlMode::VariableBitrate => { - (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0) + (0, 0, 0, self.steered_bitrate().saturating_mul(3) / 2, 66, 0) } RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), }; @@ -742,7 +976,7 @@ impl Encoder { out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate( EncMiscParameterFrameRate::new(packed, 0), ))); - if bits > 0 { + if bits > 0 && !std::mem::take(&mut self.rc.steered) { // The buffer starts full. Starting at three quarters full cost a // quarter of a window of budget: radeonsi then spent 12.5% under the // ask on a 2 s clip, and the gap is exactly that quarter over the @@ -832,13 +1066,20 @@ fn fourcc(bit_depth: u8) -> u32 { /// cros-libva writes a mutated image back to the surface when the image is /// dropped (`vaPutImage`), so `fill` runs against the image's own bytes and /// the write-back happens at the end of this function. -fn write_surface( +fn write_surface( display: &Display, - surface: &Surface, + surface: &ec_va::va::Surface, fourcc: u32, size: (u32, u32), fill: impl FnOnce(&VAImage, &mut [u8]), ) -> Result<()> { + if let Ok(mut image) = ec_va::va::Image::derive_from(surface, size) + && image.image().format.fourcc == fourcc + { + let layout = *image.image(); + fill(&layout, AsMut::<[u8]>::as_mut(&mut image)); + return Ok(()); + } let format = ec_va::surface::image_format(display, fourcc)?; let mut image = ec_va::surface::create_image(surface, format, size, size)?; let layout = *image.image(); @@ -847,12 +1088,7 @@ fn write_surface( } /// Upload one frame into a surface as NV12. -fn upload( - context: &Rc, - frame: &I420, - surface: &Surface, - coded: (u32, u32), -) -> Result<()> { +fn upload(context: &Rc, frame: &I420, surface: &Surface, coded: (u32, u32)) -> Result<()> { let display: &Display = context.display(); let (w, h) = (frame.width as usize, frame.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); @@ -899,7 +1135,10 @@ fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: (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)] { + 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); @@ -916,6 +1155,51 @@ fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: }) } +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/lib.rs b/crates/ec-hw/src/lib.rs index f1da9c67..6955c883 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -25,11 +25,11 @@ //! call [`Frame::to_i420_16`] instead — that is the lossless path that keeps //! all ten bits. //! -//! Encoding is 10-bit too, for AV1: `EncoderConfig::ten_bit()` allocates P010 +//! Encoding is 10-bit too, for H.265 (Main10) and AV1: `EncoderConfig::ten_bit()` allocates P010 //! surfaces and takes its pixels through [`Encoder::encode_16`] (or straight -//! from a 10-bit [`Frame`], with no conversion at all). H.264 and H.265 stay -//! 8-bit here, because High and Main — the profiles this crate configures — -//! are 8-bit profiles. +//! from a 10-bit [`Frame`], with no conversion at all). H.264 stays +//! 8-bit here, because the profiles this crate configures for it +//! are 8-bit. //! //! # Shape //! diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index ea4d5373..ec513c46 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -1218,7 +1218,7 @@ fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option Option { +fn ffprobe_pix_fmt(path: &Path, format: &str) -> Option { let out = Command::new("ffprobe") .args([ "-v", @@ -1230,7 +1230,7 @@ fn ffprobe_pix_fmt(path: &Path) -> Option { "-of", "default=nw=1:nk=1", "-f", - "obu", + format, ]) .arg(path) .output() @@ -1241,12 +1241,13 @@ fn ffprobe_pix_fmt(path: &Path) -> Option { /// Encode 10-bit planes and return the bitstream. fn encode_stream_16( display: &Rc, + codec: EncCodec, planes: &[I420_16], qp: u32, rate_control: RateControlMode, ) -> Result, ec_hw::Error> { let (width, height) = (planes[0].width, planes[0].height); - let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); + let mut config = EncoderConfig::new(codec, width, height).ten_bit(); config.gop_size = 60; config.framerate = (24, 1); config.rate_control = match rate_control { @@ -1268,6 +1269,52 @@ fn encode_stream_16( Ok(out) } +#[test] +fn hevc_main10_encode_round_trips() { + let Some(display) = display() else { return }; + let dir = std::env::temp_dir().join("ec-hw-hevc-10bit"); + let _ = std::fs::create_dir_all(&dir); + let Some((_, _, planes)) = ten_bit_source(&dir, 10) else { + eprintln!("skipped: no 10-bit source could be built"); + return; + }; + let (width, height) = (planes[0].width, planes[0].height); + let data = match encode_stream_16( + &display, + EncCodec::H265, + &planes, + 26, + RateControlMode::ConstantQp { qp: 26 }, + ) { + Ok(data) => data, + Err(e) => { + eprintln!("skipped: 10-bit HEVC encode unavailable ({e})"); + return; + } + }; + let path = dir.join("hw-10bit.hevc"); + std::fs::write(&path, &data).expect("write the coded stream"); + assert_eq!( + ffprobe_pix_fmt(&path, "hevc").as_deref(), + Some("yuv420p10le") + ); + let mut reference = + Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); + let mut worst = f64::INFINITY; + for (i, source) in planes.iter().enumerate() { + let theirs = reference + .next(width, height) + .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); + let db = psnr(&theirs, &Planes::from_16bit(source)); + assert!(db > 30.0, "frame {i}: {db:.2} dB from the 10-bit source"); + worst = worst.min(db); + } + println!( + "HEVC Main10 encode {width}x{height}: {} bytes, worst frame {worst:.2} dB", + data.len() + ); +} + /// 10-bit AV1 hardware encode, proved by two decoders and by two readings of /// the stream's bit depth. /// @@ -1289,6 +1336,7 @@ fn av1_10bit_encode_agrees_between_two_decoders() { let (width, height) = (planes[0].width, planes[0].height); let data = match encode_stream_16( &display, + EncCodec::Av1, &planes, 90, RateControlMode::ConstantQp { qp: 90 }, @@ -1303,19 +1351,13 @@ fn av1_10bit_encode_agrees_between_two_decoders() { std::fs::write(&path, &data).expect("write the coded stream"); assert_eq!( - ffprobe_pix_fmt(&path).as_deref(), + ffprobe_pix_fmt(&path, "obu").as_deref(), Some("yuv420p10le"), "the coded stream's sequence header does not say 10-bit" ); - // The two refusals this depth added, exercised rather than asserted in - // prose: 10-bit H.265 (High and Main are 8-bit profiles, so this crate - // never asks the driver), and 8-bit pixels handed to a 10-bit encoder. - let ten_bit_hevc = EncoderConfig::new(EncCodec::H265, width, height).ten_bit(); - assert!( - Encoder::new(&display, ten_bit_hevc).is_err(), - "a 10-bit HEVC encoder was built out of an 8-bit profile" - ); + let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit(); + assert!(Encoder::new(&display, ten_bit_h264).is_err()); let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); config.rate_control = RateControlMode::ConstantQp { qp: 90 }; let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); @@ -1551,8 +1593,13 @@ fn av1_10bit_bd_row_vs_software() { let mut ours = Vec::new(); for qp in [180u32, 140, 100, 60] { - let data = match encode_stream_16(&display, &planes, qp, RateControlMode::ConstantQp { qp }) - { + let data = match encode_stream_16( + &display, + EncCodec::Av1, + &planes, + qp, + RateControlMode::ConstantQp { qp }, + ) { Ok(data) => data, Err(e) => { eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); @@ -1990,6 +2037,7 @@ fn av1_encode_speed() { let start = Instant::now(); match encode_stream_16( &display, + EncCodec::Av1, &planes, 90, RateControlMode::ConstantQp { qp: 90 }, @@ -3599,3 +3647,53 @@ fn a_broken_gop_is_refused_on_every_codec() { println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default()); } } + +#[test] +fn ten_bit_prime_submit_matches_the_cpu_path() { + let Some(file) = std::env::var_os("EC_HEVC10").map(PathBuf::from) else { + return; + }; + let Some(display) = display() else { return }; + let data = std::fs::read(file).expect("fixture is readable"); + 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() + ); +} diff --git a/tools/edith-sink/Cargo.toml b/tools/edith-sink/Cargo.toml deleted file mode 100644 index 38c48a78..00000000 --- a/tools/edith-sink/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "edith-sink" -version.workspace = true -edition.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[dependencies] -ec-core.workspace = true -ec-dsp.workspace = true -ec-hw.workspace = true -ec-mp4.workspace = true -ec-va.workspace = true - -[lints.rust] -unsafe_code = "forbid" diff --git a/tools/edith-sink/src/main.rs b/tools/edith-sink/src/main.rs deleted file mode 100644 index 52c97f1c..00000000 --- a/tools/edith-sink/src/main.rs +++ /dev/null @@ -1,370 +0,0 @@ -use std::fs::File; -use std::io::{self, BufWriter, Read}; -use std::path::{Path, PathBuf}; -use std::process::ExitCode; -use std::str::FromStr; -use std::sync::mpsc::{self, Receiver, SyncSender}; -use std::thread; - -use ec_core::{Buf, ColorInfo, CodecId, CodecParameters, Muxer, Packet, StreamInfo, TimeBase}; -use ec_dsp::rgb::rgba_to_i420_709; -use ec_hw::{CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; -use ec_mp4::Mp4Muxer; -use ec_mp4::config::{annex_b_to_hvcc, av1c_record, avcc_record, h264_split_annex_b, hvcc_record}; - -type Res = Result; - -const OBU_SEQUENCE_HEADER: u8 = 1; -const OBU_TEMPORAL_DELIMITER: u8 = 2; - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Codec { - H264, - Hevc, - Av1, -} - -impl Codec { - fn enc(self) -> EncCodec { - match self { - Codec::H264 => EncCodec::H264, - Codec::Hevc => EncCodec::H265, - Codec::Av1 => EncCodec::Av1, - } - } -} - -struct Args { - width: u32, - height: u32, - rate: u32, - codec: Codec, - qp: u32, - dev: Option, - out: PathBuf, -} - -fn value(it: &mut impl Iterator, flag: &str) -> Res { - it.next().ok_or_else(|| format!("{flag} needs a value")) -} - -fn number(text: &str, flag: &str) -> Res { - text.parse().map_err(|_| format!("{flag}: bad number {text}")) -} - -fn parse_args() -> Res { - let mut size = None; - let mut rate = 30; - let mut codec = Codec::Hevc; - let mut qp = 16; - let mut dev = None; - let mut out = None; - let mut it = std::env::args().skip(1); - while let Some(flag) = it.next() { - match flag.as_str() { - "-s" => { - let text = value(&mut it, &flag)?; - let (w, h) = text - .split_once('x') - .ok_or_else(|| format!("-s: expected WxH, got {text}"))?; - size = Some((number(w, "-s")?, number(h, "-s")?)); - } - "-r" => rate = number(&value(&mut it, &flag)?, "-r")?, - "--qp" => qp = number(&value(&mut it, &flag)?, "--qp")?, - "--codec" => { - codec = match value(&mut it, &flag)?.as_str() { - "hevc" => Codec::Hevc, - "h264" => Codec::H264, - "av1" => Codec::Av1, - other => return Err(format!("unknown codec {other}")), - } - } - "--dev" => dev = Some(PathBuf::from(value(&mut it, &flag)?)), - "-o" => out = Some(PathBuf::from(value(&mut it, &flag)?)), - other => return Err(format!("unknown argument {other}")), - } - } - let (width, height) = size.ok_or("missing -s WxH")?; - let out = out.ok_or("missing -o FILE")?; - if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 { - return Err("size must be non-zero and even".into()); - } - if rate == 0 { - return Err("-r must be positive".into()); - } - if qp > 51 { - return Err("--qp must be 0..51".into()); - } - Ok(Args { - width, - height, - rate, - codec, - qp, - dev, - out, - }) -} - -fn blank(width: u32, height: u32) -> I420 { - let (w, h) = (width as usize, height as usize); - let chroma = (w / 2) * (h / 2); - I420 { - y: vec![0; w * h], - u: vec![0; chroma], - v: vec![0; chroma], - width, - height, - } -} - -fn read_frame(src: &mut impl Read, buf: &mut [u8], index: u64) -> Res { - let mut filled = 0; - while filled < buf.len() { - match src.read(&mut buf[filled..]) { - Ok(0) => break, - Ok(n) => filled += n, - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(e) => return Err(format!("stdin: {e}")), - } - } - match filled { - 0 => Ok(false), - n if n == buf.len() => Ok(true), - n => Err(format!( - "partial frame {index}: {n} of {} bytes", - buf.len() - )), - } -} - -fn read_frames( - width: u32, - height: u32, - tx: SyncSender, - recycled: Receiver, -) -> Res { - let (w, h) = (width as usize, height as usize); - let mut stdin = io::stdin().lock(); - let mut rgba = vec![0u8; w * h * 4]; - let mut count = 0u64; - while read_frame(&mut stdin, &mut rgba, count)? { - let mut frame = recycled - .try_recv() - .unwrap_or_else(|_| blank(width, height)); - rgba_to_i420_709(&rgba, w, h, &mut frame.y, &mut frame.u, &mut frame.v); - if tx.send(frame).is_err() { - break; - } - count += 1; - } - if count == 0 { - return Err("no frames on stdin".into()); - } - Ok(count) -} - -fn leb128(bytes: &[u8]) -> Res<(usize, usize)> { - let mut value = 0u64; - for (i, &b) in bytes.iter().take(8).enumerate() { - value |= u64::from(b & 0x7F) << (7 * i); - if (b & 0x80) == 0 { - let size = usize::try_from(value).map_err(|e| e.to_string())?; - return Ok((size, i + 1)); - } - } - Err("bad AV1 leb128 size".into()) -} - -fn av1_obus(data: &[u8]) -> Res> { - let mut out = Vec::new(); - let mut at = 0; - while at < data.len() { - let head = data[at]; - let kind = (head >> 3) & 0x0F; - if (head & 0x02) == 0 { - return Err("AV1 OBU without a size field".into()); - } - let mut pos = at + 1 + usize::from((head & 0x04) != 0); - let (size, used) = leb128(data.get(pos..).unwrap_or(&[]))?; - pos += used; - let end = pos - .checked_add(size) - .filter(|&end| end <= data.len()) - .ok_or("truncated AV1 OBU")?; - out.push((kind, &data[at..end])); - at = end; - } - Ok(out) -} - -fn config_record(codec: Codec, data: &[u8]) -> Res<(CodecId, Vec)> { - match codec { - Codec::H264 => { - let (_, _, params) = h264_split_annex_b(data).ok_or("first frame has no slice")?; - let (sps, pps) = params.ok_or("first frame has no SPS/PPS")?; - Ok((CodecId::H264, avcc_record(&sps, &pps))) - } - Codec::Hevc => { - let record = hvcc_record(data, false).ok_or("first frame has no VPS/SPS/PPS")?; - Ok((CodecId::H265, record)) - } - Codec::Av1 => { - let seq = av1_obus(data)? - .into_iter() - .find(|(kind, _)| *kind == OBU_SEQUENCE_HEADER) - .map(|(_, obu)| obu) - .ok_or("first frame has no sequence header")?; - Ok((CodecId::Av1, av1c_record(false, seq))) - } - } -} - -fn sample_of(codec: Codec, data: &[u8]) -> Res> { - match codec { - Codec::H264 => h264_split_annex_b(data) - .map(|(sample, _, _)| sample) - .ok_or_else(|| "coded frame has no slice".into()), - Codec::Hevc => annex_b_to_hvcc(data).ok_or_else(|| "coded frame has no NAL".into()), - Codec::Av1 => Ok(av1_obus(data)? - .into_iter() - .filter(|(kind, _)| *kind != OBU_TEMPORAL_DELIMITER) - .flat_map(|(_, obu)| obu.iter().copied()) - .collect()), - } -} - -fn open_sink( - out: &Path, - codec: Codec, - args: &Args, - first: &CodedFrame, -) -> Res<(Mp4Muxer>, u32)> { - let (codec_id, extradata) = config_record(codec, &first.data)?; - let file = File::create(out).map_err(|e| format!("{}: {e}", out.display()))?; - let mut mux = Mp4Muxer::new(BufWriter::new(file)).map_err(|e| e.to_string())?; - let mut params = CodecParameters::new(codec_id); - params.extradata = Some(Buf::from(extradata)); - if let ec_core::MediaParameters::Video(video) = &mut params.media { - video.width = args.width; - video.height = args.height; - video.frame_rate = Some(TimeBase::new(i64::from(args.rate), 1)); - } - let info = StreamInfo::new(0, TimeBase::new(1, i64::from(args.rate)), params); - let stream = mux.add_stream(info).map_err(|e| e.to_string())?; - mux.set_color( - stream, - ColorInfo { - primaries: 1, - transfer: 1, - matrix: 1, - full_range: false, - }, - ) - .map_err(|e| e.to_string())?; - Ok((mux, stream)) -} - -struct Partial<'a>(Option<&'a Path>); - -impl Drop for Partial<'_> { - fn drop(&mut self) { - if let Some(path) = self.0 { - let _ = std::fs::remove_file(path); - } - } -} - -fn run() -> Res { - let args = parse_args()?; - let display = match &args.dev { - Some(path) => ec_va::open_path(path), - None => ec_va::open(), - } - .map_err(|e| e.to_string())?; - - let qp = if args.codec == Codec::Av1 { - args.qp * 255 / 51 - } else { - args.qp - }; - let mut config = EncoderConfig::new(args.codec.enc(), args.width, args.height) - .colour(1, 1, 1, false); - config.framerate = (args.rate, 1); - config.gop_size = args.rate; - config.rate_control = RateControlMode::ConstantQp { qp }; - let mut encoder = Encoder::new(&display, config).map_err(|e| e.to_string())?; - - let (frame_tx, frame_rx) = mpsc::sync_channel::(2); - let (recycle_tx, recycle_rx) = mpsc::channel::(); - let (width, height) = (args.width, args.height); - let reader = thread::spawn(move || read_frames(width, height, frame_tx, recycle_rx)); - - let mut sink: Option<(Mp4Muxer>, u32)> = None; - let mut partial = Partial(None); - for (index, frame) in frame_rx.iter().enumerate() { - let index = index as i64; - let coded = encoder - .encode( - &frame, - FrameMetadata { - timestamp: index, - force_keyframe: false, - }, - ) - .map_err(|e| e.to_string())?; - let _ = recycle_tx.send(frame); - if sink.is_none() { - sink = Some(open_sink(&args.out, args.codec, &args, &coded)?); - partial.0 = Some(&args.out); - } - let (mux, stream) = sink.as_mut().ok_or("no output stream")?; - let mut packet = Packet::new( - *stream, - TimeBase::new(1, i64::from(args.rate)), - sample_of(args.codec, &coded.data)?, - ); - packet.pts = Some(index); - packet.dts = Some(index); - packet.duration = Some(1); - packet.flags.keyframe = coded.is_keyframe; - mux.write_packet(&packet).map_err(|e| e.to_string())?; - } - - let frames = reader - .join() - .map_err(|_| "reader thread panicked".to_string())??; - let (mut mux, _) = sink.ok_or("no output stream")?; - mux.finish().map_err(|e| e.to_string())?; - partial.0 = None; - Ok(frames) -} - -fn quiet_libva() -> Option { - if std::env::var_os("LIBVA_MESSAGING_LEVEL").is_some() { - return None; - } - let exe = std::env::current_exe().ok()?; - let status = std::process::Command::new(exe) - .args(std::env::args_os().skip(1)) - .env("LIBVA_MESSAGING_LEVEL", "1") - .status() - .ok()?; - Some(ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1))) -} - -fn main() -> ExitCode { - if let Some(code) = quiet_libva() { - return code; - } - match run() { - Ok(frames) => { - eprintln!("edith-sink: {frames} frames"); - ExitCode::SUCCESS - } - Err(e) => { - eprintln!("edith-sink: {e}"); - ExitCode::FAILURE - } - } -}