forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

lib.rs2173 lines, 92.0 KiBHistoryRawDownload
1//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV1
2//! where the GPU has an entrypoint for it), shipped as a
3//! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
4//! libva/gbm/drm. Every entry point is
5//! `extern "C"`, catches unwinds and reports failure as a null pointer or a
6//! negative code: the caller's contract is "any failure means use the software
7//! codec".
8//!
9//! That guarantee rests on `panic = "unwind"`, and it has a floor it can never
10//! reach whatever the panic strategy is: Mesa runs its own C worker threads and
11//! calls libc `abort()` from them when the video ring resets (measured
12//! 2026-08-13, `vcn_unified_0`, mesa 26.1.6). No `catch_unwind` can see a
13//! foreign thread's `abort`. So no *encode* entry point of this plugin is
14//! called in the editor's process any more: the editor still `dlopen`s the
15//! library to see whether the `vh_enc_*` symbols are there at all, which opens
16//! no VA-API display and starts no driver thread, and every call through them is
17//! made by the `hw-encode-child` helper, one process per session. A driver that
18//! aborts now costs an export its seat rather than costing a person their
19//! session ([`engine::hwproc`](../engine/hwproc/index.html)).
20//!
21//! corner-cut: *decode* is still in the editor's own address space, where the
22//! same abort would still be fatal -- and the same ring hangs it (mmhub page
23//! faults, this box, 2026-08-13). The upgrade path is the seam that already
24//! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in
25//! `hwproc` and let the same helper hold both.
26
27mod slice_fix;
28
29use std::collections::VecDeque;
30use std::ffi::{CStr, c_char, c_void};
31use std::os::fd::IntoRawFd;
32use std::panic::{AssertUnwindSafe, catch_unwind};
33use std::path::{Path, PathBuf};
34use std::rc::Rc;
35
36use cros_codecs::backend::vaapi::decoder::VaapiBackend;
37use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
38use cros_codecs::codec::av1::parser::Profile as Av1Profile;
39use cros_codecs::codec::h264::parser::Profile as H264Profile;
40use cros_codecs::codec::h265::parser::Profile as H265Profile;
41use cros_codecs::decoder::stateless::av1::Av1;
42use cros_codecs::decoder::stateless::h264::H264;
43use cros_codecs::decoder::stateless::h265::H265;
44use cros_codecs::decoder::stateless::vp9::Vp9;
45use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
46use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
47use cros_codecs::encoder::av1::EncoderConfig as Av1Config;
48use cros_codecs::encoder::h264::EncoderConfig as H264Config;
49use cros_codecs::encoder::h265::ColourDescription as H265Colour;
50use cros_codecs::encoder::h265::EncoderConfig as H265Config;
51use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder;
52use cros_codecs::encoder::stateless::h264::StatelessEncoder;
53use cros_codecs::encoder::stateless::h265::StatelessEncoder as H265StatelessEncoder;
54use cros_codecs::encoder::{
55 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
56};
57use cros_codecs::image_processing::nv12_to_i420;
58use cros_codecs::libva::{
59 Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat,
60 VAProfile,
61};
62use cros_codecs::video_frame::VideoFrame;
63use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
64use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
65use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
66use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
67use gbm::{BufferObjectFlags, Format as GbmFormat};
68
69use engine::demux::{Codec, Demuxer};
70use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta};
71
72type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
73type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
74type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle;
75
76/// One decoder per codec the demuxer can hand us. They all share the VA-API
77/// backend and therefore the same [`Handle`], so everything past `decode` is
78/// common; which one exists is decided by the container, never by the caller --
79/// which is why the plugin's C ABI is unchanged and an older `libengine_hw.so`
80/// still loads and still decodes H.264 (it simply refuses the newer codecs'
81/// files at `Demuxer`).
82///
83/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0 and 2, AV1
84/// Main at either depth.
85/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit
86/// I420 every frame here is ([`Session::emit`]).
87///
88/// corner-cut: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample
89/// interface all the way to the renderer. That costs the low two bits of a Main
90/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every
91/// stage between here and the texture upload, not to this file.
92/// VP9 profile 2 reaches the P010 pool like the rest: a VP9 stream states its
93/// depth in no container record the way an `av1C` or an `hvcC` does, so
94/// `Demuxer` reads it off the first keyframe's uncompressed header
95/// (`demux::vp9_bit_depth`) rather than assuming the 8 bits of profile 0.
96enum Decoder {
97 H264(Dec<H264>),
98 Hevc(Dec<H265>),
99 Vp9(Dec<Vp9>),
100 Av1(Dec<Av1>),
101}
102
103impl Decoder {
104 fn get(&mut self) -> &mut dyn StatelessVideoDecoder<Handle = Handle> {
105 match self {
106 Self::H264(d) => d,
107 Self::Hevc(d) => d,
108 Self::Vp9(d) => d,
109 Self::Av1(d) => d,
110 }
111 }
112}
113
114type Encoder = StatelessEncoder<
115 GenericDmaVideoFrame,
116 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
117>;
118type Av1Encoder = Av1StatelessEncoder<
119 GenericDmaVideoFrame,
120 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
121>;
122type HevcEncoder = H265StatelessEncoder<
123 GenericDmaVideoFrame,
124 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
125>;
126
127/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
128/// mode should always either hand back an event or accept input; this only
129/// exists so a misbehaving driver returns an error instead of hanging the app.
130const STALL_LIMIT: u32 = 10_000;
131
132/// How many undecodable access units a seek may drop before the session gives
133/// up and calls the stream broken. An open GOP's leading pictures are a handful
134/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one
135/// we restarted in the middle of, so the error is real and the caller still
136/// hears it.
137const LEADING_LIMIT: u32 = 64;
138
139/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and
140/// therefore how many extra buffers the pool reserves the moment a caller asks
141/// for one. The export's decode channel is two pictures deep and it encodes the
142/// one it is holding, so at most four are ever outstanding; the rest is margin,
143/// at ~3 MB of video memory each.
144const DMA_HOLD: usize = 6;
145
146/// How far ahead of the decode position [`Session::seek_to`] walks forward
147/// rather than flushing, in seconds of the stream's own frames. A silence cut
148/// lands the next span ahead of the decoder by the length of what it removed
149/// -- tenths of a second -- and walking that forward costs only the decode of
150/// the frames in between, dropped without the read-back ([`Session::pump`]'s
151/// skip path) with the decoder's reference chain and pipeline depth left
152/// standing. The flush it replaces costs a decoder reset, a demuxer seek to
153/// the random access point, up to a group of skip-decoded pictures behind it,
154/// and a full re-prime before the first frame is out again (~178 ms measured
155/// at 4K, which is longer than the clips a silence cut leaves); past half a
156/// second of walking, the skip-decode run alone approaches that bill and a
157/// real seek wins.
158const FORWARD_SECS: f64 = 0.5;
159
160/// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate.
161/// `0` for a rate the stream does not really state, which is "never forward"
162/// -- exactly the flush every reposition did before this distinction existed.
163fn forward_limit(frame_rate: f64) -> u32 {
164 (FORWARD_SECS * frame_rate).round().max(0.) as u32
165}
166
167/// How a reposition to `target` (a 0-based display frame) is reached from
168/// `position`, the frame the session would hand out next. Pure arithmetic,
169/// so every shape of the answer is testable without a GPU.
170#[derive(Debug, PartialEq, Eq, Clone, Copy)]
171enum Reposition {
172 /// Decode forward from where the session stands, dropping this many
173 /// pictures on the way: no flush, no demuxer seek, no re-prime.
174 Forward(u32),
175 /// Flush the decoder and seek the demuxer to the random access point at
176 /// or before `target`.
177 Flush,
178}
179
180fn reposition(position: i64, target: i64, frame_count: u32, limit: u32) -> Reposition {
181 // A decoder cannot walk backwards, and a target at or past the last frame
182 // is not one decoding forward can hand out -- both take the seek that has
183 // always handled them, EOF included.
184 if target < position || target >= i64::from(frame_count) {
185 return Reposition::Flush;
186 }
187 match u32::try_from(target - position) {
188 Ok(ahead) if ahead <= limit => Reposition::Forward(ahead),
189 _ => Reposition::Flush,
190 }
191}
192
193/// The skip a forward reposition leaves standing: `ahead` itself, replacing
194/// whatever skip was undrained -- `_standing` is read by no one, on purpose.
195/// [`Session::pump`] advances `position` for every handle it pops, dropped
196/// and delivered alike, so the next picture delivered is always
197/// `position + skip`: only a replacement keeps that on the target. An
198/// accumulate would land `ahead` frames past it -- and silently, because the
199/// pictures keep arriving (a stacked reseek before the first drains, or a
200/// flush whose RAP skip is still standing when a forward span is asked).
201fn forward_skip(_standing: u32, ahead: u32) -> u32 {
202 ahead
203}
204
205struct Session {
206 decoder: Decoder,
207 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
208 /// queried once at open.
209 nv12_format: VAImageFormat,
210 /// Whether the surfaces are P010 rather than NV12, which is the one thing
211 /// the read-back has to do differently.
212 ten_bit: bool,
213 pool: FramePool<GenericDmaVideoFrame>,
214 demuxer: Demuxer,
215 meta: VhMeta,
216 ready: VecDeque<Handle>,
217 /// Remaining bytes of the access unit currently being fed, if any.
218 pending: Vec<u8>,
219 timestamp: u64,
220 flushed: bool,
221 /// Pictures still to be decoded and thrown away to land on a seek target.
222 skip: u32,
223 /// The display frame the next `pump` would hand out, however it gets
224 /// there: one further along for every handle taken off `ready`, skipped
225 /// past and delivered alike. The one thing that can tell a reposition
226 /// *ahead* of the decoder from one behind it ([`Session::seek_to`]).
227 position: i64,
228 /// Access units dropped because they referenced pictures this session never
229 /// decoded -- see [`Session::pump`]. Counted rather than flagged so the
230 /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a
231 /// picture is handed out, which is where the window closes.
232 leading: u32,
233 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
234 /// which is exactly why the pointers are only valid until the next call.
235 out: Vec<u8>,
236 luma: usize,
237 chroma: usize,
238 /// What the caller's encoder can read straight off the GPU, asked once per
239 /// [`vh_next_frame_dma`] call and `None` for every read-back caller.
240 want: Option<VhDma>,
241 /// The descriptor the last such call produced, its file descriptor already
242 /// belonging to the caller. `None` says that picture was read back instead.
243 dma: Option<VhDma>,
244 /// Pictures handed out as DRM-PRIME buffers, newest last: the pool takes a
245 /// buffer back the moment its handle drops, and the decoder would write the
246 /// next picture straight into the one an encoder is still reading. Bounded
247 /// by [`Session::hold`], which is what the pool reserved for it.
248 held: VecDeque<Handle>,
249 /// Extra pool buffers reserved for [`Session::held`]: [`DMA_HOLD`] once a
250 /// caller has asked for a buffer *before* the pool was sized, and 0
251 /// otherwise -- a session whose pool is already sized may not hold anything
252 /// back, because those buffers are the decoder's own.
253 hold: usize,
254 /// Whether the pool has been sized, which happens once, at the first
255 /// `FormatChanged`.
256 sized: bool,
257}
258
259/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
260/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
261/// linear single-plane R8 buffer big enough for luma + chroma and describe the
262/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
263/// with two planes at known offsets, which is exactly what the descriptor in
264/// `GenericDmaVideoFrame` emits.
265///
266/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0
267/// shape with 16-bit samples, so the buffer is simply twice as wide.
268fn alloc_nv12(
269 gbm: &gbm::Device<std::fs::File>,
270 coded: Resolution,
271 ten_bit: bool,
272) -> Result<GenericDmaVideoFrame, String> {
273 let rows = coded.height + coded.height.div_ceil(2);
274 let width = coded.width * if ten_bit { 2 } else { 1 };
275 let bo = gbm
276 .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
277 .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?;
278 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
279 let fd = bo.fd().map_err(|e| e.to_string())?;
280 GenericDmaVideoFrame::new(
281 vec![std::fs::File::from(fd)],
282 nv12_layout(coded, pitch, ten_bit),
283 )
284}
285
286/// Two NV12 (or P010) planes packed one after the other in a single buffer
287/// object.
288fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout {
289 FrameLayout {
290 format: (
291 Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }),
292 0, /* DRM_FORMAT_MOD_LINEAR */
293 ),
294 size: coded,
295 planes: vec![
296 PlaneLayout {
297 buffer_index: 0,
298 offset: 0,
299 stride: pitch,
300 },
301 PlaneLayout {
302 buffer_index: 0,
303 offset: pitch * coded.height as usize,
304 stride: pitch,
305 },
306 ],
307 }
308}
309
310/// First render node that gives us both a VA display and a GBM device. Which
311/// node is the right one is a per-machine question, so we probe rather than
312/// hardcode renderD128.
313fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
314 let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
315 .ok()?
316 .flatten()
317 .map(|e| e.path())
318 .filter(|p| {
319 p.file_name()
320 .and_then(|n| n.to_str())
321 .is_some_and(|n| n.starts_with("renderD"))
322 })
323 .collect();
324 nodes.sort();
325 nodes.into_iter().find_map(|node| {
326 let display = Display::open_drm_display(&node).ok()?;
327 let file = std::fs::OpenOptions::new()
328 .read(true)
329 .write(true)
330 .open(&node)
331 .ok()?;
332 let gbm = gbm::Device::new(file).ok()?;
333 Some((display, gbm))
334 })
335}
336
337impl Session {
338 fn open(path: &Path) -> Option<Self> {
339 let (meta, demuxer) = Demuxer::open(path).ok()?;
340 let (display, gbm) = open_devices()?;
341 // A 10-bit stream decodes into P010 surfaces and is read back through a
342 // P010 image; a driver that has no such image format is one this cannot
343 // read 10-bit off at all, which is a null session and a software
344 // fallback like any other refusal here.
345 let ten_bit = demuxer.bit_depth() > 8;
346 let want = if ten_bit {
347 VA_FOURCC_P010
348 } else {
349 VA_FOURCC_NV12
350 };
351 let nv12_format = display
352 .query_image_formats()
353 .ok()?
354 .into_iter()
355 .find(|f| f.fourcc == want)?;
356 let decoder = match meta.codec {
357 Codec::H264 => {
358 Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?)
359 }
360 Codec::Hevc => {
361 Decoder::Hevc(Dec::<H265>::new_vaapi(display, BlockingMode::Blocking).ok()?)
362 }
363 Codec::Vp9 => {
364 Decoder::Vp9(Dec::<Vp9>::new_vaapi(display, BlockingMode::Blocking).ok()?)
365 }
366 Codec::Av1 => {
367 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
368 }
369 };
370 let pool = FramePool::new(move |info: &StreamInfo| {
371 alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")
372 });
373 Some(Self {
374 decoder,
375 nv12_format,
376 ten_bit,
377 pool,
378 demuxer,
379 meta: VhMeta {
380 width: meta.width,
381 height: meta.height,
382 frame_rate: meta.frame_rate,
383 frame_count: meta.frame_count,
384 },
385 ready: VecDeque::new(),
386 pending: Vec::new(),
387 timestamp: 0,
388 flushed: false,
389 skip: 0,
390 position: 0,
391 // A stream read from its own beginning has no missing references
392 // and therefore no leading pictures to forgive: the window opens
393 // only for a session positioned somewhere else ([`Session::open_at`]),
394 // so a file whose first picture will not decode is still refused at
395 // the door rather than opening onto nothing.
396 leading: LEADING_LIMIT,
397 out: Vec::new(),
398 luma: 0,
399 chroma: 0,
400 want: None,
401 dma: None,
402 held: VecDeque::new(),
403 hold: 0,
404 sized: false,
405 })
406 }
407
408 /// As [`Session::open`], but positioned so the first picture handed out is
409 /// sample `target_sample` (1-based): decode restarts at the sync sample at
410 /// or before it and the pictures in between are dropped unread.
411 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
412 let mut session = Self::open(path)?;
413 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
414 // display frames -- and answers with a signed one, since a sync sample
415 // inside what the edit list trims sits before frame 0.
416 let target_frame = target_sample.saturating_sub(1);
417 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
418 session.skip = (i64::from(target_frame) - first).max(0) as u32;
419 session.position = first;
420 if target_frame > 0 {
421 session.leading = 0;
422 }
423 Some(session)
424 }
425
426 /// Repositions an **open** session, exactly as [`Session::open_at`] positions
427 /// a new one: the next [`Session::pump`] hands back sample `target_sample`.
428 ///
429 /// This is what a seek costs when the session is kept, and most of it is
430 /// skippable: a target *ahead* of where the decoder stands, within
431 /// [`FORWARD_SECS`] of it, is reached by decoding on and dropping the
432 /// pictures in between ([`reposition`]) -- no flush, no demuxer seek, no
433 /// re-prime -- which is the landing a silence cut leaves at every boundary
434 /// it cuts to, a fraction of a second ahead of the clip that just ended.
435 /// Everything else pays the demuxer seek and the decoder flush, and *not*
436 /// the VA-API initialisation (~90 ms measured), the render node probe, the
437 /// container parse and the surface pool that opening one again pays for.
438 ///
439 /// The flush is the whole of the decoder's reset: cros-codecs finishes what
440 /// is in flight and goes to `Reset`, from where it resumes on the next
441 /// parameter set or key frame -- and every sync sample this demuxer hands
442 /// out carries the parameter sets in front of it (`demux`'s `is_sync`
443 /// re-injection), which is exactly where a seek lands. The pictures the
444 /// flush makes ready are dropped with `ready`: they belong to where the
445 /// session *was*.
446 fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
447 // The same arithmetic `open_at` does, for the same reason.
448 let target_frame = target_sample.saturating_sub(1);
449 if let Reposition::Forward(ahead) = reposition(
450 self.position,
451 i64::from(target_frame),
452 self.meta.frame_count,
453 forward_limit(self.meta.frame_rate),
454 ) {
455 // Nothing about the session moves but the skip: not the decoder,
456 // not the access unit half-fed to it, not the pictures already
457 // waiting in `ready` -- the skip walks past all of them exactly
458 // as it walks past the ones still to decode, one `position` step
459 // per handle either way. It *replaces* whatever skip was
460 // standing, never adds to it: `position` already counts every
461 // handle popped, dropped ones included, so the picture delivered
462 // is always `position + skip` ([`forward_skip`]) -- an accumulate
463 // would land `ahead` frames past the target, silently.
464 self.skip = forward_skip(self.skip, ahead);
465 return Ok(());
466 }
467 self.decoder.get().flush().map_err(|e| e.to_string())?;
468 // Drain what the flush completed, dropping every handle: each one holds
469 // a pool buffer out of circulation, and none of them is ours to show.
470 while let Some(event) = self.decoder.get().next_event() {
471 if let DecoderEvent::FormatChanged = event {
472 let info = self
473 .decoder
474 .get()
475 .stream_info()
476 .ok_or("format changed without stream info")?
477 .clone();
478 self.pool.resize(&info);
479 }
480 }
481 self.ready.clear();
482 self.pending.clear();
483 self.flushed = false;
484 let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
485 self.skip = (i64::from(target_frame) - first).max(0) as u32;
486 self.position = first;
487 // ...and the same open-GOP window: a session positioned anywhere but the
488 // start may meet leading pictures that reference what it never decoded.
489 self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT };
490 Ok(())
491 }
492
493 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
494 fn pump(&mut self) -> Result<bool, String> {
495 let mut stalls = 0u32;
496 loop {
497 // Stop draining as soon as we have a picture: every handle we hold
498 // keeps a pool buffer out of circulation.
499 while self.ready.is_empty() {
500 match self.decoder.get().next_event() {
501 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
502 Some(DecoderEvent::FormatChanged) => {
503 let mut info = self
504 .decoder
505 .get()
506 .stream_info()
507 .ok_or("format changed without stream info")?
508 .clone();
509 // The buffers a caller may hold on to are *extra*: the
510 // count the decoder asks for is what it needs to keep
511 // decoding, and lending one of those out is a stall.
512 info.min_num_frames += self.hold;
513 self.pool.resize(&info);
514 self.sized = true;
515 }
516 None => break,
517 }
518 }
519 if let Some(handle) = self.ready.pop_front() {
520 // One picture further along, shown or skipped past alike:
521 // this is the only place [`Session::position`] walks.
522 self.position += 1;
523 // Seek discards: dropping the handle skips the `vaGetImage`
524 // read-back (~1.2 ms/picture) and frees its pool buffer.
525 if self.skip > 0 {
526 self.skip -= 1;
527 continue;
528 }
529 self.deliver(handle);
530 // Past the random access point's leading pictures: a decode
531 // error from here on is a real one again.
532 self.leading = LEADING_LIMIT;
533 return Ok(true);
534 }
535 if self.flushed {
536 return Ok(false);
537 }
538
539 if self.pending.is_empty() {
540 match self.demuxer.next_access_unit() {
541 Ok(Some(au)) => self.pending = au,
542 Ok(None) => {
543 self.decoder.get().flush().map_err(|e| e.to_string())?;
544 self.flushed = true;
545 continue;
546 }
547 Err(e) => return Err(e.to_string()),
548 }
549 }
550
551 let Self {
552 decoder,
553 pool,
554 pending,
555 timestamp,
556 leading,
557 ..
558 } = self;
559 match decoder
560 .get()
561 .decode(*timestamp, pending, &mut || pool.alloc())
562 {
563 Ok(0) => return Err("decoder consumed no input".into()),
564 Ok(n) => {
565 pending.drain(..n.min(pending.len()));
566 if pending.is_empty() {
567 *timestamp += 1;
568 }
569 stalls = 0;
570 }
571 // Both mean "handle pending events, then resubmit the same data".
572 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
573 stalls += 1;
574 if stalls > STALL_LIMIT {
575 return Err("decoder stalled waiting for output buffers".into());
576 }
577 }
578 // A picture that references pictures we never decoded, which is
579 // what an open GOP's leading pictures are after a seek: they
580 // display *before* the random access point we restarted at, so
581 // they are not ours to show and the stream is not broken. Drop
582 // the rest of the access unit (they are picture-aligned) and
583 // walk on -- failing here is what used to make a Blu-ray remux
584 // fall back to software on 17 seeks out of 20.
585 Err(e) if *leading < LEADING_LIMIT => {
586 if *leading == 0 {
587 eprintln!("engine_hw: skipping leading pictures after seek ({e})");
588 }
589 *leading += 1;
590 pending.clear();
591 *timestamp += 1;
592 }
593 Err(e) => return Err(e.to_string()),
594 }
595 }
596 }
597
598 /// Hands one decoded picture to the caller: as the buffer it was decoded
599 /// into where that is what the caller asked for and the encoder on the
600 /// other side can read it, and as read-back I420 everywhere else.
601 fn deliver(&mut self, handle: Handle) {
602 self.dma = None;
603 if self.hold > 0 && let Some(dma) = self.export_dma(&handle) {
604 self.meta.width = dma.width;
605 self.meta.height = dma.height;
606 self.dma = Some(dma);
607 // Kept out of the pool until the caller is [`DMA_HOLD`] pictures
608 // past it, by which time nothing is reading it any more.
609 self.held.push_back(handle);
610 while self.held.len() > self.hold {
611 self.held.pop_front();
612 }
613 return;
614 }
615 self.emit(handle);
616 }
617
618 /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the
619 /// caller's encoder takes -- one composed two-plane layer in at most two
620 /// objects, the fourcc and both sizes it asked for. `None` for every other
621 /// answer, and the caller then gets the pixels it always got rather than a
622 /// failure.
623 fn export_dma(&self, handle: &Handle) -> Option<VhDma> {
624 let want = self.want?;
625 let res = handle.display_resolution();
626 if (res.width, res.height) != (want.width, want.height) {
627 return None;
628 }
629 // Cheap no-op in blocking mode, but the encoder must never read a
630 // surface the decoder has not finished writing.
631 let _ = DecodedHandle::sync(handle);
632 let borrowed = handle.borrow();
633 // The *display* surface for the same reason [`Session::emit`] reads it:
634 // an AV1 picture with film grain is displayed from a second surface.
635 let mut desc = borrowed.display_surface().export_prime().ok()?;
636 let layer = desc.layers.first()?;
637 if desc.layers.len() != 1
638 || layer.num_planes != 2
639 || desc.fourcc != want.fourcc
640 || desc.width != want.coded_width
641 || desc.height != want.coded_height
642 {
643 return None;
644 }
645 // Whatever the driver says the two planes live in, said back to it
646 // unchanged on the import: radeonsi answers with an object per plane,
647 // other drivers with one for both, and neither is ours to reinterpret.
648 let (offset, stride) = (
649 [layer.offset[0], layer.offset[1]],
650 [layer.pitch[0], layer.pitch[1]],
651 );
652 let planes = [layer.object_index[0] as usize, layer.object_index[1] as usize];
653 if planes[0] != 0 || planes[1] > 1 || desc.objects.len() != planes[1] + 1 {
654 return None;
655 }
656 let modifier = desc.objects[0].drm_format_modifier;
657 // Handed over with the descriptor: the caller closes them.
658 let second = (planes[1] == 1)
659 .then(|| desc.objects.pop().map(|object| object.fd.into_raw_fd()))
660 .flatten()
661 .unwrap_or(-1);
662 let first = desc.objects.remove(0).fd.into_raw_fd();
663 Some(VhDma {
664 fd: [first, second],
665 fourcc: desc.fourcc,
666 modifier,
667 coded_width: desc.width,
668 coded_height: desc.height,
669 width: res.width,
670 height: res.height,
671 offset,
672 stride,
673 })
674 }
675
676 /// Copies a decoded NV12 surface into `self.out` as packed I420.
677 fn emit(&mut self, handle: Handle) {
678 let res = handle.display_resolution();
679 let (w, h) = (res.width as usize, res.height as usize);
680 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
681 if self.luma != w * h || self.chroma != cw * ch {
682 self.luma = w * h;
683 self.chroma = cw * ch;
684 self.out = vec![0u8; self.luma + 2 * self.chroma];
685 }
686 self.meta.width = res.width;
687 self.meta.height = res.height;
688
689 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
690 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
691 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
692 // driver copies into host-visible memory for us instead.
693 // Cheap no-op in blocking mode, but pixels must never be read early.
694 let _ = DecodedHandle::sync(&handle);
695 let borrowed = handle.borrow();
696 let size = (w as u32, h as u32);
697 // The *display* surface, which is the reconstructed picture for every
698 // codec here but the second, grain-synthesized one for an AV1 frame that
699 // asks for film grain -- reading the reconstructed surface of such a
700 // frame would show the film with its grain stripped off.
701 let image = Image::create_from(borrowed.display_surface(), self.nv12_format, size, size)
702 .expect("vaGetImage failed");
703 let va = *image.image();
704 let data: &[u8] = image.as_ref();
705
706 let (dst_y, rest) = self.out.split_at_mut(self.luma);
707 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
708 if self.ten_bit {
709 p010_to_i420(
710 &data[va.offsets[Y_PLANE] as usize..],
711 va.pitches[Y_PLANE] as usize,
712 dst_y,
713 &data[va.offsets[UV_PLANE] as usize..],
714 va.pitches[UV_PLANE] as usize,
715 dst_u,
716 dst_v,
717 w,
718 h,
719 );
720 return;
721 }
722 nv12_to_i420(
723 &data[va.offsets[Y_PLANE] as usize..],
724 va.pitches[Y_PLANE] as usize,
725 dst_y,
726 w,
727 &data[va.offsets[UV_PLANE] as usize..],
728 va.pitches[UV_PLANE] as usize,
729 dst_u,
730 cw,
731 dst_v,
732 cw,
733 w,
734 h,
735 );
736 }
737
738 fn fill(&self, out: &mut VhFrame) {
739 let w = self.meta.width as usize;
740 let cw = w.div_ceil(2);
741 out.y = self.out.as_ptr();
742 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
743 unsafe {
744 out.u = self.out.as_ptr().add(self.luma);
745 out.v = self.out.as_ptr().add(self.luma + self.chroma);
746 }
747 out.y_stride = w;
748 out.u_stride = cw;
749 out.v_stride = cw;
750 out.width = self.meta.width;
751 out.height = self.meta.height;
752 }
753}
754
755/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface
756/// whose samples are 16-bit little-endian with the value in the **high** bits,
757/// which is what P010 means. The high byte of each pair is therefore the 10-bit
758/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a
759/// second read of the low byte costs more than the half-bit it would buy.
760fn p010_to_i420(
761 src_y: &[u8],
762 src_y_pitch: usize,
763 dst_y: &mut [u8],
764 src_uv: &[u8],
765 src_uv_pitch: usize,
766 dst_u: &mut [u8],
767 dst_v: &mut [u8],
768 width: usize,
769 height: usize,
770) {
771 for row in 0..height {
772 let src = &src_y[row * src_y_pitch..];
773 let dst = &mut dst_y[row * width..row * width + width];
774 for (x, out) in dst.iter_mut().enumerate() {
775 *out = src[2 * x + 1];
776 }
777 }
778 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
779 for row in 0..ch {
780 let src = &src_uv[row * src_uv_pitch..];
781 let (u, v) = (
782 &mut dst_u[row * cw..row * cw + cw],
783 &mut dst_v[row * cw..row * cw + cw],
784 );
785 for x in 0..cw {
786 u[x] = src[4 * x + 1];
787 v[x] = src[4 * x + 3];
788 }
789 }
790}
791
792/// Opens `path` for hardware decode, positioned so the first
793/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
794/// the start of the stream). Returns null on any failure at all: no libva
795/// runtime, no render node, unsupported profile, unreadable file.
796///
797/// # Safety
798/// `path` must be a valid NUL-terminated C string.
799#[unsafe(no_mangle)]
800pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
801 catch_unwind(AssertUnwindSafe(|| {
802 if path.is_null() {
803 return std::ptr::null_mut();
804 }
805 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
806 let path = unsafe { CStr::from_ptr(path) };
807 let Ok(path) = path.to_str() else {
808 return std::ptr::null_mut();
809 };
810 match Session::open_at(Path::new(path), target_sample) {
811 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
812 None => std::ptr::null_mut(),
813 }
814 }))
815 .unwrap_or(std::ptr::null_mut())
816}
817
818/// Fills `out` with stream metadata. 0 on success, negative on failure.
819///
820/// # Safety
821/// `session` must come from [`vh_open_at`] and `out` must be writable.
822#[unsafe(no_mangle)]
823pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
824 catch_unwind(AssertUnwindSafe(|| {
825 if session.is_null() || out.is_null() {
826 return -1;
827 }
828 // SAFETY: caller-guaranteed live session and writable destination.
829 unsafe {
830 let session = &*(session as *const Session);
831 (*out).width = session.meta.width;
832 (*out).height = session.meta.height;
833 (*out).frame_rate = session.meta.frame_rate;
834 (*out).frame_count = session.meta.frame_count;
835 }
836 0
837 }))
838 .unwrap_or(-1)
839}
840
841/// 1 when `out` holds the next picture in display order, 0 at clean end of
842/// stream, negative on error. Plane pointers stay valid until the next call.
843///
844/// # Safety
845/// `session` must come from [`vh_open_at`] and `out` must be writable.
846#[unsafe(no_mangle)]
847pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
848 catch_unwind(AssertUnwindSafe(|| {
849 if session.is_null() || out.is_null() {
850 return -1;
851 }
852 // SAFETY: caller-guaranteed live session and writable destination.
853 let session = unsafe { &mut *(session as *mut Session) };
854 match session.pump() {
855 Ok(true) => {
856 // SAFETY: `out` is non-null and writable per the contract.
857 session.fill(unsafe { &mut *out });
858 1
859 }
860 Ok(false) => 0,
861 Err(e) => {
862 eprintln!("engine_hw: {e}");
863 -2
864 }
865 }
866 }))
867 .unwrap_or(-1)
868}
869
870/// Repositions an open session so the next [`vh_next_frame`] returns sample
871/// `target_sample` (1-based, as [`vh_open_at`]). 0 on success, negative on
872/// failure -- and a caller that gets one closes the session and opens another,
873/// which is what it did for every seek before this symbol existed.
874///
875/// # Safety
876/// `session` must come from [`vh_open_at`] and still be open.
877#[unsafe(no_mangle)]
878pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i32 {
879 catch_unwind(AssertUnwindSafe(|| {
880 if session.is_null() {
881 return -1;
882 }
883 // SAFETY: caller-guaranteed live session.
884 let session = unsafe { &mut *(session as *mut Session) };
885 match session.seek_to(target_sample) {
886 Ok(()) => 0,
887 Err(e) => {
888 eprintln!("engine_hw: seek failed: {e}");
889 -2
890 }
891 }
892 }))
893 .unwrap_or(-1)
894}
895
896/// As [`vh_next_frame`], but hands the picture over *on the GPU* where it can
897/// be: `dma` is filled and its `fd` belongs to the caller (who closes it) when
898/// the decoded surface is exactly what an encoder of `coded_width` x
899/// `coded_height` carrying a `width` x `height` picture reads, and `out` is
900/// filled with read-back I420 exactly as [`vh_next_frame`] fills it otherwise.
901/// `dma.fd` below zero is what says which happened.
902///
903/// The buffer stays out of the decoder's pool for [`DMA_HOLD`] further
904/// pictures and no longer: encode it before asking for that many more. Only a
905/// session that has never read a frame back may hand buffers over at all --
906/// those extra pool buffers are reserved at the first picture, and a decoder
907/// robbed of its own would stall.
908///
909/// # Safety
910/// `session` must come from [`vh_open_at`]; `out` and `dma` must be writable.
911#[unsafe(no_mangle)]
912pub unsafe extern "C" fn vh_next_frame_dma(
913 session: *mut c_void,
914 out: *mut VhFrame,
915 dma: *mut VhDma,
916 coded_width: u32,
917 coded_height: u32,
918 width: u32,
919 height: u32,
920) -> i32 {
921 catch_unwind(AssertUnwindSafe(|| {
922 if session.is_null() || out.is_null() || dma.is_null() {
923 return -1;
924 }
925 // SAFETY: caller-guaranteed live session and writable destinations.
926 let session = unsafe { &mut *(session as *mut Session) };
927 // SAFETY: as above.
928 unsafe { *dma = VhDma::default() };
929 // A pool sized without the reserve has nothing to lend: this session
930 // has been read back from, so it stays that way.
931 if !session.sized || session.hold > 0 {
932 session.hold = DMA_HOLD;
933 session.want = Some(VhDma {
934 fourcc: VA_FOURCC_NV12,
935 coded_width,
936 coded_height,
937 width,
938 height,
939 ..VhDma::default()
940 });
941 }
942 let pumped = session.pump();
943 session.want = None;
944 match pumped {
945 Ok(true) => {
946 match session.dma.take() {
947 // SAFETY: `dma` is non-null and writable per the contract.
948 Some(desc) => unsafe { *dma = desc },
949 // SAFETY: as above, for `out`.
950 None => session.fill(unsafe { &mut *out }),
951 }
952 1
953 }
954 Ok(false) => 0,
955 Err(e) => {
956 eprintln!("engine_hw: {e}");
957 -2
958 }
959 }
960 }))
961 .unwrap_or(-1)
962}
963
964/// Releases a session. Safe to call with null.
965///
966/// # Safety
967/// `session` must come from [`vh_open_at`] and must not be used afterwards.
968#[unsafe(no_mangle)]
969pub unsafe extern "C" fn vh_close(session: *mut c_void) {
970 let _ = catch_unwind(AssertUnwindSafe(|| {
971 if !session.is_null() {
972 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
973 drop(unsafe { Box::from_raw(session as *mut Session) });
974 }
975 }));
976}
977
978/// What each codec needs of the driver before this plugin can claim it: the
979/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here
980/// would open -- `None` for the one this plugin has no encoder for at all, so a
981/// GPU with a VP9 encode entrypoint is never reported as one edith can
982/// reach. The encode profiles are the very ones [`EncSession::open_codec`]
983/// asks for, which is what keeps this a description of the plugin rather than a
984/// second opinion about it.
985const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile::Type>); 4] = [
986 (
987 CAP_H264,
988 &[
989 VAProfile::VAProfileH264ConstrainedBaseline,
990 VAProfile::VAProfileH264Main,
991 VAProfile::VAProfileH264High,
992 ],
993 &[],
994 Some(VAProfile::VAProfileH264Main),
995 ),
996 (
997 CAP_HEVC,
998 &[VAProfile::VAProfileHEVCMain],
999 &[VAProfile::VAProfileHEVCMain10],
1000 // 8-bit Main only: the encoder here opens Main whatever the source was,
1001 // so a Main 10 entrypoint is a *decode* claim on this line and nothing
1002 // more. Main 10 encode would be a second profile here and a 10-bit input
1003 // buffer in `EncSession`, neither of which exists yet.
1004 Some(VAProfile::VAProfileHEVCMain),
1005 ),
1006 (
1007 CAP_VP9,
1008 &[VAProfile::VAProfileVP9Profile0],
1009 &[VAProfile::VAProfileVP9Profile2],
1010 None,
1011 ),
1012 (
1013 CAP_AV1,
1014 &[VAProfile::VAProfileAV1Profile0],
1015 // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit
1016 // is the same one and the P010 read-back is what decides.
1017 &[VAProfile::VAProfileAV1Profile0],
1018 Some(VAProfile::VAProfileAV1Profile0),
1019 ),
1020];
1021
1022/// This machine's decode and encode seats, asked of the driver rather than
1023/// assumed: which profiles it has, which entrypoints each of those carries, and
1024/// whether a P010 image exists to read a 10-bit picture back through. Only
1025/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
1026/// half of the intersection.
1027///
1028/// `None` when there is no display to ask at all, which is the same "software
1029/// only" a missing plugin means.
1030fn query_caps() -> Option<VhCaps> {
1031 let (display, _gbm) = open_devices()?;
1032 let profiles = display.query_config_profiles().ok()?;
1033 let p010 = display
1034 .query_image_formats()
1035 .is_ok_and(|formats| formats.iter().any(|f| f.fourcc == VA_FOURCC_P010));
1036 let has = |profile: VAProfile::Type, entrypoint: VAEntrypoint::Type| {
1037 profiles.contains(&profile)
1038 && display
1039 .query_config_entrypoints(profile)
1040 .is_ok_and(|e| e.contains(&entrypoint))
1041 };
1042 let decodes = |list: &[VAProfile::Type]| {
1043 list.iter()
1044 .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD))
1045 };
1046 let mut caps = VhCaps::default();
1047 for (bit, eight, ten, encode) in CAP_TABLE {
1048 if decodes(eight) {
1049 caps.decode |= bit;
1050 }
1051 if p010 && decodes(ten) {
1052 caps.decode_10bit |= bit;
1053 }
1054 // Both entrypoints, exactly as the encoder's own open takes either.
1055 if encode.is_some_and(|p| {
1056 has(p, VAEntrypoint::VAEntrypointEncSlice) || has(p, VAEntrypoint::VAEntrypointEncSliceLP)
1057 }) {
1058 caps.encode |= bit;
1059 }
1060 }
1061 Some(caps)
1062}
1063
1064/// Fills `out` with what this machine and this plugin can do together. 0 on
1065/// success, negative when there is nothing to report -- an *optional* symbol on
1066/// purpose, so the caller resolving it is free to be older or newer than this.
1067///
1068/// Costs one VA-API init; the caller caches the answer.
1069///
1070/// # Safety
1071/// `out` must be writable.
1072#[unsafe(no_mangle)]
1073pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 {
1074 catch_unwind(AssertUnwindSafe(|| {
1075 if out.is_null() {
1076 return -1;
1077 }
1078 let Some(caps) = query_caps() else {
1079 return -1;
1080 };
1081 // SAFETY: caller-guaranteed writable destination.
1082 unsafe { *out = caps };
1083 0
1084 }))
1085 .unwrap_or(-1)
1086}
1087
1088/// How many pictures a group of them holds -- the low-delay predictor's
1089/// `limit`, which is the *only* thing that decides whether a picture is an IDR.
1090///
1091/// One for an intra-only seat, and that is not a tuning: the predictor counts
1092/// `counter % limit`, so a limit of one pins the counter at zero, every picture
1093/// takes the keyframe branch with `idr` set, and every access unit carries a
1094/// fresh SPS and PPS
1095/// (`cros-codecs/encoder/stateless/predictor.rs:107`, `h264/predictor.rs:139`).
1096/// Two seconds otherwise, which is what a seek may land on in an ordinary file.
1097///
1098/// Forcing a key frame per picture is a different thing and does *not* make an
1099/// intra file: that path passes `idr = false`, writes no parameter sets, and
1100/// [`fix_slice_nal_headers`] then marks the slice non-IDR -- how a 60-picture
1101/// "all-intra" hardware proxy came out with one sync point in it.
1102fn gop_limit(framerate: u32, intra_only: bool) -> u16 {
1103 match intra_only {
1104 true => 1,
1105 // Saturating and clamped: the caller pins the rate to 1..240 before it
1106 // gets here, and a limit that wrapped to zero would divide by zero in
1107 // the predictor -- a guard costs nothing next to that.
1108 false => framerate.saturating_mul(2).clamp(1, u16::MAX as u32) as u16,
1109 }
1110}
1111
1112fn align16(v: u32) -> u32 {
1113 v.div_ceil(16) * 16
1114}
1115
1116fn align64(v: u32) -> u32 {
1117 v.div_ceil(64) * 64
1118}
1119
1120/// Fills in slice NAL header bytes the driver left at zero.
1121///
1122/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
1123/// `nal_unit_type` from state it only ever populates out of a *packed* slice
1124/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
1125/// "use packed headers" TODO). Every other bit of the slice is correct, so the
1126/// whole damage is one byte per slice: measured on radeonsi, patching it turns
1127/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
1128///
1129/// An all-zero byte after a start code is never valid H.264, so drivers that do
1130/// write the header (Intel's, which is what cros-codecs was built against) fall
1131/// straight through this.
1132///
1133/// corner-cut: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
1134/// vendored cros-codecs backend, which means synthesizing the entire slice
1135/// header there rather than correcting two fields here.
1136fn fix_slice_nal_headers(au: &mut [u8]) {
1137 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
1138 // there, so an SPS seen earlier in this unit is what makes the slice one.
1139 let mut idr = false;
1140 let mut i = 0;
1141 while i + 3 < au.len() {
1142 if au[i..i + 3] != [0, 0, 1] {
1143 i += 1;
1144 continue;
1145 }
1146 let nal = &mut au[i + 3];
1147 if *nal == 0 {
1148 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
1149 // emits is a short-term reference (no B-frames, no disposables).
1150 *nal = if idr { 0x65 } else { 0x41 };
1151 } else if *nal & 0x1f == 7 {
1152 idr = true;
1153 }
1154 i += 3;
1155 }
1156}
1157
1158/// One hardware H.264 encode session.
1159///
1160/// Pictures the caller already has on the GPU go straight in
1161/// ([`EncSession::encode_dma`]) and touch none of what follows. The rest --
1162/// pixels in the caller's memory -- go through [`enc_depth`] reusable NV12
1163/// buffer objects: the caller's
1164/// I420 planes are interleaved into the next one and the encoder imports it as a
1165/// VA surface. Reuse is safe because a buffer is only written again once the
1166/// access unit coded *from* it has been polled back -- the encoder runs in
1167/// blocking mode and a coded unit in hand means the GPU has finished reading its
1168/// input -- and [`EncSession::encode`] holds exactly that many pictures in
1169/// flight, no more.
1170///
1171/// **Why more than one.** With a single buffer the picture had to be coded
1172/// before the next one could be written into it, so a frame cost the CPU's
1173/// interleave *plus* the GPU's encode end to end (6.7 ms + 2.5 ms at 1080p on
1174/// radeonsi, measured 2026-08-13). With two, the interleave of the next picture
1175/// runs while the GPU codes this one and the frame costs the longer of them.
1176struct EncSession {
1177 /// Boxed because the three codecs are three types and everything past
1178 /// `encode` is the same trait: one session type serves them all, which is
1179 /// what keeps the C ABI at one new symbol per codec (the open) instead of
1180 /// four.
1181 encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>>,
1182 /// Which codec the open picked, kept because one thing past it still
1183 /// differs: the H.264 driver leaves a *NAL* header byte at zero, and
1184 /// neither an HEVC access unit nor an AV1 temporal unit has that one.
1185 codec: EncCodec,
1186 /// The H.264 counters the driver zeroes, rewritten per access unit
1187 /// ([`slice_fix`]).
1188 counters: slice_fix::SliceCounters,
1189 /// Owns the DRM node the buffer objects below were allocated from.
1190 _gbm: gbm::Device<std::fs::File>,
1191 /// [`enc_depth`] input buffers, used round-robin.
1192 frames: Vec<GenericDmaVideoFrame>,
1193 /// How many of them there are, which is how many pictures may be in the
1194 /// encoder at once.
1195 depth: usize,
1196 /// Which of them the next picture is written into.
1197 slot: usize,
1198 /// Pictures submitted whose access unit has not been polled back yet, which
1199 /// is what says whether the buffer about to be written is free.
1200 in_flight: usize,
1201 layout: FrameLayout,
1202 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
1203 coded: Resolution,
1204 width: usize,
1205 height: usize,
1206 timestamp: u64,
1207 drained: bool,
1208 /// Coded access units the encoder has finished but the caller has not
1209 /// collected yet, in encode order (which is display order: no B-frames).
1210 ready: VecDeque<Vec<u8>>,
1211 /// The access unit currently handed out, kept alive until the next call.
1212 out: Vec<u8>,
1213 /// One padded output row, staged in ordinary memory and copied across whole
1214 /// -- [`EncSession::upload`] says why.
1215 row: Vec<u8>,
1216}
1217
1218/// How many pictures may be in the encoder at once. Two is what it takes to
1219/// overlap the CPU's interleave with the GPU's encode; more would buy nothing,
1220/// since the interleave is the longer of the two and a third buffer would only
1221/// hold a picture waiting for a lane that is never idle.
1222const ENC_DEPTH: usize = 2;
1223
1224/// How many pictures *this* seat may hold, which is [`ENC_DEPTH`] for H.264 and
1225/// one for the other two.
1226///
1227/// Depth 2 means a submitted picture must hand its access unit back on the next
1228/// poll, and [`EncSession::encode`] treats a seat that does not as an error --
1229/// it cannot write into a buffer the GPU may still be reading. That contract
1230/// was measured on the H.264 seat and only there. HEVC and AV1 on this plugin
1231/// are intra-only and go through the same driver, so they very probably behave
1232/// the same way; "very probably" is not what a hard error should rest on, and
1233/// the GPU has been unavailable since the measurement was possible. They keep
1234/// the old one-buffer behaviour -- the picture coded before the next is
1235/// written, exactly as every seat did before -- until someone measures them.
1236///
1237/// The intra-only seat ([`vh_enc_open_intra`]) is keyed by codec like any other
1238/// and therefore takes the two, which is the answer and not an oversight: it is
1239/// the same H.264 entrypoint with every inter dependency removed, so a picture
1240/// there is finished no later than one on the seat the two was measured on.
1241fn enc_depth(codec: EncCodec) -> usize {
1242 match codec {
1243 EncCodec::H264 => ENC_DEPTH,
1244 EncCodec::Hevc | EncCodec::Av1 => 1,
1245 }
1246}
1247
1248/// Which codec an [`EncSession`] was opened for. Decided once, at the open, the
1249/// way the H.264 seat's dimensions are -- everything after it is one trait.
1250#[derive(Clone, Copy, PartialEq, Eq)]
1251enum EncCodec {
1252 H264,
1253 Hevc,
1254 Av1,
1255}
1256
1257impl EncSession {
1258 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
1259 Self::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::H264)
1260 }
1261
1262 fn open_codec(
1263 width: u32,
1264 height: u32,
1265 fps_num: u32,
1266 fps_den: u32,
1267 bitrate: u64,
1268 codec: EncCodec,
1269 ) -> Option<Self> {
1270 Self::open_seat(width, height, fps_num, fps_den, bitrate, codec, false, None)
1271 }
1272
1273 #[allow(clippy::too_many_arguments)]
1274 fn open_seat(
1275 width: u32,
1276 height: u32,
1277 fps_num: u32,
1278 fps_den: u32,
1279 bitrate: u64,
1280 codec: EncCodec,
1281 intra_only: bool,
1282 colour: Option<H265Colour>,
1283 ) -> Option<Self> {
1284 // NV12 chroma is half resolution, so odd dimensions have no packing;
1285 // and radeonsi refuses encode contexts below 64x64 (measured).
1286 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
1287 return None;
1288 }
1289 // The HEVC entrypoint's own floor, which is a different number: the same
1290 // driver that takes a 128x128 H.264 context answers `VaError(19)` to an
1291 // HEVC one below 384x384 (measured 2026-08-13 on radeonsi). Said here so
1292 // a small export falls back to software at the open rather than through
1293 // a driver refusal, and so the C ABI never claims a seat it has not got.
1294 if codec == EncCodec::Hevc && (width < 384 || height < 384) {
1295 return None;
1296 }
1297 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
1298 return None;
1299 }
1300 let (display, gbm) = open_devices()?;
1301 // A macroblock is 16 wide; an HEVC coding tree block is 64, and that
1302 // seat's parameter sets declare the picture at coding-tree size (see the
1303 // vendored `h265/predictor.rs`), so the surface has to carry every row
1304 // those sets promise.
1305 let align = match codec {
1306 EncCodec::Hevc => align64,
1307 _ => align16,
1308 };
1309 let coded = Resolution {
1310 width: align(width),
1311 height: align(height),
1312 };
1313 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
1314 let profile = match codec {
1315 EncCodec::Av1 => VAProfile::VAProfileAV1Profile0,
1316 EncCodec::Hevc => VAProfile::VAProfileHEVCMain,
1317 EncCodec::H264 => VAProfile::VAProfileH264Main,
1318 };
1319 // The driver's own answer to "can you encode this at all": a GPU with no
1320 // AV1 encode entrypoint is what makes the caller fall back to `rav1e`,
1321 // and asking here is what turns that into a null rather than a failed
1322 // encode session halfway through an export.
1323 let entrypoints = display.query_config_entrypoints(profile).ok()?;
1324 if !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSlice)
1325 && !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP)
1326 {
1327 return None;
1328 }
1329 let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);
1330 // No B-frames on either codec: coded order stays display order, which is
1331 // what both muxers' duration-only timing assumes.
1332 //
1333 // A limit of **1** is what makes a seat intra-only, and it is the whole
1334 // mechanism: the low-delay predictor counts `counter % limit`, so with a
1335 // limit of one that counter is always zero, every picture takes the
1336 // keyframe branch *with `idr` set*, and each access unit is therefore an
1337 // IDR carrying a fresh SPS and PPS
1338 // (`cros-codecs/encoder/stateless/predictor.rs:107` and
1339 // `h264/predictor.rs:139-163`). Forcing a key frame per picture is not
1340 // the same thing and does not do it: `force_keyframe` takes the same
1341 // branch with `idr` **false**, so no parameter sets are written, and a
1342 // driver that leaves the NAL header byte at zero then gets its slices
1343 // marked non-IDR by [`fix_slice_nal_headers`] -- which is exactly how a
1344 // 60-frame "all-intra" hardware proxy came out with one sync point in it.
1345 let pred_structure = PredictionStructure::LowDelay {
1346 limit: gop_limit(framerate, intra_only),
1347 };
1348 let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match codec {
1349 EncCodec::Av1 => {
1350 // Constant quality, because that is the only rate control the
1351 // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses
1352 // anything else outright); 128 of 255 is its own reference
1353 // value. The caller's bitrate therefore does not reach this
1354 // seat -- it reaches `rav1e`, which is the other one.
1355 //
1356 // corner-cut: bitrate-driven AV1 on the GPU needs `VA_RC_CBR`
1357 // wired through that backend, which is a change in the vendored
1358 // crate rather than here.
1359 let config = Av1Config {
1360 profile: Av1Profile::Profile0,
1361 resolution: Resolution { width, height },
1362 pred_structure,
1363 initial_tunings: Tunings {
1364 rate_control: RateControl::ConstantQuality(128),
1365 framerate,
1366 ..Default::default()
1367 },
1368 ..Default::default()
1369 };
1370 Box::new(
1371 Av1Encoder::new_vaapi(
1372 display,
1373 config,
1374 Fourcc::from(b"NV12"),
1375 coded,
1376 low_power,
1377 BlockingMode::Blocking,
1378 )
1379 .ok()?,
1380 )
1381 }
1382 EncCodec::Hevc => {
1383 // **Every picture an IDR**, which is the one place this seat
1384 // does not mirror the H.264 one. A GOP's P slices come out of
1385 // this driver undecodable: the slice segment headers are the
1386 // *driver's* to write (as they are for H.264) and radeonsi
1387 // writes a constant picture order count into every one of them,
1388 // so a decoder sees frame after frame claiming to be the same
1389 // output picture. Measured 2026-08-13: with the default GOP,
1390 // only the leading IDR of each group decodes.
1391 //
1392 // So the hardware seat is intra-only exactly as the software one
1393 // is (`export::Enc::open_hevc`), and an HEVC export is an
1394 // intraframe master either way -- the same file, coded by the
1395 // GPU instead of by twelve cores.
1396 //
1397 // corner-cut: inter HEVC on this GPU needs the slice segment
1398 // header written here rather than by the driver
1399 // (`VAEncPackedHeaderSlice`), which is a change in the vendored
1400 // backend; upgrade path is that, or a driver that writes a
1401 // correct POC.
1402 let config = H265Config {
1403 resolution: Resolution { width, height },
1404 profile: H265Profile::Main,
1405 level: slice_fix::hevc_level(width, height, fps_num, fps_den),
1406 pred_structure: PredictionStructure::LowDelay { limit: 1 },
1407 initial_tunings: Tunings {
1408 rate_control: RateControl::ConstantBitrate(bitrate),
1409 framerate,
1410 ..Default::default()
1411 },
1412 // What the SPS tells a decoder the samples mean. Without it
1413 // libavcodec reads this stream's colour as "unspecified" and
1414 // renders it BT.601 whatever the container says -- the HEVC
1415 // decoder takes the bitstream's answer and overwrites the
1416 // container's with it, so an untagged 709 export is a
1417 // visible shift (`engine::export::video_signal_type` writes
1418 // the same three code points on the software seat).
1419 colour,
1420 };
1421 Box::new(
1422 HevcEncoder::new_vaapi(
1423 display,
1424 config,
1425 Fourcc::from(b"NV12"),
1426 coded,
1427 low_power,
1428 BlockingMode::Blocking,
1429 )
1430 .ok()?,
1431 )
1432 }
1433 EncCodec::H264 => {
1434 let config = H264Config {
1435 resolution: Resolution { width, height },
1436 profile: H264Profile::Main,
1437 level: slice_fix::h264_level(width, height, fps_num, fps_den),
1438 pred_structure,
1439 initial_tunings: Tunings {
1440 rate_control: RateControl::ConstantBitrate(bitrate),
1441 framerate,
1442 ..Default::default()
1443 },
1444 };
1445 Box::new(
1446 Encoder::new_vaapi(
1447 display,
1448 config,
1449 Fourcc::from(b"NV12"),
1450 coded,
1451 low_power,
1452 BlockingMode::Blocking,
1453 )
1454 .ok()?,
1455 )
1456 }
1457 };
1458 // Allocated at the aligned size, so the buffer's pitch is never smaller
1459 // than a padded row.
1460 let depth = enc_depth(codec);
1461 let frames: Vec<_> = (0..depth)
1462 .map(|_| alloc_nv12(&gbm, coded, false))
1463 .collect::<Result<_, _>>()
1464 .ok()?;
1465 let layout = nv12_layout(coded, frames[0].get_plane_pitch()[0], false);
1466 Some(Self {
1467 encoder,
1468 codec,
1469 _gbm: gbm,
1470 frames,
1471 depth,
1472 slot: 0,
1473 in_flight: 0,
1474 counters: slice_fix::SliceCounters::default(),
1475 layout,
1476 coded,
1477 width: width as usize,
1478 height: height as usize,
1479 timestamp: 0,
1480 drained: false,
1481 ready: VecDeque::new(),
1482 out: Vec::new(),
1483 row: Vec::new(),
1484 })
1485 }
1486
1487 /// Interleaves one packed I420 picture into the NV12 input buffer `slot`.
1488 ///
1489 /// **Row at a time, through ordinary memory.** The mapping below is the
1490 /// GPU's own buffer, which is write-combining: a store of a byte or two
1491 /// costs a partial-buffer flush, while one `memcpy` of a whole row costs a
1492 /// burst. Interleaving the chroma directly into it was 8.2 ms a picture at
1493 /// 1080p against 6.7 ms staged (measured 2026-08-13 on radeonsi, alternating
1494 /// the two paths frame by frame inside one export so the machine's load
1495 /// weighed on both), and the picture is four fifths of what a hardware
1496 /// export spends per frame. The padding is written the same way and for the
1497 /// same reason: it used to be a four-byte second store per row.
1498 ///
1499 /// # Safety
1500 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
1501 /// declared stride.
1502 unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> {
1503 let (w, h) = (self.width, self.height);
1504 let (cw, ch) = (w / 2, h / 2);
1505 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
1506 // Two fields at once: the buffer is mapped for writing while the staging
1507 // row is written into, and they are not the same field.
1508 let Self { frames, row, .. } = self;
1509 let frame = &mut frames[slot];
1510 let pitch = frame.get_plane_pitch();
1511 let mapping = frame.map_mut()?;
1512 let planes = mapping.get();
1513 row.resize(aw, 0);
1514 let row_buf = &mut row[..];
1515 {
1516 let mut dst = planes[0].borrow_mut();
1517 for row in 0..ah {
1518 // SAFETY: caller contract; rows past the picture repeat the last.
1519 let s = unsafe {
1520 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
1521 };
1522 row_buf[..w].copy_from_slice(s);
1523 // Macroblock padding: replicate the edge rather than leave the
1524 // buffer's garbage there, which would cost bitrate for nothing.
1525 row_buf[w..].fill(s[w - 1]);
1526 dst[row * pitch[0]..row * pitch[0] + aw].copy_from_slice(row_buf);
1527 }
1528 }
1529 let mut dst = planes[1].borrow_mut();
1530 for row in 0..ah / 2 {
1531 let src_row = row.min(ch - 1);
1532 // SAFETY: as above, for the two chroma planes.
1533 let (u, v) = unsafe {
1534 (
1535 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
1536 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
1537 )
1538 };
1539 for x in 0..cw {
1540 row_buf[2 * x] = u[x];
1541 row_buf[2 * x + 1] = v[x];
1542 }
1543 for x in w..aw {
1544 row_buf[x] = row_buf[x - 2];
1545 }
1546 dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf);
1547 }
1548 Ok(())
1549 }
1550
1551 /// # Safety
1552 /// As [`EncSession::upload`].
1553 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
1554 // The buffer this picture is written into is the one whose own access
1555 // unit is already in hand -- `in_flight` is held below `depth` at the
1556 // end of every call, so the round-robin never catches the GPU up. At
1557 // depth 1 that is the picture just coded, which is the one-buffer
1558 // behaviour every seat had before ([`enc_depth`]).
1559 let slot = self.slot;
1560 // SAFETY: caller contract, forwarded.
1561 unsafe { self.upload(src, slot)? };
1562 self.slot = (self.slot + 1) % self.depth;
1563 let meta = FrameMetadata {
1564 timestamp: self.timestamp,
1565 layout: self.layout.clone(),
1566 force_keyframe,
1567 };
1568 self.timestamp += 1;
1569 self.encoder
1570 .encode(meta, self.frames[slot].clone())
1571 .map_err(|e| e.to_string())?;
1572 self.in_flight += 1;
1573 // ...and the picture before it is collected here rather than this one:
1574 // that is the whole overlap, the GPU coding what was just submitted
1575 // while the caller decodes and interleaves the next picture.
1576 while self.in_flight >= self.depth {
1577 if !self.pull()? {
1578 // Blocking mode: a picture accepted and no coded unit for the
1579 // one before it means the encoder is not answering, and the
1580 // next upload would overwrite a buffer the GPU still reads.
1581 return Err("the encoder took a picture and returned nothing coded".into());
1582 }
1583 }
1584 Ok(())
1585 }
1586
1587 /// Encodes a picture the decoder left on the GPU: the buffer is imported as
1588 /// a surface of this session's own shape and read there, so nothing of it
1589 /// ever passes through the CPU -- no `vaGetImage` on the way out of the
1590 /// decoder and no interleave on the way in here.
1591 ///
1592 /// The geometry is checked rather than trusted: a buffer of another shape
1593 /// would be coded as garbage, and the caller asked
1594 /// [`vh_enc_dma_geometry`] what this seat takes before the decoder ever
1595 /// handed one over.
1596 ///
1597 /// **No deferred poll here, unlike [`EncSession::encode`].** That one holds
1598 /// [`enc_depth`] pictures in flight to overlap the *next* picture's CPU
1599 /// interleave with this one's encode; a picture arriving on the GPU has no
1600 /// interleave to overlap, so there is nothing to defer for and the access
1601 /// units are collected as soon as they exist. What the depth still buys is
1602 /// the input buffer, and this path uses none of `frames`: the surface is the
1603 /// decoder's, held for us by its own [`DMA_HOLD`] contract, and draining
1604 /// every call is what keeps that hold short.
1605 ///
1606 /// It is counted in `in_flight` all the same, because one session takes both
1607 /// kinds -- an untouched clip hands buffers over while a graded one or a gap
1608 /// goes through the pixel path -- and a submission missing from the count is
1609 /// a `frames` slot the pixel path would believe free one picture too early.
1610 fn encode_dma(&mut self, dma: &VhDma, force_keyframe: bool) -> Result<(), String> {
1611 if dma.fd[0] < 0
1612 || dma.fourcc != VA_FOURCC_NV12
1613 || (dma.coded_width, dma.coded_height) != (self.coded.width, self.coded.height)
1614 || (dma.width as usize, dma.height as usize) != (self.width, self.height)
1615 {
1616 return Err(format!(
1617 "imported buffer is {}x{} in {} coded {}x{}, not {}x{} coded {}x{}",
1618 dma.width,
1619 dma.height,
1620 dma.fourcc,
1621 dma.coded_width,
1622 dma.coded_height,
1623 self.width,
1624 self.height,
1625 self.coded.width,
1626 self.coded.height
1627 ));
1628 }
1629 // One object or two, exactly as the decoder's driver described them:
1630 // the buffers stay the caller's, so each is dup'd for the frame below.
1631 let mut files = Vec::new();
1632 for fd in dma.fd.iter().copied().take_while(|fd| *fd >= 0) {
1633 // SAFETY: the descriptor's handles are the caller's, open for the
1634 // length of the call.
1635 let owned = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }
1636 .try_clone_to_owned()
1637 .map_err(|e| format!("dup of the imported buffer failed: {e}"))?;
1638 files.push(std::fs::File::from(owned));
1639 }
1640 let objects = files.len();
1641 let layout = FrameLayout {
1642 format: (Fourcc::from(b"NV12"), dma.modifier),
1643 size: self.coded,
1644 planes: (0..2)
1645 .map(|plane| PlaneLayout {
1646 buffer_index: plane.min(objects - 1),
1647 offset: dma.offset[plane] as usize,
1648 stride: dma.stride[plane] as usize,
1649 })
1650 .collect(),
1651 };
1652 let frame = GenericDmaVideoFrame::new(files, layout.clone())?;
1653 let meta = FrameMetadata {
1654 timestamp: self.timestamp,
1655 layout,
1656 force_keyframe,
1657 };
1658 self.timestamp += 1;
1659 self.encoder
1660 .encode(meta, frame)
1661 .map_err(|e| e.to_string())?;
1662 self.in_flight += 1;
1663 self.collect()
1664 }
1665
1666 /// Moves every access unit the encoder has finished into `ready`.
1667 fn collect(&mut self) -> Result<(), String> {
1668 while self.pull()? {}
1669 Ok(())
1670 }
1671
1672 /// One finished access unit into `ready`; `false` where the encoder has
1673 /// none to give.
1674 fn pull(&mut self) -> Result<bool, String> {
1675 let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? else {
1676 return Ok(false);
1677 };
1678 let mut au = coded.bitstream;
1679 if self.codec == EncCodec::H264 {
1680 fix_slice_nal_headers(&mut au);
1681 self.counters.fix_au(&mut au);
1682 }
1683 self.ready.push_back(au);
1684 self.in_flight = self.in_flight.saturating_sub(1);
1685 Ok(true)
1686 }
1687
1688 /// Hands the oldest finished access unit to the caller, or reports that
1689 /// there is none.
1690 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
1691 let Some(au) = self.ready.pop_front() else {
1692 return 0;
1693 };
1694 self.out = au;
1695 // SAFETY: caller-guaranteed writable destinations.
1696 unsafe {
1697 *out = self.out.as_ptr();
1698 *out_len = self.out.len();
1699 }
1700 1
1701 }
1702}
1703
1704/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
1705/// constant bitrate `bitrate` bits per second. Returns null on any failure at
1706/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
1707/// the driver will not take -- and the caller falls back to software.
1708#[unsafe(no_mangle)]
1709pub extern "C" fn vh_enc_open(
1710 width: u32,
1711 height: u32,
1712 fps_num: u32,
1713 fps_den: u32,
1714 bitrate: u64,
1715) -> *mut c_void {
1716 catch_unwind(AssertUnwindSafe(|| {
1717 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
1718 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1719 None => std::ptr::null_mut(),
1720 }
1721 }))
1722 .unwrap_or(std::ptr::null_mut())
1723}
1724
1725/// The same H.264 seat, **intra-only**: every access unit it hands back is an
1726/// IDR carrying its own SPS and PPS, so every frame of the file is a frame a
1727/// decoder may be started from. What a proxy is coded with
1728/// (`engine::proxy`), and never a delivery -- the file is much bigger for it.
1729///
1730/// A symbol of its own rather than a flag on [`vh_enc_open`], so that a plugin
1731/// built before this existed simply has no intra seat and the caller falls back
1732/// to the software encoder (whose `gop_size = 1` says the same thing) instead of
1733/// being handed a long-GOP file that claims to be all-intra. The session it
1734/// returns is fed, drained and closed through the very same three entry points.
1735#[unsafe(no_mangle)]
1736pub extern "C" fn vh_enc_open_intra(
1737 width: u32,
1738 height: u32,
1739 fps_num: u32,
1740 fps_den: u32,
1741 bitrate: u64,
1742) -> *mut c_void {
1743 catch_unwind(AssertUnwindSafe(|| {
1744 match EncSession::open_seat(
1745 width,
1746 height,
1747 fps_num,
1748 fps_den,
1749 bitrate,
1750 EncCodec::H264,
1751 true,
1752 None,
1753 ) {
1754 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1755 None => std::ptr::null_mut(),
1756 }
1757 }))
1758 .unwrap_or(std::ptr::null_mut())
1759}
1760
1761/// The same, coding AV1 instead of H.264: null unless this GPU has an AV1
1762/// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in
1763/// software instead. `bitrate` is not used by this codec (see `EncSession::open`:
1764/// the vendored backend is constant-quality only) and is taken all the same, so
1765/// the two opens stay one signature.
1766///
1767/// The session it returns is fed, drained and closed through `vh_enc_frame`,
1768/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
1769/// out of them is AV1 temporal units rather than Annex-B access units.
1770#[unsafe(no_mangle)]
1771pub extern "C" fn vh_enc_av1_open(
1772 width: u32,
1773 height: u32,
1774 fps_num: u32,
1775 fps_den: u32,
1776 bitrate: u64,
1777) -> *mut c_void {
1778 catch_unwind(AssertUnwindSafe(|| {
1779 match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Av1) {
1780 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1781 None => std::ptr::null_mut(),
1782 }
1783 }))
1784 .unwrap_or(std::ptr::null_mut())
1785}
1786
1787/// The same, coding HEVC: null unless this GPU has an HEVC encode entrypoint and
1788/// the picture is at least 384x384 ([`EncSession::open_codec`] states that floor
1789/// and where it was measured), and the caller then encodes HEVC in software
1790/// instead.
1791///
1792/// **Intra-only**: every picture it hands back is an IDR carrying its own VPS,
1793/// SPS and PPS, which is what makes the file decodable at all on this driver --
1794/// see the `EncCodec::Hevc` arm of [`EncSession::open_codec`]. `bitrate` is the
1795/// constant bitrate the GPU codes at, as the H.264 seat's is.
1796///
1797/// The session it returns is fed, drained and closed through `vh_enc_frame`,
1798/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
1799/// out of them is Annex-B HEVC access units.
1800///
1801/// The last four arguments are what the SPS says the samples mean -- the three
1802/// H.273 code points and the range flag -- and they are part of the *symbol*
1803/// rather than a later setter because the parameter sets are built when the
1804/// sequence starts. A seat that signalled nothing is read back as "unspecified"
1805/// and rendered BT.601, the container's own tag notwithstanding, which is why
1806/// this replaced the colourless `vh_enc_hevc_open`: an engine older than this
1807/// symbol finds none and takes the software intra seat, which has always
1808/// written the VUI.
1809#[unsafe(no_mangle)]
1810pub extern "C" fn vh_enc_hevc_open_colour(
1811 width: u32,
1812 height: u32,
1813 fps_num: u32,
1814 fps_den: u32,
1815 bitrate: u64,
1816 colour_primaries: u32,
1817 transfer_characteristics: u32,
1818 matrix_coeffs: u32,
1819 full_range: i32,
1820) -> *mut c_void {
1821 catch_unwind(AssertUnwindSafe(|| {
1822 match EncSession::open_seat(
1823 width,
1824 height,
1825 fps_num,
1826 fps_den,
1827 bitrate,
1828 EncCodec::Hevc,
1829 false,
1830 Some(H265Colour {
1831 colour_primaries,
1832 transfer_characteristics,
1833 matrix_coeffs,
1834 full_range: full_range != 0,
1835 }),
1836 ) {
1837 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1838 None => std::ptr::null_mut(),
1839 }
1840 }))
1841 .unwrap_or(std::ptr::null_mut())
1842}
1843
1844/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
1845/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
1846/// error. The bytes stay valid until the next call on this session.
1847///
1848/// # Safety
1849/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
1850/// picture at their declared strides, and `out`/`out_len` must be writable.
1851#[unsafe(no_mangle)]
1852pub unsafe extern "C" fn vh_enc_frame(
1853 session: *mut c_void,
1854 frame: *const VhFrame,
1855 force_key: i32,
1856 out: *mut *const u8,
1857 out_len: *mut usize,
1858) -> i32 {
1859 catch_unwind(AssertUnwindSafe(|| {
1860 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
1861 return -1;
1862 }
1863 // SAFETY: caller-guaranteed live session and readable frame.
1864 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
1865 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
1866 return -1;
1867 }
1868 if frame.width as usize != session.width
1869 || frame.height as usize != session.height
1870 || frame.y_stride < session.width
1871 || frame.u_stride < session.width / 2
1872 || frame.v_stride < session.width / 2
1873 {
1874 return -1;
1875 }
1876 // SAFETY: caller contract on the plane pointers, sizes checked above.
1877 match unsafe { session.encode(frame, force_key != 0) } {
1878 Ok(()) => session.take(out, out_len),
1879 Err(e) => {
1880 eprintln!("engine_hw: {e}");
1881 -2
1882 }
1883 }
1884 }))
1885 .unwrap_or(-1)
1886}
1887
1888/// What a decoded buffer must look like to reach this encoder without a copy:
1889/// the surface size it codes in, written to `coded_width`/`coded_height`. 1 on
1890/// an answer, negative on none. NV12 and the size this session was opened for
1891/// are the rest of the shape, and the caller already knows both.
1892///
1893/// # Safety
1894/// `session` must come from [`vh_enc_open`]; both outputs must be writable.
1895#[unsafe(no_mangle)]
1896pub unsafe extern "C" fn vh_enc_dma_geometry(
1897 session: *mut c_void,
1898 coded_width: *mut u32,
1899 coded_height: *mut u32,
1900) -> i32 {
1901 catch_unwind(AssertUnwindSafe(|| {
1902 if session.is_null() || coded_width.is_null() || coded_height.is_null() {
1903 return -1;
1904 }
1905 // SAFETY: caller-guaranteed live session and writable destinations.
1906 unsafe {
1907 let session = &*(session as *const EncSession);
1908 *coded_width = session.coded.width;
1909 *coded_height = session.coded.height;
1910 }
1911 1
1912 }))
1913 .unwrap_or(-1)
1914}
1915
1916/// Encodes one picture the decoder left on the GPU, described by `dma` -- whose
1917/// file descriptor stays the *caller's*, borrowed for the length of the call.
1918/// Same answer and same lifetime rule as [`vh_enc_frame`]; a buffer of a shape
1919/// this session cannot read is an error and not a silent re-shape.
1920///
1921/// # Safety
1922/// `session` must come from [`vh_enc_open`], `dma` must be readable and its
1923/// descriptor open, and `out`/`out_len` must be writable.
1924#[unsafe(no_mangle)]
1925pub unsafe extern "C" fn vh_enc_frame_dma(
1926 session: *mut c_void,
1927 dma: *const VhDma,
1928 force_key: i32,
1929 out: *mut *const u8,
1930 out_len: *mut usize,
1931) -> i32 {
1932 catch_unwind(AssertUnwindSafe(|| {
1933 if session.is_null() || dma.is_null() || out.is_null() || out_len.is_null() {
1934 return -1;
1935 }
1936 // SAFETY: caller-guaranteed live session and readable descriptor.
1937 let (session, dma) = unsafe { (&mut *(session as *mut EncSession), &*dma) };
1938 match session.encode_dma(dma, force_key != 0) {
1939 Ok(()) => session.take(out, out_len),
1940 Err(e) => {
1941 eprintln!("engine_hw: {e}");
1942 -2
1943 }
1944 }
1945 }))
1946 .unwrap_or(-1)
1947}
1948
1949/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
1950/// 0 once every picture fed has been handed back, negative on error. Same
1951/// lifetime rule as [`vh_enc_frame`].
1952///
1953/// # Safety
1954/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
1955#[unsafe(no_mangle)]
1956pub unsafe extern "C" fn vh_enc_drain(
1957 session: *mut c_void,
1958 out: *mut *const u8,
1959 out_len: *mut usize,
1960) -> i32 {
1961 catch_unwind(AssertUnwindSafe(|| {
1962 if session.is_null() || out.is_null() || out_len.is_null() {
1963 return -1;
1964 }
1965 // SAFETY: caller-guaranteed live session.
1966 let session = unsafe { &mut *(session as *mut EncSession) };
1967 if !session.drained {
1968 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
1969 eprintln!("engine_hw: {e}");
1970 return -2;
1971 }
1972 session.drained = true;
1973 }
1974 match session.collect() {
1975 Ok(()) => session.take(out, out_len),
1976 Err(e) => {
1977 eprintln!("engine_hw: {e}");
1978 -2
1979 }
1980 }
1981 }))
1982 .unwrap_or(-1)
1983}
1984
1985/// Releases an encode session. Safe to call with null.
1986///
1987/// # Safety
1988/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
1989#[unsafe(no_mangle)]
1990pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
1991 let _ = catch_unwind(AssertUnwindSafe(|| {
1992 if !session.is_null() {
1993 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
1994 drop(unsafe { Box::from_raw(session as *mut EncSession) });
1995 }
1996 }));
1997}
1998
1999#[cfg(test)]
2000mod tests {
2001 use super::*;
2002
2003 /// The one number that decides whether a hardware file is intra-only, and
2004 /// the one this seat got wrong: a proxy asks for a group of one picture, so
2005 /// every picture is an IDR with its own parameter sets. Needs no GPU --
2006 /// which is the point, since the seat itself cannot be opened without one.
2007 #[test]
2008 fn an_intra_seat_asks_for_a_group_of_one_picture() {
2009 assert_eq!(gop_limit(30, true), 1, "a proxy is every frame a start");
2010 assert_eq!(gop_limit(24, true), 1);
2011 // ...and an ordinary export keeps its two seconds between them.
2012 assert_eq!(gop_limit(30, false), 60);
2013 assert_eq!(gop_limit(24, false), 48);
2014 // A rate no file has, and the clamp that keeps the limit a `u16`
2015 // rather than a wrapped one: `0` would divide by zero in the predictor.
2016 assert_eq!(gop_limit(0, false), 1);
2017 assert_eq!(gop_limit(u32::MAX, false), u16::MAX);
2018 }
2019
2020 /// What that group of one writes into the sequence header, which is the
2021 /// half that shipped broken: the predictor hands the limit straight to
2022 /// `SpsBuilder::max_frame_num` (`h264/predictor.rs:89`), and `1.ilog2()`
2023 /// is 0, so the old `0u8 - 4u8` wrapped to 252 in release. Every intra-only
2024 /// hardware file then carried `log2_max_frame_num_minus4 = 252` -- outside
2025 /// the spec's 0..=12 -- and no decoder would parse it. Zero is the right
2026 /// answer, not merely a legal one: `frame_num` never leaves 0 when every
2027 /// picture is an IDR. No GPU: this is the bitstream side of the seat.
2028 #[test]
2029 fn an_intra_seat_writes_a_sequence_header_a_decoder_can_read() {
2030 use cros_codecs::codec::h264::parser::SpsBuilder;
2031
2032 let limit = u32::from(gop_limit(30, true));
2033 let sps = SpsBuilder::new().max_frame_num(limit).max_pic_order_cnt_lsb(limit * 2).build();
2034 assert_eq!(sps.log2_max_frame_num_minus4, 0, "252 is what a wrap looks like");
2035 assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 0);
2036 // The ordinary export's limit is untouched by the saturation, and a
2037 // limit at the top of the `u16` stays inside the spec's 0..=12.
2038 let long = u32::from(gop_limit(30, false));
2039 assert_eq!(SpsBuilder::new().max_frame_num(long).build().log2_max_frame_num_minus4, 1);
2040 assert!(
2041 SpsBuilder::new().max_frame_num(u32::MAX).build().log2_max_frame_num_minus4 <= 12
2042 );
2043 }
2044
2045 /// The other half of the same fault: a slice is marked IDR only where the
2046 /// access unit carries an SPS, so a "forced key frame" that writes no
2047 /// parameter sets reads back as an ordinary I picture -- no decoder starts
2048 /// there, and `sync_points` does not count it.
2049 #[test]
2050 fn only_a_unit_carrying_parameter_sets_is_marked_idr() {
2051 // SPS (0x67) + PPS (0x68) + a slice the driver left at zero.
2052 let mut with_sets = vec![0, 0, 1, 0x67, 9, 0, 0, 1, 0x68, 9, 0, 0, 1, 0x00, 9];
2053 fix_slice_nal_headers(&mut with_sets);
2054 assert_eq!(with_sets[13], 0x65, "IDR slice after an SPS");
2055 // The same unit without them: a key frame the encoder was merely asked
2056 // for, which is what the hardware proxy used to be full of.
2057 let mut bare = vec![0, 0, 1, 0x00, 9];
2058 fix_slice_nal_headers(&mut bare);
2059 assert_eq!(bare[3], 0x41, "no parameter sets, no IDR");
2060 }
2061
2062 /// Runs against whatever GPU this machine has -- and passes on one with no
2063 /// VA-API at all, which is exactly what `None` means here. What it pins is
2064 /// the *shape* of the answer, the contents being the driver's: nothing may
2065 /// be claimed that this plugin cannot actually reach.
2066 #[test]
2067 fn the_caps_query_never_claims_more_than_this_plugin_implements() {
2068 let Some(caps) = query_caps() else {
2069 return;
2070 };
2071 eprintln!("{caps:?}");
2072 // Encode is this plugin's three seats and no others, whatever
2073 // entrypoints the driver has: a VP9 EncSlice is not an encoder here.
2074 assert_eq!(
2075 caps.encode & !(CAP_H264 | CAP_HEVC | CAP_AV1),
2076 0,
2077 "{caps:?}"
2078 );
2079 // A 10-bit claim is a decode claim -- same profile family, read back
2080 // through P010 -- and there is no 10-bit encode path at all.
2081 assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}");
2082 // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
2083 assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
2084 }
2085
2086 /// Every shape of the forward-or-flush decision a reposition makes, with
2087 /// no GPU in sight: the boundary a silence cut leaves is a target a few
2088 /// frames *ahead* of the decoder and that is the walk; behind it, past the
2089 /// reach, and past the end of the stream are the flush.
2090 #[test]
2091 fn a_target_ahead_within_the_reach_walks_forward() {
2092 use Reposition::{Flush, Forward};
2093 // A 30 fps stream, so the reach is [`FORWARD_SECS`] of it.
2094 let (count, limit) = (10_000u32, forward_limit(30.0));
2095 assert_eq!(forward_limit(30.0), 15);
2096 // The boundary a 0.3 s silence cut leaves: 9 frames ahead, dropped
2097 // unread on the way to exactly the target.
2098 assert_eq!(reposition(120, 129, count, limit), Forward(9));
2099 // Exactly at the reach, and a reseek to exactly where the decoder
2100 // stands (a superseded span's landing): nothing to do but not flush.
2101 assert_eq!(reposition(120, 135, count, limit), Forward(15));
2102 assert_eq!(reposition(120, 120, count, limit), Forward(0));
2103 // One frame past either end of the walk is the flush's.
2104 assert_eq!(reposition(120, 136, count, limit), Flush);
2105 assert_eq!(reposition(120, 119, count, limit), Flush);
2106 assert_eq!(reposition(120, 0, count, limit), Flush);
2107 // The last frame of the stream is a frame like any other...
2108 assert_eq!(reposition(9_995, 9_999, count, limit), Forward(4));
2109 // ...while a target at or past the end is not one decoding forward
2110 // can hand out: EOF falls back to the seek that always handled it.
2111 assert_eq!(reposition(9_995, 10_000, count, limit), Flush);
2112 assert_eq!(reposition(9_995, 60_000, count, limit), Flush);
2113 // From the end itself -- everything delivered, `pump` at clean EOF --
2114 // even a target inside the stream is behind.
2115 assert_eq!(reposition(10_000, 9_999, count, limit), Flush);
2116 }
2117
2118 /// The reach is time, carried at the stream's own rate, and a stream that
2119 /// states no rate gets none of it: such a session keeps the behaviour
2120 /// every reposition had, rather than a skip of nonsense frames.
2121 #[test]
2122 fn the_reach_is_half_a_second_at_the_streams_own_rate() {
2123 assert_eq!(forward_limit(23.976), 12);
2124 assert_eq!(forward_limit(24.0), 12);
2125 assert_eq!(forward_limit(60.0), 30);
2126 assert_eq!(forward_limit(0.0), 0);
2127 assert_eq!(forward_limit(f64::NAN), 0);
2128 assert_eq!(forward_limit(-30.0), 0);
2129 }
2130
2131 /// The drain machine's one law, held across *stacked* repositions: the
2132 /// picture delivered is `position + skip`, `position` advancing one per
2133 /// handle popped ([`Session::pump`]). A second forward reseek before the
2134 /// first's skip has drained must land on its own target -- the skip is
2135 /// replaced ([`forward_skip`]), never added to, or every reseek inside
2136 /// another's window walks its predecessor's frames past the target and
2137 /// the pictures keep arriving, only wrong.
2138 #[test]
2139 fn stacked_forward_reseeks_land_exactly_on_their_target() {
2140 use Reposition::Forward;
2141 let (count, limit) = (10_000u32, forward_limit(30.0));
2142 let land = |position: i64, skip: u32| position + i64::from(skip);
2143 let (mut position, mut skip) = (100i64, 0u32);
2144 let Forward(ahead) = reposition(position, 110, count, limit) else {
2145 panic!("110 is within the reach of 100")
2146 };
2147 skip = forward_skip(skip, ahead);
2148 let Forward(ahead) = reposition(position, 114, count, limit) else {
2149 panic!("114 is within the reach of 100")
2150 };
2151 skip = forward_skip(skip, ahead);
2152 assert_eq!(land(position, skip), 114, "the second target, exactly");
2153
2154 // A flush whose RAP skip is still undrained when a forward span is
2155 // asked: the flush stood at its RAP with `skip` toward its own
2156 // target, and the forward reseek through that window replaces it.
2157 position = 200;
2158 skip = 12;
2159 let Forward(ahead) = reposition(position, 208, count, limit) else {
2160 panic!("208 is within the reach of 200")
2161 };
2162 skip = forward_skip(skip, ahead);
2163 assert_eq!(land(position, skip), 208, "a flush's undrained skip does not compound");
2164
2165 // ...and a reseek to exactly where the decoder stands cancels
2166 // whatever was standing: the next handle is shown, not skipped past.
2167 let Forward(ahead) = reposition(position, position, count, limit) else {
2168 panic!("a session's own position is within its reach")
2169 };
2170 skip = forward_skip(skip, ahead);
2171 assert_eq!((ahead, land(position, skip)), (0, position));
2172 }
2173}