PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Render Video to animated GIF (shareable output)
Brandon Thomas6417c13b69ba
diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rsindex 61fc00fae..297813afe 100644--- a/crates/codecs/src/web.rs+++ b/crates/codecs/src/web.rs@@ -143,6 +143,68 @@ pub fn encode_gif_indexed(width: u32, height: u32, indices: &[u8], palette: &[[uOk(out)}+/// One frame of an animated GIF: palette indices, its (local) palette, an optional transparent+/// index, and the on-screen delay in centiseconds.+pub struct GifFrame {+ pub indices: Vec<u8>,+ pub palette: Vec<[u8; 3]>,+ pub transparent: Option<u8>,+ pub delay_cs: u16,+}++/// Encode an animated GIF (GIF89a). Each frame carries its own local colour table; `loop_forever`+/// adds the NETSCAPE2.0 looping extension.+pub fn encode_gif_animated(width: u32, height: u32, frames: &[GifFrame], loop_forever: bool) -> Result<Vec<u8>, CodecError> {+ let (w, h) = (width as usize, height as usize);+ if width == 0 || height == 0 || width > 65535 || height > 65535 {+ return Err(gif_err("GIF size must be 1..=65535"));+ }+ if frames.is_empty() {+ return Err(gif_err("an animated GIF needs at least one frame"));+ }+ let mut out = b"GIF89a".to_vec();+ out.extend((width as u16).to_le_bytes());+ out.extend((height as u16).to_le_bytes());+ out.push(0x70); // no global colour table, 8-bit colour resolution+ out.push(0); // background colour index+ out.push(0); // pixel aspect ratio+ if loop_forever {+ out.extend([0x21, 0xFF, 0x0B]);+ out.extend_from_slice(b"NETSCAPE2.0");+ out.extend([0x03, 0x01, 0x00, 0x00, 0x00]); // loop count 0 = forever+ }+ for f in frames {+ if f.palette.is_empty() || f.palette.len() > 256 || f.indices.len() != w * h || f.indices.iter().any(|&i| usize::from(i) >= f.palette.len()) {+ return Err(gif_err("every frame's palette must have 1..=256 entries covering its indices"));+ }+ let bits = (1..=8u8).find(|b| (1usize << b) >= f.palette.len()).unwrap_or(8);+ // Graphic Control Extension: disposal 1 (leave), delay, optional transparency.+ let packed = if f.transparent.is_some() { 0x05 } else { 0x04 };+ out.extend([0x21, 0xF9, 0x04, packed]);+ out.extend(f.delay_cs.to_le_bytes());+ out.push(f.transparent.unwrap_or(0));+ out.push(0);+ // Image Descriptor with a Local Colour Table.+ out.push(0x2C);+ out.extend([0, 0, 0, 0]);+ out.extend((width as u16).to_le_bytes());+ out.extend((height as u16).to_le_bytes());+ out.push(0x80 | (bits - 1));+ for i in 0..(1usize << bits) {+ out.extend(f.palette.get(i).copied().unwrap_or([0, 0, 0]));+ }+ let min = bits.max(2);+ out.push(min);+ for chunk in lzw_encode(&f.indices, min).chunks(255) {+ out.push(chunk.len() as u8);+ out.extend_from_slice(chunk);+ }+ out.push(0);+ }+ out.push(0x3B);+ Ok(out)+}+fn put_multibyte(out: &mut Vec<u8>, v: u32) {let mut groups = vec![(v & 0x7f) as u8];let mut v = v >> 7;@@ -355,3 +417,37 @@ mod subsampling_tests {}}}++#[cfg(test)]+mod anim_tests {+ use super::*;++ #[test]+ fn animated_gif_has_header_and_frames() {+ let frames: Vec<GifFrame> = (0..3)+ .map(|i| GifFrame {+ indices: vec![i as u8; 4],+ palette: vec![[0, 0, 0], [255, 0, 0], [0, 255, 0]],+ transparent: None,+ delay_cs: 4,+ })+ .collect();+ let g = encode_gif_animated(2, 2, &frames, true).unwrap();+ assert_eq!(&g[..6], b"GIF89a");+ assert_eq!(*g.last().unwrap(), 0x3B);+ // Three image descriptors (0x2C) for three frames.+ assert_eq!(g.iter().filter(|&&b| b == 0x2C).count(), 3);+ // NETSCAPE loop extension present.+ assert!(g.windows(11).any(|w| w == b"NETSCAPE2.0"));+ // First frame still decodes.+ let img = crate::decode(&g).unwrap();+ assert_eq!(img.dimensions(), (2, 2));+ }++ #[test]+ fn rejects_bad_frames() {+ assert!(encode_gif_animated(2, 2, &[], false).is_err());+ let bad = GifFrame { indices: vec![0; 3], palette: vec![[0, 0, 0]], transparent: None, delay_cs: 1 };+ assert!(encode_gif_animated(2, 2, &[bad], false).is_err());+ }+}diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rsindex 0e223e721..5ed7df0b8 100644--- a/crates/engine/src/video_cmds.rs+++ b/crates/engine/src/video_cmds.rs@@ -284,7 +284,37 @@ fn render_video(s: &mut Session, p: &Value) -> Result<Value> {let st = s.active().ok_or(EngineError::NoDocument)?;let base = (*st.doc).clone();let frames = base.timeline.as_ref().map_or(1, |t| t.duration).max(1);+ let fps = base.timeline.as_ref().map_or(30.0, |t| t.fps).max(1.0);let stem = base.name.rsplit_once('.').map_or(base.name.as_str(), |(a, _)| a).to_string();+ let fmt = base.pixel_format();+ let bounds = base.bounds();+ let (w, h) = (bounds.width() as usize, bounds.height() as usize);++ // Animated GIF: one file, every frame quantised to its own palette.+ if format.eq_ignore_ascii_case("gif") {+ use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind};+ let delay = (100.0 / fps).round().clamp(1.0, 65535.0) as u16;+ let mut gframes = Vec::with_capacity(frames);+ for f in 0..frames {+ let mut doc = base.clone();+ if let Some(t) = &mut doc.timeline {+ t.current = f;+ }+ sync(&mut doc);+ let surf = crate::file_cmds::flattened(&doc, fmt);+ let mut px = vec![[0.0f32; 4]; w * h];+ surf.read_rgba_into(bounds, &mut px);+ let pal = quantize::build_palette(&px, PaletteKind::Adaptive, 256, Forced::None).map_err(EngineError::Other)?;+ let idx = quantize::quantize(&mut px, w, &pal, Dither::None, 1.0, None);+ gframes.push(photocraft_codecs::web::GifFrame { indices: idx, palette: pal, transparent: None, delay_cs: delay });+ }+ let gif = photocraft_codecs::web::encode_gif_animated(w as u32, h as u32, &gframes, true).map_err(|e| EngineError::Other(e.to_string()))?;+ let path = format!("{dir}/{stem}.gif");+ std::fs::write(&path, &gif).map_err(|e| EngineError::Other(format!("write `{path}`: {e}")))?;+ return Ok(json!({"frames": frames, "file": path}));+ }++ // Image sequence.let opts = photocraft_io::ExportOptions::default();let mut files = Vec::new();for f in 0..frames {diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/video_cmds/tests.rsindex 44746d519..ccab39201 100644--- a/crates/engine/src/video_cmds/tests.rs+++ b/crates/engine/src/video_cmds/tests.rs@@ -99,3 +99,19 @@ fn frames_to_layers_and_render_video() {assert!(rr["frames"].as_u64().unwrap() >= 2);assert!(std::path::Path::new(&out).exists());}++#[test]+fn render_video_to_animated_gif() {+ let dir = tmpdir("gifsrc");+ write_png(&format!("{dir}/a.png"), 10, 8, "#ff0000");+ write_png(&format!("{dir}/b.png"), 10, 8, "#00ff00");+ write_png(&format!("{dir}/c.png"), 10, 8, "#0000ff");+ let mut s = session();+ s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": dir})).unwrap();+ let out = tmpdir("gifout");+ let r = s.execute("file.export.renderVideo", json!({"dir": out, "format": "gif"})).unwrap();+ assert_eq!(r["frames"], 3);+ let gif = std::fs::read(r["file"].as_str().unwrap()).unwrap();+ assert_eq!(&gif[..6], b"GIF89a");+ assert_eq!(gif.iter().filter(|&&b| b == 0x2C).count(), 3); // 3 frames+}