Skip to main content

moq_ext_sources/
bounce.rs

1//! A bouncing-square test picture that can be drawn for any instant.
2
3use std::{f64::consts::TAU, time::Duration};
4
5use moq_net::Timestamp;
6
7use crate::{
8    Error,
9    video::{self, I420, Size, Surface},
10};
11
12/// How long the background takes through all hues.
13const HUE_PERIOD: Duration = Duration::from_secs(12);
14
15/// How long the square takes from one edge to the other.
16const CROSSING: Duration = Duration::from_millis(1500);
17
18/// The luma of the background.
19const BACKGROUND: u8 = 110;
20
21/// The luma of the square.
22const WHITE: u8 = 235;
23
24/// The chroma of a grey, which the square has.
25const NEUTRAL: u8 = 128;
26
27/// How far the background's chroma swings from [`NEUTRAL`].
28const SATURATION: f64 = 50.0;
29
30/// A white square bouncing left and right on a background that drifts through the hues.
31///
32/// Motion follows elapsed time rather than a frame count, so
33/// [`draw`](Self::draw) returns a consistent picture for any instant. The
34/// square crosses the picture in 1.5 s, the hue cycles every 12 s, and the
35/// pictures are I420. [`VideoSource::test_bounce`](crate::VideoSource::test_bounce)
36/// draws it at a fixed rate.
37///
38/// # Examples
39///
40/// ```
41/// use std::time::Duration;
42///
43/// use moq_ext_sources::BouncePattern;
44///
45/// let pattern = BouncePattern::new(moq_video::Size::new(640, 360))?;
46/// let frame = pattern.draw(Duration::from_millis(250))?;
47/// assert_eq!(frame.timestamp.as_micros(), Ok(250_000));
48/// # Ok::<_, moq_ext_sources::Error>(())
49/// ```
50#[derive(Debug, Clone)]
51pub struct BouncePattern {
52    size: Size,
53    side: u32,
54}
55
56impl BouncePattern {
57    /// Returns the pattern drawn at `size`.
58    ///
59    /// # Errors
60    ///
61    /// Fails with [`Error::InvalidConfig`] if a dimension of `size` is zero or
62    /// odd, which I420 cannot hold.
63    pub fn new(size: Size) -> Result<Self, Error> {
64        let Size { width, height } = size;
65        if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 {
66            return Err(Error::invalid(format!(
67                "the bounce pattern needs an even, non-zero size, not {width}x{height}"
68            )));
69        }
70        // Even, so the square covers whole chroma samples where it can.
71        let side = (height * 2 / 9 / 2 * 2).clamp(2, width);
72        Ok(Self { size, side })
73    }
74
75    /// Returns the size the pattern is drawn at.
76    #[must_use]
77    pub fn size(&self) -> Size {
78        self.size
79    }
80
81    /// Returns the left edge of the square `elapsed` after the start, in pixels.
82    ///
83    /// The square starts at the left edge and bounces between the edges at a
84    /// constant speed.
85    #[must_use]
86    pub fn square_left(&self, elapsed: Duration) -> u32 {
87        let travel = f64::from(self.size.width - self.side);
88        // Goes from 0 to 2 over a round trip. Past 1 the square is on its way back.
89        let phase = (elapsed.as_secs_f64() / CROSSING.as_secs_f64()).rem_euclid(2.0);
90        let along = if phase <= 1.0 { phase } else { 2.0 - phase };
91        (along * travel).round() as u32
92    }
93
94    /// Returns the picture `elapsed` after the start, stamped with `elapsed`.
95    ///
96    /// # Errors
97    ///
98    /// Fails with [`Error::InvalidConfig`] if `elapsed` is beyond what a
99    /// timestamp holds.
100    pub fn draw(&self, elapsed: Duration) -> Result<video::Frame, Error> {
101        let timestamp = u64::try_from(elapsed.as_micros())
102            .ok()
103            .and_then(|micros| Timestamp::from_micros(micros).ok())
104            .ok_or_else(|| Error::invalid(format!("{elapsed:?} is beyond a timestamp")))?;
105        // Unreachable, since `new` checked the size.
106        let surface = self
107            .surface(elapsed)
108            .map_err(|err| Error::invalid(err.to_string()))?;
109        Ok(video::Frame::new(timestamp, surface))
110    }
111
112    /// Returns the picture `elapsed` after the start.
113    ///
114    /// Only fails if the planes do not fit the size, which [`new`](Self::new) rules out.
115    pub(crate) fn surface(&self, elapsed: Duration) -> Result<Surface, video::Error> {
116        let (width, height) = (self.size.width as usize, self.size.height as usize);
117        let side = self.side as usize;
118        let hue = TAU * (elapsed.as_secs_f64() / HUE_PERIOD.as_secs_f64()).fract();
119        let u = (f64::from(NEUTRAL) + SATURATION * hue.cos()) as u8;
120        let v = (f64::from(NEUTRAL) + SATURATION * hue.sin()) as u8;
121        let luma = width * height;
122        let quarter = luma / 4;
123        let mut data = vec![BACKGROUND; luma];
124        data.resize(luma + quarter, u);
125        data.resize(luma + 2 * quarter, v);
126
127        let x = self.square_left(elapsed) as usize;
128        let y = (height - side) / 2;
129        for row in y..y + side {
130            data[row * width + x..row * width + x + side].fill(WHITE);
131        }
132        // Every chroma sample the square touches, so its edges carry no hue.
133        let half_width = width / 2;
134        let columns = x / 2..(x + side).div_ceil(2);
135        for row in y / 2..(y + side).div_ceil(2) {
136            for plane in [luma, luma + quarter] {
137                let at = plane + row * half_width;
138                data[at + columns.start..at + columns.end].fill(NEUTRAL);
139            }
140        }
141        Ok(Surface::I420(I420::new(self.size, data)?))
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    const SIZE: Size = Size {
150        width: 640,
151        height: 360,
152    };
153
154    /// Returns the luma plane of the picture at `elapsed`.
155    fn luma(pattern: &BouncePattern, elapsed: Duration) -> Vec<u8> {
156        let frame = pattern.draw(elapsed).unwrap();
157        let size = pattern.size();
158        frame.surface.to_i420().unwrap().data()[..(size.width * size.height) as usize].to_vec()
159    }
160
161    /// Returns the left edge of the square, read off the middle row.
162    fn left_in_picture(pattern: &BouncePattern, elapsed: Duration) -> u32 {
163        let size = pattern.size();
164        let row = (size.height / 2 * size.width) as usize;
165        let luma = luma(pattern, elapsed);
166        (0..size.width)
167            .find(|&x| luma[row + x as usize] == WHITE)
168            .expect("the square is on the middle row")
169    }
170
171    /// The frame is I420 at the size asked for, stamped with the elapsed time.
172    #[test]
173    fn frames_are_i420_at_the_size_and_time() {
174        let pattern = BouncePattern::new(SIZE).unwrap();
175        let frame = pattern.draw(Duration::from_millis(1234)).unwrap();
176        assert_eq!(frame.timestamp.as_micros(), Ok(1_234_000));
177        let Surface::I420(image) = &frame.surface else {
178            panic!("not I420");
179        };
180        assert_eq!(image.size(), SIZE);
181        assert_eq!(image.data().len(), 640 * 360 * 3 / 2);
182    }
183
184    /// The square is 80 pixels at 640x360 and scales with the height.
185    #[test]
186    fn the_square_scales_with_the_height() {
187        assert_eq!(BouncePattern::new(SIZE).unwrap().side, 80);
188        assert_eq!(BouncePattern::new(Size::new(1280, 720)).unwrap().side, 160);
189        assert_eq!(BouncePattern::new(Size::new(4, 360)).unwrap().side, 4);
190        let tiny = BouncePattern::new(Size::new(2, 2)).unwrap();
191        tiny.draw(Duration::from_secs(1)).unwrap();
192    }
193
194    /// An elapsed time beyond a timestamp fails instead of wrapping.
195    #[test]
196    fn an_elapsed_time_beyond_a_timestamp_is_refused() {
197        let pattern = BouncePattern::new(Size::new(2, 2)).unwrap();
198        assert!(pattern.draw(Duration::MAX).is_err());
199        // Would wrap to zero microseconds if cast.
200        let wraps = Duration::from_micros(u64::MAX) + Duration::from_micros(1);
201        assert!(pattern.draw(wraps).is_err());
202    }
203
204    /// An odd or empty size has no I420 picture.
205    #[test]
206    fn odd_sizes_are_refused() {
207        for size in [Size::new(641, 360), Size::new(640, 361), Size::new(0, 360)] {
208            assert!(BouncePattern::new(size).is_err(), "{size:?}");
209        }
210    }
211
212    /// The square starts at the left, reaches the right after one crossing, and comes back.
213    #[test]
214    fn the_square_bounces_between_the_edges() {
215        let pattern = BouncePattern::new(SIZE).unwrap();
216        let right = 640 - 80;
217        for (elapsed, expected) in [
218            (Duration::ZERO, 0),
219            (CROSSING / 2, right / 2),
220            (CROSSING, right),
221            (CROSSING * 3 / 2, right / 2),
222            (CROSSING * 2, 0),
223            (CROSSING * 41, right),
224        ] {
225            assert_eq!(pattern.square_left(elapsed), expected, "at {elapsed:?}");
226            assert_eq!(
227                left_in_picture(&pattern, elapsed),
228                expected,
229                "at {elapsed:?}"
230            );
231        }
232    }
233
234    /// The square moves the same distance every 50 ms for a minute, folded at the edges.
235    #[test]
236    fn the_square_moves_at_a_constant_speed() {
237        let pattern = BouncePattern::new(SIZE).unwrap();
238        let step = Duration::from_millis(50);
239        let right = f64::from(640 - 80);
240        let expected = right * step.as_secs_f64() / CROSSING.as_secs_f64();
241        let xs: Vec<f64> = (0..1200u32)
242            .map(|k| f64::from(pattern.square_left(step * k)))
243            .collect();
244        for pair in xs.windows(2) {
245            let moved = (pair[1] - pair[0]).abs();
246            let at_edge = pair.iter().any(|&x| x <= expected || x >= right - expected);
247            assert!(
248                (moved - expected).abs() <= 1.0 || at_edge,
249                "moved {moved} px, expected {expected:.1} px, at {pair:?}"
250            );
251            assert!(moved > 0.0, "paused at {pair:?}");
252        }
253    }
254
255    /// The background drifts through the hues and the square stays grey.
256    #[test]
257    fn the_background_drifts_through_the_hues() {
258        let pattern = BouncePattern::new(SIZE).unwrap();
259        let chroma = |elapsed: Duration| {
260            let frame = pattern.draw(elapsed).unwrap();
261            let data = frame.surface.to_i420().unwrap().data().to_vec();
262            let (u, v) = (640 * 360, 640 * 360 * 5 / 4);
263            // The top-left sample is background, and the square starts at the left.
264            let square = 90 * 320 + 10;
265            (data[u], data[v], data[u + square], data[v + square])
266        };
267        assert_eq!(chroma(Duration::ZERO), (178, 128, 128, 128));
268        assert_eq!(chroma(HUE_PERIOD / 4).1, 178);
269        assert_eq!(chroma(HUE_PERIOD / 2).0, 78);
270        assert_eq!(chroma(HUE_PERIOD).0, 178);
271    }
272}