Skip to main content

moq_ext_sources/source/
scaled.rs

1//! A video source that scales another source's frames to I420 as they arrive.
2
3use std::{sync::Arc, time::Instant};
4
5use n0_future::task::AbortOnDropHandle;
6use tracing::{Instrument, debug, debug_span, warn};
7
8use super::{Demand, Driver, VideoFormat, VideoSource};
9use crate::{Error, frames::FrameSlot, video};
10
11impl VideoSource {
12    /// Returns a source of this source's frames scaled to `size`, as I420 in CPU memory.
13    ///
14    /// The output is always CPU I420, so this is not meant for publishing:
15    /// a GPU frame would be downloaded and uploaded again for a hardware
16    /// encoder. Use `VideoRendition::with_size` in `moq-ext-publisher`
17    /// instead, which keeps GPU frames on the GPU.
18    ///
19    /// GPU frames are scaled on their device where supported. The picture is
20    /// stretched to exactly `size`, and only the newest frame is scaled.
21    ///
22    /// A frame that can never be scaled ends the source, even over a
23    /// [`switchable`](Self::switchable) input that later moves on, and
24    /// [`failure`](Self::failure) returns why.
25    ///
26    /// # Errors
27    ///
28    /// Returns [`Error::InvalidConfig`] if `size` is zero or odd.
29    ///
30    /// # Panics
31    ///
32    /// Panics when called outside a Tokio runtime.
33    pub fn scaled(&self, size: video::Size) -> Result<Self, Error> {
34        if size.width == 0
35            || size.height == 0
36            || !size.width.is_multiple_of(2)
37            || !size.height.is_multiple_of(2)
38        {
39            return Err(Error::invalid(format!(
40                "cannot scale to {size}: I420 needs an even, non-zero size"
41            )));
42        }
43        let slot = FrameSlot::new();
44        let reader = slot.reader();
45        let demand = Demand::default();
46        let format = VideoFormat {
47            size,
48            rate: self.format().rate,
49        };
50        let span = debug_span!("scaled", input = self.label(), %size);
51        let task = AbortOnDropHandle::new(n0_future::task::spawn(
52            run(self.clone(), size, slot, demand.clone()).instrument(span),
53        ));
54        let driver = Driver::Derived {
55            input: self.clone(),
56            _task: task,
57        };
58        Ok(Self::with_demand(
59            format!("{}-scaled", self.label()),
60            format,
61            reader,
62            Default::default(),
63            driver,
64            demand,
65        ))
66    }
67}
68
69/// Scales the frames of `input` to `size` into `slot` while `demand` wants them.
70///
71/// Returns once `input` ends, or once a frame can never be scaled. Records
72/// the input's failure, or its own, in `slot`.
73async fn run(input: VideoSource, size: video::Size, slot: FrameSlot, demand: Demand) {
74    // Observed, so the input is wanted only while the scaled source is.
75    let mut frames = input.observe();
76    let mut wanted = demand.watch();
77    let mut guard = None;
78    // Whether the last frame failed to scale, so a run of failures warns once.
79    let mut failing = false;
80    // A keyframe request on the input that no scaled frame has carried yet.
81    let mut keyframe = false;
82    loop {
83        let want = *wanted.borrow_and_update();
84        if want != guard.is_some() {
85            guard = want.then(|| input.want());
86        }
87        // The demand cannot close: this task holds it.
88        let frame = if guard.is_some() {
89            tokio::select! {
90                frame = frames.next() => frame,
91                _ = wanted.changed() => continue,
92            }
93        } else {
94            tokio::select! {
95                () = frames.closed() => None,
96                _ = wanted.changed() => continue,
97            }
98        };
99        let Some(frame) = frame else { break };
100        let at = frames.sent_at().unwrap_or_else(Instant::now);
101        keyframe |= frames.keyframe_requested();
102        match tokio::task::spawn_blocking(move || to_i420(frame, size)).await {
103            Ok(Ok(frame)) => {
104                failing = false;
105                if std::mem::take(&mut keyframe) {
106                    slot.request_keyframe();
107                }
108                slot.send_at(frame, at);
109            }
110            Ok(Err(err)) if is_permanent(&err) => {
111                warn!(error = format_args!("{err:#}"), "cannot scale this input");
112                slot.fail(Arc::new(Error::device(err)));
113                return;
114            }
115            Ok(Err(err)) if !failing => {
116                failing = true;
117                warn!(
118                    error = format_args!("{err:#}"),
119                    "cannot scale a frame, skipping frames until one scales"
120                );
121            }
122            Ok(Err(err)) => debug!(error = format_args!("{err:#}"), "cannot scale a frame"),
123            Err(err) => {
124                let err = Error::device_msg(format!("the scaling task failed: {err}"));
125                slot.fail(Arc::new(err));
126                return;
127            }
128        }
129    }
130    if let Some(failure) = input.failure() {
131        slot.fail(failure);
132    }
133}
134
135/// Returns whether `err` fails every later frame of the same input too.
136///
137/// An input delivers one kind of surface, so a surface this build or platform
138/// cannot scale at all will not scale on the next frame either.
139fn is_permanent(err: &video::Error) -> bool {
140    matches!(err, video::Error::Unsupported(_))
141}
142
143/// Returns `frame` scaled to `size` in I420, or `frame` itself if it already is.
144fn to_i420(frame: Arc<video::Frame>, size: video::Size) -> Result<Arc<video::Frame>, video::Error> {
145    if frame.size() == size && matches!(frame.surface, video::Surface::I420(_)) {
146        return Ok(frame);
147    }
148    let image = if frame.size() == size {
149        frame.surface.to_i420()?.into_owned()
150    } else {
151        // A GPU surface scales on its device, and only the small picture is
152        // downloaded.
153        frame
154            .surface
155            .resize(size, &Default::default())?
156            .into_i420()?
157    };
158    Ok(Arc::new(video::Frame::new(
159        frame.timestamp,
160        video::Surface::I420(image),
161    )))
162}
163
164#[cfg(test)]
165mod tests {
166    use std::time::Duration;
167
168    use super::*;
169    use crate::FrameSender;
170
171    const TIMEOUT: Duration = Duration::from_secs(5);
172
173    fn format(size: video::Size) -> VideoFormat {
174        VideoFormat {
175            size,
176            rate: video::FrameRate::new(30, 1).expect("a valid rate"),
177        }
178    }
179
180    fn push_rgba(sender: &FrameSender<video::Frame>, size: video::Size, micros: u64) {
181        let len = (size.width * size.height * 4) as usize;
182        let surface = video::Surface::rgba(&vec![128; len], size).expect("a valid size");
183        let timestamp = moq_net::Timestamp::from_micros(micros).expect("in range");
184        sender
185            .push(video::Frame::new(timestamp, surface))
186            .expect("open");
187    }
188
189    async fn next(frames: &mut crate::VideoFrames) -> Arc<video::Frame> {
190        tokio::time::timeout(TIMEOUT, frames.next())
191            .await
192            .expect("a frame in time")
193            .expect("the stream is open")
194    }
195
196    #[tokio::test]
197    async fn frames_arrive_scaled_in_i420_with_their_timestamp() {
198        let big = video::Size::new(8, 6);
199        let small = video::Size::new(4, 2);
200        let (sender, source) = VideoSource::push(format(big));
201        let scaled = source.scaled(small).expect("a valid size");
202        assert_eq!(scaled.format().size, small);
203        assert_eq!(scaled.format().rate, source.format().rate);
204        let mut frames = scaled.frames();
205        push_rgba(&sender, big, 42);
206        let frame = next(&mut frames).await;
207        assert_eq!(frame.size(), small);
208        assert!(matches!(frame.surface, video::Surface::I420(_)));
209        assert_eq!(frame.timestamp.as_micros(), Ok(42));
210    }
211
212    #[tokio::test]
213    async fn a_frame_of_the_right_size_in_i420_passes_through() {
214        let size = video::Size::new(4, 2);
215        let (sender, source) = VideoSource::push(format(size));
216        let scaled = source.scaled(size).expect("a valid size");
217        let mut input = source.observe();
218        let mut frames = scaled.frames();
219        let rgba = video::Surface::rgba(&[128; 32], size).expect("4x2");
220        let image = rgba.to_i420().expect("a CPU picture").into_owned();
221        let timestamp = moq_net::Timestamp::from_micros(2).expect("in range");
222        sender
223            .push(video::Frame::new(timestamp, video::Surface::I420(image)))
224            .expect("open");
225        let pushed = next(&mut input).await;
226        assert!(Arc::ptr_eq(&pushed, &next(&mut frames).await));
227    }
228
229    /// A keyframe request on the input marks the next scaled frame, and only that one.
230    #[tokio::test]
231    async fn a_keyframe_request_reaches_the_scaled_frames() {
232        let big = video::Size::new(8, 6);
233        let (sender, source) = VideoSource::push(format(big));
234        let scaled = source.scaled(video::Size::new(4, 2)).expect("a valid size");
235        let mut frames = scaled.frames();
236        push_rgba(&sender, big, 1);
237        next(&mut frames).await;
238        assert!(!frames.keyframe_requested());
239        sender.request_keyframe();
240        push_rgba(&sender, big, 2);
241        assert_eq!(next(&mut frames).await.timestamp.as_micros(), Ok(2));
242        assert!(frames.keyframe_requested(), "the frame after the request");
243        push_rgba(&sender, big, 3);
244        assert_eq!(next(&mut frames).await.timestamp.as_micros(), Ok(3));
245        assert!(!frames.keyframe_requested(), "a request marks one frame");
246    }
247
248    #[test]
249    fn only_an_unsupported_surface_fails_the_source() {
250        assert!(is_permanent(&video::Error::Unsupported(
251            "an external Vulkan surface".into()
252        )));
253        assert!(!is_permanent(&video::Error::CodecGone("reset".into())));
254    }
255
256    #[tokio::test]
257    async fn the_label_names_the_input() {
258        let (_sender, source) = VideoSource::push(format(video::Size::new(4, 4)));
259        let scaled = source.scaled(video::Size::new(2, 2)).expect("a valid size");
260        assert_eq!(scaled.label(), format!("{}-scaled", source.label()));
261    }
262
263    #[test]
264    fn an_odd_or_empty_size_is_refused() {
265        let (_sender, source) = VideoSource::push(format(video::Size::new(4, 4)));
266        for size in [video::Size::new(3, 2), video::Size::new(0, 2)] {
267            assert!(matches!(
268                source.scaled(size),
269                Err(Error::InvalidConfig { .. })
270            ));
271        }
272    }
273
274    #[tokio::test]
275    async fn the_input_is_wanted_only_while_the_scaled_source_is() {
276        let size = video::Size::new(4, 4);
277        let (sender, source) = VideoSource::push(format(size));
278        let scaled = source.scaled(video::Size::new(2, 2)).expect("a valid size");
279        let mut demand = sender.demand();
280        assert!(!*demand.borrow());
281        let frames = scaled.frames();
282        tokio::time::timeout(TIMEOUT, demand.wait_for(|wanted| *wanted))
283            .await
284            .expect("the input became wanted")
285            .expect("the input is open");
286        drop(frames);
287        tokio::time::timeout(TIMEOUT, demand.wait_for(|wanted| !*wanted))
288            .await
289            .expect("the input stopped being wanted")
290            .expect("the input is open");
291    }
292
293    /// The scaled source keeps its input running, and lets go of it once dropped.
294    #[tokio::test]
295    async fn the_scaled_source_owns_its_input() {
296        let size = video::Size::new(4, 4);
297        let (sender, source) = VideoSource::push(format(size));
298        let scaled = source.scaled(video::Size::new(2, 2)).expect("a valid size");
299        drop(source);
300        assert!(
301            !sender.is_closed(),
302            "the input closed under the scaled source"
303        );
304        let mut frames = scaled.frames();
305        push_rgba(&sender, size, 3);
306        assert_eq!(next(&mut frames).await.timestamp.as_micros(), Ok(3));
307
308        drop(scaled);
309        tokio::time::timeout(TIMEOUT, sender.closed())
310            .await
311            .expect("the input closed with the scaled source");
312        assert!(
313            tokio::time::timeout(TIMEOUT, frames.next())
314                .await
315                .expect("the stream ended")
316                .is_none(),
317            "a frames handle outlived its source"
318        );
319    }
320
321    #[tokio::test]
322    async fn the_scaled_source_ends_with_its_input() {
323        let size = video::Size::new(4, 4);
324        let (sender, source) = VideoSource::push(format(size));
325        let scaled = source.scaled(video::Size::new(2, 2)).expect("a valid size");
326        drop(source);
327        let mut frames = scaled.frames();
328        push_rgba(&sender, size, 5);
329        assert_eq!(next(&mut frames).await.timestamp.as_micros(), Ok(5));
330        drop(sender);
331        assert!(
332            tokio::time::timeout(TIMEOUT, frames.next())
333                .await
334                .expect("the stream ended")
335                .is_none()
336        );
337        assert!(scaled.failure().is_none());
338    }
339
340    #[tokio::test]
341    async fn the_scaled_source_reports_the_failure_of_its_input() {
342        let size = video::Size::new(4, 4);
343        let source = VideoSource::spawn("failing", format(size), |_sender| {
344            Err(Error::device_msg("the screen went away"))
345        })
346        .expect("the thread starts");
347        let scaled = source.scaled(video::Size::new(2, 2)).expect("a valid size");
348        let mut frames = scaled.frames();
349        assert!(
350            tokio::time::timeout(TIMEOUT, frames.next())
351                .await
352                .expect("the stream ended")
353                .is_none()
354        );
355        assert!(matches!(
356            scaled.failure().as_deref(),
357            Some(Error::Device { .. })
358        ));
359    }
360}