Skip to main content

rtflow_mount/
derived.rs

1//! Per-mount cache for payloads derived from a frame that are identical for
2//! every subscriber (for example Annex-B → AVCC conversion for HTTP-FLV).
3//!
4//! Without it, N viewers of one mount each run the same conversion over the
5//! same bytes. Entries are matched by `Arc` identity — never by pointer or
6//! timestamp — so a recycled allocation can never return a stale payload.
7
8use bytes::Bytes;
9use rtflow_media::AccessUnit;
10use std::{
11    collections::VecDeque,
12    sync::{Arc, Mutex},
13};
14
15pub struct DerivedPayloadCache {
16    capacity: usize,
17    entries: Mutex<VecDeque<(Arc<AccessUnit>, Arc<Bytes>)>>,
18}
19
20impl DerivedPayloadCache {
21    pub fn new(capacity: usize) -> Self {
22        Self {
23            capacity,
24            entries: Mutex::new(VecDeque::new()),
25        }
26    }
27
28    /// Payload derived from `frame`, building it on a miss.
29    ///
30    /// The build runs while the cache is locked so concurrent subscribers of
31    /// the same frame wait for the first result instead of each converting
32    /// the same bytes (that would defeat the cache exactly at the moment all
33    /// viewers receive the frame).
34    pub fn get_or_insert<F>(&self, frame: &Arc<AccessUnit>, build: F) -> Option<Arc<Bytes>>
35    where
36        F: FnOnce(&AccessUnit) -> Option<Bytes>,
37    {
38        let mut entries = self
39            .entries
40            .lock()
41            .unwrap_or_else(std::sync::PoisonError::into_inner);
42        if let Some((_, payload)) = entries
43            .iter()
44            .find(|(cached, _)| Arc::ptr_eq(cached, frame))
45        {
46            return Some(payload.clone());
47        }
48        let payload = Arc::new(build(frame)?);
49        entries.push_back((frame.clone(), payload.clone()));
50        let keep = self.capacity.max(1);
51        while entries.len() > keep {
52            entries.pop_front();
53        }
54        Some(payload)
55    }
56
57    /// Number of cached frames (bounded by `capacity`).
58    pub fn len(&self) -> usize {
59        self.entries
60            .lock()
61            .unwrap_or_else(std::sync::PoisonError::into_inner)
62            .len()
63    }
64
65    pub fn is_empty(&self) -> bool {
66        self.len() == 0
67    }
68
69    pub fn clear(&self) {
70        self.entries
71            .lock()
72            .unwrap_or_else(std::sync::PoisonError::into_inner)
73            .clear();
74    }
75}
76
77impl std::fmt::Debug for DerivedPayloadCache {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("DerivedPayloadCache")
80            .field("capacity", &self.capacity)
81            .field("len", &self.len())
82            .finish()
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use rtflow_media::Codec;
90    use std::time::Duration;
91
92    fn frame(timestamp: u32) -> Arc<AccessUnit> {
93        Arc::new(AccessUnit {
94            nal_offsets: None,
95            track_id: 0,
96            codec: Codec::H264,
97            pts: Duration::ZERO,
98            dts: None,
99            rtp_timestamp: timestamp,
100            is_keyframe: true,
101            data: bytes::Bytes::from(vec![0u8; 8]),
102        })
103    }
104
105    #[test]
106    fn builds_once_per_frame_and_evicts_oldest() {
107        let cache = DerivedPayloadCache::new(2);
108        let first = frame(1);
109        let mut builds = 0;
110        for _ in 0..5 {
111            let payload = cache
112                .get_or_insert(&first, |_| {
113                    builds += 1;
114                    Some(bytes::Bytes::from_static(b"one"))
115                })
116                .unwrap();
117            assert_eq!(&payload[..], b"one");
118        }
119        assert_eq!(builds, 1);
120
121        let second = frame(2);
122        let third = frame(3);
123        for frame in [&second, &third] {
124            cache
125                .get_or_insert(frame, |_| Some(bytes::Bytes::from_static(b"x")))
126                .unwrap();
127        }
128        assert_eq!(cache.len(), 2);
129        // The first frame was evicted, so it is rebuilt.
130        cache
131            .get_or_insert(&first, |_| Some(bytes::Bytes::from_static(b"again")))
132            .unwrap();
133        assert_eq!(cache.len(), 2);
134    }
135
136    #[test]
137    fn no_payload_is_cached_when_the_build_returns_none() {
138        let cache = DerivedPayloadCache::new(2);
139        let frame = frame(1);
140        assert!(cache.get_or_insert(&frame, |_| None).is_none());
141        assert!(cache.is_empty());
142    }
143}