forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs1001 lines, 37.9 KiBHistoryRawDownload
1//! Hardware encoding: H.264, HEVC and AV1.
2//!
3//! The bitstream writers in [`headers`] are pure. The parameter buffers are
4//! built from cros-libva's typed constructors in each codec module.
5//!
6//! One frame in, one coded frame out. The GOP is IDR-then-P with a single
7//! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames`
8//! reports one list-0 reference for HEVC) and what an editor's export wants:
9//! no reordering, so a coded frame comes back in the call that fed it.
10//!
11//! # AV1
12//!
13//! AV1 encode was opt-in until 2026-09-07, after a submission on an older
14//! driver took the GPU down. It is on by default now because the refusal was
15//! retired by measurement, not by opinion: on mesa 26.1.8 (gfx1200) ffmpeg's
16//! own `av1_vaapi` encodes, this path encodes, and `gpu.rs`'s
17//! `av1_encode_agrees_between_two_decoders` proves every coded frame decodes
18//! identically through `ec-av1` and libdav1d. Unlike H.264 and HEVC, the
19//! driver composes no headers of its own from thin air: it parses the
20//! sequence and frame header OBUs this crate packs (see `enc::headers::av1`)
21//! and writes the stream's headers from them.
22//!
23//! AV1 encodes at 8 or 10 bits ([`EncoderConfig::bit_depth`]); 10-bit is the
24//! depth his own library is stored at, and `gpu.rs`'s
25//! `av1_10bit_encode_agrees_between_two_decoders` proves a 10-bit stream out
26//! of this path decodes identically through `ec-av1` and libdav1d with
27//! ffprobe reading `yuv420p10le` out of the sequence header.
28//!
29//! # Rate control
30//!
31//! [`RateControlMode`] is not advisory: it is set as
32//! `VAConfigAttribRateControl` when the VA config is created, so an encoder
33//! built for CQP ignores a bitrate handed to it later. CQP, CBR, VBR and QVBR
34//! are all measured by `gpu.rs`'s `av1_encode_rate_control_lands`, which
35//! prints what each mode delivered against what it was asked for.
36
37#![allow(dead_code)] // the header writers wait for the encoder port
38
39use std::collections::VecDeque;
40use std::rc::Rc;
41
42use ec_va::caps::{Entrypoint, Profile};
43use ec_va::va::SurfaceMemoryDescriptor;
44use ec_va::va::{
45 BufferType, EncMiscParameter, EncMiscParameterBufferQualityLevel, EncMiscParameterFrameRate,
46 EncMiscParameterHRD, EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType,
47 RcFlags,
48 VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE,
49 VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10,
50 VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage,
51};
52use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp};
53
54use crate::error::{Error, Result};
55use crate::frame::{Frame, I420, I420_16};
56use crate::pool::{PooledSurface, SurfacePool};
57use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms};
58
59pub use crate::types::{
60 CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings,
61};
62
63mod av1;
64mod h264;
65mod headers;
66mod hevc;
67
68/// `VA_RC_QVBR`, `va.h:1652`. radeonsi advertises it in
69/// `VAConfigAttribRateControl` (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8).
70const VA_RC_QVBR: u32 = 0x0000_0400;
71
72impl H264Profile {
73 /// The VA profile the driver is asked for.
74 fn va_profile(self) -> Profile {
75 match self {
76 H264Profile::ConstrainedBaseline => Profile::H264ConstrainedBaseline,
77 H264Profile::Main => Profile::H264Main,
78 H264Profile::High => Profile::H264High,
79 }
80 }
81}
82
83/// Pictures the pipelined path keeps in flight before the oldest is read back.
84const DEPTH: usize = 3;
85
86impl RateControlMode {
87 /// The `VAConfigAttribRateControl` value this mode is configured with.
88 ///
89 /// The attribute is set at config creation, not per picture: a driver
90 /// that was configured for CQP ignores a bitrate handed to it later
91 /// (which is how the AV1 path measured CQP-only until 2026-09-07).
92 fn va_mode(self) -> u32 {
93 match self {
94 RateControlMode::ConstantQp { .. } => ec_va::va::VA_RC_CQP,
95 RateControlMode::ConstantBitrate => ec_va::va::VA_RC_CBR,
96 RateControlMode::VariableBitrate => ec_va::va::VA_RC_VBR,
97 RateControlMode::Qvbr { .. } => VA_RC_QVBR,
98 }
99 }
100}
101
102/// A picture submitted but not yet read back.
103struct InFlight<D: SurfaceMemoryDescriptor> {
104 picture: ec_va::picture::Picture<ec_va::picture::PictureEnd, Rc<ec_va::va::Surface<D>>>,
105 coded: ec_va::picture::EncCodedBuffer,
106 source: Rc<ec_va::va::Surface<D>>,
107 leases: Vec<Rc<PooledSurface>>,
108 timestamp: i64,
109 keyframe: bool,
110}
111
112/// A hardware encoder.
113/// A hardware encoder.
114pub struct Encoder {
115 /// The GPU reset epoch this encoder was created in.
116 born_epoch: u64,
117 config: EncoderConfig,
118 context: Rc<Context>,
119 pool: SurfacePool,
120 coded_size: (u32, u32),
121 /// The reconstruction of the previous picture, the single reference.
122 reference: Option<Rc<PooledSurface>>,
123 /// Pictures coded since the last key frame.
124 gop_position: u32,
125 /// Key frames coded so far. Consecutive IDR pictures must differ in
126 /// `idr_pic_id` (7.4.3), so this alternates the id even at GOP 1.
127 idr_count: u32,
128 tunings: Tunings,
129 /// Set when the rate control parameters have to be resent.
130 tunings_dirty: bool,
131 rc: RateFeedback,
132 profile: Profile,
133 /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`]
134 /// on a source that is not the encoder's own format or size; built lazily,
135 /// since most encoders never see one.
136 vpp: Option<Vpp>,
137 /// The small pool [`Encoder::vpp`] converts into, round-robined rather
138 /// than pool-acquired: each conversion is fully synced before this
139 /// encoder's own picture submission returns, so two surfaces are enough
140 /// to never hand out one still in flight.
141 vpp_surfaces: Vec<Rc<Surface>>,
142 vpp_next: usize,
143 /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back.
144 pending: VecDeque<InFlight<()>>,
145}
146
147impl Encoder {
148 /// Build an encoder for `config` on `display`.
149 ///
150 /// H.264 and HEVC are ported to cros-libva; AV1 is refused with
151 /// [`Error::Unsupported`].
152 pub fn new(display: &Rc<Display>, config: EncoderConfig) -> Result<Encoder> {
153 let born_epoch = crate::reset::gpu_reset_epoch();
154 if crate::reset::gpu_recently_reset() {
155 return Err(Error::hw_reset(
156 "the GPU was reset moments ago; new hardware sessions wait out the grace period",
157 ));
158 }
159 if config.bit_depth != 8 && config.bit_depth != 10 {
160 return Err(Error::config(format!(
161 "encoder bit depth {} : this crate encodes 8-bit, or 10-bit H.265/AV1",
162 config.bit_depth
163 )));
164 }
165 if config.bit_depth == 10 && config.codec == EncCodec::H264 {
166 return Err(Error::config(
167 "10-bit encode is H.265 and AV1 only here: the H.264 profiles this crate \
168 configures are 8-bit",
169 ));
170 }
171 let (profile, block) = match config.codec {
172 EncCodec::H264 => (config.h264_profile.va_profile(), 16),
173 EncCodec::H265 if config.bit_depth == 10 => (Profile::HEVCMain10, 32),
174 EncCodec::H265 => (Profile::HEVCMain, 32),
175 EncCodec::Av1 => (Profile::AV1Profile0, 64),
176 };
177 let coded_size = (
178 config.width.next_multiple_of(block),
179 config.height.next_multiple_of(block),
180 );
181
182 let caps = CapReport::probe(display)?;
183 let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| {
184 Error::unsupported(
185 format!("{profile:?} encode"),
186 "the driver advertises no EncSlice entrypoint for this profile",
187 )
188 })?;
189 if let Some(surfaces) = &entry.surfaces
190 && !surfaces.allows(coded_size.0, coded_size.1)
191 {
192 // The minimum encode size is a driver fact, not a guess: radeonsi
193 // refuses anything under 96x32 for H.264.
194 return Err(Error::unsupported(
195 format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1),
196 format!(
197 "the driver accepts {:?}..{:?} x {:?}..{:?}",
198 surfaces.min_width,
199 surfaces.max_width,
200 surfaces.min_height,
201 surfaces.max_height
202 ),
203 ));
204 }
205
206 // The packed-header attribute is not decoration: a config that does not
207 // ask for them gets a driver that writes its own headers and silently
208 // ignores the application's (measured on radeonsi — the parameter sets
209 // went in, the slice header did not, and every P picture came back
210 // missing its `byte_alignment()`).
211 let packed = entry.packed_headers
212 & (VA_ENC_PACKED_HEADER_SEQUENCE
213 | VA_ENC_PACKED_HEADER_PICTURE
214 | VA_ENC_PACKED_HEADER_SLICE);
215 let config_id = Config::new(
216 display,
217 profile,
218 Entrypoint::EncSlice,
219 &[
220 ConfigAttrib::rt_format(if config.bit_depth == 10 {
221 VA_RT_FORMAT_YUV420_10
222 } else {
223 VA_RT_FORMAT_YUV420
224 }),
225 ConfigAttrib {
226 type_: VAConfigAttribType::VAConfigAttribRateControl,
227 value: config.rate_control.va_mode(),
228 },
229 ConfigAttrib {
230 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
231 value: packed,
232 },
233 ],
234 )?;
235 let spec = surface_spec(config.bit_depth, coded_size);
236 // Input, reconstruction, one reference, and slack for the pictures
237 // the pipelined path keeps in flight.
238 let surfaces = ec_va::create_pool(display, &spec, 12)?;
239 for s in &surfaces {
240 fill_zero(display, s, coded_size, config.bit_depth)?;
241 }
242 let context = ec_va::picture::create_context(
243 display,
244 &config_id,
245 coded_size.0,
246 coded_size.1,
247 Some(&surfaces),
248 true,
249 )?;
250 let pool = SurfacePool::from_surfaces(surfaces, &spec);
251
252 Ok(Encoder {
253 born_epoch,
254 tunings: Tunings {
255 bitrate: config.bitrate,
256 framerate: config.framerate,
257 },
258 config,
259 context,
260 pool,
261 coded_size,
262 reference: None,
263 gop_position: 0,
264 idr_count: 0,
265 tunings_dirty: true,
266 rc: RateFeedback::default(),
267 profile,
268 vpp: None,
269 vpp_surfaces: Vec::new(),
270 vpp_next: 0,
271 pending: VecDeque::new(),
272 })
273 }
274
275 /// The coded (block-aligned) size the driver works at.
276 pub fn coded_size(&self) -> (u32, u32) {
277 self.coded_size
278 }
279
280 /// Change bitrate or frame rate; takes effect on the next frame.
281 pub fn tune(&mut self, tunings: Tunings) {
282 self.tunings = tunings;
283 self.tunings_dirty = true;
284 self.rc = RateFeedback::default();
285 }
286
287 /// Encode one frame and return its coded bytes.
288 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
289 if !self.pending.is_empty() {
290 return Err(Error::config(
291 "encode: pipelined frames pending; call flush first",
292 ));
293 }
294 if self.config.bit_depth != 8 {
295 return Err(Error::config(format!(
296 "encode: this encoder is configured for {} bits; call encode_16",
297 self.config.bit_depth
298 )));
299 }
300 self.check_size(frame.width, frame.height)?;
301 let input = self
302 .pool
303 .acquire()
304 .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
305 upload(&self.context, frame, input.surface(), self.coded_size)?;
306 self.encode_settled(Rc::clone(input.surface()), meta)
307 }
308
309 /// Submit one frame without waiting for it; the oldest pending frame comes back
310 /// once more than [`DEPTH`] are in flight.
311 pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result<Option<CodedFrame>> {
312 if self.config.bit_depth != 8 {
313 return Err(Error::config(format!(
314 "submit: this encoder is configured for {} bits; call submit_16",
315 self.config.bit_depth
316 )));
317 }
318 self.check_size(frame.width, frame.height)?;
319 let input = self
320 .pool
321 .acquire()
322 .ok_or_else(|| Error::config("submit: every surface is still in use"))?;
323 upload(&self.context, frame, input.surface(), self.coded_size)?;
324 self.push_pipelined(input, meta)
325 }
326
327 /// The [`Encoder::submit`] of a 10-bit encoder.
328 pub fn submit_16(
329 &mut self,
330 frame: &I420_16,
331 meta: FrameMetadata,
332 ) -> Result<Option<CodedFrame>> {
333 if self.config.bit_depth != 10 {
334 return Err(Error::config(format!(
335 "submit_16: this encoder is configured for {} bits; call submit",
336 self.config.bit_depth
337 )));
338 }
339 self.check_size(frame.width, frame.height)?;
340 let input = self
341 .pool
342 .acquire()
343 .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?;
344 upload_16(&self.context, frame, input.surface(), self.coded_size)?;
345 self.push_pipelined(input, meta)
346 }
347
348 /// Read back every pending frame, oldest first.
349 pub fn flush(&mut self) -> Result<Vec<CodedFrame>> {
350 let mut out = Vec::with_capacity(self.pending.len());
351 while let Some(f) = self.pending.pop_front() {
352 out.push(self.finish(f)?);
353 }
354 Ok(out)
355 }
356
357 fn push_pipelined(
358 &mut self,
359 input: Rc<PooledSurface>,
360 meta: FrameMetadata,
361 ) -> Result<Option<CodedFrame>> {
362 let source = Rc::clone(input.surface());
363 let in_flight = self.submit_settled(source, meta, vec![input])?;
364 self.pending.push_back(in_flight);
365 if self.pending.len() > DEPTH {
366 self.retire_oldest()
367 } else {
368 Ok(None)
369 }
370 }
371
372 /// Pipelined encode of an imported surface: a GPU copy into a pool surface
373 /// whose padding is then zeroed, matching the CPU upload path. A surface of
374 /// the coded size is copied whole; any other size is scaled to the
375 /// configured width x height, so one capture can feed several layers.
376 pub fn submit_prime(
377 &mut self,
378 surface: Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>,
379 meta: FrameMetadata,
380 ) -> Result<Option<CodedFrame>> {
381 let input = self
382 .pool
383 .acquire()
384 .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?;
385 let dest = if surface.size() == self.coded_size {
386 (0, 0, 0, 0)
387 } else {
388 (0, 0, self.config.width, self.config.height)
389 };
390 self.vpp()?
391 .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?;
392 zero_padding(
393 self.context.display(),
394 input.surface(),
395 self.config.bit_depth,
396 (self.config.width, self.config.height),
397 self.coded_size,
398 )?;
399 self.push_pipelined(input, meta)
400 }
401
402 fn retire_oldest(&mut self) -> Result<Option<CodedFrame>> {
403 match self.pending.pop_front() {
404 Some(f) => self.finish(f).map(Some),
405 None => Ok(None),
406 }
407 }
408
409 /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder.
410 ///
411 /// Samples are 0..1023 in the low ten bits of each `u16`, shifted into
412 /// P010's top ten bits on upload. Only a 10-bit (H.265/AV1) encoder takes this path.
413 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
414 if !self.pending.is_empty() {
415 return Err(Error::config(
416 "encode_16: pipelined frames pending; call flush first",
417 ));
418 }
419 if self.config.bit_depth != 10 {
420 return Err(Error::config(format!(
421 "encode_16: this encoder is configured for {} bits; call encode",
422 self.config.bit_depth
423 )));
424 }
425 self.check_size(frame.width, frame.height)?;
426 let input = self
427 .pool
428 .acquire()
429 .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
430 upload_16(&self.context, frame, input.surface(), self.coded_size)?;
431 self.encode_settled(Rc::clone(input.surface()), meta)
432 }
433
434 /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back,
435 /// no re-upload, just the decoder's picture handed straight to the
436 /// encoder as its source. This is the path a decode-then-encode pipeline
437 /// (e.g. a transcode) wants — the alternative is a full frame through
438 /// system memory and back for no reason.
439 ///
440 /// A source whose size differs from the encoder's coded size, or whose
441 /// depth differs from the encoder's, goes through the GPU video-processing
442 /// pipeline into an NV12 surface of the encoder's size first.
443 ///
444 /// Refused, rather than silently working around, when:
445 /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id
446 /// only means anything on the display that created it.
447 /// - `frame`'s bit depth is neither 8 nor 10.
448 pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result<CodedFrame> {
449 if !self.pending.is_empty() {
450 return Err(Error::config(
451 "encode_frame: pipelined frames pending; call flush first",
452 ));
453 }
454 if frame.bit_depth != 8 && frame.bit_depth != 10 {
455 return Err(Error::unsupported(
456 format!("encode_frame of a {}-bit source", frame.bit_depth),
457 "the VPP conversion this crate builds reads 8-bit NV12 and 10-bit P010 only",
458 ));
459 }
460 if !Rc::ptr_eq(frame.display(), self.context.display()) {
461 return Err(Error::config(
462 "encode_frame: the frame was decoded on a different Display than this encoder",
463 ));
464 }
465 let source =
466 if frame.bit_depth != self.config.bit_depth || frame.coded_size != self.coded_size {
467 self.vpp_into_pool(frame.surface(), frame.display_size)?
468 } else {
469 Rc::clone(frame.surface())
470 };
471 self.encode_settled(source, meta)
472 }
473
474 /// Encode a surface imported with [`ec_va::Surface::import_prime`] or
475 /// decoded elsewhere on this encoder's display: read by the GPU in place.
476 ///
477 /// The surface must be NV12, since H.264 is 8-bit only. A surface of another
478 /// size goes through the same GPU conversion as [`Encoder::encode_frame`];
479 /// `display_size` is the picture's visible size (its cropped size, when the
480 /// surface is padded to the codec's block size).
481 pub fn encode_surface<D: SurfaceMemoryDescriptor>(
482 &mut self,
483 surface: &Rc<ec_va::va::Surface<D>>,
484 display_size: (u32, u32),
485 meta: FrameMetadata,
486 ) -> Result<CodedFrame> {
487 if !self.pending.is_empty() {
488 return Err(Error::config(
489 "encode_surface: pipelined frames pending; call flush first",
490 ));
491 }
492 if surface.size() != self.coded_size {
493 let converted = self.vpp_into_pool(surface, display_size)?;
494 self.encode_settled(converted, meta)
495 } else {
496 self.encode_settled(Rc::clone(surface), meta)
497 }
498 }
499
500 fn check_size(&self, width: u32, height: u32) -> Result<()> {
501 if width != self.config.width || height != self.config.height {
502 return Err(Error::config(format!(
503 "encoder configured for {}x{} was given a {}x{} frame",
504 self.config.width, self.config.height, width, height
505 )));
506 }
507 Ok(())
508 }
509
510 /// Place a source surface's visible rect into this encoder's coded size,
511 /// in NV12, on the GPU: a whole-surface convert when the source is
512 /// already the encoder's coded size, a region copy/convert otherwise.
513 /// Builds the VPP pipeline and its two-surface pool on first use, painting
514 /// the pool black so any padding beyond `display_size` a region copy never
515 /// touches is deterministic.
516 fn vpp(&mut self) -> Result<&Vpp> {
517 if self.vpp.is_none() {
518 let spec = surface_spec(self.config.bit_depth, self.coded_size);
519 let display = Rc::clone(self.context.display());
520 let surfaces = ec_va::create_pool(&display, &spec, 2)?;
521 for s in &surfaces {
522 fill_black(&display, s, self.coded_size, self.config.bit_depth)?;
523 }
524 let vpp = Vpp::new(
525 &display,
526 VA_RT_FORMAT_YUV420 | VA_RT_FORMAT_YUV420_10,
527 self.coded_size.0,
528 self.coded_size.1,
529 )?;
530 self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect();
531 self.vpp = Some(vpp);
532 }
533 Ok(self.vpp.as_ref().expect("just built above if it was None"))
534 }
535
536 fn vpp_into_pool<D: SurfaceMemoryDescriptor>(
537 &mut self,
538 source: &ec_va::va::Surface<D>,
539 display_size: (u32, u32),
540 ) -> Result<Rc<Surface>> {
541 self.vpp()?;
542 let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]);
543 self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len();
544 let whole = display_size == self.coded_size;
545 let vpp = self.vpp()?;
546 if whole {
547 Ok(vpp.convert(source, dest)?)
548 } else {
549 let rect = (0, 0, display_size.0, display_size.1);
550 Ok(vpp.convert_region(source, rect, dest, rect)?)
551 }
552 }
553
554 /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`]
555 /// and [`Encoder::encode_surface`]: submit, then read back at once.
556 fn encode_settled<D: SurfaceMemoryDescriptor>(
557 &mut self,
558 source: Rc<ec_va::va::Surface<D>>,
559 meta: FrameMetadata,
560 ) -> Result<CodedFrame> {
561 let in_flight = self.submit_settled(source, meta, Vec::new())?;
562 self.finish(in_flight)
563 }
564
565 fn submit_settled<D: SurfaceMemoryDescriptor>(
566 &mut self,
567 source: Rc<ec_va::va::Surface<D>>,
568 meta: FrameMetadata,
569 mut leases: Vec<Rc<PooledSurface>>,
570 ) -> Result<InFlight<D>> {
571 if crate::reset::gpu_reset_epoch() != self.born_epoch {
572 return Err(Error::hw_reset(
573 "the GPU was reset after this encoder was created; its context is lost",
574 ));
575 }
576 let keyframe = meta.force_keyframe
577 || self.reference.is_none()
578 || self.gop_position >= self.config.gop_size.max(1);
579
580 let recon = self
581 .pool
582 .acquire()
583 .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?;
584
585 // 6 bits per pixel of headroom: an intra frame at a low quantiser is the
586 // worst case, and a coded buffer that overflows loses the picture.
587 let coded_bytes_len = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20);
588 let coded = ec_va::error::va_ok(
589 "vaCreateBuffer",
590 self.context.create_enc_coded(coded_bytes_len as usize),
591 )?;
592
593 let mut params = Vec::new();
594 match self.config.codec {
595 EncCodec::H264 => h264::parameters(self, &recon, coded.id(), keyframe, &mut params)?,
596 EncCodec::H265 => hevc::parameters(self, &recon, coded.id(), keyframe, &mut params)?,
597 EncCodec::Av1 => av1::parameters(self, &recon, coded.id(), keyframe, &mut params)?,
598 }
599 params.extend(self.rate_control_buffers()?);
600 let mut buffers = Vec::with_capacity(params.len());
601 for ty in params {
602 buffers.push(ec_va::picture::buffer(&self.context, ty)?);
603 }
604
605 let picture = ec_va::picture::submit(&self.context, Rc::clone(&source), buffers)?;
606 if let Some(previous) = self.reference.replace(recon) {
607 leases.push(previous);
608 }
609 if keyframe {
610 self.idr_count = self.idr_count.wrapping_add(1);
611 }
612 self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };
613 Ok(InFlight {
614 picture,
615 coded,
616 source,
617 leases,
618 timestamp: meta.timestamp,
619 keyframe,
620 })
621 }
622
623 fn finish<D: SurfaceMemoryDescriptor>(&mut self, f: InFlight<D>) -> Result<CodedFrame> {
624 crate::reset::sync_watched(&f.source)?;
625 let InFlight {
626 picture,
627 coded,
628 leases,
629 timestamp,
630 keyframe,
631 ..
632 } = f;
633 drop(picture);
634
635 let mut data = {
636 let mapped = ec_va::error::va_ok(
637 "vaMapBuffer",
638 ec_va::picture::MappedCodedBuffer::new(&coded),
639 )?;
640 let mut out = Vec::new();
641 for segment in mapped.segments() {
642 out.extend_from_slice(segment.buf);
643 }
644 out
645 };
646 if data.is_empty() {
647 return Err(Error::config("the encoder produced an empty coded buffer"));
648 }
649 self.track_rate(data.len());
650 if self.config.codec == EncCodec::Av1 {
651 // Every AV1 temporal unit begins with a temporal delimiter (5.6),
652 // and this driver emits none: its coded buffer starts at the
653 // sequence header. ffmpeg's demuxer refuses such a stream
654 // ("Missing Temporal Delimiter"), so the two bytes are prepended
655 // here rather than left to the caller.
656 data.splice(0..0, [0x12u8, 0x00]);
657 }
658 drop(coded);
659 drop(leases);
660 Ok(CodedFrame {
661 data,
662 timestamp,
663 is_keyframe: keyframe,
664 recovery: false,
665 })
666 }
667
668 fn steered_bitrate(&self) -> u32 {
669 self.rc.steered_bitrate(self.tunings.bitrate)
670 }
671
672 fn track_rate(&mut self, bytes: usize) {
673 if self.rc.track(bytes, self.config.rate_control, self.tunings) {
674 self.tunings_dirty = true;
675 }
676 }
677
678 /// The misc parameter buffers that carry rate control, resent when tuned.
679 fn rate_control_buffers(&mut self) -> Result<Vec<BufferType>> {
680 if !self.tunings_dirty {
681 return Ok(Vec::new());
682 }
683 self.tunings_dirty = false;
684 // VBR's `bits_per_second` is the peak, not the average: libva takes
685 // the average as `target_percentage` of it, so an average-rate ask
686 // becomes a 1.5x ceiling at 66%.
687 let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control {
688 RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0),
689 RateControlMode::ConstantBitrate => (0, 0, 0, self.steered_bitrate(), 100, 0),
690 RateControlMode::VariableBitrate => {
691 (0, 0, 0, self.steered_bitrate().saturating_mul(3) / 2, 66, 0)
692 }
693 RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality),
694 };
695 let rc_flags = RcFlags::new(0, 0, 0, 0, 0, 0, 0, 0, 0);
696 let mut out = vec![BufferType::EncMiscParameter(EncMiscParameter::RateControl(
697 EncMiscParameterRateControl::new(
698 bits,
699 target,
700 RATE_WINDOW_MS,
701 initial_qp,
702 min_qp,
703 0,
704 rc_flags,
705 0,
706 max_qp,
707 quality,
708 0,
709 ),
710 ))];
711 // libva packs a fractional rate as `den << 16 | num`, and a whole one
712 // as the plain numerator.
713 let num = self.tunings.framerate.0.max(1);
714 let den = self.tunings.framerate.1.max(1);
715 let packed = if den <= 1 {
716 num
717 } else {
718 (den << 16) | (num & 0xffff)
719 };
720 out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(
721 EncMiscParameterFrameRate::new(packed, 0),
722 )));
723 if self.config.quality > 0 {
724 out.push(BufferType::EncMiscParameter(EncMiscParameter::QualityLevel(
725 EncMiscParameterBufferQualityLevel::new(self.config.quality),
726 )));
727 }
728 if bits > 0 && !self.rc.take_steered() {
729 // The buffer starts full. Starting at three quarters full cost a
730 // quarter of a window of budget: radeonsi then spent 12.5% under the
731 // ask on a 2 s clip, and the gap is exactly that quarter over the
732 // clip length (measured, 2026-10-16). Its size: see `hrd_buffer_ms`.
733 let buffer_ms = u64::from(hrd_buffer_ms(&self.config));
734 let hrd_bits = (u64::from(bits) * buffer_ms / 1000) as u32;
735 out.push(BufferType::EncMiscParameter(EncMiscParameter::HRD(
736 EncMiscParameterHRD::new(hrd_bits, hrd_bits),
737 )));
738 }
739 Ok(out)
740 }
741
742 /// Append one packed header: its parameter buffer, then its bytes.
743 ///
744 /// Both go in the same picture, in this order, which is what the driver
745 /// reads them in (`va.h:2446`).
746 pub(crate) fn push_packed(
747 &self,
748 packed: &headers::Packed,
749 out: &mut Vec<BufferType>,
750 ) -> Result<()> {
751 let kind = match packed.kind {
752 headers::PACKED_HEADER_SEQUENCE => EncPackedHeaderType::Sequence,
753 headers::PACKED_HEADER_PICTURE => EncPackedHeaderType::Picture,
754 headers::PACKED_HEADER_SLICE => EncPackedHeaderType::Slice,
755 other => {
756 return Err(Error::config(format!("unknown packed header kind {other}")));
757 }
758 };
759 out.push(BufferType::EncPackedHeaderParameter(
760 EncPackedHeaderParameter::new(kind, packed.bits, true),
761 ));
762 out.push(BufferType::EncPackedHeaderData(packed.bytes.clone()));
763 Ok(())
764 }
765
766 pub(crate) fn context(&self) -> &Rc<Context> {
767 &self.context
768 }
769
770 pub(crate) fn config(&self) -> &EncoderConfig {
771 &self.config
772 }
773
774 pub(crate) fn reference(&self) -> Option<&Rc<PooledSurface>> {
775 self.reference.as_ref()
776 }
777
778 pub(crate) fn gop_position(&self) -> u32 {
779 self.gop_position
780 }
781
782 /// Key frames submitted before the picture now being coded (the count is
783 /// bumped once a picture is submitted), so the first IDR reads 0.
784 pub(crate) fn idr_count(&self) -> u32 {
785 self.idr_count
786 }
787
788 /// The VA profile this encoder was configured with.
789 pub fn profile(&self) -> Profile {
790 self.profile
791 }
792}
793
794/// The surface format an encoder of `bit_depth` works in.
795fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec {
796 let spec = if bit_depth == 10 {
797 SurfaceSpec::p010(size.0, size.1)
798 } else {
799 SurfaceSpec::nv12(size.0, size.1)
800 };
801 spec.with_usage_hint(VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER)
802}
803
804/// The image fourcc matching `bit_depth`.
805fn fourcc(bit_depth: u8) -> u32 {
806 if bit_depth == 10 {
807 VA_FOURCC_P010
808 } else {
809 VA_FOURCC_NV12
810 }
811}
812
813/// Copy `surface`'s image through `fill`, then write it back.
814///
815/// cros-libva writes a mutated image back to the surface when the image is
816/// dropped (`vaPutImage`), so `fill` runs against the image's own bytes and
817/// the write-back happens at the end of this function.
818fn write_surface<D: SurfaceMemoryDescriptor>(
819 display: &Display,
820 surface: &ec_va::va::Surface<D>,
821 fourcc: u32,
822 size: (u32, u32),
823 fill: impl FnOnce(&VAImage, &mut [u8]),
824) -> Result<()> {
825 if let Ok(mut image) = ec_va::va::Image::derive_from(surface, size)
826 && image.image().format.fourcc == fourcc
827 {
828 let layout = *image.image();
829 fill(&layout, AsMut::<[u8]>::as_mut(&mut image));
830 return Ok(());
831 }
832 let format = ec_va::surface::image_format(display, fourcc)?;
833 let mut image = ec_va::surface::create_image(surface, format, size, size)?;
834 let layout = *image.image();
835 fill(&layout, AsMut::<[u8]>::as_mut(&mut image));
836 Ok(())
837}
838
839/// Upload one frame into a surface as NV12.
840fn upload(context: &Rc<Context>, frame: &I420, surface: &Surface, coded: (u32, u32)) -> Result<()> {
841 let display: &Display = context.display();
842 let (w, h) = (frame.width as usize, frame.height as usize);
843 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
844 write_surface(display, surface, VA_FOURCC_NV12, coded, |layout, data| {
845 let y_pitch = layout.pitches[0] as usize;
846 let uv_pitch = layout.pitches[1] as usize;
847 let y_base = layout.offsets[0] as usize;
848 let uv_base = layout.offsets[1] as usize;
849 // The two planes are written in turn; the loops are the interleave
850 // `i420_to_nv12` does for callers that own both buffers.
851 for row in 0..h {
852 let d = y_base + row * y_pitch;
853 if let Some(dst) = data.get_mut(d..d + w) {
854 dst.copy_from_slice(&frame.y[row * w..row * w + w]);
855 } else {
856 break;
857 }
858 }
859 for row in 0..ch {
860 let d = uv_base + row * uv_pitch;
861 let Some(dst) = data.get_mut(d..d + cw * 2) else {
862 break;
863 };
864 for col in 0..cw {
865 dst[col * 2] = frame.u[row * cw + col];
866 dst[col * 2 + 1] = frame.v[row * cw + col];
867 }
868 }
869 })
870}
871
872/// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the
873/// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a
874/// region copy's untouched padding reads the same deterministic value on
875/// every driver instead of whatever the fresh allocation contained.
876fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> {
877 write_surface(display, surface, fourcc(bit_depth), size, |layout, data| {
878 // P010 carries the sample in the top ten bits, so black is the 8-bit
879 // value shifted up by six, little endian.
880 let samples = |eight: u8| -> Vec<u8> {
881 if bit_depth == 8 {
882 vec![eight]
883 } else {
884 (u16::from(eight) << 6).to_le_bytes().to_vec()
885 }
886 };
887 for (plane, value, rows) in [
888 (0usize, 16u8, size.1 as usize),
889 (1, 128, size.1 as usize / 2),
890 ] {
891 let pitch = layout.pitches[plane] as usize;
892 let base = layout.offsets[plane] as usize;
893 let unit = samples(value);
894 let width = size.0 as usize * unit.len();
895 for row in 0..rows {
896 let start = base + row * pitch;
897 if let Some(line) = data.get_mut(start..start + width) {
898 for px in line.chunks_exact_mut(unit.len()) {
899 px.copy_from_slice(&unit);
900 }
901 }
902 }
903 }
904 })
905}
906
907fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> {
908 write_surface(display, surface, fourcc(bit_depth), size, |_, data| {
909 data.fill(0)
910 })
911}
912
913fn zero_padding<D: SurfaceMemoryDescriptor>(
914 display: &Display,
915 surface: &ec_va::va::Surface<D>,
916 bit_depth: u8,
917 (w, h): (u32, u32),
918 coded: (u32, u32),
919) -> Result<()> {
920 if (w, h) == coded {
921 return Ok(());
922 }
923 let (fourcc, px) = if bit_depth > 8 {
924 (VA_FOURCC_P010, 2)
925 } else {
926 (VA_FOURCC_NV12, 1)
927 };
928 let (w, h, cw, ch) = (
929 w as usize * px,
930 h as usize,
931 coded.0 as usize * px,
932 coded.1 as usize,
933 );
934 write_surface(display, surface, fourcc, coded, |layout, data| {
935 for (plane, rows, last, start) in [
936 (0, h, ch, w),
937 (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)),
938 ] {
939 let pitch = layout.pitches[plane] as usize;
940 let base = layout.offsets[plane] as usize;
941 for row in 0..last {
942 let from = if row < rows { start } else { 0 };
943 if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw)
944 {
945 dst.fill(0);
946 }
947 }
948 }
949 })
950}
951
952/// Upload one 10-bit frame into a surface as P010: samples move from the low
953/// ten bits of the caller's `u16` into P010's top ten.
954fn upload_16(
955 context: &Rc<Context>,
956 frame: &I420_16,
957 surface: &Surface,
958 coded: (u32, u32),
959) -> Result<()> {
960 let display: &Display = context.display();
961 let (w, h) = (frame.width as usize, frame.height as usize);
962 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
963 write_surface(display, surface, VA_FOURCC_P010, coded, |layout, data| {
964 let y_pitch = layout.pitches[0] as usize;
965 let uv_pitch = layout.pitches[1] as usize;
966 let y_base = layout.offsets[0] as usize;
967 let uv_base = layout.offsets[1] as usize;
968 for row in 0..h {
969 let d = y_base + row * y_pitch;
970 let Some(dst) = data.get_mut(d..d + w * 2) else {
971 break;
972 };
973 for col in 0..w {
974 let v = (frame.y[row * w + col] & 0x3ff) << 6;
975 dst[col * 2..col * 2 + 2].copy_from_slice(&v.to_le_bytes());
976 }
977 }
978 for row in 0..ch {
979 let d = uv_base + row * uv_pitch;
980 let Some(dst) = data.get_mut(d..d + cw * 4) else {
981 break;
982 };
983 for col in 0..cw {
984 let u = (frame.u[row * cw + col] & 0x3ff) << 6;
985 let v = (frame.v[row * cw + col] & 0x3ff) << 6;
986 dst[col * 4..col * 4 + 2].copy_from_slice(&u.to_le_bytes());
987 dst[col * 4 + 2..col * 4 + 4].copy_from_slice(&v.to_le_bytes());
988 }
989 }
990 })
991}
992
993#[cfg(test)]
994mod tests {
995 use super::*;
996
997 #[test]
998 fn default_profile_is_high() {
999 assert_eq!(H264Profile::default(), H264Profile::High);
1000 }
1001}