bouncing_square/
bouncing-square.rs

1use simple_ffmpeg as ffmpeg;
2use ffmpeg::Color;
3
4const FACTOR: usize = 40;
5const WIDTH: usize = 16 * FACTOR;
6const HEIGHT: usize = 9 * FACTOR;
7const FPS: u32 = 60;
8const PIXEL_COUNT: usize = WIDTH * HEIGHT;
9
10fn draw_rect(pixels: &mut [Color], width: usize, x0: i32, y0: i32, w: i32, h: i32, color: Color) {
11    let height = pixels.len() / width;
12    for y in y0..=(y0 + h) {
13        if (0..height as i32).contains(&y) {
14            for x in x0..=(x0 + w) {
15                if (0..width as i32).contains(&x) {
16                    pixels[(y * width as i32 + x) as usize] = color;
17                }
18            }
19        }
20    }
21}
22
23fn main() -> ffmpeg::Result<()> {
24    let mut pixels: [Color; PIXEL_COUNT] = [0; PIXEL_COUNT];
25
26    let mut ffmpeg = ffmpeg::start("out.mp4", WIDTH, HEIGHT, FPS)?;
27
28    let mut x = 0;
29    let mut y = 0;
30    let mut dx = 1;
31    let mut dy = 1;
32    let w = 50;
33    let h = 50;
34    for _ in 0..(60 * FPS) {
35        pixels.fill(0);
36        draw_rect(&mut pixels, WIDTH, x, y, w, h, 0xFF00FF00);
37        ffmpeg.send_frame(&pixels)?;
38
39        let new_x = x + dx;
40        if (0..WIDTH as i32 - w).contains(&new_x) {
41            x = new_x;
42        } else {
43            dx *= -1;
44        }
45
46        let new_y = y + dy;
47        if (0..HEIGHT as i32 - h).contains(&new_y) {
48            y = new_y;
49        } else {
50            dy *= -1;
51        }
52    }
53
54    ffmpeg.finalize()?;
55
56    Ok(())
57}