rtflow_mount/handle.rs
1use super::*;
2
3/// One RFC 4585 NACK request forwarded to the sender for `track_id`.
4#[doc(hidden)]
5#[derive(Clone, Debug)]
6pub struct NackRequest {
7 pub track_id: u8,
8 pub sequences: Vec<u16>,
9}
10
11/// Shared per-mount state (data plane, counters, lifecycle).
12#[doc(hidden)]
13pub struct Mount {
14 pub id: MountId,
15 pub config: MountConfig,
16 pub frames: Arc<frame_bus::FrameBus>,
17 pub(crate) consumer_queue_capacity: usize,
18 /// PLI/FIR/NACK feedback forwarded to local sources (track id).
19 pub keyframe_requests: broadcast::Sender<u8>,
20 /// NACK sequence lists for the interleaved sender's retransmission cache.
21 pub nack_requests: broadcast::Sender<NackRequest>,
22 /// Optional per-mount live NPT timeline override.
23 pub timeline: Option<rtflow_rtsp::range::TimelineMode>,
24 pub stats: StreamCounters,
25 /// Live media description. RTMP/SRT publishers update this from
26 /// sequence headers/metadata after the mount was created.
27 /// Shared so control-plane readers (per request / per segment) clone an
28 /// `Arc` instead of the whole description.
29 pub description: std::sync::RwLock<Arc<MediaDescription>>,
30 pub startup_cache: Mutex<KeyframeCache>,
31 #[allow(dead_code)] // read by update_description from protocol crates
32 pub startup_cache_config: crate::continuity::StartupCacheConfig,
33 /// Per-track bootstrap frame: fixed slots indexed by track_id (avoids
34 /// hashing + allocating on every pushed frame).
35 pub bootstrap: Mutex<[Option<AccessUnit>; 256]>,
36 /// Expected codec per track id, for O(1) push validation without
37 /// cloning the whole MediaDescription on every frame.
38 pub codec_by_track: std::sync::RwLock<[Option<Codec>; 256]>,
39 /// Read by feature-gated adapters (metrics exporter, RTMP/WebRTC).
40 #[allow(dead_code)]
41 pub event_sink: Arc<dyn EventSink>,
42 pub cancel: CancellationToken,
43 pub proxy_running: AtomicBool,
44 pub publishers: AtomicUsize,
45 pub publisher_claimed: AtomicBool,
46 /// Unique active play sessions (clients) on this mount. Tracked by the
47 /// RTSP session layer (one per connection, regardless of how many
48 /// tracks it subscribed); `broadcast::Receiver` count counts track
49 /// subscriptions instead and would show 2 for a single video+audio
50 /// client.
51 pub active_sessions: AtomicUsize,
52 pub max_queued_bytes_per_session: usize,
53 /// SDP fmtp parameters received via ANNOUNCE, keyed by track_id.
54 pub announce_fmtp: Mutex<HashMap<u8, Arc<str>>>,
55 /// Latest RTMP AVC/HEVC/AAC sequence headers published to this mount,
56 /// keyed by track_id — so RTMP play sessions can initialize decoders
57 /// before the first GOP arrives.
58 /// Read by the RTMP play path (feature-gated).
59 #[allow(dead_code)]
60 pub rtmp_seq_headers: Mutex<HashMap<u8, Bytes>>,
61 /// Payloads derived once per frame and shared by every subscriber of this
62 /// mount (e.g. Annex-B → AVCC for HTTP-FLV).
63 pub derived_payloads: crate::derived::DerivedPayloadCache,
64}
65
66/// Build the fixed codec lookup table from a media description.
67#[doc(hidden)]
68pub fn codec_lookup_table(description: &MediaDescription) -> [Option<Codec>; 256] {
69 let mut table = [None; 256];
70 for track in &description.tracks {
71 table[track.id as usize] = Some(track.codec);
72 }
73 table
74}
75
76/// Keys of frames covered by a startup snapshot.
77///
78/// Consumers that first drain the `startup` frames returned by
79/// `Mount::subscribe_with_startup` and then read the broadcast receiver
80/// will receive the same frames twice: the broadcast ring replays frames
81/// that were sent before subscription. Skip any receiver frame whose
82/// `(track_id, rtp_timestamp)` matches one of these keys.
83pub fn startup_dedup_keys(startup: &[Arc<AccessUnit>]) -> std::collections::HashSet<(u8, u32)> {
84 startup
85 .iter()
86 .map(|unit| (unit.track_id, unit.rtp_timestamp))
87 .collect()
88}
89
90/// How far back a new subscriber may start relative to the newest cached
91/// frame. Bounding the startup window keeps the on-screen delay close to
92/// the real-time edge instead of replaying the whole cache.
93///
94/// Low-latency trade-off: a fresh player first replays this window (paced
95/// at media rate), so the on-screen delay equals roughly the window length
96/// until it catches the live edge. 500ms keeps startup delay in the
97/// sub-second range (VLC + zerolatency encoder total ~300-800ms); the
98/// window still starts at the nearest keyframe so decoding is immediate.
99pub const STARTUP_WINDOW: std::time::Duration = std::time::Duration::from_millis(500);
100
101impl Drop for Mount {
102 fn drop(&mut self) {
103 self.cancel.cancel();
104 self.frames.close();
105 }
106}
107
108impl Mount {
109 /// Ask a local source to emit a keyframe on `track_id`.
110 /// Ask local sources to produce a keyframe on `track_id`.
111 #[doc(hidden)]
112 pub fn request_keyframe(&self, track_id: u8) {
113 let _ = self.keyframe_requests.send(track_id);
114 }
115
116 /// Cancellation token for this mount's data plane (cancelled on
117 /// unregister or server shutdown).
118 #[allow(dead_code)] // used by the RTSP server session layer
119 /// Mount-scoped cancellation token (children of the server token).
120 pub fn cancel_token(&self) -> CancellationToken {
121 self.cancel.clone()
122 }
123
124 /// Publish a frame while maintaining the startup keyframe cache and the
125 /// per-track bootstrap frame for new subscribers.
126 pub fn publish_cached(
127 &self,
128 frame: AccessUnit,
129 ) -> std::result::Result<usize, crate::FrameRecvError> {
130 if frame.data.len() > self.max_queued_bytes_per_session {
131 return Err(crate::FrameRecvError::Lagged(0));
132 }
133 self.auto_inject_fmtp(&frame);
134 let frame = Arc::new(frame);
135 // A cancelled mount (unregistered, or its server shutting down) must
136 // not keep accepting data: publishers would silently write into a
137 // detached mount while new registrations of the same path split the
138 // stream.
139 if self.cancel.is_cancelled() {
140 return Err(crate::FrameRecvError::Closed);
141 }
142 {
143 // Cache updates are best-effort: a concurrent subscriber holding
144 // the lock must not block the publisher hot path, and dropping
145 // one frame from the cache is harmless.
146 if let Ok(mut cache) = self.startup_cache.try_lock() {
147 cache.push(frame.clone());
148 }
149 }
150 self.stats
151 .add_published_bytes(u64::try_from(frame.data.len()).unwrap_or(u64::MAX));
152 self.update_bootstrap(&frame);
153 let result = self
154 .frames
155 .send(frame)
156 .map(|_| self.frames.receiver_count());
157 if tracing::enabled!(tracing::Level::DEBUG) && self.frames.receiver_count() == 0 {
158 tracing::debug!("mount: frames.send dropped (no receivers)");
159 }
160 result
161 }
162
163 /// Current media description snapshot.
164 pub fn description_snapshot(&self) -> Arc<MediaDescription> {
165 self.description
166 .read()
167 .unwrap_or_else(std::sync::PoisonError::into_inner)
168 .clone()
169 }
170
171 /// Replace the media description (RTMP/SRT sequence headers/metadata).
172 /// Rebuilds the codec lookup table and startup cache; protocol senders
173 /// take a snapshot per session/request, so this must happen before the
174 /// first PLAY/segmenter subscription.
175 #[allow(dead_code)] // called by RTMP/SRT ingest when those features are enabled
176 pub fn update_description(
177 &self,
178 description: MediaDescription,
179 ) -> rtflow_core::error::Result<()> {
180 let mut current = self
181 .description
182 .write()
183 .unwrap_or_else(std::sync::PoisonError::into_inner);
184 *current = Arc::new(description.clone());
185 *self
186 .codec_by_track
187 .write()
188 .unwrap_or_else(std::sync::PoisonError::into_inner) = codec_lookup_table(&description);
189 {
190 let cache = KeyframeCache::new(&description, self.startup_cache_config)?;
191 *self
192 .startup_cache
193 .lock()
194 .unwrap_or_else(std::sync::PoisonError::into_inner) = cache;
195 }
196 Ok(())
197 }
198
199 /// Keep the latest (key)frame per track for RTP-Info/SDP timing even
200 /// while no subscriber is attached: PLAY answers need a rtptime base
201 /// the moment a client connects, before the first GOP lands in the
202 /// startup cache.
203 /// Auto-inject SDP fmtp from the first keyframe carrying parameter
204 /// sets (hardware encoders like HiMPP often emit SPS/PPS separated
205 /// from the IDR slices). DESCRIBE merges this into the SDP when the
206 /// description has no explicit fmtp. Cheap: runs on keyframes only,
207 /// once per track, and also while no subscriber is attached (the
208 /// very first keyframe typically arrives before the first PLAY).
209 pub fn auto_inject_fmtp(&self, frame: &AccessUnit) {
210 if !frame.is_keyframe {
211 return;
212 }
213 let codec = self
214 .codec_by_track
215 .read()
216 .unwrap_or_else(std::sync::PoisonError::into_inner)
217 .get(frame.track_id as usize)
218 .copied()
219 .flatten();
220 let Some(codec) = codec else {
221 return;
222 };
223 if !matches!(
224 codec,
225 rtflow_media::Codec::H264 | rtflow_media::Codec::H265 | rtflow_media::Codec::Opus
226 ) {
227 return;
228 }
229 {
230 let lock = self
231 .announce_fmtp
232 .lock()
233 .unwrap_or_else(std::sync::PoisonError::into_inner);
234 if lock.contains_key(&frame.track_id) {
235 return;
236 }
237 }
238 use rtflow_media::bitstream::{
239 h264_fmtp, h264_parameter_sets, h265_fmtp, h265_parameter_sets,
240 };
241 let fmtp = match codec {
242 rtflow_media::Codec::H264 => {
243 let sets = h264_parameter_sets(&frame.data);
244 match (sets.sps.as_deref(), sets.pps.as_deref()) {
245 (Some(sps), Some(pps)) => Some(h264_fmtp(sps, pps)),
246 _ => None,
247 }
248 }
249 rtflow_media::Codec::H265 => {
250 let sets = h265_parameter_sets(&frame.data);
251 match (
252 sets.vps.as_deref(),
253 sets.sps.as_deref(),
254 sets.pps.as_deref(),
255 ) {
256 (Some(vps), Some(sps), Some(pps)) => Some(h265_fmtp(vps, sps, pps)),
257 _ => None,
258 }
259 }
260 // RFC 7587: same parameters the WebRTC path announces.
261 rtflow_media::Codec::Opus => Some("minptime=10;useinbandfec=1".to_string()),
262 _ => None,
263 };
264 if let Some(fmtp) = fmtp {
265 tracing::debug!("auto fmtp for track {}: {fmtp}", frame.track_id);
266 self.announce_fmtp
267 .lock()
268 .unwrap_or_else(std::sync::PoisonError::into_inner)
269 .insert(frame.track_id, Arc::from(fmtp));
270 }
271 }
272
273 pub fn update_bootstrap(&self, frame: &AccessUnit) {
274 if frame.data.len() <= self.max_queued_bytes_per_session
275 && (!matches!(
276 frame.codec,
277 rtflow_media::Codec::H264 | rtflow_media::Codec::H265
278 ) || frame.is_keyframe)
279 && let Ok(mut bootstrap) = self.bootstrap.try_lock()
280 {
281 bootstrap[frame.track_id as usize] = Some(frame.clone());
282 }
283 }
284
285 #[allow(dead_code)] // used by RTSP sessions when the server feature is on
286 pub fn subscribe_with_startup(
287 &self,
288 track_id: u8,
289 ) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
290 {
291 let cache = self
292 .startup_cache
293 .lock()
294 .unwrap_or_else(std::sync::PoisonError::into_inner);
295 let receiver = self.frames.subscribe();
296 let mut startup = cache.snapshot(track_id);
297 let mut bytes = startup.iter().fold(0usize, |total, frame| {
298 total.saturating_add(frame.data.len())
299 });
300 if bytes > self.max_queued_bytes_per_session {
301 // Roll off the oldest frames up to the limit instead of
302 // clearing the whole snapshot (keep a decodable start).
303 while bytes > self.max_queued_bytes_per_session && startup.len() > 1 {
304 bytes -= startup.remove(0).data.len();
305 }
306 while startup.first().is_some_and(|f| !f.is_keyframe) && startup.len() > 1 {
307 startup.remove(0);
308 }
309 }
310 // Bound how far back a new subscriber starts: a snapshot that
311 // reaches seconds into the past makes the on-screen delay equal
312 // to the whole cached window. Keep at most STARTUP_WINDOW of
313 // media, cutting at the nearest keyframe.
314 if let Some(last) = startup.last() {
315 let cutoff = last.pts.saturating_sub(STARTUP_WINDOW);
316 match startup
317 .iter()
318 .position(|frame| frame.pts >= cutoff && frame.is_keyframe)
319 {
320 Some(cut) => {
321 // Window contains a keyframe: start playback there
322 // (decodes immediately, replay ≤ STARTUP_WINDOW).
323 startup.drain(..cut);
324 }
325 None => {
326 // No keyframe inside the window (GOP > STARTUP_WINDOW):
327 // the current GOP start was missed. Like mainstream
328 // surveillance cameras, drop the snapshot and wait
329 // for the next IDR (the sender's awaiting_key gate
330 // handles that) instead of replaying from an old GOP
331 // start — the viewer would otherwise stay a full GOP
332 // behind the live edge (and the old start may already
333 // have been evicted, causing a black screen).
334 startup.clear();
335 }
336 }
337 }
338 // Deliberately no bootstrap fallback here: an empty snapshot
339 // means "wait for the next IDR" (sender's awaiting_key gate),
340 // matching surveillance-camera startup. The bootstrap frame is
341 // still used for RTP-Info rtptime so the PLAY answer always
342 // carries a timing base.
343 (receiver, startup)
344 }
345 }
346
347 pub fn subscribe_with_all_startup(&self) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
348 let receiver = self.frames.subscribe();
349 {
350 let cache = self
351 .startup_cache
352 .lock()
353 .unwrap_or_else(std::sync::PoisonError::into_inner);
354 let mut startup = cache.snapshot_all();
355 let mut bytes = startup.iter().fold(0usize, |total, frame| {
356 total.saturating_add(frame.data.len())
357 });
358 if bytes > self.max_queued_bytes_per_session {
359 // Roll off the oldest frames instead of clearing the snapshot.
360 while bytes > self.max_queued_bytes_per_session && startup.len() > 1 {
361 bytes = bytes.saturating_sub(startup.remove(0).data.len());
362 }
363 while startup.first().is_some_and(|f| !f.is_keyframe) && startup.len() > 1 {
364 startup.remove(0);
365 }
366 }
367 // Bound the startup window (see STARTUP_WINDOW).
368 if let Some(last) = startup.last() {
369 let cutoff = last.pts.saturating_sub(STARTUP_WINDOW);
370 if let Some(cut) = startup
371 .iter()
372 .position(|frame| frame.pts >= cutoff && frame.is_keyframe)
373 {
374 startup.drain(..cut);
375 }
376 }
377 (receiver, startup)
378 }
379 }
380}
381
382// ---------------------------------------------------------------------------
383// MountHandle (public API)
384// ---------------------------------------------------------------------------
385
386#[derive(Clone)]
387pub struct MountHandle {
388 pub path: rtflow_core::identity::MountId,
389 pub description: Arc<MediaDescription>,
390 pub(crate) inner: Arc<Mount>,
391}
392
393impl MountHandle {
394 /// Shared mount state behind this handle (control-plane access).
395 pub fn mount(&self) -> &Arc<Mount> {
396 &self.inner
397 }
398
399 /// Current dynamic description (reflects RTMP/SRT sequence headers).
400 pub fn description(&self) -> Arc<MediaDescription> {
401 self.inner.description_snapshot()
402 }
403
404 /// Replace the media description for an ingest-created mount.
405 pub fn update_description(
406 &self,
407 description: MediaDescription,
408 ) -> rtflow_core::error::Result<()> {
409 self.inner.update_description(description)
410 }
411
412 pub fn publisher(&self) -> Result<LocalPublisher> {
413 match &self.inner.config {
414 MountConfig::Local { .. } => {
415 self.inner.publishers.fetch_add(1, Ordering::AcqRel);
416 }
417 MountConfig::Publisher { .. } => {
418 // A claimed Publisher mount is exclusively owned by the
419 // RTSP RECORD session: refuse extra publishers instead of
420 // silently creating a second, interleaved stream.
421 if self.inner.publisher_claimed.load(Ordering::Acquire) {
422 tracing::warn!(
423 mount = %self.inner.id,
424 "publisher attach refused: mount is claimed by an RTSP session"
425 );
426 return Err(Error::Conflict(
427 "publisher is already claimed by an RTSP session".into(),
428 ));
429 }
430 self.inner.publishers.fetch_add(1, Ordering::AcqRel);
431 }
432 #[allow(unreachable_patterns)] // only reachable with proxy/VOD mounts
433 _ => {
434 tracing::warn!(
435 mount = %self.inner.id,
436 "publisher attach refused: mount type does not accept publishers"
437 );
438 return Err(Error::Conflict("mount does not accept publishers".into()));
439 }
440 }
441 tracing::info!(
442 mount = %self.inner.id,
443 publishers = self.inner.publishers.load(Ordering::Relaxed),
444 "publisher attached"
445 );
446 Ok(LocalPublisher {
447 inner: self.inner.clone(),
448 active: true,
449 })
450 }
451
452 /// Request a keyframe from a local source (RTCP PLI/FIR/NACK action).
453 pub fn request_keyframe(&self, track_id: u8) {
454 self.inner.request_keyframe(track_id);
455 }
456
457 pub fn subscribe(&self) -> crate::FrameReceiver {
458 self.inner.frames.subscribe()
459 }
460
461 /// Subscribe to live frames together with a cached decodable stream start.
462 #[allow(dead_code)] // used by RTSP sessions and HLS/HTTP-FLV adapters
463 pub fn subscribe_with_startup(&self) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
464 self.inner.subscribe_with_all_startup()
465 }
466
467 pub fn announce_fmtp(&self) -> HashMap<u8, Arc<str>> {
468 self.inner
469 .announce_fmtp
470 .lock()
471 .unwrap_or_else(std::sync::PoisonError::into_inner)
472 .clone()
473 }
474
475 /// Get a shared reference to the live announce_fmtp source.
476 ///
477 /// Unlike `announce_fmtp()` which returns a snapshot, this allows
478 /// long-lived tasks to poll for updates as publishers ANNOUNCE.
479 #[doc(hidden)]
480 pub fn announce_fmtp_source(&self) -> Arc<Mount> {
481 self.inner.clone()
482 }
483
484 /// Cancellation token tied to the mount lifetime.
485 pub fn cancellation_token(&self) -> CancellationToken {
486 self.inner.cancel.clone()
487 }
488
489 /// Mount path, suitable as the canonical HTTP asset prefix.
490 /// Stable identity of this mount (independent of its path string).
491 pub fn mount_id(&self) -> &rtflow_core::identity::MountId {
492 &self.inner.id
493 }
494
495 pub fn path(&self) -> &str {
496 self.inner.id.as_str()
497 }
498
499 pub fn snapshot(&self) -> MountSnapshot {
500 // Unique sessions, not track subscriptions: one client with a
501 // video+audio pair counts once.
502 let subscribers = self.inner.active_sessions.load(Ordering::Relaxed);
503 // HTTP-FLV / WS-FLV / HLS subscribers hold a broadcast receiver
504 // but never register an RTSP session; a publisher's power gate
505 // (`subscriber_count + broadcast_receivers == 0` → stop pushing)
506 // would otherwise stall browser playback after the startup
507 // snapshot. RTSP track subscriptions are included here too.
508 let broadcast_receivers = self.inner.frames.receiver_count();
509 let s = self.inner.stats.snapshot(subscribers);
510 let (startup_cache_frames, startup_cache_bytes) = self
511 .inner
512 .startup_cache
513 .lock()
514 .unwrap_or_else(std::sync::PoisonError::into_inner)
515 .usage();
516 MountSnapshot {
517 subscriber_count: s.subscribers,
518 broadcast_receivers,
519 publisher_connected: self.inner.publishers.load(Ordering::Relaxed) > 0,
520 proxy_state: match &self.inner.config {
521 MountConfig::Proxy { upstream } => Some(upstream.state()),
522 _ => None,
523 },
524 stats: s,
525 startup_cache_frames,
526 startup_cache_bytes,
527 consumer_queue_capacity: self.inner.consumer_queue_capacity,
528 }
529 }
530}