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 const JOURNEY_GIF_MAX_MS: u64 = 36_000;
56
57fn 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
65pub 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#[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
121fn 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
150pub 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
213fn 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); 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 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
297pub fn encode_package_gif<W: Write>(
299 pkg: &crate::ScenePackage,
300 theme: Theme,
301 buddy: bool,
302 loop_ms: u64,
303 smoothness: Smoothness,
304 out: W,
305) -> Result<GifStats, GifError> {
306 if !valid_loop_ms(loop_ms) {
307 return Err(GifError::LoopLength(loop_ms));
308 }
309 if pkg.width > u32::from(u16::MAX) || pkg.height > u32::from(u16::MAX) {
310 return Err(GifError::TooLarge {
311 width: pkg.width,
312 height: pkg.height,
313 });
314 }
315 let palette = pkg
316 .palette(theme)
317 .ok_or(GifError::Build(BuildError::ThemeLocked(theme)))?
318 .clone();
319 let loop_ms = gif_loop(pkg.graph(theme).and_then(|g| g.journey.as_ref()), loop_ms);
320 let started = Instant::now();
321 let clock = Clock::Loop(loop_ms);
322 let (rendered, written) = encode_frames(
323 pkg.width,
324 pkg.height,
325 &palette,
326 loop_ms,
327 smoothness,
328 out,
329 |t| {
330 pkg.frame(theme, buddy, t, clock)
331 .map(|(img, _)| img)
332 .expect("theme checked above")
333 },
334 )?;
335 Ok(GifStats {
336 width: pkg.width,
337 height: pkg.height,
338 loop_ms,
339 frames_rendered: rendered,
340 frames_written: written,
341 elapsed_ms: started.elapsed().as_millis() as u64,
342 })
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348
349 #[test]
350 fn delays_sum_exactly_to_the_loop() {
351 for loop_ms in [6000u64, 12000] {
352 for s in [
353 Smoothness::BatterySaver,
354 Smoothness::Balanced,
355 Smoothness::Smooth,
356 Smoothness::VerySmooth,
357 Smoothness::UltraSmooth,
358 ] {
359 let d = frame_delays(loop_ms, s.gif_delay_cs());
360 assert_eq!(d.iter().map(|&x| u64::from(x)).sum::<u64>(), loop_ms / 10);
361 let (min, max) = (*d.iter().min().unwrap(), *d.iter().max().unwrap());
362 assert!(max - min <= 1, "{s:?}: delays {min}..{max}");
363 assert!(u32::from(min) >= 2, "browsers clamp delays under 2 cs");
364 }
365 }
366 let d = frame_delays(6000, 16);
368 assert!(d.contains(&16) && d.contains(&15) || d.contains(&16) && d.contains(&17));
369 }
370
371 #[test]
372 fn rejects_loops_that_cannot_be_seamless() {
373 assert!(valid_loop_ms(6000) && valid_loop_ms(12000));
374 assert!(!valid_loop_ms(3000) && !valid_loop_ms(10000) && !valid_loop_ms(0));
375 }
376}