forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

pool.rs137 lines, 4.4 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//! `Rc<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 ec_va::{Surface, SurfaceSpec};
14use std::ops::Deref;
15use std::rc::{Rc, Weak};
16use std::sync::Mutex;
17
18struct PoolInner {
19 /// Every surface, in allocation order.
20 all: Mutex<Vec<Rc<Surface>>>,
21 free: Mutex<Vec<Rc<Surface>>>,
22}
23
24/// A fixed-size pool of identically specified surfaces.
25#[derive(Clone)]
26pub struct SurfacePool {
27 inner: Rc<PoolInner>,
28 spec: SurfaceSpec,
29}
30
31impl SurfacePool {
32 /// Wrap surfaces that were allocated with `spec`. The caller creates them
33 /// with [`ec_va::create_pool`] first, because a decode context needs them as
34 /// its render targets before the pool can own them.
35 pub fn from_surfaces(surfaces: Vec<Surface>, spec: &SurfaceSpec) -> SurfacePool {
36 let all: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect();
37 SurfacePool {
38 inner: Rc::new(PoolInner {
39 free: Mutex::new(all.clone()),
40 all: Mutex::new(all),
41 }),
42 spec: *spec,
43 }
44 }
45
46 /// The spec every surface in this pool was allocated with.
47 pub fn spec(&self) -> &SurfaceSpec {
48 &self.spec
49 }
50
51 /// Total surfaces in the pool.
52 pub fn len(&self) -> usize {
53 self.inner.all.lock().map(|all| all.len()).unwrap_or(0)
54 }
55
56 /// True when the pool holds no surfaces at all.
57 pub fn is_empty(&self) -> bool {
58 self.len() == 0
59 }
60
61 /// Add surfaces allocated with the pool's spec, free for [`SurfacePool::acquire`].
62 pub fn grow(&self, surfaces: Vec<Surface>) {
63 let surfaces: Vec<Rc<Surface>> = surfaces.into_iter().map(Rc::new).collect();
64 if let Ok(mut all) = self.inner.all.lock() {
65 all.extend(surfaces.iter().cloned());
66 }
67 if let Ok(mut free) = self.inner.free.lock() {
68 free.extend(surfaces);
69 }
70 }
71
72 /// Surfaces currently available.
73 pub fn available(&self) -> usize {
74 self.inner.free.lock().map(|f| f.len()).unwrap_or(0)
75 }
76
77 /// Take a free surface, or `None` when every one is still in use.
78 ///
79 /// A `None` is the caller's cue to release output frames, not an error: a
80 /// decoder that has handed out its whole pool is waiting on the consumer.
81 pub fn acquire(&self) -> Option<Rc<PooledSurface>> {
82 // A poisoned lock means another thread panicked while holding it; the
83 // free list is a plain Vec, so its contents are still consistent.
84 let mut free = match self.inner.free.lock() {
85 Ok(free) => free,
86 Err(poisoned) => poisoned.into_inner(),
87 };
88 let surface = free.pop()?;
89 Some(Rc::new(PooledSurface {
90 surface,
91 pool: Rc::downgrade(&self.inner),
92 }))
93 }
94}
95
96/// A surface on loan from a [`SurfacePool`]; returns to it on drop.
97pub struct PooledSurface {
98 surface: Rc<Surface>,
99 pool: Weak<PoolInner>,
100}
101
102impl PooledSurface {
103 /// The surface itself, for the calls that want an owned `Rc<Surface>`.
104 pub fn surface(&self) -> &Rc<Surface> {
105 &self.surface
106 }
107}
108
109impl Deref for PooledSurface {
110 type Target = Rc<Surface>;
111
112 fn deref(&self) -> &Rc<Surface> {
113 &self.surface
114 }
115}
116
117impl std::fmt::Debug for PooledSurface {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_struct("PooledSurface")
120 .field("id", &self.surface.id())
121 .finish()
122 }
123}
124
125impl Drop for PooledSurface {
126 fn drop(&mut self) {
127 let Some(pool) = self.pool.upgrade() else {
128 // The pool is gone, so the surface simply drops with this handle.
129 return;
130 };
131 let mut free = match pool.free.lock() {
132 Ok(free) => free,
133 Err(poisoned) => poisoned.into_inner(),
134 };
135 free.push(Rc::clone(&self.surface));
136 }
137}