use std::cell::Cell;
use std::sync::{Arc, Mutex, Weak};
use anyhow::{anyhow, Context as _};
use crate::{bindings, Display, Surface, UsageHint, VA_FOURCC_NV12, VA_RT_FORMAT_YUV420};
pub(crate) struct SurfacePool {
display: Arc<Display>,
width: u32,
height: u32,
hint: UsageHint,
pub(crate) free: Arc<FreeList>,
pub(crate) allocated: Cell<usize>,
}
pub(crate) struct FreeList {
pub(crate) surfaces: Mutex<Vec<Surface<()>>>,
pub(crate) capacity: usize,
}
impl SurfacePool {
pub(crate) fn new(display: &Arc<Display>, (width, height): (u32, u32), hint: UsageHint, capacity: usize) -> Self {
Self {
display: Arc::clone(display),
width,
height,
hint,
free: Arc::new(FreeList {
surfaces: Mutex::new(Vec::new()),
capacity,
}),
allocated: Cell::new(0),
}
}
pub(crate) fn alloc(&self) -> anyhow::Result<PooledSurface> {
let recycled = self.free.surfaces.lock().expect("poisoned").pop();
let surface = match recycled {
Some(surface) => surface,
None => {
let surface = self
.display
.create_surfaces::<()>(
VA_RT_FORMAT_YUV420,
Some(VA_FOURCC_NV12),
self.width,
self.height,
Some(self.hint),
vec![()],
)
.map_err(|e| anyhow!("create a {}x{} surface: {e:?}", self.width, self.height))?
.pop()
.context("VA-API returned an empty surface list")?;
self.allocated.set(self.allocated.get() + 1);
tracing::debug!(
"allocated surface {} at {}x{}",
self.allocated.get(),
self.width,
self.height
);
surface
}
};
Ok(PooledSurface {
surface: Some(surface),
free: Arc::downgrade(&self.free),
})
}
}
pub(crate) struct PooledSurface {
surface: Option<Surface<()>>,
free: Weak<FreeList>,
}
impl PooledSurface {
pub(crate) fn unpooled(surface: Surface<()>) -> Self {
Self {
surface: Some(surface),
free: Weak::new(),
}
}
pub(crate) fn get(&self) -> &Surface<()> {
self.surface.as_ref().expect("surface is taken only on drop")
}
pub(crate) fn id(&self) -> bindings::VASurfaceID {
self.get().id()
}
}
impl Drop for PooledSurface {
fn drop(&mut self) {
let (Some(surface), Some(free)) = (self.surface.take(), self.free.upgrade()) else {
return;
};
let mut surfaces = free.surfaces.lock().expect("poisoned");
if surfaces.len() < free.capacity {
surfaces.push(surface);
}
}
}