zenavif 0.1.6

Pure Rust AVIF image codec powered by rav1d and zenravif
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
//! Tests for animated AVIF decoding
//!
//! Test vectors are at tests/vectors/libavif/colors-animated-*.avif

#[cfg(feature = "encode")]
use almost_enough::StopExt;
use almost_enough::Unstoppable;
use std::fs;
use zenavif::{AnimationDecoder, DecoderConfig, decode_animation, decode_animation_with};

/// Load a test vector, returning None if the file doesn't exist (CI without vectors).
fn load_vector(path: &str) -> Option<Vec<u8>> {
    match fs::read(path) {
        Ok(data) => Some(data),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            eprintln!("skipping: {path} not found (download with: just download-vectors)");
            None
        }
        Err(e) => panic!("Failed to read {path}: {e}"),
    }
}

fn animated_vector(name: &str) -> Option<Vec<u8>> {
    load_vector(&format!("tests/vectors/libavif/{name}"))
}

/// Return early from a test if the vector is None (missing in CI).
macro_rules! require_vector {
    ($expr:expr) => {
        match $expr {
            Some(data) => data,
            None => return,
        }
    };
}

#[test]
fn decode_8bpc_no_alpha() {
    let data = require_vector!(animated_vector("colors-animated-8bpc.avif"));
    let anim = decode_animation(&data).unwrap();

    assert!(anim.frames.len() > 1, "expected multiple frames");
    assert!(!anim.info.has_alpha, "8bpc no-alpha should not have alpha");
    assert_eq!(anim.info.loop_count, 1, "play-once = loop_count 1");

    // All frames should have consistent dimensions
    let first = &anim.frames[0];
    let w = first.pixels.width();
    let h = first.pixels.height();
    assert!(w > 0 && h > 0, "frame dimensions should be positive");
    for (i, frame) in anim.frames.iter().enumerate() {
        assert_eq!(frame.pixels.width(), w, "frame {i} width mismatch");
        assert_eq!(frame.pixels.height(), h, "frame {i} height mismatch");
        assert!(
            frame.duration_ms > 0,
            "frame {i} should have nonzero duration"
        );
    }

    eprintln!(
        "8bpc no-alpha: {} frames, {}x{}, loop={}",
        anim.frames.len(),
        w,
        h,
        anim.info.loop_count
    );
}

#[test]
fn decode_8bpc_with_alpha() {
    let data = require_vector!(animated_vector("colors-animated-8bpc-alpha-exif-xmp.avif"));
    let anim = decode_animation(&data).unwrap();

    assert!(anim.frames.len() > 1, "expected multiple frames");
    assert!(anim.info.has_alpha, "should have alpha track");
    assert_eq!(anim.info.loop_count, 0, "infinite loop = loop_count 0");

    // All frames should be RGBA since we have alpha
    for (i, frame) in anim.frames.iter().enumerate() {
        assert!(
            frame.pixels.has_alpha(),
            "frame {i} should have alpha channel"
        );
    }

    eprintln!(
        "8bpc alpha: {} frames, {}x{}, loop={}",
        anim.frames.len(),
        anim.frames[0].pixels.width(),
        anim.frames[0].pixels.height(),
        anim.info.loop_count
    );
}

#[test]
fn decode_12bpc_keyframes() {
    let data = require_vector!(animated_vector(
        "colors-animated-12bpc-keyframes-0-2-3.avif"
    ));
    let anim = decode_animation(&data).unwrap();

    assert!(anim.frames.len() > 1, "expected multiple frames");

    // 12bpc should produce 16-bit output
    for (i, frame) in anim.frames.iter().enumerate() {
        let is_16bit = frame.pixels.descriptor().channel_type().byte_size() == 2;
        assert!(is_16bit, "frame {i} should be 16-bit for 12bpc source");
    }

    eprintln!(
        "12bpc: {} frames, {}x{}, has_alpha={}",
        anim.frames.len(),
        anim.frames[0].pixels.width(),
        anim.frames[0].pixels.height(),
        anim.info.has_alpha,
    );
}

#[test]
fn decode_8bpc_audio_track_skipped() {
    // This file has color + audio tracks; audio should be skipped
    let data = require_vector!(animated_vector("colors-animated-8bpc-audio.avif"));
    let anim = decode_animation(&data).unwrap();

    assert!(anim.frames.len() > 1, "expected multiple frames");
    // Audio track should not cause errors or appear as alpha
    eprintln!(
        "8bpc audio: {} frames, has_alpha={}",
        anim.frames.len(),
        anim.info.has_alpha,
    );
}

#[test]
fn decode_8bpc_depth() {
    let data = require_vector!(animated_vector("colors-animated-8bpc-depth-exif-xmp.avif"));
    let anim = decode_animation(&data).unwrap();

    assert!(anim.frames.len() > 1, "expected multiple frames");
    eprintln!(
        "8bpc depth: {} frames, has_alpha={}",
        anim.frames.len(),
        anim.info.has_alpha,
    );
}

#[test]
fn still_image_returns_unsupported() {
    // A non-animated AVIF should return Error::Unsupported
    let data = require_vector!(load_vector(
        "tests/vectors/libavif/kodim03_yuv420_8bpc.avif"
    ));
    let result = decode_animation(&data);
    assert!(
        result.is_err(),
        "still image should fail for animation decode"
    );
}

#[test]
fn animation_with_config_and_cancellation() {
    let data = require_vector!(animated_vector("colors-animated-8bpc.avif"));
    let config = DecoderConfig::new().threads(1);
    let anim = decode_animation_with(&data, &config, &Unstoppable).unwrap();
    assert!(anim.frames.len() > 1);
}

#[test]
fn frame_durations_sum_positive() {
    let data = require_vector!(animated_vector("colors-animated-8bpc.avif"));
    let anim = decode_animation(&data).unwrap();

    let total_ms: u64 = anim.frames.iter().map(|f| f.duration_ms as u64).sum();
    assert!(total_ms > 0, "total animation duration should be positive");
    eprintln!(
        "total duration: {}ms across {} frames",
        total_ms,
        anim.frames.len()
    );
}

#[test]
fn decode_12bpc_produces_16bit_with_full_range() {
    let data = require_vector!(animated_vector(
        "colors-animated-12bpc-keyframes-0-2-3.avif"
    ));
    let anim = decode_animation(&data).unwrap();

    for (i, frame) in anim.frames.iter().enumerate() {
        use zenpixels::PixelDescriptor;
        let desc = frame.pixels.descriptor();
        if desc.layout_compatible(PixelDescriptor::RGBA16) {
            let img = frame.pixels.try_as_imgref::<rgb::Rgba<u16>>().unwrap();
            // Check that at least some pixels use values > 255 (proving 16-bit)
            let max_val = img
                .buf()
                .iter()
                .map(|p| p.r.max(p.g).max(p.b))
                .max()
                .unwrap_or(0);
            eprintln!(
                "frame {i}: {}x{} RGBA16, max channel value={max_val}",
                img.width(),
                img.height()
            );
            assert!(
                max_val > 255,
                "12bpc should produce values > 255, got max={max_val}"
            );
        } else if desc.layout_compatible(PixelDescriptor::RGB16) {
            let img = frame.pixels.try_as_imgref::<rgb::Rgb<u16>>().unwrap();
            let max_val = img
                .buf()
                .iter()
                .map(|p| p.r.max(p.g).max(p.b))
                .max()
                .unwrap_or(0);
            eprintln!(
                "frame {i}: {}x{} RGB16, max channel value={max_val}",
                img.width(),
                img.height()
            );
            assert!(
                max_val > 255,
                "12bpc should produce values > 255, got max={max_val}"
            );
        } else {
            panic!("frame {i}: expected 16-bit, got {:?}", desc);
        }
    }
}

#[cfg(feature = "encode")]
#[test]
fn animation_encode_decode_roundtrip_rgb8() {
    use imgref::ImgVec;
    use rgb::RGB8;
    use zenavif::{AnimationFrame, EncoderConfig, encode_animation_rgb8};

    // Create 3 frames of solid color: red, green, blue
    let colors = [
        RGB8 {
            r: 200,
            g: 30,
            b: 30,
        },
        RGB8 {
            r: 30,
            g: 200,
            b: 30,
        },
        RGB8 {
            r: 30,
            g: 30,
            b: 200,
        },
    ];
    let frames: Vec<AnimationFrame> = colors
        .iter()
        .map(|&c| AnimationFrame {
            pixels: ImgVec::new(vec![c; 64 * 64], 64, 64),
            duration_ms: 100,
        })
        .collect();

    let config = EncoderConfig::new().quality(80.0).speed(10);
    let encoded = encode_animation_rgb8(&frames, &config, Unstoppable.into_token()).unwrap();
    eprintln!(
        "encoded {} frames, {} bytes",
        encoded.frame_count,
        encoded.avif_file.len()
    );
    assert_eq!(encoded.frame_count, 3);

    // Decode it back
    let decoded = decode_animation(&encoded.avif_file).unwrap();
    assert_eq!(decoded.frames.len(), 3);
    assert_eq!(decoded.info.frame_count, 3);

    for (i, frame) in decoded.frames.iter().enumerate() {
        assert_eq!(frame.pixels.width(), 64, "frame {i} width");
        assert_eq!(frame.pixels.height(), 64, "frame {i} height");
        assert_eq!(frame.duration_ms, 100, "frame {i} duration");
        eprintln!(
            "decoded frame {i}: {}x{}, {}ms",
            frame.pixels.width(),
            frame.pixels.height(),
            frame.duration_ms
        );
    }
}

#[cfg(feature = "encode")]
#[test]
fn animation_encode_decode_roundtrip_rgba8() {
    use imgref::ImgVec;
    use rgb::RGBA8;
    use zenavif::{AnimationFrameRgba, EncoderConfig, encode_animation_rgba8};

    // 2 frames with semi-transparent pixels
    let frames = vec![
        AnimationFrameRgba {
            pixels: ImgVec::new(
                vec![
                    RGBA8 {
                        r: 255,
                        g: 0,
                        b: 0,
                        a: 128
                    };
                    32 * 32
                ],
                32,
                32,
            ),
            duration_ms: 200,
        },
        AnimationFrameRgba {
            pixels: ImgVec::new(
                vec![
                    RGBA8 {
                        r: 0,
                        g: 0,
                        b: 255,
                        a: 200
                    };
                    32 * 32
                ],
                32,
                32,
            ),
            duration_ms: 300,
        },
    ];

    let config = EncoderConfig::new().quality(80.0).speed(10);
    let encoded = encode_animation_rgba8(&frames, &config, Unstoppable.into_token()).unwrap();
    eprintln!(
        "encoded {} frames, {} bytes",
        encoded.frame_count,
        encoded.avif_file.len()
    );

    let decoded = decode_animation(&encoded.avif_file).unwrap();
    assert_eq!(decoded.frames.len(), 2);
    assert!(decoded.info.has_alpha, "roundtrip should preserve alpha");

    for (i, frame) in decoded.frames.iter().enumerate() {
        assert!(frame.pixels.has_alpha(), "frame {i} should have alpha");
        eprintln!(
            "decoded frame {i}: {}x{}, {}ms, has_alpha={}",
            frame.pixels.width(),
            frame.pixels.height(),
            frame.duration_ms,
            frame.pixels.has_alpha()
        );
    }
}

// ---- AnimationDecoder (frame-by-frame) tests ----

#[test]
fn frame_by_frame_matches_batch() {
    let data = require_vector!(animated_vector("colors-animated-8bpc.avif"));
    let config = DecoderConfig::new().threads(1);

    // Batch decode
    let batch = decode_animation_with(&data, &config, &Unstoppable).unwrap();

    // Frame-by-frame decode
    let mut decoder = AnimationDecoder::new(&data, &config).unwrap();
    assert_eq!(decoder.info().frame_count, batch.info.frame_count);
    assert_eq!(decoder.info().loop_count, batch.info.loop_count);
    assert_eq!(decoder.info().has_alpha, batch.info.has_alpha);
    assert_eq!(decoder.remaining_frames(), batch.frames.len());

    for (i, batch_frame) in batch.frames.iter().enumerate() {
        assert_eq!(decoder.frame_index(), i);
        let frame = decoder
            .next_frame(&Unstoppable)
            .unwrap()
            .unwrap_or_else(|| panic!("expected frame {i}"));

        assert_eq!(
            frame.pixels.width(),
            batch_frame.pixels.width(),
            "frame {i} width mismatch"
        );
        assert_eq!(
            frame.pixels.height(),
            batch_frame.pixels.height(),
            "frame {i} height mismatch"
        );
        assert_eq!(
            frame.duration_ms, batch_frame.duration_ms,
            "frame {i} duration mismatch"
        );
        assert_eq!(
            frame.pixels.has_alpha(),
            batch_frame.pixels.has_alpha(),
            "frame {i} alpha mismatch"
        );
    }

    // Should return None after all frames
    assert_eq!(decoder.remaining_frames(), 0);
    assert!(decoder.next_frame(&Unstoppable).unwrap().is_none());
}

#[test]
fn frame_by_frame_12bpc() {
    let data = require_vector!(animated_vector(
        "colors-animated-12bpc-keyframes-0-2-3.avif"
    ));
    let config = DecoderConfig::new().threads(1);

    let mut decoder = AnimationDecoder::new(&data, &config).unwrap();
    let total = decoder.info().frame_count;
    assert!(total > 1, "expected multiple frames");

    let mut decoded_count = 0;
    while let Some(frame) = decoder.next_frame(&Unstoppable).unwrap() {
        let is_16bit = frame.pixels.descriptor().channel_type().byte_size() == 2;
        assert!(
            is_16bit,
            "frame {} should be 16-bit for 12bpc source",
            decoded_count
        );
        decoded_count += 1;
    }

    assert_eq!(decoded_count, total);
    eprintln!("frame-by-frame 12bpc: decoded {decoded_count} frames");
}

#[test]
fn frame_by_frame_cancellation() {
    use enough::StopReason;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct StopAfter {
        count: AtomicUsize,
    }

    impl enough::Stop for StopAfter {
        fn check(&self) -> std::result::Result<(), StopReason> {
            let n = self.count.fetch_add(1, Ordering::Relaxed);
            // Allow enough calls for setup + first frame, stop on second
            if n > 10 {
                Err(StopReason::Cancelled)
            } else {
                Ok(())
            }
        }
    }

    let data = require_vector!(animated_vector("colors-animated-8bpc.avif"));
    let config = DecoderConfig::new().threads(1);
    let mut decoder = AnimationDecoder::new(&data, &config).unwrap();

    let stop = StopAfter {
        count: AtomicUsize::new(0),
    };

    // First frame should succeed
    let first = decoder.next_frame(&stop);
    if first.is_ok() {
        // Subsequent frames should eventually fail with cancellation
        let mut got_cancel = false;
        for _ in 0..decoder.remaining_frames() {
            match decoder.next_frame(&stop) {
                Err(_) => {
                    got_cancel = true;
                    break;
                }
                Ok(None) => break,
                Ok(Some(_)) => continue,
            }
        }
        assert!(
            got_cancel || decoder.remaining_frames() == 0,
            "should have been cancelled or completed"
        );
    }
    // If even the first frame was cancelled, that's also valid
    eprintln!(
        "cancellation test: stopped at frame {}",
        decoder.frame_index()
    );
}

#[test]
fn frame_by_frame_still_image_returns_unsupported() {
    let data = require_vector!(load_vector(
        "tests/vectors/libavif/kodim03_yuv420_8bpc.avif"
    ));
    let result = AnimationDecoder::new(&data, &DecoderConfig::default());
    assert!(
        result.is_err(),
        "AnimationDecoder should reject still images"
    );
}

#[cfg(feature = "encode")]
#[test]
fn animation_encode_decode_roundtrip_rgb16() {
    use imgref::ImgVec;
    use rgb::RGB16;
    use zenavif::{AnimationFrame16, EncoderConfig, encode_animation_rgb16};

    // Create 3 frames of solid color (full u16 range)
    let colors = [
        RGB16 {
            r: 51200,
            g: 6400,
            b: 6400,
        },
        RGB16 {
            r: 6400,
            g: 51200,
            b: 6400,
        },
        RGB16 {
            r: 6400,
            g: 6400,
            b: 51200,
        },
    ];
    let frames: Vec<AnimationFrame16> = colors
        .iter()
        .map(|&c| AnimationFrame16 {
            pixels: ImgVec::new(vec![c; 64 * 64], 64, 64),
            duration_ms: 100,
        })
        .collect();

    let config = EncoderConfig::new().quality(80.0).speed(10);
    let encoded = encode_animation_rgb16(&frames, &config, Unstoppable.into_token()).unwrap();
    eprintln!(
        "rgb16 encoded {} frames, {} bytes",
        encoded.frame_count,
        encoded.avif_file.len()
    );
    assert_eq!(encoded.frame_count, 3);

    // Decode with prefer_8bit(false) to get native 16-bit output
    let config = DecoderConfig::new().prefer_8bit(false);
    let decoded = decode_animation_with(&encoded.avif_file, &config, &Unstoppable).unwrap();
    assert_eq!(decoded.frames.len(), 3);
    assert_eq!(decoded.info.frame_count, 3);

    for (i, frame) in decoded.frames.iter().enumerate() {
        assert_eq!(frame.pixels.width(), 64, "frame {i} width");
        assert_eq!(frame.pixels.height(), 64, "frame {i} height");
        assert_eq!(frame.duration_ms, 100, "frame {i} duration");

        // 10-bit source with prefer_8bit(false) should decode to 16-bit output
        let is_16bit = frame.pixels.descriptor().channel_type().byte_size() == 2;
        assert!(
            is_16bit,
            "frame {i} should be 16-bit for 10-bit source, got {:?}",
            frame.pixels.descriptor()
        );
    }
}

#[cfg(feature = "encode")]
#[test]
fn animation_encode_decode_roundtrip_rgba16() {
    use imgref::ImgVec;
    use rgb::RGBA16;
    use zenavif::{AnimationFrameRgba16, EncoderConfig, encode_animation_rgba16};

    // 2 frames with semi-transparent pixels (full u16 range)
    let frames = vec![
        AnimationFrameRgba16 {
            pixels: ImgVec::new(
                vec![
                    RGBA16 {
                        r: 57600,
                        g: 6400,
                        b: 6400,
                        a: 32768
                    };
                    32 * 32
                ],
                32,
                32,
            ),
            duration_ms: 200,
        },
        AnimationFrameRgba16 {
            pixels: ImgVec::new(
                vec![
                    RGBA16 {
                        r: 6400,
                        g: 6400,
                        b: 57600,
                        a: 51200
                    };
                    32 * 32
                ],
                32,
                32,
            ),
            duration_ms: 300,
        },
    ];

    let config = EncoderConfig::new().quality(80.0).speed(10);
    let encoded = encode_animation_rgba16(&frames, &config, Unstoppable.into_token()).unwrap();
    eprintln!(
        "rgba16 encoded {} frames, {} bytes",
        encoded.frame_count,
        encoded.avif_file.len()
    );

    // Decode with prefer_8bit(false) to get native 16-bit output
    let dec_config = DecoderConfig::new().prefer_8bit(false);
    let decoded = decode_animation_with(&encoded.avif_file, &dec_config, &Unstoppable).unwrap();
    assert_eq!(decoded.frames.len(), 2);
    assert!(decoded.info.has_alpha, "roundtrip should preserve alpha");

    for (i, frame) in decoded.frames.iter().enumerate() {
        assert!(frame.pixels.has_alpha(), "frame {i} should have alpha");

        let is_rgba16 = frame
            .pixels
            .descriptor()
            .layout_compatible(zenpixels::PixelDescriptor::RGBA16);
        assert!(is_rgba16, "frame {i} should be RGBA16 for 10-bit source");
    }
}