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, Theme, 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/// The longest journey loop a GIF holds whole; past it, a journey's GIF is
54/// an excerpt of the length asked for (its land jumps where it repeats).
55pub const JOURNEY_GIF_MAX_MS: u64 = 36_000;
56
57/// The GIF's length: the one asked for, or a short journey's own loop.
58fn gif_loop(journey: Option<&clairlune_scene::Journey>, asked: u64) -> u64 {
59    match journey {
60        Some(j) if j.loop_ms <= JOURNEY_GIF_MAX_MS => j.loop_ms,
61        _ => asked,
62    }
63}
64
65/// Per-frame delays in centiseconds that sum exactly to the loop, as even as
66/// possible around the target (e.g. a mix of 16 and 17 cs).
67pub fn frame_delays(loop_ms: u64, target_cs: u32) -> Vec<u16> {
68    let total = loop_ms / 10;
69    let n = ((total as f64 / f64::from(target_cs.max(1))).round() as u64).max(1);
70    (0..n)
71        .map(|i| ((i + 1) * total / n - i * total / n) as u16)
72        .collect()
73}
74
75#[derive(Debug)]
76pub enum GifError {
77    Build(BuildError),
78    Encode(gif::EncodingError),
79    LoopLength(u64),
80    TooLarge { width: u32, height: u32 },
81}
82
83impl fmt::Display for GifError {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        match self {
86            GifError::Build(e) => write!(f, "{e}"),
87            GifError::Encode(e) => write!(f, "GIF encoding failed: {e}"),
88            GifError::LoopLength(ms) => write!(
89                f,
90                "loop length {ms} ms isn't a multiple of the {LOOP_MS} ms particle period, so it couldn't loop seamlessly"
91            ),
92            GifError::TooLarge { width, height } => {
93                write!(
94                    f,
95                    "{width}x{height} is larger than GIF allows (65535 px per side)"
96                )
97            }
98        }
99    }
100}
101
102impl std::error::Error for GifError {}
103
104impl From<gif::EncodingError> for GifError {
105    fn from(e: gif::EncodingError) -> Self {
106        GifError::Encode(e)
107    }
108}
109
110/// What an export produced.
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct GifStats {
113    pub width: u32,
114    pub height: u32,
115    pub loop_ms: u64,
116    pub frames_rendered: usize,
117    pub frames_written: usize,
118    pub elapsed_ms: u64,
119}
120
121/// Bounding box `(x0, y0, x1, y1)` (exclusive end) of pixels that differ.
122fn changed_box(a: &IndexedImage, b: &IndexedImage) -> Option<(u32, u32, u32, u32)> {
123    let w = a.width as usize;
124    let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
125    for (y, (ra, rb)) in a
126        .pixels
127        .chunks_exact(w)
128        .zip(b.pixels.chunks_exact(w))
129        .enumerate()
130    {
131        if ra == rb {
132            continue;
133        }
134        let first = ra.iter().zip(rb).position(|(p, q)| p != q).unwrap();
135        let last = w
136            - 1
137            - ra.iter()
138                .rev()
139                .zip(rb.iter().rev())
140                .position(|(p, q)| p != q)
141                .unwrap();
142        x0 = x0.min(first);
143        x1 = x1.max(last + 1);
144        y0 = y0.min(y);
145        y1 = y + 1;
146    }
147    (x0 != usize::MAX).then_some((x0 as u32, y0 as u32, x1 as u32, y1 as u32))
148}
149
150/// Renders a seamless looping GIF of a recipe.
151pub fn encode_gif<W: Write>(
152    recipe: &SceneRecipe,
153    opts: &BuildOptions,
154    loop_ms: u64,
155    smoothness: Smoothness,
156    out: W,
157) -> Result<GifStats, GifError> {
158    if !valid_loop_ms(loop_ms) {
159        return Err(GifError::LoopLength(loop_ms));
160    }
161    if opts.width > u32::from(u16::MAX) || opts.height > u32::from(u16::MAX) {
162        return Err(GifError::TooLarge {
163            width: opts.width,
164            height: opts.height,
165        });
166    }
167    let started = Instant::now();
168    let graph = build(recipe, opts).map_err(GifError::Build)?;
169    let loop_ms = gif_loop(graph.journey.as_ref(), loop_ms);
170    let atlas = GlyphAtlas::for_grid(&graph.grid);
171    let palette = IndexedPalette::for_graph(&graph);
172    let background = bake_static(&graph, &atlas);
173    let journey = crate::JourneyBake::new(&graph, &atlas);
174    let clock = Clock::Loop(loop_ms);
175    let (rendered, written) = encode_frames(
176        opts.width,
177        opts.height,
178        &palette,
179        loop_ms,
180        smoothness,
181        out,
182        |t| match &journey {
183            Some(j) => {
184                let bg = j.background_at(&graph, &background, t);
185                render_frame_clocked(&bg, &graph, &atlas, &palette, t, clock)
186            }
187            None => render_frame_clocked(&background, &graph, &atlas, &palette, t, clock),
188        },
189    )?;
190    let stats = GifStats {
191        width: opts.width,
192        height: opts.height,
193        loop_ms,
194        frames_rendered: rendered,
195        frames_written: written,
196        elapsed_ms: started.elapsed().as_millis() as u64,
197    };
198    tracing::info!(
199        target: "clairlune_render",
200        seed = recipe.seed,
201        recipe_hash = %recipe.hash_hex(),
202        width = opts.width,
203        height = opts.height,
204        loop_ms,
205        frames_rendered = stats.frames_rendered,
206        frames_written = stats.frames_written,
207        elapsed_ms = stats.elapsed_ms,
208        "gif encoded"
209    );
210    Ok(stats)
211}
212
213/// Writes a looping GIF from a frame source: one global palette, changed
214/// boxes only, identical frames merged. Returns frames rendered and written.
215fn encode_frames<W: Write>(
216    width: u32,
217    height: u32,
218    palette: &IndexedPalette,
219    loop_ms: u64,
220    smoothness: Smoothness,
221    out: W,
222    mut frame_at: impl FnMut(u64) -> IndexedImage,
223) -> Result<(usize, usize), GifError> {
224    let mut global = palette.rgb_bytes();
225    global.resize(256 * 3, 0); // index 255 stays free as the transparent colour
226    let (w16, h16) = (width as u16, height as u16);
227    let mut enc = gif::Encoder::new(out, w16, h16, &global)?;
228    enc.set_repeat(gif::Repeat::Infinite)?;
229    let delays = frame_delays(loop_ms, smoothness.gif_delay_cs());
230    let mut prev: Option<IndexedImage> = None;
231    let mut pending: Option<gif::Frame<'static>> = None;
232    let mut written = 0usize;
233    let mut t_cs = 0u64;
234    for &d in &delays {
235        let img = frame_at(t_cs * 10);
236        t_cs += u64::from(d);
237        let frame = match &prev {
238            None => gif::Frame {
239                width: w16,
240                height: h16,
241                delay: d,
242                dispose: gif::DisposalMethod::Keep,
243                buffer: img.pixels.clone().into(),
244                ..gif::Frame::default()
245            },
246            Some(p) => match changed_box(p, &img) {
247                None => {
248                    // Identical frame: extend the previous frame instead.
249                    if let Some(f) = pending.as_mut() {
250                        f.delay += d;
251                    }
252                    continue;
253                }
254                Some((x0, y0, x1, y1)) => {
255                    let (bw, bh) = (x1 - x0, y1 - y0);
256                    let mut buf = Vec::with_capacity((bw * bh) as usize);
257                    for y in y0..y1 {
258                        let row = (y * img.width) as usize;
259                        for x in x0..x1 {
260                            let i = row + x as usize;
261                            buf.push(if img.pixels[i] == p.pixels[i] {
262                                TRANSPARENT_INDEX
263                            } else {
264                                img.pixels[i]
265                            });
266                        }
267                    }
268                    gif::Frame {
269                        left: x0 as u16,
270                        top: y0 as u16,
271                        width: bw as u16,
272                        height: bh as u16,
273                        delay: d,
274                        dispose: gif::DisposalMethod::Keep,
275                        transparent: Some(TRANSPARENT_INDEX),
276                        buffer: buf.into(),
277                        ..gif::Frame::default()
278                    }
279                }
280            },
281        };
282        if let Some(f) = pending.take() {
283            enc.write_frame(&f)?;
284            written += 1;
285        }
286        pending = Some(frame);
287        prev = Some(img);
288    }
289    if let Some(f) = pending.take() {
290        enc.write_frame(&f)?;
291        written += 1;
292    }
293    drop(enc);
294    Ok((delays.len(), written))
295}
296
297/// Exports a saved scene as a looping GIF, exactly as saved (no generator).
298pub fn encode_package_gif<W: Write>(
299    pkg: &crate::ScenePackage,
300    theme: Theme,
301    buddy: bool,
302    loop_ms: u64,
303    smoothness: Smoothness,
304    signature: Option<&str>,
305    out: W,
306) -> Result<GifStats, GifError> {
307    if !valid_loop_ms(loop_ms) {
308        return Err(GifError::LoopLength(loop_ms));
309    }
310    if pkg.width > u32::from(u16::MAX) || pkg.height > u32::from(u16::MAX) {
311        return Err(GifError::TooLarge {
312            width: pkg.width,
313            height: pkg.height,
314        });
315    }
316    let palette = pkg
317        .palette(theme)
318        .ok_or(GifError::Build(BuildError::ThemeLocked(theme)))?
319        .clone();
320    let loop_ms = gif_loop(pkg.graph(theme).and_then(|g| g.journey.as_ref()), loop_ms);
321    let started = Instant::now();
322    let clock = Clock::Loop(loop_ms);
323    // Each frame signed the same way, so unchanged frames still merge.
324    let signature = signature.and_then(|s| crate::Signature::new(pkg.width, pkg.height, s));
325    let (rendered, written) = encode_frames(
326        pkg.width,
327        pkg.height,
328        &palette,
329        loop_ms,
330        smoothness,
331        out,
332        |t| {
333            let mut img = pkg
334                .frame(theme, buddy, t, clock)
335                .map(|(img, _)| img)
336                .expect("theme checked above");
337            if let Some(s) = &signature {
338                s.apply(&mut img);
339            }
340            img
341        },
342    )?;
343    Ok(GifStats {
344        width: pkg.width,
345        height: pkg.height,
346        loop_ms,
347        frames_rendered: rendered,
348        frames_written: written,
349        elapsed_ms: started.elapsed().as_millis() as u64,
350    })
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn delays_sum_exactly_to_the_loop() {
359        for loop_ms in [6000u64, 12000] {
360            for s in [
361                Smoothness::BatterySaver,
362                Smoothness::Balanced,
363                Smoothness::Smooth,
364                Smoothness::VerySmooth,
365                Smoothness::UltraSmooth,
366            ] {
367                let d = frame_delays(loop_ms, s.gif_delay_cs());
368                assert_eq!(d.iter().map(|&x| u64::from(x)).sum::<u64>(), loop_ms / 10);
369                let (min, max) = (*d.iter().min().unwrap(), *d.iter().max().unwrap());
370                assert!(max - min <= 1, "{s:?}: delays {min}..{max}");
371                assert!(u32::from(min) >= 2, "browsers clamp delays under 2 cs");
372            }
373        }
374        // 6 s at Battery saver: 37.5 frames of 16 cs, so a 16/17 mix.
375        let d = frame_delays(6000, 16);
376        assert!(d.contains(&16) && d.contains(&15) || d.contains(&16) && d.contains(&17));
377    }
378
379    #[test]
380    fn rejects_loops_that_cannot_be_seamless() {
381        assert!(valid_loop_ms(6000) && valid_loop_ms(12000));
382        assert!(!valid_loop_ms(3000) && !valid_loop_ms(10000) && !valid_loop_ms(0));
383    }
384}