moq_ext_sources/source/
sender.rs1use std::sync::{Arc, Mutex};
4
5use tokio::sync::watch;
6use tokio_util::sync::CancellationToken;
7
8use crate::{SourceClosed, audio, frames::FrameSlot, video};
9
10#[derive(Debug, Clone, Default)]
16pub struct Demand {
17 count: Arc<Mutex<usize>>,
18 wanted: watch::Sender<bool>,
19}
20
21impl Demand {
22 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 #[must_use]
35 pub fn watch(&self) -> watch::Receiver<bool> {
36 self.wanted.subscribe()
37 }
38}
39
40#[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
57pub(super) trait Sink<T>: Send + Sync + 'static {
61 fn deliver(&self, frame: T);
63
64 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
78pub type PcmFanout = tokio::sync::broadcast::Sender<audio::Frame>;
82
83pub type WeakPcmFanout = tokio::sync::broadcast::WeakSender<audio::Frame>;
85
86impl Sink<audio::Frame> for PcmFanout {
87 fn deliver(&self, frame: audio::Frame) {
88 let _ = self.send(frame);
91 }
92}
93
94#[derive(derive_more::Debug)]
105pub struct FrameSender<T> {
106 #[debug(skip)]
107 sink: Arc<dyn Sink<T>>,
108 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 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 #[must_use]
154 pub fn demand(&self) -> watch::Receiver<bool> {
155 self.demand.watch()
156 }
157
158 #[must_use]
160 pub fn is_closed(&self) -> bool {
161 self.closed.is_cancelled()
162 }
163
164 pub async fn closed(&self) {
168 self.closed.cancelled().await;
169 }
170}
171
172impl FrameSender<video::Frame> {
173 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 #[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}