Skip to content

Instantly share code, notes, and snippets.

@tetsu-koba
Last active January 26, 2024 13:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetsu-koba/14083c6705b69017bbc7fb97602f610a to your computer and use it in GitHub Desktop.
Save tetsu-koba/14083c6705b69017bbc7fb97602f610a to your computer and use it in GitHub Desktop.
2D graphics animation tool using cairo rust binding and ffmpeg
2D graphics animation tool using cairo rust binding and ffmpeg
extern crate cairo;
use std::io::Write;
use std::process::{Command, Stdio};
use std::f64::consts::PI;
use cairo::{ImageSurface, Format, Context};
fn draw(surface: &ImageSurface, f: i32) {
let cr = Context::new(surface);
let width = surface.get_width() as f64;
let height = surface.get_height() as f64;
let dx = f as f64 * 1.0;
cr.set_source_rgb(1.0, 1.0, 1.0);
cr.paint();
let cx = width / 2.0;
let cy = height / 2.0;
let r = cy;
let cstart = -0.5 * PI;
let cend = cstart + 2.0 * PI * ((f + 1) as f64) / 300.0;
cr.move_to(cx, cy);
cr.line_to(cx, 0.0);
cr.arc(cx, cy, r, cstart, cend);
cr.line_to(cx, cy);
cr.set_source_rgba(0.0, 0.5, 0.0, 0.2);
cr.fill();
cr.select_font_face(
"sans-serif",
cairo::FontSlant::Normal,
cairo::FontWeight::Normal,
);
cr.set_font_size(70.0);
cr.move_to(600.0 - dx, 100.0);
cr.set_source_rgb(0.0, 0.0, 1.0);
cr.show_text("Hello, world! 1234567890");
cr.fill();
}
fn make_cmdline(width: i32, height: i32, framerate: i32) -> String {
format!(
"ffmpeg -f rawvideo -pix_fmt bgra -s {width}x{height} -i - -pix_fmt yuv420p -r {framerate} -y out.mp4",
width = width,
height = height,
framerate = framerate
)
}
fn make_movie(width: i32, height: i32, framerate: i32, frames: i32) {
let mut surface =
ImageSurface::create(Format::ARgb32, width, height).expect("Couldn't create surface");
let mut child = Command::new("/bin/sh")
.args(&["-c", &make_cmdline(width, height, framerate)])
.stdin(Stdio::piped())
.spawn()
.expect("failed to execute child");
{
// limited borrow of stdin
let child_stdin = child.stdin.as_mut().expect("failed to get stdin");
(0..frames).for_each(|f| {
draw(&surface, f);
let d = surface.get_data().expect("Failed to get_data");
child_stdin.write_all(&d).expect("Failed to write to file");
});
}
child.wait().expect("child process wasn't running");
}
fn main() {
make_movie(1280, 720, 30, 300);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment