Skip to main content

clairlune_render/
gif_export.rs

1//! Seamless GIF export (PLAN.md section 6.4).
2//!
3//! - One global palette: the scene palette (at most 255 colours, by
4//!   construction) plus index 255 as the transparent colour. No per-frame
5//!   quantisation, no dithering.
6//! - Frame 0 is the full image. Every later frame is exactly one sub-image: the
7//!   bounding box of pixels that changed, with unchanged pixels inside it set to
8//!   the transparent index (helps LZW), `DisposalMethod::Keep`. A frame identical
9//!   to the previous one is merged into the previous frame's delay.
10//! - Delays are whole centiseconds, dithered so they sum exactly to the loop.
11//! - The loop length is a multiple of the particle period, and the character
12//!   follows its loop script (`Clock::Loop`), so the last frame flows into the
13//!   first with no seam.
14
15use crate::clock::Clock;
16use crate::frame::render_frame_clocked;
17use crate::palette::TRANSPARENT_INDEX;
18use crate::{GlyphAtlas, IndexedImage, IndexedPalette, bake_static};
19use clairlune_scene::particles::LOOP_MS;
20use clairlune_scene::{BuildError, BuildOptions, SceneRecipe, build};
21use std::fmt;
22use std::io::Write;
23use std::time::Instant;
24
25/// Smoothness (PLAN.md section 5.3), capped by what GIF delays can express.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Smoothness {
28    BatterySaver,
29    Balanced,
30    Smooth,
31    VerySmooth,
32    UltraSmooth,
33}
34
35impl Smoothness {
36    /// Target delay per frame in centiseconds: about 6, 12, 25, 33 and 50 fps.
37    pub fn gif_delay_cs(self) -> u32 {
38        match self {
39            Smoothness::BatterySaver => 16,
40            Smoothness::Balanced => 8,
41            Smoothness::Smooth => 4,
42            Smoothness::VerySmooth => 3,
43            Smoothness::UltraSmooth => 2,
44        }
45    }
46}
47
48/// Valid loop lengths: whole multiples of the particle period.
49pub fn valid_loop_ms(loop_ms: u64) -> bool {
50    loop_ms > 0 && loop_ms.is_multiple_of(LOOP_MS)
51}
52
53/// Per-frame delays in centiseconds that sum exactly to the loop, as even as
54/// possible around the target (e.g. a mix of 16 and 17 cs).
55pub fn frame_delays(loop_ms: u64, target_cs: u32) -> Vec<u16> {
56    let total = loop_ms / 10;
57    let n = ((total as f64 / f64::from(target_cs.max(1))).round() as u64).max(1);
58    (0..n)
59        .map(|i| ((i + 1) * total / n - i * total / n) as u16)
60        .collect()
61}
62
63#[derive(Debug)]
64pub enum GifError {
65    Build(BuildError),
66    Encode(gif::EncodingError),
67    LoopLength(u64),
68    TooLarge { width: u32, height: u32 },
69}
70
71impl fmt::Display for GifError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            GifError::Build(e) => write!(f, "{e}"),
75            GifError::Encode(e) => write!(f, "GIF encoding failed: {e}"),
76            GifError::LoopLength(ms) => write!(
77                f,
78                "loop length {ms} ms isn't a multiple of the {LOOP_MS} ms particle period, so it couldn't loop seamlessly"
79            ),
80            GifError::TooLarge { width, height } => {
81                write!(
82                    f,
83                    "{width}x{height} is larger than GIF allows (65535 px per side)"
84                )
85            }
86        }
87    }
88}
89
90impl std::error::Error for GifError {}
91
92impl From<gif::EncodingError> for GifError {
93    fn from(e: gif::EncodingError) -> Self {
94        GifError::Encode(e)
95    }
96}
97
98/// What an export produced.
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub struct GifStats {
101    pub width: u32,
102    pub height: u32,
103    pub loop_ms: u64,
104    pub frames_rendered: usize,
105    pub frames_written: usize,
106    pub elapsed_ms: u64,
107}
108
109/// Bounding box `(x0, y0, x1, y1)` (exclusive end) of pixels that differ.
110fn changed_box(a: &IndexedImage, b: &IndexedImage) -> Option<(u32, u32, u32, u32)> {
111    let w = a.width as usize;
112    let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
113    for (y, (ra, rb)) in a
114        .pixels
115        .chunks_exact(w)
116        .zip(b.pixels.chunks_exact(w))
117        .enumerate()
118    {
119        if ra == rb {
120            continue;
121        }
122        let first = ra.iter().zip(rb).position(|(p, q)| p != q).unwrap();
123        let last = w
124            - 1
125            - ra.iter()
126                .rev()
127                .zip(rb.iter().rev())
128                .position(|(p, q)| p != q)
129                .unwrap();
130        x0 = x0.min(first);
131        x1 = x1.max(last + 1);
132        y0 = y0.min(y);
133        y1 = y + 1;
134    }
135    (x0 != usize::MAX).then_some((x0 as u32, y0 as u32, x1 as u32, y1 as u32))
136}
137
138/// Renders a seamless looping GIF of a recipe.
139pub fn encode_gif<W: Write>(
140    recipe: &SceneRecipe,
141    opts: &BuildOptions,
142    loop_ms: u64,
143    smoothness: Smoothness,
144    out: W,
145) -> Result<GifStats, GifError> {
146    if !valid_loop_ms(loop_ms) {
147        return Err(GifError::LoopLength(loop_ms));
148    }
149    if opts.width > u32::from(u16::MAX) || opts.height > u32::from(u16::MAX) {
150        return Err(GifError::TooLarge {
151            width: opts.width,
152            height: opts.height,
153        });
154    }
155    let started = Instant::now();
156    let graph = build(recipe, opts).map_err(GifError::Build)?;
157    let atlas = GlyphAtlas::for_grid(&graph.grid);
158    let palette = IndexedPalette::new(&graph.family);
159    let background = bake_static(&graph, &atlas);
160
161    let mut global = palette.rgb_bytes();
162    global.resize(256 * 3, 0); // index 255 stays free as the transparent colour
163    let (w16, h16) = (opts.width as u16, opts.height as u16);
164    let mut enc = gif::Encoder::new(out, w16, h16, &global)?;
165    enc.set_repeat(gif::Repeat::Infinite)?;
166
167    let delays = frame_delays(loop_ms, smoothness.gif_delay_cs());
168    let clock = Clock::Loop(loop_ms);
169    let mut prev: Option<IndexedImage> = None;
170    let mut pending: Option<gif::Frame<'static>> = None;
171    let mut written = 0usize;
172    let mut t_cs = 0u64;
173    for &d in &delays {
174        let img = render_frame_clocked(&background, &graph, &atlas, &palette, t_cs * 10, clock);
175        t_cs += u64::from(d);
176        let frame = match &prev {
177            None => gif::Frame {
178                width: w16,
179                height: h16,
180                delay: d,
181                dispose: gif::DisposalMethod::Keep,
182                buffer: img.pixels.clone().into(),
183                ..gif::Frame::default()
184            },
185            Some(p) => match changed_box(p, &img) {
186                None => {
187                    // Identical frame: extend the previous frame instead.
188                    if let Some(f) = pending.as_mut() {
189                        f.delay += d;
190                    }
191                    continue;
192                }
193                Some((x0, y0, x1, y1)) => {
194                    let (bw, bh) = (x1 - x0, y1 - y0);
195                    let mut buf = Vec::with_capacity((bw * bh) as usize);
196                    for y in y0..y1 {
197                        let row = (y * img.width) as usize;
198                        for x in x0..x1 {
199                            let i = row + x as usize;
200                            buf.push(if img.pixels[i] == p.pixels[i] {
201                                TRANSPARENT_INDEX
202                            } else {
203                                img.pixels[i]
204                            });
205                        }
206                    }
207                    gif::Frame {
208                        left: x0 as u16,
209                        top: y0 as u16,
210                        width: bw as u16,
211                        height: bh as u16,
212                        delay: d,
213                        dispose: gif::DisposalMethod::Keep,
214                        transparent: Some(TRANSPARENT_INDEX),
215                        buffer: buf.into(),
216                        ..gif::Frame::default()
217                    }
218                }
219            },
220        };
221        if let Some(f) = pending.take() {
222            enc.write_frame(&f)?;
223            written += 1;
224        }
225        pending = Some(frame);
226        prev = Some(img);
227    }
228    if let Some(f) = pending.take() {
229        enc.write_frame(&f)?;
230        written += 1;
231    }
232    drop(enc);
233    let stats = GifStats {
234        width: opts.width,
235        height: opts.height,
236        loop_ms,
237        frames_rendered: delays.len(),
238        frames_written: written,
239        elapsed_ms: started.elapsed().as_millis() as u64,
240    };
241    tracing::info!(
242        target: "clairlune_render",
243        seed = recipe.seed,
244        recipe_hash = %recipe.hash_hex(),
245        width = opts.width,
246        height = opts.height,
247        loop_ms,
248        frames_rendered = stats.frames_rendered,
249        frames_written = stats.frames_written,
250        elapsed_ms = stats.elapsed_ms,
251        "gif encoded"
252    );
253    Ok(stats)
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn delays_sum_exactly_to_the_loop() {
262        for loop_ms in [6000u64, 12000] {
263            for s in [
264                Smoothness::BatterySaver,
265                Smoothness::Balanced,
266                Smoothness::Smooth,
267                Smoothness::VerySmooth,
268                Smoothness::UltraSmooth,
269            ] {
270                let d = frame_delays(loop_ms, s.gif_delay_cs());
271                assert_eq!(d.iter().map(|&x| u64::from(x)).sum::<u64>(), loop_ms / 10);
272                let (min, max) = (*d.iter().min().unwrap(), *d.iter().max().unwrap());
273                assert!(max - min <= 1, "{s:?}: delays {min}..{max}");
274                assert!(u32::from(min) >= 2, "browsers clamp delays under 2 cs");
275            }
276        }
277        // 6 s at Battery saver: 37.5 frames of 16 cs, so a 16/17 mix.
278        let d = frame_delays(6000, 16);
279        assert!(d.contains(&16) && d.contains(&15) || d.contains(&16) && d.contains(&17));
280    }
281
282    #[test]
283    fn rejects_loops_that_cannot_be_seamless() {
284        assert!(valid_loop_ms(6000) && valid_loop_ms(12000));
285        assert!(!valid_loop_ms(3000) && !valid_loop_ms(10000) && !valid_loop_ms(0));
286    }
287}