forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5a2f5efTahinli3 months ago1409 commits

pool.rs132 lines, 4.0 KiBHistoryRawDownload
1//! A recycling pool of decode/encode surfaces.
2//!
3//! Surfaces are allocated once, in one `vaCreateSurfaces` call, and handed out
4//! as [`PooledSurface`]s that return themselves to the free list on drop.
5//! Two things hold a surface at the same time — the reference picture buffer
6//! and a frame the caller has not finished with — so ownership is an
7//! `Arc<PooledSurface>` and the recycle happens when the last of them goes.
8//!
9//! Reallocating per frame would be the alternative, and it is precisely what
10//! makes a VA-API pipeline stutter: every `vaCreateSurfaces` is a kernel
11//! allocation plus a driver-side tiling decision.
12
13use std::ops::Deref;
14use std::sync::{Arc, Mutex, Weak};
15
16use ec_va::{Display, Surface, SurfaceSpec};
17
18use crate::error::Result;
19
20struct PoolInner {
21 /// Every surface, in allocation order. Also the context's render targets.
22 all: Vec<Arc<Surface>>,
23 free: Mutex<Vec<Arc<Surface>>>,
24}
25
26/// A fixed-size pool of identically specified surfaces.
27#[derive(Clone)]
28pub struct SurfacePool {
29 inner: Arc<PoolInner>,
30 spec: SurfaceSpec,
31}
32
33impl SurfacePool {
34 /// Allocate `count` surfaces matching `spec`.
35 pub fn new(display: &Arc<Display>, spec: &SurfaceSpec, count: usize) -> Result<SurfacePool> {
36 let all = Surface::create_pool(display, spec, count)?;
37 Ok(SurfacePool {
38 inner: Arc::new(PoolInner {
39 free: Mutex::new(all.clone()),
40 all,
41 }),
42 spec: *spec,
43 })
44 }
45
46 /// Every surface in the pool — what a `Context` wants as its render targets.
47 pub fn targets(&self) -> &[Arc<Surface>] {
48 &self.inner.all
49 }
50
51 /// The spec every surface in this pool was allocated with.
52 pub fn spec(&self) -> &SurfaceSpec {
53 &self.spec
54 }
55
56 /// Total surfaces in the pool.
57 pub fn len(&self) -> usize {
58 self.inner.all.len()
59 }
60
61 /// True when the pool holds no surfaces at all.
62 pub fn is_empty(&self) -> bool {
63 self.inner.all.is_empty()
64 }
65
66 /// Surfaces currently available.
67 pub fn available(&self) -> usize {
68 self.inner.free.lock().map(|f| f.len()).unwrap_or(0)
69 }
70
71 /// Take a free surface, or `None` when every one is still in use.
72 ///
73 /// A `None` is the caller's cue to release output frames, not an error: a
74 /// decoder that has handed out its whole pool is waiting on the consumer.
75 pub fn acquire(&self) -> Option<Arc<PooledSurface>> {
76 // A poisoned lock means another thread panicked while holding it; the
77 // free list is a plain Vec, so its contents are still consistent and
78 // there is nothing to recover from.
79 let mut free = match self.inner.free.lock() {
80 Ok(free) => free,
81 Err(poisoned) => poisoned.into_inner(),
82 };
83 let surface = free.pop()?;
84 Some(Arc::new(PooledSurface {
85 surface,
86 pool: Arc::downgrade(&self.inner),
87 }))
88 }
89}
90
91/// A surface on loan from a [`SurfacePool`]; returns to it on drop.
92pub struct PooledSurface {
93 surface: Arc<Surface>,
94 pool: Weak<PoolInner>,
95}
96
97impl PooledSurface {
98 /// The surface itself, for the calls that want an owned `Arc<Surface>`.
99 pub fn surface(&self) -> &Arc<Surface> {
100 &self.surface
101 }
102}
103
104impl Deref for PooledSurface {
105 type Target = Arc<Surface>;
106
107 fn deref(&self) -> &Arc<Surface> {
108 &self.surface
109 }
110}
111
112impl std::fmt::Debug for PooledSurface {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("PooledSurface")
115 .field("id", &self.surface.id())
116 .finish()
117 }
118}
119
120impl Drop for PooledSurface {
121 fn drop(&mut self) {
122 let Some(pool) = self.pool.upgrade() else {
123 // The pool is gone, so the surface simply drops with this handle.
124 return;
125 };
126 let mut free = match pool.free.lock() {
127 Ok(free) => free,
128 Err(poisoned) => poisoned.into_inner(),
129 };
130 free.push(Arc::clone(&self.surface));
131 }
132}