Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: buffer GIF file output

jatmna60f98825861
diff --git a/crates/enc-gif/examples/benchmark.rs b/crates/enc-gif/examples/benchmark.rs
new file mode 100644
index 000000000..6e0b55830
--- /dev/null
+++ b/crates/enc-gif/examples/benchmark.rs
@@ -0,0 +1,64 @@
+use cap_enc_gif::GifEncoderWrapper;
+use std::{error::Error, hint::black_box, io, path::PathBuf, time::Instant};
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let mut args = std::env::args().skip(1);
+ let fixture = args.next().unwrap_or_default();
+ let path = args
+ .next()
+ .map(PathBuf::from)
+ .ok_or_else(|| io::Error::other("usage: benchmark <texture|ui> <output.gif>"))?;
+ if !matches!(fixture.as_str(), "texture" | "ui") || args.next().is_some() {
+ return Err(io::Error::other("usage: benchmark <texture|ui> <output.gif>").into());
+ }
+
+ let (width, height, count) = (960usize, 540usize, 60usize);
+ let frames: Vec<Vec<u8>> = (0..count)
+ .map(|frame| {
+ let mut bytes = vec![0; width * height * 4];
+ for y in 0..height {
+ for x in 0..width {
+ let value = if fixture == "ui" {
+ if y < 45 {
+ 5
+ } else if x < 160 {
+ 10
+ } else {
+ let sx = x - 160;
+ let sy = y + frame * 3;
+ if sy % 54 < 20 && sx % 340 < 240 {
+ 20 + ((sy / 54) % 7) as u8 * 4
+ } else if sy % 54 < 23 && sx % 340 < 280 {
+ 9
+ } else {
+ 63
+ }
+ }
+ } else {
+ let hash = ((x / 2 + frame * 7) as u32).wrapping_mul(747796405)
+ ^ (y as u32 / 2).wrapping_mul(2891336453);
+ ((hash ^ (hash >> 16)) % 64) as u8
+ };
+ let offset = (y * width + x) * 4;
+ bytes[offset..offset + 4].copy_from_slice(&[
+ (value & 3) * 85,
+ ((value >> 2) & 3) * 85,
+ ((value >> 4) & 3) * 85,
+ 255,
+ ]);
+ }
+ }
+ bytes
+ })
+ .collect();
+
+ let start = Instant::now();
+ let mut encoder = GifEncoderWrapper::new(&path, width as u32, height as u32, 30)?;
+ for frame in &frames {
+ encoder.add_frame(black_box(frame), width * 4)?;
+ }
+ encoder.finish()?;
+ let elapsed = start.elapsed().as_secs_f64() * 1000.0;
+ println!("{elapsed:.3},{}", std::fs::metadata(path)?.len());
+ Ok(())
+}
diff --git a/crates/enc-gif/src/lib.rs b/crates/enc-gif/src/lib.rs
index c471bde98..aa4c38c29 100644
--- a/crates/enc-gif/src/lib.rs
+++ b/crates/enc-gif/src/lib.rs
@@ -1,6 +1,7 @@
use gifski::{Collector, Repeat, Settings};
use rgb::RGBA8;
use std::fs::File;
+use std::io::{BufWriter, Write};
use std::path::Path;
use std::thread::{self, JoinHandle};
use thiserror::Error;
@@ -84,9 +85,7 @@ impl GifEncoderWrapper {
let output_path = path.as_ref().to_path_buf();
let writer_thread = thread::spawn(move || {
let file = File::create(output_path).map_err(GifEncodingError::Io)?;
- writer
- .write(file, &mut gifski::progress::NoProgress {})
- .map_err(|e| GifEncodingError::Gifski(e.to_string()))
+ write_gif(writer, file)
});
Ok(Self {
@@ -197,6 +196,14 @@ impl GifEncoderWrapper {
}
}
+fn write_gif(writer: gifski::Writer, output: impl Write) -> Result<(), GifEncodingError> {
+ let mut output = BufWriter::new(output);
+ writer
+ .write(&mut output, &mut gifski::progress::NoProgress {})
+ .map_err(|e| GifEncodingError::Gifski(e.to_string()))?;
+ output.flush().map_err(GifEncodingError::Io)
+}
+
impl Drop for GifEncoderWrapper {
fn drop(&mut self) {
if !self.finished && self.collector.is_some() {
@@ -212,3 +219,59 @@ impl Drop for GifEncoderWrapper {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io;
+
+ fn single_frame_writer() -> gifski::Writer {
+ let (collector, writer) = gifski::new(Settings {
+ width: Some(2),
+ height: Some(2),
+ ..Settings::default()
+ })
+ .unwrap();
+ collector
+ .add_frame_rgba(
+ 0,
+ imgref::Img::new(vec![RGBA8::new(255, 0, 0, 255); 4], 2, 2),
+ 0.0,
+ )
+ .unwrap();
+ drop(collector);
+ writer
+ }
+
+ #[test]
+ fn buffered_output_matches_unbuffered_gif() {
+ let mut expected = Vec::new();
+ single_frame_writer()
+ .write(&mut expected, &mut gifski::progress::NoProgress {})
+ .unwrap();
+ assert!(expected.len() < BufWriter::new(Vec::<u8>::new()).capacity());
+ assert_eq!(expected.last(), Some(&0x3b));
+
+ let mut actual = Vec::new();
+ write_gif(single_frame_writer(), &mut actual).unwrap();
+ assert_eq!(actual, expected);
+ }
+
+ #[test]
+ fn buffered_tail_write_error_is_returned() {
+ struct FailingOutput;
+
+ impl Write for FailingOutput {
+ fn write(&mut self, _: &[u8]) -> io::Result<usize> {
+ Err(io::Error::other("output full"))
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ let error = write_gif(single_frame_writer(), FailingOutput).unwrap_err();
+ assert!(matches!(error, GifEncodingError::Io(error) if error.to_string() == "output full"));
+ }
+}