rtflow-mount 0.7.0

Stream mount registry, publisher handles and broadcast bus for rtflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
use super::*;

/// One RFC 4585 NACK request forwarded to the sender for `track_id`.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct NackRequest {
    pub track_id: u8,
    pub sequences: Vec<u16>,
}

/// Shared per-mount state (data plane, counters, lifecycle).
#[doc(hidden)]
pub struct Mount {
    pub id: MountId,
    pub config: MountConfig,
    pub frames: Arc<frame_bus::FrameBus>,
    pub(crate) consumer_queue_capacity: usize,
    /// PLI/FIR/NACK feedback forwarded to local sources (track id).
    pub keyframe_requests: broadcast::Sender<u8>,
    /// NACK sequence lists for the interleaved sender's retransmission cache.
    pub nack_requests: broadcast::Sender<NackRequest>,
    /// Optional per-mount live NPT timeline override.
    pub timeline: Option<rtflow_rtsp::range::TimelineMode>,
    pub stats: StreamCounters,
    /// Live media description. RTMP/SRT publishers update this from
    /// sequence headers/metadata after the mount was created.
    /// Shared so control-plane readers (per request / per segment) clone an
    /// `Arc` instead of the whole description.
    pub description: std::sync::RwLock<Arc<MediaDescription>>,
    pub startup_cache: Mutex<KeyframeCache>,
    #[allow(dead_code)] // read by update_description from protocol crates
    pub startup_cache_config: crate::continuity::StartupCacheConfig,
    /// Per-track bootstrap frame: fixed slots indexed by track_id (avoids
    /// hashing + allocating on every pushed frame).
    pub bootstrap: Mutex<[Option<AccessUnit>; 256]>,
    /// Expected codec per track id, for O(1) push validation without
    /// cloning the whole MediaDescription on every frame.
    pub codec_by_track: std::sync::RwLock<[Option<Codec>; 256]>,
    /// Read by feature-gated adapters (metrics exporter, RTMP/WebRTC).
    #[allow(dead_code)]
    pub event_sink: Arc<dyn EventSink>,
    pub cancel: CancellationToken,
    pub proxy_running: AtomicBool,
    pub publishers: AtomicUsize,
    pub publisher_claimed: AtomicBool,
    /// Unique active play sessions (clients) on this mount. Tracked by the
    /// RTSP session layer (one per connection, regardless of how many
    /// tracks it subscribed); `broadcast::Receiver` count counts track
    /// subscriptions instead and would show 2 for a single video+audio
    /// client.
    pub active_sessions: AtomicUsize,
    pub max_queued_bytes_per_session: usize,
    /// SDP fmtp parameters received via ANNOUNCE, keyed by track_id.
    pub announce_fmtp: Mutex<HashMap<u8, Arc<str>>>,
    /// Latest RTMP AVC/HEVC/AAC sequence headers published to this mount,
    /// keyed by track_id — so RTMP play sessions can initialize decoders
    /// before the first GOP arrives.
    /// Read by the RTMP play path (feature-gated).
    #[allow(dead_code)]
    pub rtmp_seq_headers: Mutex<HashMap<u8, Bytes>>,
    /// Payloads derived once per frame and shared by every subscriber of this
    /// mount (e.g. Annex-B → AVCC for HTTP-FLV).
    pub derived_payloads: crate::derived::DerivedPayloadCache,
}

/// Build the fixed codec lookup table from a media description.
#[doc(hidden)]
pub fn codec_lookup_table(description: &MediaDescription) -> [Option<Codec>; 256] {
    let mut table = [None; 256];
    for track in &description.tracks {
        table[track.id as usize] = Some(track.codec);
    }
    table
}

/// Keys of frames covered by a startup snapshot.
///
/// Consumers that first drain the `startup` frames returned by
/// `Mount::subscribe_with_startup` and then read the broadcast receiver
/// will receive the same frames twice: the broadcast ring replays frames
/// that were sent before subscription. Skip any receiver frame whose
/// `(track_id, rtp_timestamp)` matches one of these keys.
pub fn startup_dedup_keys(startup: &[Arc<AccessUnit>]) -> std::collections::HashSet<(u8, u32)> {
    startup
        .iter()
        .map(|unit| (unit.track_id, unit.rtp_timestamp))
        .collect()
}

/// How far back a new subscriber may start relative to the newest cached
/// frame. Bounding the startup window keeps the on-screen delay close to
/// the real-time edge instead of replaying the whole cache.
///
/// Low-latency trade-off: a fresh player first replays this window (paced
/// at media rate), so the on-screen delay equals roughly the window length
/// until it catches the live edge. 500ms keeps startup delay in the
/// sub-second range (VLC + zerolatency encoder total ~300-800ms); the
/// window still starts at the nearest keyframe so decoding is immediate.
pub const STARTUP_WINDOW: std::time::Duration = std::time::Duration::from_millis(500);

impl Drop for Mount {
    fn drop(&mut self) {
        self.cancel.cancel();
        self.frames.close();
    }
}

impl Mount {
    /// Ask a local source to emit a keyframe on `track_id`.
    /// Ask local sources to produce a keyframe on `track_id`.
    #[doc(hidden)]
    pub fn request_keyframe(&self, track_id: u8) {
        let _ = self.keyframe_requests.send(track_id);
    }

    /// Cancellation token for this mount's data plane (cancelled on
    /// unregister or server shutdown).
    #[allow(dead_code)] // used by the RTSP server session layer
    /// Mount-scoped cancellation token (children of the server token).
    pub fn cancel_token(&self) -> CancellationToken {
        self.cancel.clone()
    }

    /// Publish a frame while maintaining the startup keyframe cache and the
    /// per-track bootstrap frame for new subscribers.
    pub fn publish_cached(
        &self,
        frame: AccessUnit,
    ) -> std::result::Result<usize, crate::FrameRecvError> {
        if frame.data.len() > self.max_queued_bytes_per_session {
            return Err(crate::FrameRecvError::Lagged(0));
        }
        self.auto_inject_fmtp(&frame);
        let frame = Arc::new(frame);
        // A cancelled mount (unregistered, or its server shutting down) must
        // not keep accepting data: publishers would silently write into a
        // detached mount while new registrations of the same path split the
        // stream.
        if self.cancel.is_cancelled() {
            return Err(crate::FrameRecvError::Closed);
        }
        {
            // Cache updates are best-effort: a concurrent subscriber holding
            // the lock must not block the publisher hot path, and dropping
            // one frame from the cache is harmless.
            if let Ok(mut cache) = self.startup_cache.try_lock() {
                cache.push(frame.clone());
            }
        }
        self.stats
            .add_published_bytes(u64::try_from(frame.data.len()).unwrap_or(u64::MAX));
        self.update_bootstrap(&frame);
        let result = self
            .frames
            .send(frame)
            .map(|_| self.frames.receiver_count());
        if tracing::enabled!(tracing::Level::DEBUG) && self.frames.receiver_count() == 0 {
            tracing::debug!("mount: frames.send dropped (no receivers)");
        }
        result
    }

    /// Current media description snapshot.
    pub fn description_snapshot(&self) -> Arc<MediaDescription> {
        self.description
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    /// Replace the media description (RTMP/SRT sequence headers/metadata).
    /// Rebuilds the codec lookup table and startup cache; protocol senders
    /// take a snapshot per session/request, so this must happen before the
    /// first PLAY/segmenter subscription.
    #[allow(dead_code)] // called by RTMP/SRT ingest when those features are enabled
    pub fn update_description(
        &self,
        description: MediaDescription,
    ) -> rtflow_core::error::Result<()> {
        let mut current = self
            .description
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *current = Arc::new(description.clone());
        *self
            .codec_by_track
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = codec_lookup_table(&description);
        {
            let cache = KeyframeCache::new(&description, self.startup_cache_config)?;
            *self
                .startup_cache
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = cache;
        }
        Ok(())
    }

    /// Keep the latest (key)frame per track for RTP-Info/SDP timing even
    /// while no subscriber is attached: PLAY answers need a rtptime base
    /// the moment a client connects, before the first GOP lands in the
    /// startup cache.
    /// Auto-inject SDP fmtp from the first keyframe carrying parameter
    /// sets (hardware encoders like HiMPP often emit SPS/PPS separated
    /// from the IDR slices). DESCRIBE merges this into the SDP when the
    /// description has no explicit fmtp. Cheap: runs on keyframes only,
    /// once per track, and also while no subscriber is attached (the
    /// very first keyframe typically arrives before the first PLAY).
    pub fn auto_inject_fmtp(&self, frame: &AccessUnit) {
        if !frame.is_keyframe {
            return;
        }
        let codec = self
            .codec_by_track
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(frame.track_id as usize)
            .copied()
            .flatten();
        let Some(codec) = codec else {
            return;
        };
        if !matches!(
            codec,
            rtflow_media::Codec::H264 | rtflow_media::Codec::H265 | rtflow_media::Codec::Opus
        ) {
            return;
        }
        {
            let lock = self
                .announce_fmtp
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if lock.contains_key(&frame.track_id) {
                return;
            }
        }
        use rtflow_media::bitstream::{
            h264_fmtp, h264_parameter_sets, h265_fmtp, h265_parameter_sets,
        };
        let fmtp = match codec {
            rtflow_media::Codec::H264 => {
                let sets = h264_parameter_sets(&frame.data);
                match (sets.sps.as_deref(), sets.pps.as_deref()) {
                    (Some(sps), Some(pps)) => Some(h264_fmtp(sps, pps)),
                    _ => None,
                }
            }
            rtflow_media::Codec::H265 => {
                let sets = h265_parameter_sets(&frame.data);
                match (
                    sets.vps.as_deref(),
                    sets.sps.as_deref(),
                    sets.pps.as_deref(),
                ) {
                    (Some(vps), Some(sps), Some(pps)) => Some(h265_fmtp(vps, sps, pps)),
                    _ => None,
                }
            }
            // RFC 7587: same parameters the WebRTC path announces.
            rtflow_media::Codec::Opus => Some("minptime=10;useinbandfec=1".to_string()),
            _ => None,
        };
        if let Some(fmtp) = fmtp {
            tracing::debug!("auto fmtp for track {}: {fmtp}", frame.track_id);
            self.announce_fmtp
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(frame.track_id, Arc::from(fmtp));
        }
    }

    pub fn update_bootstrap(&self, frame: &AccessUnit) {
        if frame.data.len() <= self.max_queued_bytes_per_session
            && (!matches!(
                frame.codec,
                rtflow_media::Codec::H264 | rtflow_media::Codec::H265
            ) || frame.is_keyframe)
            && let Ok(mut bootstrap) = self.bootstrap.try_lock()
        {
            bootstrap[frame.track_id as usize] = Some(frame.clone());
        }
    }

    #[allow(dead_code)] // used by RTSP sessions when the server feature is on
    pub fn subscribe_with_startup(
        &self,
        track_id: u8,
    ) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
        {
            let cache = self
                .startup_cache
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let receiver = self.frames.subscribe();
            let mut startup = cache.snapshot(track_id);
            let mut bytes = startup.iter().fold(0usize, |total, frame| {
                total.saturating_add(frame.data.len())
            });
            if bytes > self.max_queued_bytes_per_session {
                // Roll off the oldest frames up to the limit instead of
                // clearing the whole snapshot (keep a decodable start).
                while bytes > self.max_queued_bytes_per_session && startup.len() > 1 {
                    bytes -= startup.remove(0).data.len();
                }
                while startup.first().is_some_and(|f| !f.is_keyframe) && startup.len() > 1 {
                    startup.remove(0);
                }
            }
            // Bound how far back a new subscriber starts: a snapshot that
            // reaches seconds into the past makes the on-screen delay equal
            // to the whole cached window. Keep at most STARTUP_WINDOW of
            // media, cutting at the nearest keyframe.
            if let Some(last) = startup.last() {
                let cutoff = last.pts.saturating_sub(STARTUP_WINDOW);
                match startup
                    .iter()
                    .position(|frame| frame.pts >= cutoff && frame.is_keyframe)
                {
                    Some(cut) => {
                        // Window contains a keyframe: start playback there
                        // (decodes immediately, replay ≤ STARTUP_WINDOW).
                        startup.drain(..cut);
                    }
                    None => {
                        // No keyframe inside the window (GOP > STARTUP_WINDOW):
                        // the current GOP start was missed. Like mainstream
                        // surveillance cameras, drop the snapshot and wait
                        // for the next IDR (the sender's awaiting_key gate
                        // handles that) instead of replaying from an old GOP
                        // start — the viewer would otherwise stay a full GOP
                        // behind the live edge (and the old start may already
                        // have been evicted, causing a black screen).
                        startup.clear();
                    }
                }
            }
            // Deliberately no bootstrap fallback here: an empty snapshot
            // means "wait for the next IDR" (sender's awaiting_key gate),
            // matching surveillance-camera startup. The bootstrap frame is
            // still used for RTP-Info rtptime so the PLAY answer always
            // carries a timing base.
            (receiver, startup)
        }
    }

    pub fn subscribe_with_all_startup(&self) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
        let receiver = self.frames.subscribe();
        {
            let cache = self
                .startup_cache
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let mut startup = cache.snapshot_all();
            let mut bytes = startup.iter().fold(0usize, |total, frame| {
                total.saturating_add(frame.data.len())
            });
            if bytes > self.max_queued_bytes_per_session {
                // Roll off the oldest frames instead of clearing the snapshot.
                while bytes > self.max_queued_bytes_per_session && startup.len() > 1 {
                    bytes = bytes.saturating_sub(startup.remove(0).data.len());
                }
                while startup.first().is_some_and(|f| !f.is_keyframe) && startup.len() > 1 {
                    startup.remove(0);
                }
            }
            // Bound the startup window (see STARTUP_WINDOW).
            if let Some(last) = startup.last() {
                let cutoff = last.pts.saturating_sub(STARTUP_WINDOW);
                if let Some(cut) = startup
                    .iter()
                    .position(|frame| frame.pts >= cutoff && frame.is_keyframe)
                {
                    startup.drain(..cut);
                }
            }
            (receiver, startup)
        }
    }
}

// ---------------------------------------------------------------------------
// MountHandle (public API)
// ---------------------------------------------------------------------------

#[derive(Clone)]
pub struct MountHandle {
    pub path: rtflow_core::identity::MountId,
    pub description: Arc<MediaDescription>,
    pub(crate) inner: Arc<Mount>,
}

impl MountHandle {
    /// Shared mount state behind this handle (control-plane access).
    pub fn mount(&self) -> &Arc<Mount> {
        &self.inner
    }

    /// Current dynamic description (reflects RTMP/SRT sequence headers).
    pub fn description(&self) -> Arc<MediaDescription> {
        self.inner.description_snapshot()
    }

    /// Replace the media description for an ingest-created mount.
    pub fn update_description(
        &self,
        description: MediaDescription,
    ) -> rtflow_core::error::Result<()> {
        self.inner.update_description(description)
    }

    pub fn publisher(&self) -> Result<LocalPublisher> {
        match &self.inner.config {
            MountConfig::Local { .. } => {
                self.inner.publishers.fetch_add(1, Ordering::AcqRel);
            }
            MountConfig::Publisher { .. } => {
                // A claimed Publisher mount is exclusively owned by the
                // RTSP RECORD session: refuse extra publishers instead of
                // silently creating a second, interleaved stream.
                if self.inner.publisher_claimed.load(Ordering::Acquire) {
                    tracing::warn!(
                        mount = %self.inner.id,
                        "publisher attach refused: mount is claimed by an RTSP session"
                    );
                    return Err(Error::Conflict(
                        "publisher is already claimed by an RTSP session".into(),
                    ));
                }
                self.inner.publishers.fetch_add(1, Ordering::AcqRel);
            }
            #[allow(unreachable_patterns)] // only reachable with proxy/VOD mounts
            _ => {
                tracing::warn!(
                    mount = %self.inner.id,
                    "publisher attach refused: mount type does not accept publishers"
                );
                return Err(Error::Conflict("mount does not accept publishers".into()));
            }
        }
        tracing::info!(
            mount = %self.inner.id,
            publishers = self.inner.publishers.load(Ordering::Relaxed),
            "publisher attached"
        );
        Ok(LocalPublisher {
            inner: self.inner.clone(),
            active: true,
        })
    }

    /// Request a keyframe from a local source (RTCP PLI/FIR/NACK action).
    pub fn request_keyframe(&self, track_id: u8) {
        self.inner.request_keyframe(track_id);
    }

    pub fn subscribe(&self) -> crate::FrameReceiver {
        self.inner.frames.subscribe()
    }

    /// Subscribe to live frames together with a cached decodable stream start.
    #[allow(dead_code)] // used by RTSP sessions and HLS/HTTP-FLV adapters
    pub fn subscribe_with_startup(&self) -> (crate::FrameReceiver, Vec<Arc<AccessUnit>>) {
        self.inner.subscribe_with_all_startup()
    }

    pub fn announce_fmtp(&self) -> HashMap<u8, Arc<str>> {
        self.inner
            .announce_fmtp
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    /// Get a shared reference to the live announce_fmtp source.
    ///
    /// Unlike `announce_fmtp()` which returns a snapshot, this allows
    /// long-lived tasks to poll for updates as publishers ANNOUNCE.
    #[doc(hidden)]
    pub fn announce_fmtp_source(&self) -> Arc<Mount> {
        self.inner.clone()
    }

    /// Cancellation token tied to the mount lifetime.
    pub fn cancellation_token(&self) -> CancellationToken {
        self.inner.cancel.clone()
    }

    /// Mount path, suitable as the canonical HTTP asset prefix.
    /// Stable identity of this mount (independent of its path string).
    pub fn mount_id(&self) -> &rtflow_core::identity::MountId {
        &self.inner.id
    }

    pub fn path(&self) -> &str {
        self.inner.id.as_str()
    }

    pub fn snapshot(&self) -> MountSnapshot {
        // Unique sessions, not track subscriptions: one client with a
        // video+audio pair counts once.
        let subscribers = self.inner.active_sessions.load(Ordering::Relaxed);
        // HTTP-FLV / WS-FLV / HLS subscribers hold a broadcast receiver
        // but never register an RTSP session; a publisher's power gate
        // (`subscriber_count + broadcast_receivers == 0` → stop pushing)
        // would otherwise stall browser playback after the startup
        // snapshot. RTSP track subscriptions are included here too.
        let broadcast_receivers = self.inner.frames.receiver_count();
        let s = self.inner.stats.snapshot(subscribers);
        let (startup_cache_frames, startup_cache_bytes) = self
            .inner
            .startup_cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .usage();
        MountSnapshot {
            subscriber_count: s.subscribers,
            broadcast_receivers,
            publisher_connected: self.inner.publishers.load(Ordering::Relaxed) > 0,
            proxy_state: match &self.inner.config {
                MountConfig::Proxy { upstream } => Some(upstream.state()),
                _ => None,
            },
            stats: s,
            startup_cache_frames,
            startup_cache_bytes,
            consumer_queue_capacity: self.inner.consumer_queue_capacity,
        }
    }
}