Skip to main content

rtflow_mount/
publisher.rs

1use super::*;
2
3// ---------------------------------------------------------------------------
4// LocalPublisher
5// ---------------------------------------------------------------------------
6
7pub struct LocalPublisher {
8    pub(crate) inner: Arc<Mount>,
9    pub(crate) active: bool,
10}
11
12impl LocalPublisher {
13    /// Number of unique client sessions currently playing this mount.
14    pub fn subscriber_count(&self) -> usize {
15        self.inner.active_sessions.load(Ordering::Relaxed)
16    }
17
18    /// True after the mount is unregistered or its server begins shutdown.
19    pub fn is_closed(&self) -> bool {
20        self.inner.cancel.is_cancelled()
21    }
22
23    /// Subscribe to local-source keyframe requests (track id).
24    pub fn keyframe_requests(&self) -> tokio::sync::broadcast::Receiver<u8> {
25        self.inner.keyframe_requests.subscribe()
26    }
27
28    /// Request a keyframe on a track (used by RTCP feedback actions).
29    pub fn request_keyframe(&self, track_id: u8) {
30        self.inner.request_keyframe(track_id);
31    }
32
33    /// Push a frame without track validation (for protocol ingest like RTMP
34    /// where the description may not yet be populated).
35    pub fn push(&self, frame: AccessUnit) -> Result<PushResult> {
36        if frame.data.len() > self.inner.max_queued_bytes_per_session {
37            self.inner.stats.add_dropped(1);
38            return Ok(PushResult::Dropped);
39        }
40        if self.inner.frames.receiver_count() == 0 {
41            self.inner.stats.add_dropped(1);
42            // No subscribers: still keep the startup keyframe cache fresh
43            // (plus the per-track bootstrap for the RTP-Info rtptime base).
44            // Otherwise the snapshot a new PLAY sees is frozen at the last
45            // disconnect — replaying it jumps straight from stale frames
46            // to the live edge, which stalls VLC for seconds.
47            self.inner.auto_inject_fmtp(&frame);
48            self.inner.update_bootstrap(&frame);
49            if let Ok(mut cache) = self.inner.startup_cache.try_lock() {
50                cache.push(std::sync::Arc::new(frame));
51            }
52            return Ok(PushResult::DroppedNoSubscribers);
53        }
54        match self.inner.publish_cached(frame) {
55            Ok(_) => {
56                self.inner.stats.add_accepted(1);
57                Ok(PushResult::Accepted)
58            }
59            Err(_) => {
60                self.inner.stats.add_dropped(1);
61                Ok(PushResult::Dropped)
62            }
63        }
64    }
65
66    pub fn try_push(&self, frame: AccessUnit) -> Result<PushResult> {
67        // O(1) codec validation via the fixed lookup table; no per-frame
68        // MediaDescription clone + linear track search.
69        if frame.data.len() > self.inner.max_queued_bytes_per_session {
70            self.inner.stats.add_dropped(1);
71            return Ok(PushResult::Dropped);
72        }
73        let expected = self
74            .inner
75            .codec_by_track
76            .read()
77            .unwrap_or_else(std::sync::PoisonError::into_inner)[frame.track_id as usize];
78        let Some(expected) = expected else {
79            return Err(Error::Media(format!(
80                "mount has no track {}",
81                frame.track_id
82            )));
83        };
84        if expected != frame.codec {
85            return Err(Error::Media(format!(
86                "track {} expects {:?}, got {:?}",
87                frame.track_id, expected, frame.codec
88            )));
89        }
90        if self.inner.frames.receiver_count() == 0 {
91            self.inner.stats.add_dropped(1);
92            // No subscribers: still keep the startup keyframe cache fresh
93            // (plus the per-track bootstrap for the RTP-Info rtptime base).
94            // Otherwise the snapshot a new PLAY sees is frozen at the last
95            // disconnect — replaying it jumps straight from stale frames
96            // to the live edge, which stalls VLC for seconds.
97            self.inner.auto_inject_fmtp(&frame);
98            self.inner.update_bootstrap(&frame);
99            if let Ok(mut cache) = self.inner.startup_cache.try_lock() {
100                cache.push(std::sync::Arc::new(frame));
101            }
102            return Ok(PushResult::DroppedNoSubscribers);
103        }
104        match self.inner.publish_cached(frame) {
105            Ok(_) => {
106                self.inner.stats.add_accepted(1);
107                Ok(PushResult::Accepted)
108            }
109            Err(_) => {
110                self.inner.stats.add_dropped(1);
111                Ok(PushResult::Dropped)
112            }
113        }
114    }
115
116    pub async fn close(mut self) -> Result<()> {
117        self.release();
118        Ok(())
119    }
120
121    fn release(&mut self) {
122        if self.active {
123            self.inner.publishers.fetch_sub(1, Ordering::AcqRel);
124            self.active = false;
125            tracing::debug!(
126                mount = %self.inner.id,
127                publishers = self.inner.publishers.load(Ordering::Relaxed),
128                "publisher detached"
129            );
130        }
131    }
132}
133
134impl Drop for LocalPublisher {
135    fn drop(&mut self) {
136        self.release();
137    }
138}