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