forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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