moq_ext_sources/
bounce.rs1use std::{f64::consts::TAU, time::Duration};
4
5use moq_net::Timestamp;
6
7use crate::{
8 Error,
9 video::{self, I420, Size, Surface},
10};
11
12const HUE_PERIOD: Duration = Duration::from_secs(12);
14
15const CROSSING: Duration = Duration::from_millis(1500);
17
18const BACKGROUND: u8 = 110;
20
21const WHITE: u8 = 235;
23
24const NEUTRAL: u8 = 128;
26
27const SATURATION: f64 = 50.0;
29
30#[derive(Debug, Clone)]
51pub struct BouncePattern {
52 size: Size,
53 side: u32,
54}
55
56impl BouncePattern {
57 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 let side = (height * 2 / 9 / 2 * 2).clamp(2, width);
72 Ok(Self { size, side })
73 }
74
75 #[must_use]
77 pub fn size(&self) -> Size {
78 self.size
79 }
80
81 #[must_use]
86 pub fn square_left(&self, elapsed: Duration) -> u32 {
87 let travel = f64::from(self.size.width - self.side);
88 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 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 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 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 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 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 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 #[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 #[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 #[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 let wraps = Duration::from_micros(u64::MAX) + Duration::from_micros(1);
201 assert!(pattern.draw(wraps).is_err());
202 }
203
204 #[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 #[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 #[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 #[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 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}