Skip to main content

viser_ffmpeg/
cache.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use tokio::sync::RwLock;
4
5use crate::{ProbeResult, probe};
6
7/// Thread-safe probe result cache to avoid redundant ffprobe calls.
8#[derive(Debug, Clone, Default)]
9pub struct ProbeCache {
10    cache: Arc<RwLock<HashMap<String, ProbeResult>>>,
11}
12
13impl ProbeCache {
14    pub fn new() -> Self {
15        Self::default()
16    }
17
18    /// Returns cached result or calls ffprobe and caches the result.
19    pub async fn probe(&self, path: &str) -> anyhow::Result<ProbeResult> {
20        // Check read lock first
21        {
22            let cache = self.cache.read().await;
23            if let Some(result) = cache.get(path) {
24                return Ok(result.clone());
25            }
26        }
27
28        // Not cached — probe and insert
29        let result = probe(path).await?;
30        {
31            let mut cache = self.cache.write().await;
32            cache.insert(path.to_string(), result.clone());
33        }
34
35        Ok(result)
36    }
37}