use std::sync::{Arc, Mutex};
use crate::error::DecodeError;
pub(crate) struct AsyncDecoder<T> {
pub(crate) inner: Arc<Mutex<T>>,
}
impl<T: Send + 'static> AsyncDecoder<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Arc::new(Mutex::new(inner)),
}
}
pub(crate) async fn with<F, R>(&self, f: F) -> Result<R, DecodeError>
where
F: FnOnce(&mut T) -> Result<R, DecodeError> + Send + 'static,
R: Send + 'static,
{
let inner = Arc::clone(&self.inner);
tokio::task::spawn_blocking(move || {
let mut guard = inner.lock().map_err(|_| DecodeError::Ffmpeg {
code: 0,
message: "mutex poisoned".to_string(),
})?;
f(&mut *guard)
})
.await
.map_err(|e| DecodeError::Ffmpeg {
code: 0,
message: format!("spawn_blocking panicked: {e}"),
})?
}
}