diff --git a/crates/ec-hw/src/enc/av1.rs b/crates/ec-hw/src/enc/av1.rs index 5bd8a5fc..74763153 100644 --- a/crates/ec-hw/src/enc/av1.rs +++ b/crates/ec-hw/src/enc/av1.rs @@ -49,7 +49,8 @@ pub(super) fn parameters( let context = encoder.context(); let (coded_w, coded_h) = encoder.coded_size(); let (width, height) = (config.width.max(1), config.height.max(1)); - let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. }); + let cqp = config.rate_control.is_cqp(); + let ten_bit = config.bit_depth == 10; let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); let mut seq = EncSequenceParameterBufferAV1 { @@ -59,8 +60,8 @@ pub(super) fn parameters( intra_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, ..EncSequenceParameterBufferAV1::default() @@ -68,7 +69,7 @@ pub(super) fn parameters( seq.seq_fields = seq .seq_fields .enable_order_hint(1) - .bit_depth_minus8(0) + .bit_depth_minus8(if ten_bit { 2 } else { 0 }) .subsampling_x(1) .subsampling_y(1); out.push(param_buffer(context, &seq)?); @@ -84,7 +85,7 @@ pub(super) fn parameters( }; let base_qindex = match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, - RateControlMode::ConstantBitrate => 128, + _ => 128, }; // One reference, refreshed every picture: slot 0 holds the previous // reconstruction and every ref_frame_idx points at it. @@ -142,7 +143,7 @@ pub(super) fn parameters( height, seq_level_idx: level_idx, seq_tier: 0, - high_bitdepth: false, + high_bitdepth: ten_bit, colour: config.colour, }), out, diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs index 5c142b1d..e96ea460 100644 --- a/crates/ec-hw/src/enc/h264.rs +++ b/crates/ec-hw/src/enc/h264.rs @@ -44,8 +44,8 @@ pub(super) fn parameters( intra_idr_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, max_num_ref_frames: 1, picture_width_in_mbs: (coded_w / 16) as u16, @@ -84,7 +84,7 @@ pub(super) fn parameters( frame_num, pic_init_qp: match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, - RateControlMode::ConstantBitrate => 26, + _ => 26, }, ..EncPictureParameterBufferH264::default() }; diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index bfe5485e..6e1f96dc 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -50,8 +50,8 @@ pub(super) fn parameters( intra_idr_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, pic_width_in_luma_samples: coded_w as u16, pic_height_in_luma_samples: coded_h as u16, @@ -87,7 +87,7 @@ pub(super) fn parameters( collocated_ref_pic_index: 0xff, pic_init_qp: match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, - RateControlMode::ConstantBitrate => 26, + _ => 26, }, nal_unit_type: if keyframe { NAL_IDR_W_RADL diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index c0bc0fbf..94bd1fa6 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -16,6 +16,20 @@ //! driver composes no headers of its own from thin air: it parses the //! sequence and frame header OBUs this crate packs (see `enc::headers::av1`) //! and writes the stream's headers from them. +//! +//! AV1 encodes at 8 or 10 bits ([`EncoderConfig::bit_depth`]); 10-bit is the +//! depth his own library is stored at, and `gpu.rs`'s +//! `av1_10bit_encode_agrees_between_two_decoders` proves a 10-bit stream out +//! of this path decodes identically through `ec-av1` and libdav1d with +//! ffprobe reading `yuv420p10le` out of the sequence header. +//! +//! # Rate control +//! +//! [`RateControlMode`] is not advisory: it is set as +//! `VAConfigAttribRateControl` when the VA config is created, so an encoder +//! built for CQP ignores a bitrate handed to it later. CQP, CBR, VBR and QVBR +//! are all measured by `gpu.rs`'s `av1_encode_rate_control_lands`, which +//! prints what each mode delivered against what it was asked for. use std::sync::Arc; @@ -26,10 +40,10 @@ use ec_va::{ }; use crate::error::{Error, Result}; -use crate::frame::I420; +use crate::frame::{I420, I420_16}; use crate::params::enc::{ MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, - misc_bytes, + VA_RC_QVBR, misc_bytes, }; use crate::params::param_buffer; use crate::pool::{PooledSurface, SurfacePool}; @@ -60,6 +74,38 @@ pub enum RateControlMode { }, /// Constant bitrate, the driver picking quantisers to hold it. ConstantBitrate, + /// Variable bitrate: `bitrate` is the average asked for, and the driver + /// may spend up to 1.5x it inside the rate window. + VariableBitrate, + /// Quality-defined variable bitrate: the driver holds `quality` (a + /// quantiser-like target, lower is better quality) and treats `bitrate` + /// as the ceiling it may not exceed. + Qvbr { + /// The quality factor, in the codec's quantiser scale. + quality: u32, + }, +} + +impl RateControlMode { + /// The `VAConfigAttribRateControl` value this mode is configured with. + /// + /// The attribute is set at config creation, not per picture: a driver + /// that was configured for CQP ignores a bitrate handed to it later + /// (which is how the AV1 path measured CQP-only until 2026-09-07). + fn va_mode(self) -> u32 { + match self { + RateControlMode::ConstantQp { .. } => sys::VA_RC_CQP, + RateControlMode::ConstantBitrate => sys::VA_RC_CBR, + RateControlMode::VariableBitrate => sys::VA_RC_VBR, + RateControlMode::Qvbr { .. } => VA_RC_QVBR, + } + } + + /// True when the driver is told exactly which quantiser to use, so it has + /// nothing to back-annotate into the header this crate packs. + pub(crate) fn is_cqp(self) -> bool { + matches!(self, RateControlMode::ConstantQp { .. }) + } } /// What can be changed between frames without rebuilding the encoder. @@ -102,6 +148,10 @@ pub struct EncoderConfig { /// 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, + /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). + /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or + /// straight from a 10-bit [`crate::Frame`]. + pub bit_depth: u8, } /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. @@ -135,9 +185,16 @@ impl EncoderConfig { rate_control: RateControlMode::ConstantBitrate, quality: 0, colour: None, + bit_depth: 8, } } + /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`]. + pub fn ten_bit(mut self) -> EncoderConfig { + self.bit_depth = 10; + self + } + /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. pub fn colour( mut self, @@ -200,6 +257,19 @@ pub struct Encoder { impl Encoder { /// Build an encoder for `config` on `display`. pub fn new(display: &Arc, config: EncoderConfig) -> Result { + 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", + 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. + return Err(Error::config( + "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate configures (High, Main) are 8-bit", + )); + } let profile = match config.codec { // High is the profile every H.264 encoder on this driver reports and // the one a High-profile decoder expects; Main is a strict subset. @@ -217,6 +287,11 @@ impl Encoder { config.height.next_multiple_of(block), ); + let rt_format = if config.bit_depth == 10 { + sys::VA_RT_FORMAT_YUV420_10 + } else { + sys::VA_RT_FORMAT_YUV420 + }; let caps = CapReport::probe(display)?; let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { Error::unsupported( @@ -255,15 +330,18 @@ impl Encoder { profile, Entrypoint::EncSlice, &[ - ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), + ConfigAttrib::rt_format(rt_format), + ConfigAttrib { + type_: sys::VAConfigAttribRateControl, + value: config.rate_control.va_mode(), + }, ConfigAttrib { type_: sys::VAConfigAttribEncPackedHeaders, value: packed, }, ], )?; - let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_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 pool = SurfacePool::new(display, &spec, 8)?; @@ -309,6 +387,12 @@ impl Encoder { /// Encode one frame and return its coded bytes. pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + if self.config.bit_depth != 8 { + return Err(Error::config(format!( + "encode: this encoder is configured for {} bits; call encode_16", + self.config.bit_depth + ))); + } if frame.width != self.config.width || frame.height != self.config.height { return Err(Error::config(format!( "encoder configured for {}x{} was given a {}x{} frame", @@ -323,6 +407,32 @@ impl Encoder { self.encode_surface(Arc::clone(input.surface()), meta) } + /// 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`, as + /// [`crate::Frame::to_i420_16`] returns them, and are shifted into P010's + /// top ten bits on upload. + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + if self.config.bit_depth != 10 { + return Err(Error::config(format!( + "encode_16: this encoder is configured for {} bits; call encode", + self.config.bit_depth + ))); + } + if frame.width != self.config.width || frame.height != self.config.height { + return Err(Error::config(format!( + "encoder configured for {}x{} was given a {}x{} frame", + self.config.width, self.config.height, frame.width, frame.height + ))); + } + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("encode: every surface is still in use"))?; + self.upload_16(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 @@ -377,7 +487,9 @@ impl Encoder { "encode_frame: the frame was decoded on a different Display than this encoder", )); } - let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { + 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 { Arc::clone(frame.surface()) @@ -397,12 +509,11 @@ impl Encoder { display_size: (u32, u32), ) -> Result> { if self.vpp.is_none() { - let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); + let spec = surface_spec(self.config.bit_depth, self.coded_size); let display = self.context.display(); let surfaces = Surface::create_pool(display, &spec, 2)?; for s in &surfaces { - Self::fill_black(s, self.coded_size)?; + Self::fill_black(s, self.coded_size, self.config.bit_depth)?; } let vpp = Vpp::new( display, @@ -427,16 +538,26 @@ impl Encoder { /// 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(surface: &Arc, size: (u32, u32)) -> Result<()> { - let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; + fn fill_black(surface: &Arc, size: (u32, u32), bit_depth: u8) -> Result<()> { + let mut image = Image::create(surface.display(), fourcc(bit_depth), size.0, size.1)?; { let mut mapped = image.map()?; - if let Some(y) = mapped.plane_mut(0) { - y.fill(16); - } - if let Some(uv) = mapped.plane_mut(1) { - uv.fill(128); - } + // P010 carries the sample in the top ten bits, so black is the + // 8-bit value shifted up by six, little endian. + let (luma, chroma) = (16u16 << 6, 128u16 << 6); + let mut plane = |index: usize, eight: u8, ten: u16| { + if let Some(p) = mapped.plane_mut(index) { + if bit_depth == 8 { + p.fill(eight); + } else { + for sample in p.chunks_exact_mut(2) { + sample.copy_from_slice(&ten.to_le_bytes()); + } + } + } + }; + plane(0, 16, luma); + plane(1, 128, chroma); } surface.write_from(&image, size.0, size.1)?; Ok(()) @@ -514,7 +635,7 @@ impl Encoder { if self.upload.is_none() { self.upload = Some(Image::create( surface.display(), - sys::VA_FOURCC_NV12, + fourcc(self.config.bit_depth), self.coded_size.0, self.coded_size.1, )?); @@ -558,23 +679,86 @@ impl Encoder { Ok(()) } + /// Upload one 10-bit frame into a surface as P010. + /// + /// The same reused image as [`Encoder::upload`], created P010 because the + /// encoder's surfaces are; samples move from the low ten bits of the + /// caller's `u16` into P010's top ten. + fn upload_16(&mut self, frame: &I420_16, surface: &Arc) -> Result<()> { + if self.upload.is_none() { + self.upload = Some(Image::create( + surface.display(), + fourcc(self.config.bit_depth), + self.coded_size.0, + self.coded_size.1, + )?); + } + let image = self + .upload + .as_mut() + .ok_or_else(|| Error::config("no upload image"))?; + let (w, h) = (frame.width as usize, frame.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + { + let mut mapped = image.map()?; + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; + if let Some(dst) = mapped.plane_mut(0) { + for row in 0..h { + let d = row * y_pitch; + if d + w * 2 > dst.len() { + break; + } + for col in 0..w { + let v = (frame.y[row * w + col] & 0x3ff) << 6; + dst[d + col * 2..d + col * 2 + 2].copy_from_slice(&v.to_le_bytes()); + } + } + } + if let Some(dst) = mapped.plane_mut(1) { + for row in 0..ch { + let d = row * uv_pitch; + if d + cw * 4 > dst.len() { + break; + } + for col in 0..cw { + let u = (frame.u[row * cw + col] & 0x3ff) << 6; + let v = (frame.v[row * cw + col] & 0x3ff) << 6; + dst[d + col * 4..d + col * 4 + 2].copy_from_slice(&u.to_le_bytes()); + dst[d + col * 4 + 2..d + col * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + } + } + } + surface.write_from(image, self.coded_size.0, self.coded_size.1)?; + Ok(()) + } + /// The misc parameter buffers that carry rate control, resent when tuned. fn rate_control_buffers(&mut self) -> Result> { if !self.tunings_dirty { return Ok(Vec::new()); } self.tunings_dirty = false; - let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { - RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), - RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), + // VBR's `bits_per_second` is the peak, not the average: libva takes + // the average as `target_percentage` of it, so an average-rate ask + // 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::VariableBitrate => { + (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0) + } + RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), }; let rc = RateControl { bits_per_second: bits, - target_percentage: 100, + target_percentage: target, window_size: 1000, initial_qp, min_qp, max_qp, + quality_factor: quality, }; let mut out = vec![Buffer::from_bytes( &self.context, @@ -591,9 +775,13 @@ impl Encoder { &misc_bytes(MISC_FRAME_RATE, &fr.words()), )?); if bits > 0 { + // One rate window of buffer, three quarters full to start, which + // is what ffmpeg's vaapi encoder asks for: a two-window buffer + // let radeonsi's AV1 CBR undershoot the ask by 20% where ffmpeg's + // own av1_vaapi undershot by 8% on the same clip (measured). let hrd = crate::params::enc::Hrd { - initial_buffer_fullness: bits, - buffer_size: bits * 2, + initial_buffer_fullness: bits / 4 * 3, + buffer_size: bits, }; out.push(Buffer::from_bytes( &self.context, @@ -654,6 +842,25 @@ impl Encoder { } } +/// The surface format an encoder of `bit_depth` works in. +fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec { + let spec = if bit_depth == 10 { + SurfaceSpec::p010(size.0, size.1) + } else { + SurfaceSpec::nv12(size.0, size.1) + }; + spec.with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) +} + +/// The image fourcc matching `bit_depth`. +fn fourcc(bit_depth: u8) -> u32 { + if bit_depth == 10 { + sys::VA_FOURCC_P010 + } else { + sys::VA_FOURCC_NV12 + } +} + /// Collect the bytes of a coded buffer's segment list. /// /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 5beceec5..0d57ce4c 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -25,6 +25,12 @@ //! 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 +//! 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. +//! //! # Shape //! //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked diff --git a/crates/ec-hw/src/params/enc.rs b/crates/ec-hw/src/params/enc.rs index ce1fa07c..ce26c0bd 100644 --- a/crates/ec-hw/src/params/enc.rs +++ b/crates/ec-hw/src/params/enc.rs @@ -61,6 +61,11 @@ unsafe impl VaParam for PackedHeaderParameterBuffer { const TYPE: i32 = VAEncPackedHeaderParameterBufferType; } +/// `VA_RC_QVBR`, `va.h:1652`. Not in `ec_va::sys` because this is the only +/// crate that spends it; radeonsi advertises it in `VAConfigAttribRateControl` +/// (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8). +pub const VA_RC_QVBR: u32 = 0x0000_0400; + /// `VAEncMiscParameterRateControl`, `va.h:2492`. /// /// Built as words rather than as a struct because a misc parameter is submitted @@ -81,6 +86,8 @@ pub struct RateControl { pub min_qp: u32, /// Maximum quantiser. pub max_qp: u32, + /// QVBR target quality; ignored by every other mode. + pub quality_factor: u32, } impl RateControl { @@ -96,7 +103,7 @@ impl RateControl { 0, // rc_flags 0, // ICQ_quality_factor self.max_qp, - 0, // quality_factor + self.quality_factor, 0, // target_frame_size 0, 0, diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index bd64d4c8..c575496a 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -15,7 +15,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use ec_hw::{ - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode, + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, + RateControlMode, }; use ec_va::Display; @@ -918,6 +919,535 @@ fn av1_encode_agrees_between_two_decoders() { } } +// --------------------------------------------------------------------------- +// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only +// encoder does not serve his files. +// --------------------------------------------------------------------------- + +/// Film B's native 10-bit crop from the real-library manifest: `(path, seek, +/// width, height, x, y)`, the same 1920x1024 window and 00:40:00 seek the +/// software gates use (`ec-av1`'s `native_gate_clips`). +fn ten_bit_film_clip() -> Option<(PathBuf, String, u32, u32, u32, u32)> { + let manifest = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); + let text = std::fs::read_to_string(manifest).ok()?; + for line in text.lines().skip(1) { + let f: Vec<&str> = line.split('\t').collect(); + if f.len() < 7 || f[2] != "av1" || f[5] != "yuv420p10le" || f[3] != "3840" { + continue; + } + let path = PathBuf::from(f[0]); + if !path.exists() { + continue; + } + let (nw, nh): (u32, u32) = (f[3].parse().ok()?, f[4].parse().ok()?); + let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); + return Some((path, "00:40:00".into(), cw, ch, (nw - cw) / 2 & !1, (nh - ch) / 2 & !1)); + } + None +} + +/// A 10-bit gradient with real dynamic range, used when the manifest has no +/// 10-bit film: 64..940 across the frame with a moving highlight, so the +/// stream is neither flat nor 8-bit content dressed up as 10. +fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let mut f = I420_16 { + y: vec![0; w * h], + u: vec![512; cw * ch], + v: vec![512; cw * ch], + width, + height, + bit_depth: 10, + }; + for y in 0..h { + for x in 0..w { + f.y[y * w + x] = (64 + x * 700 / w + y * 176 / h) as u16; + } + } + let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); + for y in by..by + 64 { + for x in bx..bx + 64 { + f.y[y * w + x] = 940; + } + } + for y in by / 2..(by + 64) / 2 { + for x in bx / 2..(bx + 64) / 2 { + f.u[y * cw + x] = 360; + f.v[y * cw + x] = 960; + } + } + f +} + +/// Write 10-bit planes as a y4m so ffmpeg sees the same source the encoder did. +fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { + use std::io::Write; + let Ok(file) = std::fs::File::create(path) else { + return false; + }; + let mut out = std::io::BufWriter::new(file); + let (w, h) = (frames[0].width, frames[0].height); + if write!(out, "YUV4MPEG2 W{w} H{h} F{}:{} Ip A1:1 C420p10\n", fps.0, fps.1).is_err() { + return false; + } + for f in frames { + if out.write_all(b"FRAME\n").is_err() { + return false; + } + for plane in [&f.y, &f.u, &f.v] { + let bytes: Vec = plane.iter().flat_map(|s| s.to_le_bytes()).collect(); + if out.write_all(&bytes).is_err() { + return false; + } + } + } + out.flush().is_ok() +} + +/// The 10-bit source the 10-bit gates encode, plus the y4m every reference +/// encoder and every PSNR reads: his own film when the manifest has it, +/// a synthetic 10-bit gradient otherwise. The label says which — a gate that +/// does not say what it exercised proves nothing about his library. +fn ten_bit_source(dir: &Path, frames: u32) -> Option<(String, PathBuf, Vec)> { + let y4m = dir.join("source-10bit.y4m"); + let _ = std::fs::remove_file(&y4m); + if let Some((path, seek, cw, ch, x, y)) = ten_bit_film_clip() { + let ok = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-y", "-ss", &seek, "-i"]) + .arg(&path) + .args([ + "-frames:v", + &frames.to_string(), + "-vf", + &format!("crop={cw}:{ch}:{x}:{y}"), + "-pix_fmt", + "yuv420p10le", + // y4m's 10-bit chroma formats are outside its official set. + "-strict", + "-1", + ]) + .arg(&y4m) + .status() + .is_ok_and(|s| s.success()); + if ok && let Some(planes) = raw_frames_16(&y4m, cw, ch, frames) { + return Some(("film B 10-bit native crop".into(), y4m, planes)); + } + eprintln!("film B 10-bit extraction failed; falling back to the synthetic gradient"); + } + let (w, h) = (1920u32, 1024u32); + let planes: Vec = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); + write_y4m_16(&y4m, &planes, (24, 1)).then_some(("synthetic 10-bit gradient".into(), y4m, planes)) +} + +/// The same pictures as 10-bit planes, for the hardware encoder's own input. +fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(y4m) + .args(["-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-"]) + .stderr(Stdio::null()) + .output() + .ok()?; + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let frame_len = (w * h + 2 * cw * ch) * 2; + let read = |s: &[u8]| -> Vec { + s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() + }; + let mut pictures = Vec::new(); + for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { + let (y, rest) = chunk.split_at(w * h * 2); + let (u, v) = rest.split_at(cw * ch * 2); + pictures.push(I420_16 { + y: read(y), + u: read(u), + v: read(v), + width, + height, + bit_depth: 10, + }); + } + (!pictures.is_empty()).then_some(pictures) +} + +/// What ffprobe calls the stream's pixel format — for an AV1 stream that is +/// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder +/// that shares no code with the writer above. +fn ffprobe_pix_fmt(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", "error", "-select_streams", "v:0", "-show_entries", + "stream=pix_fmt", "-of", "default=nw=1:nk=1", "-f", "obu", + ]) + .arg(path) + .output() + .ok()?; + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) +} + +/// Encode 10-bit planes and return the bitstream. +fn encode_stream_16( + display: &Arc, + 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(); + config.gop_size = 60; + config.framerate = (24, 1); + config.rate_control = match rate_control { + RateControlMode::ConstantQp { .. } => RateControlMode::ConstantQp { qp }, + other => other, + }; + let mut encoder = Encoder::new(display, config)?; + let mut out = Vec::new(); + for (t, frame) in planes.iter().enumerate() { + let coded = encoder.encode_16( + frame, + FrameMetadata { timestamp: t as i64, force_keyframe: false }, + )?; + out.extend_from_slice(&coded.data); + } + Ok(out) +} + +/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of +/// the stream's bit depth. +/// +/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the +/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this +/// crate packs into the sequence header, and `ec-av1`'s own decode must +/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. +#[test] +fn av1_10bit_encode_agrees_between_two_decoders() { + let Some(display) = display() else { return }; + let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); + let _ = std::fs::create_dir_all(&dir); + let frames = 10u32; + let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { + eprintln!("skipped: no 10-bit source could be built"); + return; + }; + let _ = y4m; + let (width, height) = (planes[0].width, planes[0].height); + let data = match encode_stream_16( + &display, + &planes, + 90, + RateControlMode::ConstantQp { qp: 90 }, + ) { + Ok(data) => data, + Err(e) => { + eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); + return; + } + }; + let path = dir.join("hw-10bit.obu"); + std::fs::write(&path, &data).expect("write the coded stream"); + + assert_eq!( + ffprobe_pix_fmt(&path).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 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"); + assert!( + ten.encode(&source_frame(width, height, 0), FrameMetadata::default()).is_err(), + "8-bit pixels went into a 10-bit encoder" + ); + + let ours = ec_av1::stream::decode_stream(&data) + .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); + assert_eq!(ours.len(), planes.len(), "ec-av1 decoded {} of {frames} frames", ours.len()); + let peak = ours.iter().flat_map(|p| p.y.iter()).copied().max().unwrap_or(0); + assert!(peak > 255, "every decoded luma sample fits in 8 bits (peak {peak})"); + + let mut reference = + Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); + let mut worst = f64::INFINITY; + for (i, picture) in ours.iter().enumerate() { + let theirs = reference + .next(width, height) + .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); + let mine = Planes { + y: picture.y.clone(), + u: picture.u.clone(), + v: picture.v.clone(), + peak: 1023.0, + }; + let db = psnr(&mine, &theirs); + assert!(db.is_infinite(), "frame {i}: the two decoders disagree ({db:.2} dB)"); + let source = Planes::from_16bit(&planes[i]); + let fidelity = psnr(&mine, &source); + assert!(fidelity > 30.0, "frame {i}: coded {fidelity:.2} dB from the 10-bit source"); + worst = worst.min(fidelity); + } + println!( + "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ + yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ + sample, worst frame {worst:.2} dB from the source (10-bit domain)", + data.len() + ); +} + +/// Rate control: does an asked-for bitrate come back? +/// +/// CQP was the only mode the AV1 path had ever measured, because the config +/// was created without a `VAConfigAttribRateControl` at all — a driver +/// configured for CQP ignores a bitrate handed to it later. With the attribute +/// set, three targets are encoded in each of CBR and VBR on his own 1080p +/// content and the delivered rate is compared with the ask; the table is +/// printed either way, including the pixel format and the mode, so the row +/// says what it exercised. +#[test] +fn av1_encode_rate_control_lands() { + let Some(display) = display() else { return }; + let clips = real_clips(); + let Some((label, source)) = clips.into_iter().next() else { + eprintln!("skipped: no real-library manifest"); + return; + }; + let dir = std::env::temp_dir().join("ec-hw-av1-rc"); + let _ = std::fs::create_dir_all(&dir); + let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); + let y4m = dir.join("rc-source.y4m"); + if !extract_y4m(&source, &y4m, width, height, frames) { + eprintln!("skipped {label}: extraction failed"); + return; + } + let Some(planes) = raw_frames(&y4m, width, height, frames) else { + eprintln!("skipped {label}: no frames extracted"); + return; + }; + + println!("AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", planes.len()); + // QVBR is quality-defined: `bitrate` is a ceiling it may not exceed, not + // a target it must reach, so asking it to land on the number would be + // asking for the wrong thing. + enum Ask { + Within(f64), + Ceiling, + } + for (mode_name, mode, ask) in [ + ("CBR", RateControlMode::ConstantBitrate, Ask::Within(0.15)), + ("VBR", RateControlMode::VariableBitrate, Ask::Within(0.25)), + ("QVBR", RateControlMode::Qvbr { quality: 100 }, Ask::Ceiling), + ] { + let mut table: Vec<(u32, f64, f64)> = Vec::new(); + for target in [2_000_000u32, 6_000_000, 12_000_000] { + let mut config = EncoderConfig::new(EncCodec::Av1, width, height); + config.framerate = (fps, 1); + config.gop_size = 60; + config.bitrate = target; + config.rate_control = mode; + let mut encoder = match Encoder::new(&display, config) { + Ok(encoder) => encoder, + Err(e) => { + // A mode the driver does not advertise refuses at config + // creation; that is the driver's answer, printed as one. + eprintln!(" {mode_name}: refused by the driver ({e})"); + break; + } + }; + let mut bytes = Vec::new(); + for (i, frame) in planes.iter().enumerate() { + match encoder.encode( + frame, + FrameMetadata { timestamp: i as i64, force_keyframe: false }, + ) { + Ok(coded) => bytes.extend_from_slice(&coded.data), + Err(e) => panic!("{mode_name} at {target} bps: encode failed ({e})"), + } + } + let path = dir.join(format!("{mode_name}-{target}.obu")); + std::fs::write(&path, &bytes).expect("write"); + let delivered = + bytes.len() as f64 * 8.0 * f64::from(fps) / f64::from(planes.len() as u32); + let db = ffmpeg_psnr_at(&path, &y4m, fps).unwrap_or(f64::NAN); + println!( + " {mode_name} target {:>5} kbps -> delivered {:>6.0} kbps ({:+.1}%), {db:.2} dB", + target / 1000, + delivered / 1000.0, + (delivered / f64::from(target) - 1.0) * 100.0 + ); + table.push((target, delivered, db)); + } + if table.len() < 3 { + continue; + } + match ask { + Ask::Within(tolerance) => { + for &(target, delivered, _) in &table { + let error = delivered / f64::from(target) - 1.0; + assert!( + error.abs() <= tolerance, + "{mode_name} at {target} bps delivered {delivered:.0} bps ({:+.1}%), \ + outside +/-{:.0}%", + error * 100.0, + tolerance * 100.0 + ); + } + for pair in table.windows(2) { + assert!( + pair[1].2 > pair[0].2, + "{mode_name}: PSNR is not monotone in the target ({:?} then {:?})", + pair[0], + pair[1] + ); + } + } + Ask::Ceiling => { + for &(target, delivered, _) in &table { + assert!( + delivered <= f64::from(target) * 1.1, + "{mode_name} at a {target} bps ceiling delivered {delivered:.0} bps" + ); + } + } + } + } +} + +/// [`ffmpeg_psnr`] with the rate pinned to `fps` on both inputs. +fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option { + let rate = fps.to_string(); + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) + .arg("-i") + .arg(coded) + .args(["-r", &rate]) + .arg("-i") + .arg(source) + .args(["-lavfi", "psnr", "-f", "null", "-"]) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stderr); + let field = text.split("average:").nth(1)?; + field.split_whitespace().next()?.parse::().ok().filter(|v| v.is_finite()) +} + +/// What the GPU's 10-bit AV1 costs against 10-bit software, on his own film. +/// +/// The same shape as the 8-bit row, at film B's native 1920x1024 crop and +/// entirely in the 10-bit domain: no arm ever sees an 8-bit sample, so the +/// comparison is encoder against encoder rather than depth against depth. +/// Skips when the manifest has no 10-bit film -- a synthetic gradient would +/// be a BD-rate number about a gradient. +#[test] +fn av1_10bit_bd_row_vs_software() { + let Some(display) = display() else { return }; + let dir = std::env::temp_dir().join("ec-hw-av1-10bit-bd"); + let _ = std::fs::create_dir_all(&dir); + let frames = 12u32; + let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { + eprintln!("skipped: no 10-bit source could be built"); + return; + }; + if !label.starts_with("film") { + eprintln!("skipped: no 10-bit film in the real-library manifest ({label})"); + return; + } + let (width, height) = (planes[0].width, planes[0].height); + let coded = planes.len() as u32; + + let mut ours = Vec::new(); + for qp in [180u32, 140, 100, 60] { + let data = match encode_stream_16( + &display, + &planes, + qp, + RateControlMode::ConstantQp { qp }, + ) { + Ok(data) => data, + Err(e) => { + eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); + return; + } + }; + let path = dir.join(format!("hw10-{qp}.obu")); + std::fs::write(&path, &data).expect("write"); + if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { + ours.push((data.len() as f64 * 8.0 / f64::from(coded), db)); + } + } + let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] + .iter() + .filter_map(|q| { + software_point( + &dir, + &y4m, + "film-B-10bit", + "librav1e", + &[ + "-pix_fmt", "yuv420p10le", + "-rav1e-params", &format!("speed=6:quantizer={q}"), + "-g", "60", + ], + *q, + coded, + ) + }) + .collect(); + let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] + .iter() + .filter_map(|crf| { + software_point( + &dir, + &y4m, + "film-B-10bit", + "libaom-av1", + &[ + "-pix_fmt", "yuv420p10le", + "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", + ], + *crf, + coded, + ) + }) + .collect(); + + println!("10-bit BD row: {label}, {width}x{height} yuv420p10le, {coded} frames"); + for (name, ladder) in [ + ("hw AV1 10-bit", &ours), + ("librav1e 10-bit", &rav1e), + ("libaom 10-bit", &libaom), + ] { + println!(" {name}: {ladder:?}"); + for pair in ladder.windows(2) { + assert!( + pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, + "{name}: ladder is not monotone at {pair:?}" + ); + } + } + if ours.len() >= 3 && rav1e.len() >= 3 { + println!( + " BD-rate: hw AV1 10-bit vs librav1e speed 6 10-bit: {:+.1}%", + bd_rate(&rav1e, &ours) * 100.0 + ); + } + if ours.len() >= 3 && libaom.len() >= 3 { + println!( + " BD-rate: hw AV1 10-bit vs libaom cpu-used 6 10-bit: {:+.1}%", + bd_rate(&libaom, &ours) * 100.0 + ); + } +} + /// What the GPU's AV1 costs against software, on his own content. /// /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen @@ -1247,6 +1777,22 @@ fn av1_encode_speed() { } } } + // 10-bit at the size his own films are in: the depth his library is + // actually stored at, so the fps that matters for a real export. + let planes: Vec = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); + let start = Instant::now(); + match encode_stream_16(&display, &planes, 90, RateControlMode::ConstantQp { qp: 90 }) { + Ok(data) => { + let secs = start.elapsed().as_secs_f64(); + println!( + "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", + planes.len() as f64 / secs, + planes.len(), + data.len() * 8 / planes.len() / 1000 + ); + } + Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), + } } // --------------------------------------------------------------------------- diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index e2d2d862..9ca14014 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -43,6 +43,7 @@ fn main() { bench_h265_encode(&mut rows); bench_av1_encode(&mut rows); bench_hw_av1_encode(&mut rows); + bench_hw_av1_encode_10bit(&mut rows); bench_audio_decode(&mut rows); bench_audio_encode(&mut rows); bench_truehd(&mut rows); @@ -400,6 +401,98 @@ fn bench_hw_av1_encode(rows: &mut Vec) { }); } +/// The same row at 10 bits, which is the depth his own AV1 library is stored +/// at (`yuv420p10le`, both films). Skips as a row when there is no VA device, +/// no AV1 encode entrypoint, or no source to read. +fn bench_hw_av1_encode_10bit(rows: &mut Vec) { + let Some(src) = real_video("av1").or_else(|| real_video("hevc")).or_else(|| real_video("h264")) + else { + rows.push(missing("ec-hw av1 10-bit", "encode")); + return; + }; + let display = match ec_va::Display::open() { + Ok(display) => display, + Err(e) => { + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("no VA display ({e})"))); + return; + } + }; + let (w, h) = (1920u32, 1080u32); + let raw = extract_yuv420p10(&src, w, h, 30); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let frame_len = ((w * h + 2 * cw * ch) * 2) as usize; + let n = (raw.len() / frame_len) as u32; + if n == 0 { + rows.push(missing("ec-hw av1 10-bit", "encode")); + return; + } + let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h).ten_bit(); + cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; + let mut enc = match ec_hw::Encoder::new(&display, cfg) { + Ok(enc) => enc, + Err(e) => { + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("driver refused ({e})"))); + return; + } + }; + let read = |s: &[u8]| -> Vec { + s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() + }; + let start = Instant::now(); + let mut coded = 0usize; + for (i, frame) in raw.chunks_exact(frame_len).enumerate() { + let (y, rest) = frame.split_at((w * h * 2) as usize); + let (u, v) = rest.split_at(rest.len() / 2); + let picture = ec_hw::I420_16 { + y: read(y), + u: read(u), + v: read(v), + width: w, + height: h, + bit_depth: 10, + }; + let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false }; + match enc.encode_16(&picture, meta) { + Ok(out) => coded += out.data.len(), + Err(e) => { + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("encode failed ({e})"))); + return; + } + } + } + let wall = start.elapsed().as_secs_f64(); + let media_s = f64::from(n) / 30.0; + rows.push(Row { + component: "ec-hw av1 10-bit", + direction: "encode", + content: format!("{w}x{h} yuv420p10le, {n} frames from 00:01:00, CQP 120, {} kB", coded / 1000), + media: format!("{media_s:.1}s"), + wall_ms: wall * 1000.0, + rtf: (wall > 0.0).then_some(media_s / wall), + }); +} + +/// `extract_yuv420p` at ten bits, planar 16-bit little endian, seeked a +/// minute in: frame 0 of a film is its black leader, and a black leader codes +/// to nothing and benchmarks nothing. +fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-ss", "60", "-i"]) + .arg(src) + .args([ + "-vf", &format!("scale={w}:{h}"), + "-frames:v", &n.to_string(), + "-pix_fmt", "yuv420p10le", + "-f", "rawvideo", "-", + ]) + .output() + .expect("ffmpeg extract yuv420p10le"); + if !out.status.success() { + return Vec::new(); + } + out.stdout +} + // --------------------------------------------------------------------------- // av1: encode only -- same shape as h265. // ---------------------------------------------------------------------------