forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

lib.rs1096 lines, 47.3 KiBHistoryRawDownload
1//! Hardware decode and encode, held in a child process. This library is the
2//! whole world of the `hw-child` binary ([`child`]), the one process a video
3//! driver is allowed to kill: VA-API decode (H.264, HEVC, VP9 and AV1), VP8
4//! decode on `ec-vp8` ([`vpx`], software, linked in), and the encode seats
5//! (H.264, HEVC, and AV1 where the GPU has the entrypoint).
6//!
7//! It is a plain safe Rust crate: there is no `extern "C"` surface, no
8//! `dlopen`, and no `unsafe` anywhere in it. The editor never links it; it
9//! spawns the binary and speaks [`engine::hwproc`]'s wire to it, so an
10//! `abort()` from a driver costs the caller a fallback and nothing more.
11
12#![forbid(unsafe_code)]
13
14pub mod child;
15mod enc_ec;
16mod vpx;
17
18use std::collections::VecDeque;
19use std::os::fd::OwnedFd;
20use std::path::Path;
21use std::rc::Rc;
22
23use ec_hw::Frame;
24use ec_hw::enc::EncCodec as EcCodec;
25use ec_va::caps::Profile;
26use enc_ec::{EcEncSession, EcOpen};
27use engine::demux::{Codec, Demuxer, VideoMeta};
28use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhMeta};
29
30/// How many undecodable access units a seek may drop before the session gives
31/// up and calls the stream broken. An open GOP's leading pictures are a handful
32/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one
33/// we restarted in the middle of, so the error is real and the caller still
34/// hears it.
35/// `VA_FOURCC_NV12` and `VA_FOURCC_P010`: the four characters, little-endian.
36const VA_FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");
37const VA_FOURCC_P010: u32 = u32::from_le_bytes(*b"P010");
38
39const LEADING_LIMIT: u32 = 64;
40
41/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and
42/// therefore how many extra buffers the pool reserves the moment a caller asks
43/// for one. The export's decode channel is two pictures deep and it encodes the
44/// one it is holding, so at most four are ever outstanding; the rest is margin,
45/// at ~3 MB of video memory each.
46const DMA_HOLD: usize = 6;
47
48/// How far ahead of the decode position [`Session::seek_to`] walks forward
49/// rather than flushing, in seconds of the stream's own frames. A silence cut
50/// lands the next span ahead of the decoder by the length of what it removed
51/// -- tenths of a second -- and walking that forward costs only the decode of
52/// the frames in between, dropped without the read-back ([`Session::pump`]'s
53/// skip path) with the decoder's reference chain and pipeline depth left
54/// standing. The flush it replaces costs a decoder reset, a demuxer seek to
55/// the random access point, up to a group of skip-decoded pictures behind it,
56/// and a full re-prime before the first frame is out again (~178 ms measured
57/// at 4K, which is longer than the clips a silence cut leaves); past half a
58/// second of walking, the skip-decode run alone approaches that bill and a
59/// real seek wins.
60const FORWARD_SECS: f64 = 0.5;
61
62/// The forward reach in frames: [`FORWARD_SECS`] at the stream's own rate.
63/// `0` for a rate the stream does not really state, which is "never forward"
64/// -- exactly the flush every reposition did before this distinction existed.
65fn forward_limit(frame_rate: f64) -> u32 {
66 (FORWARD_SECS * frame_rate).round().max(0.) as u32
67}
68
69/// How a reposition to `target` (a 0-based display frame) is reached from
70/// `position`, the frame the session would hand out next. Pure arithmetic,
71/// so every shape of the answer is testable without a GPU.
72#[derive(Debug, PartialEq, Eq, Clone, Copy)]
73enum Reposition {
74 /// Decode forward from where the session stands, dropping this many
75 /// pictures on the way: no flush, no demuxer seek, no re-prime.
76 Forward(u32),
77 /// Flush the decoder and seek the demuxer to the random access point at
78 /// or before `target`.
79 Flush,
80}
81
82fn reposition(position: i64, target: i64, frame_count: u32, limit: u32) -> Reposition {
83 // A decoder cannot walk backwards, and a target at or past the last frame
84 // is not one decoding forward can hand out -- both take the seek that has
85 // always handled them, EOF included.
86 if target < position || target >= i64::from(frame_count) {
87 return Reposition::Flush;
88 }
89 match u32::try_from(target - position) {
90 Ok(ahead) if ahead <= limit => Reposition::Forward(ahead),
91 _ => Reposition::Flush,
92 }
93}
94
95/// The skip a forward reposition leaves standing: `ahead` itself, replacing
96/// whatever skip was undrained -- `_standing` is read by no one, on purpose.
97/// [`Session::pump`] advances `position` for every handle it pops, dropped
98/// and delivered alike, so the next picture delivered is always
99/// `position + skip`: only a replacement keeps that on the target. An
100/// accumulate would land `ahead` frames past it -- and silently, because the
101/// pictures keep arriving (a stacked reseek before the first drains, or a
102/// flush whose RAP skip is still standing when a forward span is asked).
103fn forward_skip(_standing: u32, ahead: u32) -> u32 {
104 ahead
105}
106
107struct Session {
108 decoder: ec_hw::Decoder,
109 /// The VA-API display the decoder's context and surfaces live on: kept
110 /// alive for as long as the session is.
111 _display: Rc<ec_va::Display>,
112 demuxer: Demuxer,
113 meta: VhMeta,
114 timestamp: i64,
115 /// `flush` has been called: the next empty `pump` is end of stream.
116 flushed: bool,
117 /// Pictures still to be decoded and thrown away to land on a seek target.
118 skip: u32,
119 /// The display frame the next `pump` would hand out, however it gets
120 /// there: one further along for every frame taken from the decoder, skipped
121 /// past and delivered alike. The one thing that can tell a reposition
122 /// *ahead* of the decoder from one behind it ([`Session::seek_to`]).
123 position: i64,
124 /// Access units dropped because they referenced pictures this session never
125 /// decoded -- see [`Session::pump`]. Counted rather than flagged so the
126 /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a
127 /// picture is handed out, which is where the window closes.
128 leading: u32,
129 /// Tightly packed I420 handed out as the picture; reused every frame,
130 /// which is exactly why a picture is only valid until the next pump.
131 out: Vec<u8>,
132 luma: usize,
133 chroma: usize,
134 /// What the caller's encoder can read straight off the GPU, asked once per
135 /// [`vh_next_frame_dma`] call and `None` for every read-back caller.
136 want: Option<VhDma>,
137 /// The descriptor the last such call produced, its file descriptor already
138 /// belonging to the caller. `None` says that picture was read back instead.
139 dma: Option<(VhDma, Vec<OwnedFd>)>,
140 /// Pictures handed out as DRM-PRIME buffers, newest last. Holding a frame
141 /// holds its surface out of the decoder's pool, so the decoder would write
142 /// the next picture into the one an encoder is still reading unless this
143 /// keeps the last [`DMA_HOLD`] of them alive.
144 held: VecDeque<Frame>,
145}
146
147/// The VA-API display the decoders run on: the first render node that opens.
148fn open_decode_display() -> Option<Rc<ec_va::Display>> {
149 ec_va::open().ok()
150}
151
152impl Session {
153 /// Assembles the VA-API half around a container that is already read --
154 /// [`OpenSession::open_at`] owns the read and routes VP8 away from here
155 /// before any device is opened.
156 fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {
157 let display = open_decode_display()?;
158 let codec = match meta.codec {
159 Codec::H264 => ec_hw::Codec::H264,
160 Codec::Hevc => ec_hw::Codec::H265,
161 Codec::Vp9 => ec_hw::Codec::Vp9,
162 Codec::Av1 => ec_hw::Codec::Av1,
163 // Routed to [`VpxSession`] by [`OpenSession::open_at`] before
164 // this half is ever built.
165 Codec::Vp8 => return None,
166 // Never offered to VA-API: `decode::hw_decodes` refuses it first.
167 Codec::Mpeg2 | Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Mpeg4 | Codec::MsMpeg4 | Codec::Raw => return None,
168 };
169 let decoder = ec_hw::Decoder::new(&display, codec).ok()?;
170 Some(Self {
171 decoder,
172 _display: display,
173 demuxer,
174 meta: VhMeta {
175 width: meta.width,
176 height: meta.height,
177 frame_rate: meta.frame_rate,
178 frame_count: meta.frame_count,
179 coded_width: meta.coded_width,
180 coded_height: meta.coded_height,
181 pixel_aspect_h: meta.pixel_aspect.h,
182 pixel_aspect_v: meta.pixel_aspect.v,
183 },
184 timestamp: 0,
185 flushed: false,
186 skip: 0,
187 position: 0,
188 // A stream read from its own beginning has no missing references
189 // and therefore no leading pictures to forgive: the window opens
190 // only for a session positioned somewhere else ([`OpenSession::open_at`]),
191 // so a file whose first picture will not decode is still refused at
192 // the door rather than opening onto nothing.
193 leading: LEADING_LIMIT,
194 out: Vec::new(),
195 luma: 0,
196 chroma: 0,
197 want: None,
198 dma: None,
199 held: VecDeque::new(),
200 })
201 }
202
203 /// Repositions an **open** session, exactly as [`OpenSession::open_at`]
204 /// positions a new one: the next [`Session::pump`] hands back sample
205 /// `target_sample`.
206 ///
207 /// A target *ahead* of where the decoder stands, within [`FORWARD_SECS`]
208 /// of it, is reached by decoding on and dropping the pictures in between
209 /// ([`reposition`]) -- no reset, no demuxer seek, no re-prime. Everything
210 /// else pays the demuxer seek and the decoder reset.
211 fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
212 // The same arithmetic `open_at` does, for the same reason.
213 let target_frame = target_sample.saturating_sub(1);
214 if let Reposition::Forward(ahead) = reposition(
215 self.position,
216 i64::from(target_frame),
217 self.meta.frame_count,
218 forward_limit(self.meta.frame_rate),
219 ) {
220 // Nothing about the session moves but the skip: it *replaces*
221 // whatever skip was standing, never adds to it ([`forward_skip`]).
222 self.skip = forward_skip(self.skip, ahead);
223 return Ok(());
224 }
225 // Discard all picture state, and whatever the decoder had completed
226 // but not yet handed out: those pictures belong to where the session
227 // *was*.
228 self.decoder.reset();
229 self.flushed = false;
230 let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
231 self.skip = (i64::from(target_frame) - first).max(0) as u32;
232 self.position = first;
233 // ...and the same open-GOP window: a session positioned anywhere but the
234 // start may meet leading pictures that reference what it never decoded.
235 self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT };
236 Ok(())
237 }
238
239 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
240 fn pump(&mut self) -> Result<bool, String> {
241 loop {
242 if let Some(frame) = self.decoder.next_frame() {
243 // One picture further along, shown or skipped past alike:
244 // this is the only place [`Session::position`] walks.
245 self.position += 1;
246 // Seek discards: dropping the frame skips the read-back and
247 // frees its pool surface.
248 if self.skip > 0 {
249 self.skip -= 1;
250 continue;
251 }
252 self.deliver(frame)?;
253 // Past the random access point's leading pictures: a decode
254 // error from here on is a real one again.
255 self.leading = LEADING_LIMIT;
256 return Ok(true);
257 }
258 if self.flushed {
259 return Ok(false);
260 }
261 match self.demuxer.next_access_unit() {
262 Ok(Some(au)) => {
263 match self.decoder.decode(&au, self.timestamp) {
264 Ok(()) => {}
265 // A picture that references pictures we never decoded,
266 // which is what an open GOP's leading pictures are after
267 // a seek: they display *before* the random access point
268 // we restarted at, so they are not ours to show and the
269 // stream is not broken. Drop the access unit and walk on.
270 Err(e) if self.leading < LEADING_LIMIT => {
271 if self.leading == 0 {
272 eprintln!("engine_hw: skipping leading pictures after seek ({e})");
273 }
274 self.leading += 1;
275 }
276 Err(e) => return Err(e.to_string()),
277 }
278 self.timestamp += 1;
279 }
280 Ok(None) => {
281 self.decoder.flush().map_err(|e| e.to_string())?;
282 self.flushed = true;
283 }
284 Err(e) => return Err(e.to_string()),
285 }
286 }
287 }
288
289 /// Hands one decoded picture to the caller: as the buffer it was decoded
290 /// into where that is what the caller asked for and the encoder on the
291 /// other side can read it, and as read-back I420 everywhere else.
292 fn deliver(&mut self, frame: Frame) -> Result<(), String> {
293 self.dma = None;
294 if self.want.is_some()
295 && let Some(dma) = self.export_dma(&frame)
296 {
297 self.meta.width = dma.0.width;
298 self.meta.height = dma.0.height;
299 self.dma = Some(dma);
300 // Kept out of the pool until the caller is [`DMA_HOLD`] pictures
301 // past it, by which time nothing is reading it any more.
302 self.held.push_back(frame);
303 while self.held.len() > DMA_HOLD {
304 self.held.pop_front();
305 }
306 return Ok(());
307 }
308 self.emit(&frame)
309 }
310
311 /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the
312 /// caller's encoder takes -- one composed two-plane layer in at most two
313 /// objects, the fourcc and both sizes it asked for. `None` for every other
314 /// answer, and the caller then gets the pixels it always got rather than a
315 /// failure.
316 fn export_dma(&self, frame: &Frame) -> Option<(VhDma, Vec<OwnedFd>)> {
317 let want = self.want?;
318 let (w, h) = frame.display_size;
319 if (w, h) != (want.width, want.height) {
320 return None;
321 }
322 let prime = frame.export_prime().ok()?;
323 // The driver describes the NV12 buffer as one layer per plane (R8 and
324 // GR88, each one plane into the same object), or as one composed layer
325 // holding both: either is the same two planes, in that order.
326 let planes: Vec<(u32, u32, u32)> = match prime.layers.as_slice() {
327 [layer] => layer.planes.clone(),
328 [luma, chroma] => {
329 let ([y], [uv]) = (luma.planes.as_slice(), chroma.planes.as_slice()) else {
330 return None;
331 };
332 vec![*y, *uv]
333 }
334 _ => return None,
335 };
336 let [(obj0, off0, pitch0), (obj1, off1, pitch1)] = planes.as_slice() else {
337 return None;
338 };
339 if prime.fourcc != want.fourcc
340 || prime.width != want.coded_width
341 || prime.height != want.coded_height
342 || *obj0 != 0
343 || *obj1 > 1
344 || prime.objects.len() != *obj1 as usize + 1
345 {
346 return None;
347 }
348 let planes = [*obj0, *obj1];
349 let (offset, stride) = ([*off0, *off1], [*pitch0, *pitch1]);
350 // Whatever the driver says the two planes live in, said back to it
351 // unchanged on the import: radeonsi answers with an object per plane,
352 // other drivers with one for both, and neither is ours to reinterpret.
353 let modifier = prime.objects[0].modifier;
354 let mut objects = prime.objects.into_iter();
355 // Owned by the caller from here: they travel to the encoder with the
356 // descriptor, one per plane object.
357 let mut fds = vec![objects.next()?.fd];
358 if planes[1] == 1 {
359 fds.push(objects.next()?.fd);
360 }
361 Some((
362 VhDma {
363 fourcc: prime.fourcc,
364 modifier,
365 coded_width: prime.width,
366 coded_height: prime.height,
367 width: w,
368 height: h,
369 offset,
370 stride,
371 },
372 fds,
373 ))
374 }
375
376 /// Copies a decoded picture into `self.out` as packed I420.
377 fn emit(&mut self, frame: &Frame) -> Result<(), String> {
378 // The read-back goes through the driver's image copy (`vaGetImage`)
379 // rather than a CPU map of the surface: on a discrete GPU that buffer
380 // lives in VRAM, and a CPU read of it runs over the PCIe BAR.
381 let i420 = frame.to_i420().map_err(|e| e.to_string())?;
382 self.luma = i420.y.len();
383 self.chroma = i420.u.len();
384 self.out.clear();
385 self.out.extend_from_slice(&i420.y);
386 self.out.extend_from_slice(&i420.u);
387 self.out.extend_from_slice(&i420.v);
388 self.meta.width = i420.width;
389 self.meta.height = i420.height;
390 Ok(())
391 }
392
393 /// The picture [`Session::pump`] or [`VpxSession::pump`] just delivered, as
394 /// packed I420 (Y, then U, then V), with its width and height.
395 fn picture(&self) -> (&[u8], u32, u32) {
396 (&self.out, self.meta.width, self.meta.height)
397 }
398}
399
400/// What the plugin is decoding a file on: the VA-API stateless decoders, or
401/// -- for VP8 alone -- libvpx in this plugin's own address space. The split
402/// is the codec's, decided once at [`OpenSession::open_at`]: VP8 opens no VA
403/// display (this GPU has no VP8 profile to ask it for, and a machine with no
404/// render node at all still decodes VP8), and the other four never touch
405/// libvpx.
406///
407/// Everything past the split is written twice -- [`Session`] for the VA-API
408/// decoders and [`VpxSession`] for libvpx -- rather than folded into one
409/// shape: the halves share the *contract* (open at a sample, pump one
410/// picture, read it back) and nothing underneath it, and a trait over
411/// "a `vaGetImage`" versus "a memcpy" is the kind of seam that hides which
412/// path a measurement ran on.
413enum OpenSession {
414 Vaapi(Box<Session>),
415 Vpx(Box<VpxSession>),
416}
417
418impl OpenSession {
419 /// Opens `path` for decode, positioned so the first picture handed out is
420 /// sample `target_sample` (1-based): decode restarts at the sync sample at
421 /// or before it and the pictures in between are dropped unread. The same
422 /// landing for both halves; the codec's half is chosen here, where the
423 /// container has been read and no device has been opened yet.
424 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
425 let (meta, demuxer) = Demuxer::open(path).ok()?;
426 let session = match meta.codec {
427 Codec::Vp8 => Self::Vpx(Box::new(VpxSession::opened(meta, demuxer)?)),
428 _ => {
429 // The GPU was reset moments ago (a hung ring: every VA context
430 // alive then was reset with it, and Mesa aborts the process on
431 // the next submit to one). A session opened now would be one of
432 // them, so it is refused and the caller takes the software seat
433 // until the grace period is over.
434 if ec_hw::gpu_recently_reset() {
435 return None;
436 }
437 Self::Vaapi(Box::new(Session::opened(meta, demuxer)?))
438 }
439 };
440 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
441 // display frames -- and answers with a signed one, since a sync sample
442 // inside what the edit list trims sits before frame 0.
443 let target_frame = target_sample.saturating_sub(1);
444 match session {
445 Self::Vaapi(mut session) => {
446 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
447 session.skip = (i64::from(target_frame) - first).max(0) as u32;
448 session.position = first;
449 if target_frame > 0 {
450 session.leading = 0;
451 }
452 Some(Self::Vaapi(session))
453 }
454 Self::Vpx(mut session) => {
455 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
456 session.skip = (i64::from(target_frame) - first).max(0) as u32;
457 session.position = first;
458 Some(Self::Vpx(session))
459 }
460 }
461 }
462
463 fn meta(&self) -> &VhMeta {
464 match self {
465 Self::Vaapi(session) => &session.meta,
466 Self::Vpx(session) => &session.meta,
467 }
468 }
469
470 fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
471 match self {
472 Self::Vaapi(session) => session.seek_to(target_sample),
473 Self::Vpx(session) => session.seek_to(target_sample),
474 }
475 }
476
477 /// The picture the last successful [`OpenSession::next_frame`] delivered as
478 /// read-back I420, with its width and height.
479 fn picture(&self) -> (&[u8], u32, u32) {
480 match self {
481 Self::Vaapi(session) => session.picture(),
482 Self::Vpx(session) => session.picture(),
483 }
484 }
485
486 /// Pumps the next picture in display order. `want` describes what the
487 /// caller's encoder can read straight off the GPU; it is only ever honoured
488 /// by the VA-API half, and it is cleared again before this returns.
489 fn next_frame(&mut self, want: Option<VhDma>) -> Result<bool, String> {
490 match self {
491 Self::Vaapi(session) => {
492 session.want = want;
493 let pumped = session.pump();
494 session.want = None;
495 pumped
496 }
497 Self::Vpx(session) => session.pump(),
498 }
499 }
500
501 /// The DRM-PRIME buffer the last [`OpenSession::next_frame`] left on the
502 /// GPU, if it did: its descriptor and the descriptors that go with it.
503 /// `None` means that picture is in [`OpenSession::picture`] instead.
504 fn take_dma(&mut self) -> Option<(VhDma, Vec<OwnedFd>)> {
505 match self {
506 Self::Vaapi(session) => session.dma.take(),
507 Self::Vpx(_) => None,
508 }
509 }
510}
511
512/// One VP8 decode session: the VP8 half of the plugin, the whole of the
513/// same job [`Session`] does for the VA-API codecs. No display, no GBM, no
514/// surface pool -- `ec-vp8` hands the planes back in memory, and the only
515/// shapes worth carrying over from the other half are the ones the caller
516/// sees: [`VhMeta`], one picture per `pump`, the same packed layout, the
517/// same skip/position arithmetic a seek is.
518///
519/// VP8 reorders nothing: every access unit fed is *at most* one picture out,
520/// in feed order (a hidden altref frame produces none), which is why
521/// `position` advances exactly as the VA-API half's does without any of its
522/// drain machinery.
523struct VpxSession {
524 dec: vpx::Decoder,
525 demuxer: Demuxer,
526 meta: VhMeta,
527 flushed: bool,
528 /// Pictures still to be decoded and thrown away to land on a seek target,
529 /// exactly [`Session`]'s field of the same name.
530 skip: u32,
531 /// The display frame the next `pump` would hand out -- [`Session`]'s
532 /// field, again: one further along for every picture pulled, skipped past
533 /// and delivered alike.
534 position: i64,
535 /// Tightly packed I420 handed out as the picture; reused every
536 /// frame, which is exactly why a picture is only valid until the next
537 /// pump.
538 out: Vec<u8>,
539 luma: usize,
540 chroma: usize,
541}
542
543impl VpxSession {
544 fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {
545 // The decoder cannot refuse to exist any more: it is linked in. The
546 // `Option` is the shape [`OpenSession::open_at`] routes on, shared
547 // with [`Session::opened`], whose failures are real.
548 Some(Self {
549 dec: vpx::Decoder::new(),
550 demuxer,
551 meta: VhMeta {
552 width: meta.width,
553 height: meta.height,
554 frame_rate: meta.frame_rate,
555 frame_count: meta.frame_count,
556 coded_width: meta.coded_width,
557 coded_height: meta.coded_height,
558 pixel_aspect_h: meta.pixel_aspect.h,
559 pixel_aspect_v: meta.pixel_aspect.v,
560 },
561 flushed: false,
562 skip: 0,
563 position: 0,
564 out: Vec::new(),
565 luma: 0,
566 chroma: 0,
567 })
568 }
569
570 /// Feeds one access unit. VP8 emits at most one picture per unit, so the
571 /// pull belongs to the `pump` loop, not here.
572 fn decode(&mut self, au: &[u8]) -> Result<(), String> {
573 self.dec.decode(au)
574 }
575
576 fn pump(&mut self) -> Result<bool, String> {
577 loop {
578 if self.flushed {
579 return Ok(false);
580 }
581 let au = match self.demuxer.next_access_unit() {
582 Ok(Some(au)) => au,
583 // End of the track. VP8 holds nothing back -- the flush is the
584 // formality [`vpx::Decoder::flush`] documents -- so the next
585 // pass finds nothing and ends the stream.
586 Ok(None) => {
587 self.dec.flush()?;
588 self.flushed = true;
589 continue;
590 }
591 Err(e) => return Err(e.to_string()),
592 };
593 self.decode(&au)?;
594 // Every fed unit is one container slot, shown or hidden: a hidden
595 // alt-ref frame takes a slot and sends no picture, exactly as the
596 // software seat's index counts it. The slot is taken, not peeked --
597 // the next fed unit overwrites it, because VP8 queues nothing.
598 let shown = self.dec.get_frame();
599 self.position += 1;
600 // Both the skip and the walk count slots, so a seek that lands
601 // past a hidden frame drops the right number of pictures.
602 if self.skip > 0 {
603 self.skip -= 1;
604 continue;
605 }
606 if let Some(pic) = shown {
607 self.emit(&pic);
608 return Ok(true);
609 }
610 }
611 }
612
613 /// Copies one decoded I420 picture into `self.out` -- [`Session::emit`]
614 /// for a decoder that hands the planes back in memory rather than behind
615 /// a `vaGetImage`. VP8 output is always 8-bit 4:2:0, so there is no
616 /// 10-bit branch to mirror.
617 fn emit(&mut self, pic: &vpx::Picture) {
618 let (w, h) = (usize::from(pic.width), usize::from(pic.height));
619 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
620 if self.luma != w * h || self.chroma != cw * ch {
621 self.luma = w * h;
622 self.chroma = cw * ch;
623 self.out = vec![0u8; self.luma + 2 * self.chroma];
624 }
625 self.meta.width = u32::from(pic.width);
626 self.meta.height = u32::from(pic.height);
627 let (dst_y, rest) = self.out.split_at_mut(self.luma);
628 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
629 // The planes stride-cover the visible frame by the `Picture`
630 // contract (4:2:0, so the chroma planes cover cw x ch), and they are
631 // owned by this session -- no lifetime to out-think, no unsafe.
632 copy_plane(&pic.y, pic.stride, dst_y, w, h);
633 copy_plane(&pic.u, pic.uv_stride, dst_u, cw, ch);
634 copy_plane(&pic.v, pic.uv_stride, dst_v, cw, ch);
635 }
636
637 /// The picture [`Session::pump`] or [`VpxSession::pump`] just delivered, as
638 /// packed I420 (Y, then U, then V), with its width and height.
639 fn picture(&self) -> (&[u8], u32, u32) {
640 (&self.out, self.meta.width, self.meta.height)
641 }
642
643 /// Repositions the session, exactly [`Session::seek_to`]: the same
644 /// forward walk within [`FORWARD_SECS`], the same demuxer seek to a sync
645 /// sample otherwise -- and for the decoder, a fresh [`vpx::Decoder`]
646 /// where the VA-API half pays a flush, because VP8 is stateful to its
647 /// last inter frame.
648 fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
649 let target_frame = target_sample.saturating_sub(1);
650 if let Reposition::Forward(ahead) = reposition(
651 self.position,
652 i64::from(target_frame),
653 self.meta.frame_count,
654 forward_limit(self.meta.frame_rate),
655 ) {
656 self.skip = forward_skip(self.skip, ahead);
657 return Ok(());
658 }
659 // Dropping every reference the decoder holds: the whole of what the
660 // FFI seat paid as destroy + re-init is now the assignment of an
661 // owned value. What makes it safe is unchanged -- the demuxer's
662 // sync-sample seek restarts the feed where the reference chain does.
663 self.dec = vpx::Decoder::new();
664 self.flushed = false;
665 let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
666 self.skip = (i64::from(target_frame) - first).max(0) as u32;
667 self.position = first;
668 Ok(())
669 }
670}
671
672/// One strided plane down to tightly packed rows: the whole of the read-back
673/// a VP8 picture costs, where the VA-API half pays `vaGetImage` for the same.
674fn copy_plane(src: &[u8], src_stride: usize, dst: &mut [u8], w: usize, h: usize) {
675 for row in 0..h {
676 let s = &src[row * src_stride..row * src_stride + w];
677 dst[row * w..(row + 1) * w].copy_from_slice(s);
678 }
679}
680
681/// One row of [`CAP_TABLE`]: the capability bit, its 8-bit and 10-bit decode profiles, and its encode profile.
682type CapRow = (u32, &'static [Profile], &'static [Profile], Option<Profile>);
683
684/// What each codec needs of the driver before this plugin can claim it: the
685/// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here
686/// would open -- `None` for the one this plugin has no encoder for at all, so a
687/// GPU with a VP9 encode entrypoint is never reported as one edith can
688/// reach. The encode profiles are the very ones the seats in [`enc_ec`] and
689/// [`EncSession::open_seat`] ask for, which is what keeps this a description of the plugin rather than a
690/// second opinion about it.
691const CAP_TABLE: [CapRow; 4] = [
692 (
693 CAP_H264,
694 &[
695 Profile::H264ConstrainedBaseline,
696 Profile::H264Main,
697 Profile::H264High,
698 ],
699 &[],
700 Some(Profile::H264Main),
701 ),
702 (
703 CAP_HEVC,
704 &[Profile::HEVCMain],
705 &[Profile::HEVCMain10],
706 // 8-bit Main only: the encoder here opens Main whatever the source was,
707 // so a Main 10 entrypoint is a *decode* claim on this line and nothing
708 // more. Main 10 encode would be a second profile here and a 10-bit input
709 // buffer in `EncSession`, neither of which exists yet.
710 Some(Profile::HEVCMain),
711 ),
712 (
713 CAP_VP9,
714 &[Profile::VP9Profile0],
715 &[Profile::VP9Profile2],
716 None,
717 ),
718 (
719 CAP_AV1,
720 &[Profile::AV1Profile0],
721 // AV1 carries 8- and 10-bit in the same profile 0, so the profile bit
722 // is the same one and the P010 read-back is what decides.
723 &[Profile::AV1Profile0],
724 Some(Profile::AV1Profile0),
725 ),
726];
727
728/// This machine's decode and encode seats, asked of the driver rather than
729/// assumed: which profiles it has, which entrypoints each of those carries, and
730/// whether a P010 image exists to read a 10-bit picture back through. Only
731/// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
732/// half of the intersection.
733///
734/// VP8 is the one bit asked of nobody: it is this plugin's own native seat
735/// (`vpx`, `ec-vp8` linked in), lit unconditionally -- no profile, no
736/// entrypoint, no display, no library to load. It rides along only when the
737/// display *is* answerable, because this symbol's shape says a displayless
738/// machine has nothing to report at all; the decode path itself needs no
739/// display for it ([`OpenSession::open_at`] routes VP8 before any device
740/// opens).
741///
742/// `None` when there is no display to ask at all, which is the same "software
743/// only" a missing plugin means.
744fn query_caps() -> Option<VhCaps> {
745 use ec_va::caps::Entrypoint;
746 let display = open_decode_display()?;
747 let report = ec_va::CapReport::probe(&display).ok()?;
748 let p010 = report.image_formats.contains(&VA_FOURCC_P010);
749 let decodes = |list: &[Profile]| list.iter().any(|&p| report.supports(p, Entrypoint::VLD));
750 let mut caps = VhCaps::default();
751 for (bit, eight, ten, encode) in CAP_TABLE {
752 if decodes(eight) {
753 caps.decode |= bit;
754 }
755 if p010 && decodes(ten) {
756 caps.decode_10bit |= bit;
757 }
758 // Both entrypoints, exactly as the encoder's own open takes either.
759 if encode.is_some_and(|p| {
760 report.supports(p, Entrypoint::EncSlice) || report.supports(p, Entrypoint::EncSliceLP)
761 }) {
762 caps.encode |= bit;
763 }
764 }
765 // The plugin's own software decoder, on its own account rather than the
766 // driver's -- the plugin's capability, never a GPU feat. Native now, so
767 // the bit has no "when it loads" condition left: it lights on every
768 // machine this plugin runs on.
769 caps.decode |= CAP_VP8;
770 Some(caps)
771}
772
773/// How many pictures a group of them holds -- the low-delay predictor's
774/// `limit`, which is the *only* thing that decides whether a picture is an IDR.
775///
776/// One for an intra-only seat, and that is not a tuning: the predictor counts
777/// `counter % limit`, so a limit of one pins the counter at zero, every picture
778/// takes the keyframe branch with `idr` set, and every access unit carries a
779/// fresh SPS and PPS
780/// (`cros-codecs/encoder/stateless/predictor.rs:107`, `h264/predictor.rs:139`).
781/// Two seconds otherwise, which is what a seek may land on in an ordinary file.
782///
783/// Forcing a key frame per picture is a different thing and does *not* make an
784/// intra file: that path passes `idr = false`, writes no parameter sets, and
785/// the slice is an ordinary I picture -- how a 60-picture "all-intra" hardware
786/// proxy came out with one sync point in it.
787fn gop_limit(framerate: u32, intra_only: bool) -> u16 {
788 match intra_only {
789 true => 1,
790 // Saturating and clamped: the caller pins the rate to 1..240 before it
791 // gets here, and a limit that wrapped to zero would divide by zero in
792 // the predictor -- a guard costs nothing next to that.
793 false => framerate.saturating_mul(2).clamp(1, u16::MAX as u32) as u16,
794 }
795}
796
797/// Opens the encode seat `open` names, or `None` where the driver has no such
798/// entrypoint or refuses the size -- the caller then takes the software encoder.
799pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession> {
800 use engine::hwproc::Seat;
801 let (codec, intra_only, colour) = match open.seat {
802 Seat::H264 => (EcCodec::H264, false, None),
803 Seat::Intra => (EcCodec::H264, true, None),
804 Seat::Av1 => (EcCodec::Av1, false, None),
805 Seat::Hevc => {
806 let (p, t, m) = open.colour.codes();
807 let narrow = |code: u16| u8::try_from(code).unwrap_or(u8::MAX);
808 (
809 EcCodec::H265,
810 true,
811 Some((narrow(p), narrow(t), narrow(m), open.colour.full_range)),
812 )
813 }
814 };
815 EcEncSession::open(EcOpen {
816 codec,
817 width: open.width,
818 height: open.height,
819 fps_num: open.fps_num,
820 fps_den: open.fps_den,
821 bitrate: open.bitrate,
822 intra_only,
823 colour,
824 })
825}
826
827#[cfg(test)]
828mod tests {
829 use super::*;
830
831 /// The one number that decides whether a hardware file is intra-only, and
832 /// the one this seat got wrong: a proxy asks for a group of one picture, so
833 /// every picture is an IDR with its own parameter sets. Needs no GPU --
834 /// which is the point, since the seat itself cannot be opened without one.
835 #[test]
836 fn an_intra_seat_asks_for_a_group_of_one_picture() {
837 assert_eq!(gop_limit(30, true), 1, "a proxy is every frame a start");
838 assert_eq!(gop_limit(24, true), 1);
839 // ...and an ordinary export keeps its two seconds between them.
840 assert_eq!(gop_limit(30, false), 60);
841 assert_eq!(gop_limit(24, false), 48);
842 // A rate no file has, and the clamp that keeps the limit a `u16`
843 // rather than a wrapped one: `0` would divide by zero in the predictor.
844 assert_eq!(gop_limit(0, false), 1);
845 assert_eq!(gop_limit(u32::MAX, false), u16::MAX);
846 }
847
848 /// What that group of one writes into the sequence header, which is the
849 /// half that shipped broken: the predictor hands the limit straight to
850 /// `SpsBuilder::max_frame_num` (`h264/predictor.rs:89`), and `1.ilog2()`
851 /// is 0, so the old `0u8 - 4u8` wrapped to 252 in release. Every intra-only
852 /// hardware file then carried `log2_max_frame_num_minus4 = 252` -- outside
853 /// the spec's 0..=12 -- and no decoder would parse it. Zero is the right
854 /// answer, not merely a legal one: `frame_num` never leaves 0 when every
855 /// picture is an IDR. No GPU: this is the bitstream side of the seat.
856 #[test]
857 fn an_intra_seat_writes_a_sequence_header_a_decoder_can_read() {
858 // The limit the intra seat asks for is one picture, and the SPS the
859 // encoder writes for it must declare the smallest frame_num the spec
860 // allows (`minus4 = 0`). A wrap would read as 252 here.
861 assert_eq!(gop_limit(30, true), 1);
862 let open = EcOpen {
863 codec: EcCodec::H264,
864 width: 320,
865 height: 240,
866 fps_num: 30,
867 fps_den: 1,
868 bitrate: 2_000_000,
869 intra_only: true,
870 colour: None,
871 };
872 // No VA-API on this machine: nothing to encode, nothing to claim.
873 let Some(mut session) = EcEncSession::open(open) else {
874 return;
875 };
876 let luma = vec![128u8; 320 * 240];
877 let chroma = vec![128u8; 160 * 120];
878 session
879 .encode(&luma, &chroma, &chroma, false)
880 .expect("the intra seat encodes a picture");
881 let au = session.next_au().expect("one access unit").to_vec();
882 let au = au.as_slice();
883 assert_eq!(
884 sps_log2_max_frame_num_minus4(au),
885 Some(0),
886 "log2_max_frame_num_minus4 = 0; 252 is what a wrap looks like"
887 );
888 }
889
890 /// `log2_max_frame_num_minus4` from the first SPS in an Annex-B access unit.
891 /// Main profile only (no chroma-format fields between the level and the
892 /// sequence parameter set id), which is the only profile this seat writes.
893 fn sps_log2_max_frame_num_minus4(au: &[u8]) -> Option<u32> {
894 let at = au.windows(4).position(|w| w == [0, 0, 1, 0x67])?;
895 // Undo emulation prevention: 0x00 0x00 0x03 -> 0x00 0x00.
896 let mut rbsp = Vec::new();
897 let mut zeros = 0;
898 for &b in &au[at + 4..] {
899 if zeros >= 2 && b == 3 {
900 zeros = 0;
901 continue;
902 }
903 zeros = if b == 0 { zeros + 1 } else { 0 };
904 if zeros > 2 && b == 1 {
905 break;
906 }
907 rbsp.push(b);
908 }
909 let bits: Vec<u8> = rbsp
910 .iter()
911 .flat_map(|b| (0..8).rev().map(move |i| (b >> i) & 1))
912 .collect();
913 fn read(bits: &[u8], pos: &mut usize, n: usize) -> Option<u32> {
914 let mut v = 0;
915 for _ in 0..n {
916 v = v << 1 | u32::from(*bits.get(*pos)?);
917 *pos += 1;
918 }
919 Some(v)
920 }
921 fn ue(bits: &[u8], pos: &mut usize) -> Option<u32> {
922 let mut zeros = 0;
923 while read(bits, pos, 1)? == 0 {
924 zeros += 1;
925 }
926 Some((1u32 << zeros) - 1 + read(bits, pos, zeros)?)
927 }
928 let mut pos = 0;
929 if read(&bits, &mut pos, 8)? != 77 {
930 return None;
931 }
932 read(&bits, &mut pos, 16)?; // constraint flags, level_idc
933 ue(&bits, &mut pos)?; // seq_parameter_set_id
934 ue(&bits, &mut pos)
935 }
936
937 /// The other half of the same fault: every picture of an intra-only seat
938 /// is an IDR, and each access unit carries its own SPS, so no decoder can
939 /// read a later picture as a non-sync one. Two pictures, each checked for a
940 /// parameter set and an IDR slice and no non-IDR slice. Needs a GPU.
941 #[test]
942 fn every_intra_only_access_unit_is_an_idr_with_parameter_sets() {
943 let open = EcOpen {
944 codec: EcCodec::H264,
945 width: 320,
946 height: 240,
947 fps_num: 30,
948 fps_den: 1,
949 bitrate: 2_000_000,
950 intra_only: true,
951 colour: None,
952 };
953 let Some(mut session) = EcEncSession::open(open) else {
954 return;
955 };
956 let luma = vec![128u8; 320 * 240];
957 let chroma = vec![128u8; 160 * 120];
958 for picture in 0..2 {
959 session
960 .encode(&luma, &chroma, &chroma, false)
961 .expect("the intra seat encodes a picture");
962 let au = session.next_au().expect("one access unit").to_vec();
963 let au = au.as_slice();
964 let kinds: Vec<u8> = au
965 .windows(4)
966 .filter(|w| w[..3] == [0, 0, 1])
967 .map(|w| w[3] & 0x1f)
968 .collect();
969 assert!(
970 kinds.contains(&7),
971 "picture {picture} carries an SPS: {kinds:?}"
972 );
973 assert!(kinds.contains(&5), "picture {picture} is an IDR: {kinds:?}");
974 assert!(
975 !kinds.contains(&1),
976 "picture {picture} has no non-IDR slice: {kinds:?}"
977 );
978 }
979 }
980
981 /// Runs against whatever GPU this machine has -- and passes on one with no
982 /// VA-API at all, which is exactly what `None` means here. What it pins is
983 /// the *shape* of the answer, the contents being the driver's: nothing may
984 /// be claimed that this plugin cannot actually reach.
985 #[test]
986 fn the_caps_query_never_claims_more_than_this_plugin_implements() {
987 let Some(caps) = query_caps() else {
988 return;
989 };
990 eprintln!("{caps:?}");
991 // Encode is this plugin's three seats and no others, whatever
992 // entrypoints the driver has: a VP9 EncSlice is not an encoder here.
993 assert_eq!(
994 caps.encode & !(CAP_H264 | CAP_HEVC | CAP_AV1),
995 0,
996 "{caps:?}"
997 );
998 // A 10-bit claim is a decode claim -- same profile family, read back
999 // through P010 -- and there is no 10-bit encode path at all.
1000 assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}");
1001 // H.264 here is 8-bit 4:2:0; the table has no 10-bit profile for it.
1002 assert_eq!(caps.decode_10bit & CAP_H264, 0, "{caps:?}");
1003 }
1004
1005 /// Every shape of the forward-or-flush decision a reposition makes, with
1006 /// no GPU in sight: the boundary a silence cut leaves is a target a few
1007 /// frames *ahead* of the decoder and that is the walk; behind it, past the
1008 /// reach, and past the end of the stream are the flush.
1009 #[test]
1010 fn a_target_ahead_within_the_reach_walks_forward() {
1011 use Reposition::{Flush, Forward};
1012 // A 30 fps stream, so the reach is [`FORWARD_SECS`] of it.
1013 let (count, limit) = (10_000u32, forward_limit(30.0));
1014 assert_eq!(forward_limit(30.0), 15);
1015 // The boundary a 0.3 s silence cut leaves: 9 frames ahead, dropped
1016 // unread on the way to exactly the target.
1017 assert_eq!(reposition(120, 129, count, limit), Forward(9));
1018 // Exactly at the reach, and a reseek to exactly where the decoder
1019 // stands (a superseded span's landing): nothing to do but not flush.
1020 assert_eq!(reposition(120, 135, count, limit), Forward(15));
1021 assert_eq!(reposition(120, 120, count, limit), Forward(0));
1022 // One frame past either end of the walk is the flush's.
1023 assert_eq!(reposition(120, 136, count, limit), Flush);
1024 assert_eq!(reposition(120, 119, count, limit), Flush);
1025 assert_eq!(reposition(120, 0, count, limit), Flush);
1026 // The last frame of the stream is a frame like any other...
1027 assert_eq!(reposition(9_995, 9_999, count, limit), Forward(4));
1028 // ...while a target at or past the end is not one decoding forward
1029 // can hand out: EOF falls back to the seek that always handled it.
1030 assert_eq!(reposition(9_995, 10_000, count, limit), Flush);
1031 assert_eq!(reposition(9_995, 60_000, count, limit), Flush);
1032 // From the end itself -- everything delivered, `pump` at clean EOF --
1033 // even a target inside the stream is behind.
1034 assert_eq!(reposition(10_000, 9_999, count, limit), Flush);
1035 }
1036
1037 /// The reach is time, carried at the stream's own rate, and a stream that
1038 /// states no rate gets none of it: such a session keeps the behaviour
1039 /// every reposition had, rather than a skip of nonsense frames.
1040 #[test]
1041 fn the_reach_is_half_a_second_at_the_streams_own_rate() {
1042 assert_eq!(forward_limit(23.976), 12);
1043 assert_eq!(forward_limit(24.0), 12);
1044 assert_eq!(forward_limit(60.0), 30);
1045 assert_eq!(forward_limit(0.0), 0);
1046 assert_eq!(forward_limit(f64::NAN), 0);
1047 assert_eq!(forward_limit(-30.0), 0);
1048 }
1049
1050 /// The drain machine's one law, held across *stacked* repositions: the
1051 /// picture delivered is `position + skip`, `position` advancing one per
1052 /// handle popped ([`Session::pump`]). A second forward reseek before the
1053 /// first's skip has drained must land on its own target -- the skip is
1054 /// replaced ([`forward_skip`]), never added to, or every reseek inside
1055 /// another's window walks its predecessor's frames past the target and
1056 /// the pictures keep arriving, only wrong.
1057 #[test]
1058 fn stacked_forward_reseeks_land_exactly_on_their_target() {
1059 use Reposition::Forward;
1060 let (count, limit) = (10_000u32, forward_limit(30.0));
1061 let land = |position: i64, skip: u32| position + i64::from(skip);
1062 let (mut position, mut skip) = (100i64, 0u32);
1063 let Forward(ahead) = reposition(position, 110, count, limit) else {
1064 panic!("110 is within the reach of 100")
1065 };
1066 skip = forward_skip(skip, ahead);
1067 let Forward(ahead) = reposition(position, 114, count, limit) else {
1068 panic!("114 is within the reach of 100")
1069 };
1070 skip = forward_skip(skip, ahead);
1071 assert_eq!(land(position, skip), 114, "the second target, exactly");
1072
1073 // A flush whose RAP skip is still undrained when a forward span is
1074 // asked: the flush stood at its RAP with `skip` toward its own
1075 // target, and the forward reseek through that window replaces it.
1076 position = 200;
1077 skip = 12;
1078 let Forward(ahead) = reposition(position, 208, count, limit) else {
1079 panic!("208 is within the reach of 200")
1080 };
1081 skip = forward_skip(skip, ahead);
1082 assert_eq!(
1083 land(position, skip),
1084 208,
1085 "a flush's undrained skip does not compound"
1086 );
1087
1088 // ...and a reseek to exactly where the decoder stands cancels
1089 // whatever was standing: the next handle is shown, not skipped past.
1090 let Forward(ahead) = reposition(position, position, count, limit) else {
1091 panic!("a session's own position is within its reach")
1092 };
1093 skip = forward_skip(skip, ahead);
1094 assert_eq!((ahead, land(position, skip)), (0, position));
1095 }
1096}