1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Smoothness {
28 BatterySaver,
29 Balanced,
30 Smooth,
31 VerySmooth,
32 UltraSmooth,
33}
34
35impl Smoothness {
36 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
48pub fn valid_loop_ms(loop_ms: u64) -> bool {
50 loop_ms > 0 && loop_ms.is_multiple_of(LOOP_MS)
51}
52
53pub 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#[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
109fn 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
138pub 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::for_graph(&graph);
159 let background = bake_static(&graph, &atlas);
160 let clock = Clock::Loop(loop_ms);
161 let (rendered, written) = encode_frames(
162 opts.width,
163 opts.height,
164 &palette,
165 loop_ms,
166 smoothness,
167 out,
168 |t| render_frame_clocked(&background, &graph, &atlas, &palette, t, clock),
169 )?;
170 let stats = GifStats {
171 width: opts.width,
172 height: opts.height,
173 loop_ms,
174 frames_rendered: rendered,
175 frames_written: written,
176 elapsed_ms: started.elapsed().as_millis() as u64,
177 };
178 tracing::info!(
179 target: "clairlune_render",
180 seed = recipe.seed,
181 recipe_hash = %recipe.hash_hex(),
182 width = opts.width,
183 height = opts.height,
184 loop_ms,
185 frames_rendered = stats.frames_rendered,
186 frames_written = stats.frames_written,
187 elapsed_ms = stats.elapsed_ms,
188 "gif encoded"
189 );
190 Ok(stats)
191}
192
193fn encode_frames<W: Write>(
196 width: u32,
197 height: u32,
198 palette: &IndexedPalette,
199 loop_ms: u64,
200 smoothness: Smoothness,
201 out: W,
202 mut frame_at: impl FnMut(u64) -> IndexedImage,
203) -> Result<(usize, usize), GifError> {
204 let mut global = palette.rgb_bytes();
205 global.resize(256 * 3, 0); let (w16, h16) = (width as u16, height as u16);
207 let mut enc = gif::Encoder::new(out, w16, h16, &global)?;
208 enc.set_repeat(gif::Repeat::Infinite)?;
209 let delays = frame_delays(loop_ms, smoothness.gif_delay_cs());
210 let mut prev: Option<IndexedImage> = None;
211 let mut pending: Option<gif::Frame<'static>> = None;
212 let mut written = 0usize;
213 let mut t_cs = 0u64;
214 for &d in &delays {
215 let img = frame_at(t_cs * 10);
216 t_cs += u64::from(d);
217 let frame = match &prev {
218 None => gif::Frame {
219 width: w16,
220 height: h16,
221 delay: d,
222 dispose: gif::DisposalMethod::Keep,
223 buffer: img.pixels.clone().into(),
224 ..gif::Frame::default()
225 },
226 Some(p) => match changed_box(p, &img) {
227 None => {
228 if let Some(f) = pending.as_mut() {
230 f.delay += d;
231 }
232 continue;
233 }
234 Some((x0, y0, x1, y1)) => {
235 let (bw, bh) = (x1 - x0, y1 - y0);
236 let mut buf = Vec::with_capacity((bw * bh) as usize);
237 for y in y0..y1 {
238 let row = (y * img.width) as usize;
239 for x in x0..x1 {
240 let i = row + x as usize;
241 buf.push(if img.pixels[i] == p.pixels[i] {
242 TRANSPARENT_INDEX
243 } else {
244 img.pixels[i]
245 });
246 }
247 }
248 gif::Frame {
249 left: x0 as u16,
250 top: y0 as u16,
251 width: bw as u16,
252 height: bh as u16,
253 delay: d,
254 dispose: gif::DisposalMethod::Keep,
255 transparent: Some(TRANSPARENT_INDEX),
256 buffer: buf.into(),
257 ..gif::Frame::default()
258 }
259 }
260 },
261 };
262 if let Some(f) = pending.take() {
263 enc.write_frame(&f)?;
264 written += 1;
265 }
266 pending = Some(frame);
267 prev = Some(img);
268 }
269 if let Some(f) = pending.take() {
270 enc.write_frame(&f)?;
271 written += 1;
272 }
273 drop(enc);
274 Ok((delays.len(), written))
275}
276
277pub fn encode_package_gif<W: Write>(
279 pkg: &crate::ScenePackage,
280 theme: Theme,
281 buddy: bool,
282 loop_ms: u64,
283 smoothness: Smoothness,
284 out: W,
285) -> Result<GifStats, GifError> {
286 if !valid_loop_ms(loop_ms) {
287 return Err(GifError::LoopLength(loop_ms));
288 }
289 if pkg.width > u32::from(u16::MAX) || pkg.height > u32::from(u16::MAX) {
290 return Err(GifError::TooLarge {
291 width: pkg.width,
292 height: pkg.height,
293 });
294 }
295 let palette = pkg
296 .palette(theme)
297 .ok_or(GifError::Build(BuildError::ThemeLocked(theme)))?
298 .clone();
299 let started = Instant::now();
300 let clock = Clock::Loop(loop_ms);
301 let (rendered, written) = encode_frames(
302 pkg.width,
303 pkg.height,
304 &palette,
305 loop_ms,
306 smoothness,
307 out,
308 |t| {
309 pkg.frame(theme, buddy, t, clock)
310 .map(|(img, _)| img)
311 .expect("theme checked above")
312 },
313 )?;
314 Ok(GifStats {
315 width: pkg.width,
316 height: pkg.height,
317 loop_ms,
318 frames_rendered: rendered,
319 frames_written: written,
320 elapsed_ms: started.elapsed().as_millis() as u64,
321 })
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[test]
329 fn delays_sum_exactly_to_the_loop() {
330 for loop_ms in [6000u64, 12000] {
331 for s in [
332 Smoothness::BatterySaver,
333 Smoothness::Balanced,
334 Smoothness::Smooth,
335 Smoothness::VerySmooth,
336 Smoothness::UltraSmooth,
337 ] {
338 let d = frame_delays(loop_ms, s.gif_delay_cs());
339 assert_eq!(d.iter().map(|&x| u64::from(x)).sum::<u64>(), loop_ms / 10);
340 let (min, max) = (*d.iter().min().unwrap(), *d.iter().max().unwrap());
341 assert!(max - min <= 1, "{s:?}: delays {min}..{max}");
342 assert!(u32::from(min) >= 2, "browsers clamp delays under 2 cs");
343 }
344 }
345 let d = frame_delays(6000, 16);
347 assert!(d.contains(&16) && d.contains(&15) || d.contains(&16) && d.contains(&17));
348 }
349
350 #[test]
351 fn rejects_loops_that_cannot_be_seamless() {
352 assert!(valid_loop_ms(6000) && valid_loop_ms(12000));
353 assert!(!valid_loop_ms(3000) && !valid_loop_ms(10000) && !valid_loop_ms(0));
354 }
355}