rtflow-mount 0.7.0

Stream mount registry, publisher handles and broadcast bus for rtflow
Documentation
//! Per-mount cache for payloads derived from a frame that are identical for
//! every subscriber (for example Annex-B → AVCC conversion for HTTP-FLV).
//!
//! Without it, N viewers of one mount each run the same conversion over the
//! same bytes. Entries are matched by `Arc` identity — never by pointer or
//! timestamp — so a recycled allocation can never return a stale payload.

use bytes::Bytes;
use rtflow_media::AccessUnit;
use std::{
    collections::VecDeque,
    sync::{Arc, Mutex},
};

pub struct DerivedPayloadCache {
    capacity: usize,
    entries: Mutex<VecDeque<(Arc<AccessUnit>, Arc<Bytes>)>>,
}

impl DerivedPayloadCache {
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            entries: Mutex::new(VecDeque::new()),
        }
    }

    /// Payload derived from `frame`, building it on a miss.
    ///
    /// The build runs while the cache is locked so concurrent subscribers of
    /// the same frame wait for the first result instead of each converting
    /// the same bytes (that would defeat the cache exactly at the moment all
    /// viewers receive the frame).
    pub fn get_or_insert<F>(&self, frame: &Arc<AccessUnit>, build: F) -> Option<Arc<Bytes>>
    where
        F: FnOnce(&AccessUnit) -> Option<Bytes>,
    {
        let mut entries = self
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some((_, payload)) = entries
            .iter()
            .find(|(cached, _)| Arc::ptr_eq(cached, frame))
        {
            return Some(payload.clone());
        }
        let payload = Arc::new(build(frame)?);
        entries.push_back((frame.clone(), payload.clone()));
        let keep = self.capacity.max(1);
        while entries.len() > keep {
            entries.pop_front();
        }
        Some(payload)
    }

    /// Number of cached frames (bounded by `capacity`).
    pub fn len(&self) -> usize {
        self.entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn clear(&self) {
        self.entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clear();
    }
}

impl std::fmt::Debug for DerivedPayloadCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DerivedPayloadCache")
            .field("capacity", &self.capacity)
            .field("len", &self.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rtflow_media::Codec;
    use std::time::Duration;

    fn frame(timestamp: u32) -> Arc<AccessUnit> {
        Arc::new(AccessUnit {
            nal_offsets: None,
            track_id: 0,
            codec: Codec::H264,
            pts: Duration::ZERO,
            dts: None,
            rtp_timestamp: timestamp,
            is_keyframe: true,
            data: bytes::Bytes::from(vec![0u8; 8]),
        })
    }

    #[test]
    fn builds_once_per_frame_and_evicts_oldest() {
        let cache = DerivedPayloadCache::new(2);
        let first = frame(1);
        let mut builds = 0;
        for _ in 0..5 {
            let payload = cache
                .get_or_insert(&first, |_| {
                    builds += 1;
                    Some(bytes::Bytes::from_static(b"one"))
                })
                .unwrap();
            assert_eq!(&payload[..], b"one");
        }
        assert_eq!(builds, 1);

        let second = frame(2);
        let third = frame(3);
        for frame in [&second, &third] {
            cache
                .get_or_insert(frame, |_| Some(bytes::Bytes::from_static(b"x")))
                .unwrap();
        }
        assert_eq!(cache.len(), 2);
        // The first frame was evicted, so it is rebuilt.
        cache
            .get_or_insert(&first, |_| Some(bytes::Bytes::from_static(b"again")))
            .unwrap();
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn no_payload_is_cached_when_the_build_returns_none() {
        let cache = DerivedPayloadCache::new(2);
        let frame = frame(1);
        assert!(cache.get_or_insert(&frame, |_| None).is_none());
        assert!(cache.is_empty());
    }
}