//! Hardware encoding: H.264, HEVC and AV1. //! //! The bitstream writers in [`headers`] are pure. The parameter buffers are //! built from cros-libva's typed constructors in each codec module. //! //! One frame in, one coded frame out. The GOP is IDR-then-P with a single //! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` //! reports one list-0 reference for HEVC) and what an editor's export wants: //! no reordering, so a coded frame comes back in the call that fed it. //! //! # AV1 //! //! AV1 encode was opt-in until 2026-09-07, after a submission on an older //! driver took the GPU down. It is on by default now because the refusal was //! retired by measurement, not by opinion: on mesa 26.1.8 (gfx1200) ffmpeg's //! own `av1_vaapi` encodes, this path encodes, and `gpu.rs`'s //! `av1_encode_agrees_between_two_decoders` proves every coded frame decodes //! identically through `ec-av1` and libdav1d. Unlike H.264 and HEVC, the //! 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::collections::VecDeque; use std::rc::Rc; use ec_va::caps::{Entrypoint, Profile}; use ec_va::va::SurfaceMemoryDescriptor; use ec_va::va::{ BufferType, EncMiscParameter, EncMiscParameterBufferQualityLevel, EncMiscParameterFrameRate, EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType, RcFlags, 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::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec}; use crate::error::{Error, Result}; use crate::frame::{I420, I420_16}; use crate::pool::{PooledSurface, SurfacePool}; use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms}; pub use crate::types::{ CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings, }; mod av1; mod h264; mod headers; mod hevc; /// `VA_RC_QVBR`, `va.h:1652`. radeonsi advertises it in /// `VAConfigAttribRateControl` (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8). const VA_RC_QVBR: u32 = 0x0000_0400; impl H264Profile { /// The VA profile the driver is asked for. fn va_profile(self) -> Profile { match self { H264Profile::ConstrainedBaseline => Profile::H264ConstrainedBaseline, H264Profile::Main => Profile::H264Main, H264Profile::High => Profile::H264High, } } } /// Pictures the pipelined path keeps in flight before the oldest is read back. const DEPTH: usize = 3; 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 { .. } => ec_va::va::VA_RC_CQP, RateControlMode::ConstantBitrate => ec_va::va::VA_RC_CBR, RateControlMode::VariableBitrate => ec_va::va::VA_RC_VBR, RateControlMode::Qvbr { .. } => VA_RC_QVBR, } } } /// 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, } enum EncFrame<'a> { I420(&'a I420), I420_16(&'a I420_16), } /// A hardware encoder. pub struct Encoder { /// The GPU reset epoch this encoder was created in. born_epoch: u64, config: EncoderConfig, context: Rc, pool: SurfacePool, coded_size: (u32, u32), /// The reconstruction of the previous picture, the single reference. reference: Option>, /// Pictures coded since the last key frame. gop_position: u32, /// Key frames coded so far. Consecutive IDR pictures must differ in /// `idr_pic_id` (7.4.3), so this alternates the id even at GOP 1. idr_count: u32, tunings: Tunings, /// Set when the rate control parameters have to be resent. tunings_dirty: bool, rc: RateFeedback, /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back. pending: VecDeque>, } impl Encoder { /// Build an encoder for `config` on `display`. /// /// H.264 and HEVC are ported to cros-libva; AV1 is refused with /// [`Error::Unsupported`]. pub fn new(display: &Rc, config: EncoderConfig) -> Result { let born_epoch = crate::reset::gpu_reset_epoch(); if crate::reset::gpu_recently_reset() { return Err(Error::hw_reset( "the GPU was reset moments ago; new hardware sessions wait out the grace period", )); } 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 H.265/AV1", config.bit_depth ))); } if config.bit_depth == 10 && config.codec == EncCodec::H264 { return Err(Error::config( "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), }; let coded_size = ( config.width.next_multiple_of(block), config.height.next_multiple_of(block), ); let caps = CapReport::probe(display)?; let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { Error::unsupported( format!("{profile:?} encode"), "the driver advertises no EncSlice entrypoint for this profile", ) })?; if let Some(surfaces) = &entry.surfaces && !surfaces.allows(coded_size.0, coded_size.1) { // The minimum encode size is a driver fact, not a guess: radeonsi // refuses anything under 96x32 for H.264. return Err(Error::unsupported( format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1), format!( "the driver accepts {:?}..{:?} x {:?}..{:?}", surfaces.min_width, surfaces.max_width, surfaces.min_height, surfaces.max_height ), )); } // The packed-header attribute is not decoration: a config that does not // ask for them gets a driver that writes its own headers and silently // ignores the application's (measured on radeonsi — the parameter sets // went in, the slice header did not, and every P picture came back // missing its `byte_alignment()`). let packed = entry.packed_headers & (VA_ENC_PACKED_HEADER_SEQUENCE | VA_ENC_PACKED_HEADER_PICTURE | VA_ENC_PACKED_HEADER_SLICE); let config_id = Config::new( display, profile, Entrypoint::EncSlice, &[ ConfigAttrib::rt_format(if config.bit_depth == 10 { VA_RT_FORMAT_YUV420_10 } else { VA_RT_FORMAT_YUV420 }), ConfigAttrib { type_: VAConfigAttribType::VAConfigAttribRateControl, value: config.rate_control.va_mode(), }, ConfigAttrib { type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders, value: packed, }, ], )?; let spec = surface_spec(config.bit_depth, coded_size); // 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, coded_size.0, coded_size.1, Some(&surfaces), true, )?; let pool = SurfacePool::from_surfaces(surfaces, &spec); Ok(Encoder { born_epoch, tunings: Tunings { bitrate: config.bitrate, framerate: config.framerate, }, config, context, pool, coded_size, reference: None, gop_position: 0, idr_count: 0, tunings_dirty: true, rc: RateFeedback::default(), pending: VecDeque::new(), }) } /// The coded (block-aligned) size the driver works at. pub fn coded_size(&self) -> (u32, u32) { self.coded_size } /// Change bitrate or frame rate; takes effect on the next frame. 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", )); } let input = self.stage(EncFrame::I420(frame))?; 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> { let input = self.stage(EncFrame::I420(frame))?; 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> { let input = self.stage(EncFrame::I420_16(frame))?; 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) } } 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 (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", )); } let input = self.stage(EncFrame::I420_16(frame))?; self.encode_settled(Rc::clone(input.surface()), meta) } fn stage(&mut self, frame: EncFrame) -> Result> { let (bits, width, height) = match frame { EncFrame::I420(f) => (8, f.width, f.height), EncFrame::I420_16(f) => (10, f.width, f.height), }; if self.config.bit_depth != bits { return Err(Error::config(format!( "this encoder is configured for {} bits", self.config.bit_depth ))); } self.check_size(width, height)?; let input = self .pool .acquire() .ok_or_else(|| Error::config("every surface is still in use"))?; match frame { EncFrame::I420(f) => upload(&self.context, f, input.surface(), self.coded_size)?, EncFrame::I420_16(f) => upload_16(&self.context, f, input.surface(), self.coded_size)?, } Ok(input) } fn check_size(&self, width: u32, height: u32) -> Result<()> { if width != self.config.width || height != self.config.height { return Err(Error::config(format!( "encoder configured for {}x{} was given a {}x{} frame", self.config.width, self.config.height, width, height ))); } Ok(()) } /// 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", )); } let keyframe = meta.force_keyframe || self.reference.is_none() || self.gop_position >= self.config.gop_size.max(1); let recon = self .pool .acquire() .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?; // 6 bits per pixel of headroom: an intra frame at a low quantiser is the // worst case, and a coded buffer that overflows loses the picture. let coded_bytes_len = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20); let coded = ec_va::error::va_ok( "vaCreateBuffer", self.context.create_enc_coded(coded_bytes_len as usize), )?; let mut params = Vec::new(); match self.config.codec { EncCodec::H264 => h264::parameters(self, &recon, coded.id(), keyframe, &mut params)?, EncCodec::H265 => hevc::parameters(self, &recon, coded.id(), keyframe, &mut params)?, EncCodec::Av1 => av1::parameters(self, &recon, coded.id(), keyframe, &mut params)?, } params.extend(self.rate_control_buffers()?); let mut buffers = Vec::with_capacity(params.len()); for ty in params { buffers.push(ec_va::picture::buffer(&self.context, ty)?); } let picture = ec_va::picture::submit(&self.context, Rc::clone(&source), buffers)?; 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 = { let mapped = ec_va::error::va_ok( "vaMapBuffer", ec_va::picture::MappedCodedBuffer::new(&coded), )?; let mut out = Vec::new(); for segment in mapped.segments() { out.extend_from_slice(segment.buf); } out }; 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 // sequence header. ffmpeg's demuxer refuses such a stream // ("Missing Temporal Delimiter"), so the two bytes are prepended // here rather than left to the caller. data.splice(0..0, [0x12u8, 0x00]); } drop(coded); drop(leases); Ok(CodedFrame { data, timestamp, is_keyframe: keyframe, recovery: false, }) } fn steered_bitrate(&self) -> u32 { self.rc.steered_bitrate(self.tunings.bitrate) } fn track_rate(&mut self, bytes: usize) { if self.rc.track(bytes, self.config.rate_control, self.tunings) { 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 { return Ok(Vec::new()); } self.tunings_dirty = false; // 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.steered_bitrate(), 100, 0), RateControlMode::VariableBitrate => { (0, 0, 0, self.steered_bitrate().saturating_mul(3) / 2, 66, 0) } RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), }; let rc_flags = RcFlags::new(0, 0, 0, 0, 0, 0, 0, 0, 0); let mut out = vec![BufferType::EncMiscParameter(EncMiscParameter::RateControl( EncMiscParameterRateControl::new( bits, target, RATE_WINDOW_MS, initial_qp, min_qp, 0, rc_flags, 0, max_qp, quality, 0, ), ))]; // libva packs a fractional rate as `den << 16 | num`, and a whole one // as the plain numerator. let num = self.tunings.framerate.0.max(1); let den = self.tunings.framerate.1.max(1); let packed = if den <= 1 { num } else { (den << 16) | (num & 0xffff) }; out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate( EncMiscParameterFrameRate::new(packed, 0), ))); if self.config.quality > 0 { out.push(BufferType::EncMiscParameter(EncMiscParameter::QualityLevel( EncMiscParameterBufferQualityLevel::new(self.config.quality), ))); } if bits > 0 && !self.rc.take_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 // clip length (measured, 2026-10-16). Its size: see `hrd_buffer_ms`. let buffer_ms = u64::from(hrd_buffer_ms(&self.config)); let hrd_bits = (u64::from(bits) * buffer_ms / 1000) as u32; out.push(BufferType::EncMiscParameter(EncMiscParameter::HRD( EncMiscParameterHRD::new(hrd_bits, hrd_bits), ))); } Ok(out) } /// Append one packed header: its parameter buffer, then its bytes. /// /// Both go in the same picture, in this order, which is what the driver /// reads them in (`va.h:2446`). pub(crate) fn push_packed( &self, packed: &headers::Packed, out: &mut Vec, ) -> Result<()> { let kind = match packed.kind { headers::PackedKind::Sequence => EncPackedHeaderType::Sequence, headers::PackedKind::Picture => EncPackedHeaderType::Picture, headers::PackedKind::Slice => EncPackedHeaderType::Slice, }; out.push(BufferType::EncPackedHeaderParameter( EncPackedHeaderParameter::new(kind, packed.bits, true), )); out.push(BufferType::EncPackedHeaderData(packed.bytes.clone())); Ok(()) } pub(crate) fn config(&self) -> &EncoderConfig { &self.config } pub(crate) fn reference(&self) -> Option<&Rc> { self.reference.as_ref() } pub(crate) fn gop_position(&self) -> u32 { self.gop_position } /// Key frames submitted before the picture now being coded (the count is /// bumped once a picture is submitted), so the first IDR reads 0. pub(crate) fn idr_count(&self) -> u32 { self.idr_count } } /// 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(VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) } /// The image fourcc matching `bit_depth`. fn fourcc(bit_depth: u8) -> u32 { if bit_depth == 10 { VA_FOURCC_P010 } else { VA_FOURCC_NV12 } } /// Copy `surface`'s image through `fill`, then write it back. /// /// 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( display: &Display, 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(); fill(&layout, AsMut::<[u8]>::as_mut(&mut image)); Ok(()) } /// Upload one frame into a surface as NV12. 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)); write_surface(display, surface, VA_FOURCC_NV12, coded, |layout, data| { let y_pitch = layout.pitches[0] as usize; let uv_pitch = layout.pitches[1] as usize; let y_base = layout.offsets[0] as usize; let uv_base = layout.offsets[1] as usize; // The two planes are written in turn; the loops are the interleave // `i420_to_nv12` does for callers that own both buffers. for row in 0..h { let d = y_base + row * y_pitch; if let Some(dst) = data.get_mut(d..d + w) { dst.copy_from_slice(&frame.y[row * w..row * w + w]); } else { break; } } for row in 0..ch { let d = uv_base + row * uv_pitch; let Some(dst) = data.get_mut(d..d + cw * 2) else { break; }; for col in 0..cw { dst[col * 2] = frame.u[row * cw + col]; dst[col * 2 + 1] = frame.v[row * cw + col]; } } }) } 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) }) } /// 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( context: &Rc, frame: &I420_16, 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)); write_surface(display, surface, VA_FOURCC_P010, coded, |layout, data| { let y_pitch = layout.pitches[0] as usize; let uv_pitch = layout.pitches[1] as usize; let y_base = layout.offsets[0] as usize; let uv_base = layout.offsets[1] as usize; for row in 0..h { let d = y_base + row * y_pitch; let Some(dst) = data.get_mut(d..d + w * 2) else { break; }; for col in 0..w { let v = (frame.y[row * w + col] & 0x3ff) << 6; dst[col * 2..col * 2 + 2].copy_from_slice(&v.to_le_bytes()); } } for row in 0..ch { let d = uv_base + row * uv_pitch; let Some(dst) = data.get_mut(d..d + cw * 4) else { 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[col * 4..col * 4 + 2].copy_from_slice(&u.to_le_bytes()); dst[col * 4 + 2..col * 4 + 4].copy_from_slice(&v.to_le_bytes()); } } }) }