forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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