takumi 1.7.0

Render UI component trees to images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
use std::{borrow::Cow, io::Write};

use gif::{Encoder as GifEncoder, Frame as GifFrame, Repeat};
use image::{
  ExtendedColorType, ImageEncoder, ImageFormat, RgbaImage,
  codecs::{ico::IcoEncoder, jpeg::JpegEncoder},
};
use png::{ColorType, DeflateCompression, Filter};
use serde::Deserialize;
use typed_builder::TypedBuilder;

/// Encode a sequence of RGBA frames into an animated WebP and write to `destination`.
pub use crate::rendering::webp::encode_animated_webp;
use crate::rendering::webp::{has_any_alpha_pixel, strip_alpha_channel, write_webp};

use crate::{Result, error::Error};

/// Output format for rendered images.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ImageOutputFormat {
  /// WebP image format, provides good compression and supports animation.
  /// It is useful for images in web contents.
  WebP,

  /// PNG image format, lossless and widely supported, and its the fastest format to encode.
  Png,

  /// JPEG image format, lossy and does not support transparency.
  Jpeg,

  /// ICO image format for favicons and application icons.
  Ico,
}

impl ImageOutputFormat {
  /// Returns the MIME type for the image output format.
  pub fn content_type(&self) -> &'static str {
    match self {
      ImageOutputFormat::WebP => "image/webp",
      ImageOutputFormat::Png => "image/png",
      ImageOutputFormat::Jpeg => "image/jpeg",
      ImageOutputFormat::Ico => "image/x-icon",
    }
  }
}

impl From<ImageOutputFormat> for ImageFormat {
  fn from(format: ImageOutputFormat) -> Self {
    match format {
      ImageOutputFormat::WebP => Self::WebP,
      ImageOutputFormat::Png => Self::Png,
      ImageOutputFormat::Jpeg => Self::Jpeg,
      ImageOutputFormat::Ico => Self::Ico,
    }
  }
}

/// Represents a single frame of an animated image.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnimationFrame {
  /// The image data for the frame.
  pub image: RgbaImage,
  /// The duration of the frame in milliseconds.
  /// Maximum value is 0xffffff (24-bit), overflow will be clamped.
  pub duration_ms: u32,
}

impl AnimationFrame {
  /// Creates a new animation frame.
  pub fn new(image: RgbaImage, duration_ms: u32) -> Self {
    Self { image, duration_ms }
  }
}

/// Encoding options for animated WebP output.
#[derive(Debug, Clone, Copy, TypedBuilder)]
#[builder(field_defaults(default))]
#[non_exhaustive]
pub struct AnimatedWebpOptions {
  /// Whether frames should be alpha-blended with previous content.
  pub blend: bool,
  /// Whether frame disposal clears to background before the next frame.
  pub dispose: bool,
  /// Number of times to loop; `None` means infinite loop.
  pub loop_count: Option<u16>,
  /// Quality in range `0..=100`; `100` is treated as lossless by native backend.
  pub quality: u8,
  /// Encoding speed in range `0..=6`; `0` is fastest (lowest compression), `6` is
  /// slowest (best compression). `None` uses the default speed of `1`.
  ///
  /// Only effective on native targets (libwebp). Ignored on WASM.
  pub speed: Option<u8>,
}

impl Default for AnimatedWebpOptions {
  fn default() -> Self {
    Self {
      blend: true,
      dispose: false,
      loop_count: None,
      quality: 100,
      speed: None,
    }
  }
}

/// Encoding options for animated PNG output.
#[derive(Debug, Clone, Copy, Default, TypedBuilder)]
#[builder(field_defaults(default))]
#[non_exhaustive]
pub struct AnimatedPngOptions {
  /// Number of times to loop; `None` means infinite loop.
  pub loop_count: Option<u16>,
}

/// Encoding options for animated GIF output.
#[derive(Debug, Clone, Copy, Default, TypedBuilder)]
#[builder(field_defaults(default))]
#[non_exhaustive]
pub struct AnimatedGifOptions {
  /// Number of times to loop; `None` means infinite loop.
  pub loop_count: Option<u16>,
}

fn duration_ms_to_gif_delay(duration_ms: u32) -> u16 {
  if duration_ms == 0 {
    0
  } else {
    duration_ms.div_ceil(10).min(u16::MAX as u32) as u16
  }
}

fn configure_png_encoder<T: Write>(encoder: &mut png::Encoder<'_, T>) {
  encoder.set_deflate_compression(DeflateCompression::Level(6));
  encoder.set_filter(Filter::NoFilter);
}

/// Writes a single rendered image to `destination` using `format`.
pub fn write_image<'a, T: Write>(
  image: Cow<'a, RgbaImage>,
  destination: &mut T,
  format: ImageOutputFormat,
  quality: Option<u8>,
) -> Result<()> {
  match format {
    ImageOutputFormat::Jpeg => {
      let width = image.width();
      let height = image.height();
      let rgb = strip_alpha_channel(image);

      let encoder = JpegEncoder::new_with_quality(destination, quality.unwrap_or(75));
      encoder.write_image(&rgb, width, height, ExtendedColorType::Rgb8)?;
    }
    ImageOutputFormat::Png => {
      let mut encoder = png::Encoder::new(destination, image.width(), image.height());
      configure_png_encoder(&mut encoder);

      let has_alpha = has_any_alpha_pixel(&image);

      let image_data = if has_alpha {
        Cow::Borrowed(image.as_raw())
      } else {
        Cow::Owned(strip_alpha_channel(image))
      };

      encoder.set_color(if has_alpha {
        ColorType::Rgba
      } else {
        ColorType::Rgb
      });

      let mut writer = encoder.write_header()?;
      writer.write_image_data(&image_data)?;
      writer.finish()?;
    }
    ImageOutputFormat::WebP => {
      write_webp(image, destination, quality)?;
    }
    ImageOutputFormat::Ico => {
      let width = image.width();
      let height = image.height();
      let encoder = IcoEncoder::new(destination);
      encoder.write_image(image.as_raw(), width, height, ExtendedColorType::Rgba8)?;
    }
  }

  Ok(())
}

/// Encode a sequence of RGBA frames into an animated GIF and write to `destination`.
pub fn encode_animated_gif<W: Write>(
  frames: Cow<'_, [AnimationFrame]>,
  destination: &mut W,
  options: AnimatedGifOptions,
) -> Result<()> {
  if frames.is_empty() {
    return Err(Error::EmptyAnimationFrames { format: "GIF" });
  }

  let width = frames[0].image.width();
  let height = frames[0].image.height();

  if width > u16::MAX as u32 || height > u16::MAX as u32 {
    return Err(Error::GifFrameDimensionsTooLarge {
      width,
      height,
      max: u16::MAX,
    });
  }

  for frame in frames.iter() {
    if frame.image.width() != width || frame.image.height() != height {
      return Err(Error::MixedAnimationFrameDimensions { format: "GIF" });
    }
  }

  let width = width as u16;
  let height = height as u16;
  let mut encoder = GifEncoder::new(destination, width, height, &[])?;
  encoder.set_repeat(options.loop_count.map_or(Repeat::Infinite, Repeat::Finite))?;

  for frame in frames.into_owned().into_iter() {
    let mut pixels = frame.image.into_raw();
    let mut gif_frame = GifFrame::from_rgba_speed(width, height, &mut pixels, 28);
    gif_frame.delay = duration_ms_to_gif_delay(frame.duration_ms);
    encoder.write_frame(&gif_frame)?;
  }

  Ok(())
}

/// Encode a sequence of RGBA frames into an animated PNG and write to `destination`.
pub fn encode_animated_png<W: Write>(
  frames: &[AnimationFrame],
  destination: &mut W,
  options: AnimatedPngOptions,
) -> Result<()> {
  if frames.is_empty() {
    return Err(Error::EmptyAnimationFrames { format: "APNG" });
  }

  let width = frames[0].image.width();
  let height = frames[0].image.height();
  for frame in frames.iter() {
    if frame.image.width() != width || frame.image.height() != height {
      return Err(Error::MixedAnimationFrameDimensions { format: "APNG" });
    }
  }

  let mut encoder = png::Encoder::new(destination, width, height);
  configure_png_encoder(&mut encoder);
  encoder.set_color(ColorType::Rgba);
  encoder.set_animated(frames.len() as u32, options.loop_count.unwrap_or(0) as u32)?;

  // Since APNG doesn't support variable frame duration, we use the minimum duration of all frames.
  let min_duration_ms = frames
    .iter()
    .map(|frame| frame.duration_ms)
    .min()
    .unwrap_or(0);

  encoder.set_frame_delay(min_duration_ms.clamp(0, u16::MAX as u32) as u16, 1000)?;

  let mut writer = encoder.write_header()?;

  for frame in frames {
    writer.write_image_data(frame.image.as_raw())?;
  }

  writer.finish()?;

  Ok(())
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
  use std::{borrow::Cow, io::Cursor, mem::MaybeUninit, slice::from_raw_parts};

  use gif::{ColorOutput, DecodeOptions};
  use image::RgbaImage;
  use libwebp_sys::WEBP_CSP_MODE::MODE_RGBA;
  use libwebp_sys::*;

  use super::{
    AnimatedGifOptions, AnimatedPngOptions, AnimatedWebpOptions, AnimationFrame, ImageOutputFormat,
    encode_animated_gif, encode_animated_png, encode_animated_webp, write_image,
  };
  use crate::rendering::{DitheringAlgorithm, apply_dithering};

  #[test]
  fn encode_animated_gif_writes_valid_animation_and_delays() {
    let frame_a = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |x, y| {
        if x == 0 && y == 0 {
          image::Rgba([255, 0, 0, 255])
        } else {
          image::Rgba([0, 0, 0, 0])
        }
      }),
      45,
    );
    let frame_b = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |x, y| {
        if x == 1 && y == 1 {
          image::Rgba([0, 255, 0, 255])
        } else {
          image::Rgba([0, 0, 0, 0])
        }
      }),
      10,
    );

    let mut bytes = Vec::new();
    let encode_result = encode_animated_gif(
      Cow::Owned(vec![frame_a, frame_b]),
      &mut bytes,
      AnimatedGifOptions {
        loop_count: Some(7),
      },
    );
    assert!(encode_result.is_ok(), "failed to encode animated gif");

    let mut decoder_options = DecodeOptions::new();
    decoder_options.set_color_output(ColorOutput::RGBA);
    let decode_result = decoder_options.read_info(Cursor::new(&bytes));
    assert!(decode_result.is_ok(), "failed to decode animated gif");

    let mut decoder = match decode_result {
      Ok(decoder) => decoder,
      Err(_) => return,
    };
    let frame_one = decoder.read_next_frame();
    assert!(frame_one.is_ok(), "missing first decoded gif frame");
    let frame_one = match frame_one {
      Ok(frame_one) => frame_one,
      Err(_) => return,
    };
    assert!(frame_one.is_some(), "missing first decoded gif frame");
    let Some(frame_one) = frame_one else {
      return;
    };
    assert_eq!(frame_one.delay, 5);

    let frame_two = decoder.read_next_frame();
    assert!(frame_two.is_ok(), "missing second decoded gif frame");
    let frame_two = match frame_two {
      Ok(frame_two) => frame_two,
      Err(_) => return,
    };
    assert!(frame_two.is_some(), "missing second decoded gif frame");
    let Some(frame_two) = frame_two else {
      return;
    };
    assert_eq!(frame_two.delay, 1);

    let frame_three = decoder.read_next_frame();
    assert!(frame_three.is_ok(), "unexpected decoder error");
    assert!(
      frame_three.unwrap_or(None).is_none(),
      "only two frames should be encoded"
    );

    assert!(
      bytes
        .windows(b"NETSCAPE2.0".len())
        .any(|chunk| chunk == b"NETSCAPE2.0"),
      "encoded gif should contain application extension for loop count"
    );
    assert!(
      bytes
        .windows(5)
        .any(|chunk| chunk == [0x03, 0x01, 0x07, 0x00, 0x00]),
      "encoded gif should store loop count = 7"
    );
  }

  #[test]
  fn encode_animated_gif_rejects_mismatched_frame_dimensions() {
    let frame_a = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |_, _| image::Rgba([255, 0, 0, 255])),
      10,
    );
    let frame_b = AnimationFrame::new(
      RgbaImage::from_fn(3, 2, |_, _| image::Rgba([0, 255, 0, 255])),
      10,
    );

    let mut bytes = Vec::new();
    let encode_result = encode_animated_gif(
      Cow::Owned(vec![frame_a, frame_b]),
      &mut bytes,
      AnimatedGifOptions::default(),
    );
    assert!(encode_result.is_err(), "mismatched frames should error");
    assert!(
      bytes.is_empty(),
      "encoder should not write bytes before validating frame dimensions"
    );
  }

  #[test]
  fn encode_animated_gif_rejects_empty_frames() {
    let mut bytes = Vec::new();
    let result = encode_animated_gif(
      Cow::Owned(Vec::new()),
      &mut bytes,
      AnimatedGifOptions::default(),
    );
    let err = result.err();
    assert!(err.is_some(), "empty frame list should be rejected");
    let Some(err) = err else {
      return;
    };
    assert_eq!(
      err.to_string(),
      "GIF animation must contain at least one frame",
      "unexpected error message: {err}"
    );
  }

  #[test]
  fn encode_animated_png_rejects_empty_frames() {
    let mut bytes = Vec::new();
    let result = encode_animated_png(&[], &mut bytes, AnimatedPngOptions::default());
    let err = result.err();
    assert!(err.is_some(), "empty frame list should be rejected");
    let Some(err) = err else {
      return;
    };
    assert_eq!(
      err.to_string(),
      "APNG animation must contain at least one frame",
      "unexpected error message: {err}"
    );
  }

  #[test]
  fn encode_animated_png_rejects_mismatched_frame_dimensions() {
    let frames = vec![
      AnimationFrame::new(
        RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])),
        100,
      ),
      AnimationFrame::new(
        RgbaImage::from_pixel(3, 2, image::Rgba([0, 255, 0, 255])),
        100,
      ),
    ];

    let mut bytes = Vec::new();
    let result = encode_animated_png(&frames, &mut bytes, AnimatedPngOptions::default());
    let err = result.err();
    assert!(err.is_some(), "mismatched frame sizes should be rejected");
    let Some(err) = err else {
      return;
    };
    assert_eq!(
      err.to_string(),
      "all APNG animation frames must share the same dimensions",
      "unexpected error message: {err}"
    );
  }

  #[test]
  fn write_image_does_not_apply_dithering() {
    let mut image = RgbaImage::new(8, 8);

    for (index, pixel) in image.as_mut().chunks_exact_mut(4).enumerate() {
      let value = (index * 3) as u8;
      pixel.copy_from_slice(&[value, value, value, 255]);
    }

    let mut dithered_image = image.clone();
    apply_dithering(&mut dithered_image, DitheringAlgorithm::OrderedBayer);

    let mut encoded_none = Vec::new();
    let mut encoded_dithered = Vec::new();

    let encode_none = write_image(
      Cow::Owned(image.clone()),
      &mut encoded_none,
      ImageOutputFormat::Png,
      None,
    );
    assert!(encode_none.is_ok(), "failed to encode non-dithered image");

    let encode_dithered = write_image(
      Cow::Owned(dithered_image),
      &mut encoded_dithered,
      ImageOutputFormat::Png,
      None,
    );
    assert!(encode_dithered.is_ok(), "failed to encode image");

    assert_ne!(encoded_none, encoded_dithered);
  }

  #[test]
  fn write_image_ico_produces_ico_header() {
    let image = RgbaImage::from_pixel(16, 16, image::Rgba([255, 0, 0, 255]));
    let mut encoded = Vec::new();
    let result = write_image(
      Cow::Owned(image),
      &mut encoded,
      ImageOutputFormat::Ico,
      None,
    );
    assert!(result.is_ok(), "failed to encode ico image");
    assert!(
      encoded.starts_with(&[0, 0, 1, 0]),
      "encoded bytes should begin with ICO header"
    );
  }

  #[test]
  fn write_image_ico_rejects_dimensions_over_256() {
    let image = RgbaImage::from_pixel(257, 16, image::Rgba([255, 0, 0, 255]));
    let mut encoded = Vec::new();
    let result = write_image(
      Cow::Owned(image),
      &mut encoded,
      ImageOutputFormat::Ico,
      None,
    );

    let err = result.err();
    assert!(err.is_some(), "expected oversized ico image to fail");
    let Some(err) = err else {
      return;
    };
    assert!(
      err
        .to_string()
        .contains("the image width must be `1..=256`, instead width 257 was provided")
    );
  }

  #[test]
  fn encode_animated_webp_respects_blend_dispose_and_loop_count() {
    let frame_a = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |x, y| {
        if x == 0 && y == 0 {
          image::Rgba([255, 0, 0, 255])
        } else {
          image::Rgba([0, 0, 0, 0])
        }
      }),
      120,
    );
    let frame_b = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |x, y| {
        if x == 1 && y == 1 {
          image::Rgba([0, 255, 0, 255])
        } else {
          image::Rgba([0, 0, 0, 0])
        }
      }),
      240,
    );

    let mut bytes = Vec::new();
    let encode_result = encode_animated_webp(
      Cow::Owned(vec![frame_a, frame_b]),
      &mut bytes,
      AnimatedWebpOptions {
        blend: true,
        dispose: true,
        loop_count: Some(7),
        quality: 100,
        speed: None,
      },
    );
    assert!(encode_result.is_ok(), "failed to encode animated webp");

    let webp_data = WebPData {
      bytes: bytes.as_ptr(),
      size: bytes.len(),
    };
    let mut state = WebPDemuxState::WEBP_DEMUX_PARSING_HEADER;
    let demux =
      unsafe { WebPDemuxInternal(&webp_data, 1, &mut state, WEBP_DEMUX_ABI_VERSION as i32) };
    assert!(!demux.is_null(), "demux should parse encoded animation");

    let loop_count = unsafe { WebPDemuxGetI(demux, WebPFormatFeature::WEBP_FF_LOOP_COUNT) };
    assert_eq!(loop_count, 7);

    let mut iter = MaybeUninit::<WebPIterator>::zeroed();
    let has_frame = unsafe { WebPDemuxGetFrame(demux, 1, iter.as_mut_ptr()) };
    assert_eq!(has_frame, 1, "first frame should be available");

    let mut iter = unsafe { iter.assume_init() };
    assert_eq!(
      iter.dispose_method,
      WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND
    );
    assert_eq!(iter.blend_method, WebPMuxAnimBlend::WEBP_MUX_BLEND);

    unsafe {
      WebPDemuxReleaseIterator(&mut iter);
      WebPDemuxDelete(demux);
    }
  }

  #[test]
  fn encode_animated_webp_lossy_produces_valid_animation() {
    // With allow_mixed=1 libwebp may choose VP8L even at quality<100 when it
    // produces a smaller file (trivial 2×2 solid-colour images always compress
    // better losslessly). We verify the output is a parseable animated WebP.
    let frame = AnimationFrame::new(
      RgbaImage::from_fn(2, 2, |_, _| image::Rgba([20, 80, 220, 255])),
      100,
    );

    let mut bytes = Vec::new();
    let encode_result = encode_animated_webp(
      Cow::Owned(vec![frame]),
      &mut bytes,
      AnimatedWebpOptions {
        quality: 70,
        ..Default::default()
      },
    );
    assert!(
      encode_result.is_ok(),
      "failed to encode lossy animated webp"
    );

    assert!(
      bytes
        .windows(4)
        .any(|chunk| chunk == b"VP8 " || chunk == b"VP8L"),
      "animation should contain a VP8 or VP8L bitstream chunk"
    );

    // Verify it parses as a valid animated WebP
    let webp_data = WebPData {
      bytes: bytes.as_ptr(),
      size: bytes.len(),
    };
    let mut state = WebPDemuxState::WEBP_DEMUX_PARSING_HEADER;
    let demux =
      unsafe { WebPDemuxInternal(&webp_data, 1, &mut state, WEBP_DEMUX_ABI_VERSION as i32) };
    assert!(!demux.is_null(), "lossy animation should be parseable");
    unsafe { WebPDemuxDelete(demux) };
  }

  #[test]
  fn encode_animated_webp_merges_consecutive_identical_frames() {
    let image_a = RgbaImage::from_fn(2, 2, |_, _| image::Rgba([120, 30, 10, 255]));
    let image_b = RgbaImage::from_fn(2, 2, |_, _| image::Rgba([5, 200, 20, 255]));
    let frame_a = AnimationFrame::new(image_a.clone(), 50);
    let frame_b = AnimationFrame::new(image_a, 70);
    let frame_c = AnimationFrame::new(image_b, 30);

    let mut bytes = Vec::new();
    let encode_result = encode_animated_webp(
      Cow::Owned(vec![frame_a, frame_b, frame_c]),
      &mut bytes,
      AnimatedWebpOptions {
        quality: 100,
        ..Default::default()
      },
    );
    assert!(
      encode_result.is_ok(),
      "failed to encode animated webp with repeated frames"
    );

    let webp_data = WebPData {
      bytes: bytes.as_ptr(),
      size: bytes.len(),
    };
    let mut state = WebPDemuxState::WEBP_DEMUX_PARSING_HEADER;
    let demux =
      unsafe { WebPDemuxInternal(&webp_data, 1, &mut state, WEBP_DEMUX_ABI_VERSION as i32) };
    assert!(!demux.is_null(), "demux should parse encoded animation");

    let frame_count = unsafe { WebPDemuxGetI(demux, WebPFormatFeature::WEBP_FF_FRAME_COUNT) };
    assert_eq!(
      frame_count, 2,
      "identical consecutive frames should be merged"
    );

    let mut iter = MaybeUninit::<WebPIterator>::zeroed();
    let has_frame = unsafe { WebPDemuxGetFrame(demux, 1, iter.as_mut_ptr()) };
    assert_eq!(has_frame, 1, "first frame should be available");
    let mut iter = unsafe { iter.assume_init() };
    assert_eq!(
      iter.duration, 120,
      "merged frame should keep total duration"
    );

    unsafe {
      WebPDemuxReleaseIterator(&mut iter);
      WebPDemuxDelete(demux);
    }
  }

  #[test]
  fn encode_animated_webp_rejects_zero_sized_frames() {
    let invalid = AnimationFrame::new(RgbaImage::new(0, 1), 10);

    let mut bytes = Vec::new();
    let result = encode_animated_webp(
      Cow::Owned(vec![invalid]),
      &mut bytes,
      AnimatedWebpOptions::default(),
    );
    let err = result.err();
    assert!(err.is_some(), "zero-sized frame should be rejected");
    let Some(err) = err else {
      return;
    };
    assert!(
      err
        .to_string()
        .contains("WebP animation frame dimensions must be in 1..=16777216"),
      "unexpected error message: {err}"
    );
  }

  #[test]
  fn encode_animated_webp_preserves_parallel_frame_order() {
    let frames = vec![
      AnimationFrame::new(
        RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])),
        10,
      ),
      AnimationFrame::new(
        RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])),
        20,
      ),
      AnimationFrame::new(
        RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 255, 255])),
        30,
      ),
      AnimationFrame::new(
        RgbaImage::from_pixel(2, 2, image::Rgba([255, 255, 0, 255])),
        40,
      ),
    ];

    let mut bytes = Vec::new();
    let encode_result = encode_animated_webp(
      Cow::Owned(frames),
      &mut bytes,
      AnimatedWebpOptions {
        quality: 100,
        ..Default::default()
      },
    );
    assert!(
      encode_result.is_ok(),
      "failed to encode animated webp in parallel"
    );

    let webp_data = WebPData {
      bytes: bytes.as_ptr(),
      size: bytes.len(),
    };
    let mut state = WebPDemuxState::WEBP_DEMUX_PARSING_HEADER;
    let demux =
      unsafe { WebPDemuxInternal(&webp_data, 1, &mut state, WEBP_DEMUX_ABI_VERSION as i32) };
    assert!(!demux.is_null(), "demux should parse encoded animation");

    let mut decoder_config = unsafe { MaybeUninit::<WebPDecoderConfig>::zeroed().assume_init() };
    let init_ok = unsafe { WebPInitDecoderConfig(&raw mut decoder_config) };
    assert!(init_ok, "decoder config should initialize");
    decoder_config.output.colorspace = MODE_RGBA;

    let expected_dominant_channels = [
      [true, false, false],
      [false, true, false],
      [false, false, true],
      [true, true, false],
    ];
    let expected_durations = [10, 20, 30, 40];

    let mut iter = MaybeUninit::<WebPIterator>::zeroed();
    let has_frame = unsafe { WebPDemuxGetFrame(demux, 1, iter.as_mut_ptr()) };
    assert_eq!(has_frame, 1, "first frame should be available");
    let mut iter = unsafe { iter.assume_init() };

    for (expected_dominant_channels, expected_duration) in
      expected_dominant_channels.iter().zip(expected_durations)
    {
      let decode_status = unsafe {
        WebPDecode(
          iter.fragment.bytes,
          iter.fragment.size,
          &raw mut decoder_config,
        )
      };
      assert_eq!(
        decode_status,
        VP8StatusCode::VP8_STATUS_OK,
        "frame payload should decode"
      );

      let rgba = unsafe {
        from_raw_parts(
          decoder_config.output.u.RGBA.rgba,
          decoder_config.output.u.RGBA.size,
        )
      };
      let channel_flags = [rgba[0] >= 250, rgba[1] >= 250, rgba[2] >= 250];
      assert_eq!(channel_flags, *expected_dominant_channels);
      assert!(rgba[3] >= 250, "decoded frame should remain opaque");
      assert_eq!(iter.duration, expected_duration);

      unsafe { WebPFreeDecBuffer(&raw mut decoder_config.output) };
      if expected_duration != expected_durations[expected_durations.len() - 1] {
        let has_next = unsafe { WebPDemuxNextFrame(&mut iter) };
        assert_eq!(has_next, 1, "next frame should be available");
      }
    }

    unsafe {
      WebPDemuxReleaseIterator(&mut iter);
      WebPDemuxDelete(demux);
    }
  }
}