Skip to main content

moq_ext_sources/source/
sender.rs

1//! The push end of a source, and the demand a source reports back to it.
2
3use std::sync::{Arc, Mutex};
4
5use tokio::sync::watch;
6use tokio_util::sync::CancellationToken;
7
8use crate::{SourceClosed, audio, frames::FrameSlot, video};
9
10/// Whether anything currently wants a source's frames.
11///
12/// Every running encoder holds a [`DemandGuard`], and so does every handle
13/// from [`VideoSource::frames`](crate::VideoSource::frames). The source is
14/// wanted while any guard lives.
15#[derive(Debug, Clone, Default)]
16pub struct Demand {
17    count: Arc<Mutex<usize>>,
18    wanted: watch::Sender<bool>,
19}
20
21impl Demand {
22    /// Registers one consumer that wants frames, for as long as the guard lives.
23    pub fn acquire(&self) -> DemandGuard {
24        let mut count = self.count.lock().expect("poisoned");
25        *count += 1;
26        self.wanted
27            .send_if_modified(|wanted| !std::mem::replace(wanted, true));
28        DemandGuard {
29            demand: self.clone(),
30        }
31    }
32
33    /// Returns a receiver that reports whether anything wants frames.
34    #[must_use]
35    pub fn watch(&self) -> watch::Receiver<bool> {
36        self.wanted.subscribe()
37    }
38}
39
40/// One consumer's claim on a source's frames, withdrawn on drop.
41#[derive(Debug)]
42#[must_use = "the demand ends when the guard is dropped"]
43pub struct DemandGuard {
44    demand: Demand,
45}
46
47impl Drop for DemandGuard {
48    fn drop(&mut self) {
49        let mut count = self.demand.count.lock().expect("poisoned");
50        *count = count.saturating_sub(1);
51        if *count == 0 {
52            self.demand.wanted.send_replace(false);
53        }
54    }
55}
56
57/// Where pushed frames go.
58///
59/// Video goes to a latest-wins slot, PCM to a bounded fan-out.
60pub(super) trait Sink<T>: Send + Sync + 'static {
61    /// Hands one frame on without blocking.
62    fn deliver(&self, frame: T);
63
64    /// Asks for a keyframe at the next frame delivered.
65    fn request_keyframe(&self) {}
66}
67
68impl Sink<video::Frame> for FrameSlot {
69    fn deliver(&self, frame: video::Frame) {
70        self.send(Arc::new(frame));
71    }
72
73    fn request_keyframe(&self) {
74        Self::request_keyframe(self);
75    }
76}
77
78/// The fan-out a PCM source writes into.
79///
80/// Every attached broadcast reads it through its own receiver.
81pub type PcmFanout = tokio::sync::broadcast::Sender<audio::Frame>;
82
83/// A [`PcmFanout`] that does not keep the source alive.
84pub type WeakPcmFanout = tokio::sync::broadcast::WeakSender<audio::Frame>;
85
86impl Sink<audio::Frame> for PcmFanout {
87    fn deliver(&self, frame: audio::Frame) {
88        // An error only means no broadcast is attached, and the frame is
89        // dropped.
90        let _ = self.send(frame);
91    }
92}
93
94/// The push end of a source.
95///
96/// [`VideoSource::push`](crate::VideoSource::push) and
97/// [`AudioSource::push`](crate::AudioSource::push) return one, and
98/// [`VideoSource::spawn`](crate::VideoSource::spawn) hands one to its closure.
99/// Pushing never blocks. A video frame replaces a pending one. PCM beyond the
100/// buffer drops the oldest frames, and the broadcast reading it counts them in
101/// its stats.
102///
103/// The source ends when every sender is dropped. Cheap to clone.
104#[derive(derive_more::Debug)]
105pub struct FrameSender<T> {
106    #[debug(skip)]
107    sink: Arc<dyn Sink<T>>,
108    /// Cancelled once the source is gone.
109    closed: CancellationToken,
110    demand: Demand,
111}
112
113impl<T> Clone for FrameSender<T> {
114    fn clone(&self) -> Self {
115        Self {
116            sink: self.sink.clone(),
117            closed: self.closed.clone(),
118            demand: self.demand.clone(),
119        }
120    }
121}
122
123impl<T: 'static> FrameSender<T> {
124    pub(super) fn new(sink: Arc<dyn Sink<T>>, closed: CancellationToken, demand: Demand) -> Self {
125        Self {
126            sink,
127            closed,
128            demand,
129        }
130    }
131
132    /// Pushes one frame.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`SourceClosed`] once every handle to the source has been dropped.
137    /// A producing loop should stop then.
138    pub fn push(&self, frame: T) -> Result<(), SourceClosed> {
139        if self.closed.is_cancelled() {
140            return Err(SourceClosed);
141        }
142        self.sink.deliver(frame);
143        Ok(())
144    }
145
146    /// Returns whether any broadcast wants frames.
147    ///
148    /// It is true while a broadcast this source feeds encodes it, which for
149    /// video means while somebody watches. A video source is also wanted
150    /// while a handle from [`VideoSource::frames`](crate::VideoSource::frames)
151    /// lives. A camera the application drives itself can idle while it is
152    /// false.
153    #[must_use]
154    pub fn demand(&self) -> watch::Receiver<bool> {
155        self.demand.watch()
156    }
157
158    /// Reports whether the source is gone.
159    #[must_use]
160    pub fn is_closed(&self) -> bool {
161        self.closed.is_cancelled()
162    }
163
164    /// Waits until the source is gone.
165    ///
166    /// Cancellation safe.
167    pub async fn closed(&self) {
168        self.closed.cancelled().await;
169    }
170}
171
172impl FrameSender<video::Frame> {
173    /// Asks every encoder of the source for a keyframe at the next frame pushed.
174    ///
175    /// Each rendition's encoder cuts on the first frame it encodes after the
176    /// request, which is the next frame pushed or a newer one if the encoder
177    /// skipped it. Several requests before one frame cut once. A source
178    /// derived from this one, such as
179    /// [`VideoSource::scaled`](crate::VideoSource::scaled), passes the
180    /// request on.
181    ///
182    /// Whether the encoder's keyframe interval restarts at a requested
183    /// keyframe depends on the backend; a producer that places every keyframe
184    /// itself sets a `join` longer than the spacing of its requests. A backend
185    /// that cannot cut ignores the request, and so does a source that nothing
186    /// encodes.
187    pub fn request_keyframe(&self) {
188        self.sink.request_keyframe();
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn demand_follows_the_guards() {
198        let demand = Demand::default();
199        let wanted = demand.watch();
200        assert!(!*wanted.borrow());
201        let first = demand.acquire();
202        let second = demand.acquire();
203        assert!(*wanted.borrow());
204        drop(first);
205        assert!(*wanted.borrow(), "one consumer still wants frames");
206        drop(second);
207        assert!(!*wanted.borrow());
208    }
209
210    /// A video sender's request reaches the reader with the next frame pushed.
211    #[test]
212    fn a_keyframe_request_marks_the_next_frame() {
213        let slot = FrameSlot::new();
214        let mut frames = slot.frames();
215        let sender: FrameSender<video::Frame> =
216            FrameSender::new(Arc::new(slot), CancellationToken::new(), Demand::default());
217        let size = video::Size::new(2, 2);
218        let frame = |micros| {
219            let surface = video::Surface::rgba(&[0; 16], size).expect("2x2");
220            video::Frame::new(
221                moq_net::Timestamp::from_micros(micros).expect("in range"),
222                surface,
223            )
224        };
225        sender.push(frame(0)).expect("open");
226        frames.try_next().expect("a frame");
227        assert!(!frames.keyframe_requested());
228        sender.request_keyframe();
229        sender.push(frame(1)).expect("open");
230        frames.try_next().expect("a frame");
231        assert!(frames.keyframe_requested());
232    }
233
234    #[test]
235    fn a_sender_to_a_gone_source_is_closed() {
236        let slot = FrameSlot::new();
237        let closed = CancellationToken::new();
238        let sender: FrameSender<video::Frame> =
239            FrameSender::new(Arc::new(slot), closed.clone(), Demand::default());
240        assert!(!sender.is_closed());
241        closed.cancel();
242        let size = video::Size::new(2, 2);
243        let surface = video::Surface::rgba(&[0; 16], size).expect("2x2");
244        let frame = video::Frame::new(moq_net::Timestamp::from_micros(0).expect("0"), surface);
245        assert_eq!(sender.push(frame), Err(SourceClosed));
246    }
247}