img4avif 0.7.0

Serverless-optimized image conversion: JPEG/PNG/WebP/HEIC → AVIF with HDR10 input support (pure Rust, Lambda-ready)
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
//! AVIF encoding via the `ravif` / `rav1e` pure-Rust AV1 encoder.
//!
//! This module wraps [`ravif::Encoder`] and converts between internal
//! [`RawImage`] representation and the types expected by `ravif`.
//!
//! ## Bit-depth selection
//!
//! | Input | Output |
//! |-------|--------|
//! | 8-bit RGBA ([`Pixels::Rgba8`]) | `encode_rgba` → 10-bit AVIF (ravif auto-selects) |
//! | 16-bit RGBA ([`Pixels::Rgba16`]) | `encode_raw_planes_10_bit` → 10-bit AVIF |
//!
//! The 16-bit path converts each RGBA16 channel (0 – 65 535) to the 10-bit
//! range (0 – 1 023) by right-shifting six bits, then converts to YCbCr using
//! the BT.601 matrix.  This matches the colour model used by the 8-bit path
//! so there is no colour-space discontinuity when mixing input depths.
//! Rounding precision in the YCbCr step is scaled to the configured quality
//! (1 – 10): quality 9–10 uses a float path (near-exact), quality 7–8 uses
//! integer fixed-point (±1 LSB), and lower qualities allow up to ±8 LSB.
//!
//! If any check fails output validation, [`Error::Encode`] is returned with a descriptive
//! message instead of silently handing back corrupt bytes to the caller.

use crate::decoder::{Pixels, RawImage};
use crate::logging::{img_debug, img_error, img_info, img_warn};
use crate::Error;

/// Minimum byte length of a structurally valid AVIF file is 20 bytes.
const MIN_AVIF_BYTES: usize = 20;

/// Encode a [`RawImage`] as AVIF.
///
/// - For **8-bit** inputs (`Pixels::Rgba8`): calls `ravif::Encoder::encode_rgba`.
///   `rav1e` auto-selects 10-bit encoding internally for better quality.
/// - For **16-bit** inputs (`Pixels::Rgba16`): calls
///   `ravif::Encoder::encode_raw_planes_10_bit` so the full 10-bit precision
///   is preserved rather than being silently discarded.
///
/// `quality` must be in **1 – 10** (higher = better), it will be scaled to 1-100 for ravif syntax.
/// `speed` must be in **1 – 10** (higher = faster).
/// `alpha_quality` must be in **1 – 10**; pass the same value as `quality`
/// for uniform quality, or a higher value (e.g. 10) to keep the alpha channel
/// visually lossless.
///
/// # Output validation
///
/// The encoded bytes are validated against the AVIF / ISOBMFF container
/// format before being returned.  [`Error::Encode`] is returned if the
/// encoder produces empty, truncated, structurally invalid output, or output
/// with an unexpected major brand or invalid box size.
///
/// # Errors
///
/// Returns [`Error::Encode`] if `rav1e` fails or produces invalid output.
pub fn encode_avif(
    image: &RawImage,
    quality: u8,
    speed: u8,
    alpha_quality: u8,
) -> Result<Vec<u8>, Error> {
    // Check if the image has any transparency
    let has_transparency = image.has_transparency();

    img_debug!(
        "encode_avif: {}×{} px, quality={}, alpha_quality={}, speed={}, depth={}, transparency={}",
        image.width,
        image.height,
        quality,
        alpha_quality,
        speed,
        match &image.pixels {
            Pixels::Rgba8(_) => "8-bit",
            Pixels::Rgba16(_) => "16-bit",
        },
        has_transparency
    );

    // Scale quality from 1-10 range to 1-100 range for ravif
    let ravif_quality = (u32::from(quality.clamp(1, 10)) * 10).min(100) as u8;

    // Only use alpha_quality if the image has transparency; otherwise use quality
    let ravif_alpha_quality = if has_transparency {
        (u32::from(alpha_quality.clamp(1, 10)) * 10).min(100) as u8
    } else {
        img_debug!("encode_avif: no transparency detected, treating alpha_quality as no-op");
        ravif_quality
    };

    let avif = match &image.pixels {
        Pixels::Rgba8(bytes) => encode_8bit(
            image.width,
            image.height,
            bytes,
            ravif_quality,
            speed,
            ravif_alpha_quality,
        ),
        Pixels::Rgba16(samples) => encode_16bit(
            image.width,
            image.height,
            samples,
            ravif_quality,
            quality,
            speed,
            ravif_alpha_quality,
        ),
    }?;

    validate_avif_output(&avif, image.width, image.height)?;

    #[cfg(feature = "dev-logging")]
    img_info!(
        "encode_avif: produced {} bytes ({:.1}× compression ratio)",
        avif.len(),
        compression_ratio(image, avif.len()),
    );
    #[cfg(not(feature = "dev-logging"))]
    img_info!("encode_avif: produced {} bytes", avif.len());

    Ok(avif)
}

/// Validate that `bytes` looks like a structurally sound AVIF file.
/// These checks are lightweight (no full ISOBMFF parse) and catch the most
/// common failure modes: empty output, truncated output, and the encoder
/// accidentally emitting raw bitstream data without wrapping it in a container.
fn validate_avif_output(bytes: &[u8], width: u32, height: u32) -> Result<(), Error> {
    if bytes.is_empty() {
        img_error!(
            "encode_avif: encoder returned empty output for {}×{} image",
            width,
            height
        );
        return Err(Error::Encode(
            "AVIF encoder produced empty output — this is a bug; please report it".into(),
        ));
    }

    if bytes.len() < MIN_AVIF_BYTES {
        img_error!(
            "encode_avif: output too short ({} bytes, expected ≥ {}) for {}×{} image",
            bytes.len(),
            MIN_AVIF_BYTES,
            width,
            height
        );
        return Err(Error::Encode(format!(
            "AVIF encoder produced truncated output ({} bytes, minimum valid AVIF is {} bytes)",
            bytes.len(),
            MIN_AVIF_BYTES,
        )));
    }

    if bytes[4..8] != *b"ftyp" {
        // Log as hex so developers can identify what the encoder actually returned.
        img_error!(
            "encode_avif: output missing ISOBMFF 'ftyp' box — bytes[0..12] = {:02x?}",
            &bytes[..bytes.len().min(12)]
        );
        return Err(Error::Encode(format!(
            "AVIF encoder produced invalid container: expected ISOBMFF 'ftyp' box at offset 4, \
             got {:02x?}",
            &bytes[4..8],
        )));
    }

    // Verify the AVIF major brand (bytes 8–11).
    if bytes[8..12] != *b"avif" && bytes[8..12] != *b"avis" {
        img_error!(
            "encode_avif: unexpected major brand — bytes[8..12] = {:02x?}",
            &bytes[8..12]
        );
        return Err(Error::Encode(format!(
            "AVIF major brand invalid: expected 'avif' or 'avis', got {:02x?}",
            &bytes[8..12],
        )));
    }

    // Verify the ftyp box size field (bytes 0–3, big-endian u32).
    let box_size = u32::from_be_bytes(bytes[0..4].try_into().unwrap()) as usize;
    if box_size < MIN_AVIF_BYTES || box_size > bytes.len() {
        img_error!(
            "encode_avif: ftyp box size {} is invalid (output is {} bytes)",
            box_size,
            bytes.len()
        );
        return Err(Error::Encode(format!(
            "AVIF ftyp box size invalid: box_size={box_size}, output length={}",
            bytes.len()
        )));
    }

    img_debug!(
        "encode_avif: output validation passed — {} bytes with ftyp box",
        bytes.len()
    );

    // Warn if the file is suspiciously small relative to the pixel count.
    // A valid AVIF for a non-trivial image is almost always > 100 bytes; a
    // very low value could indicate that the encoder silently skipped the
    // image data.
    let pixel_count = u64::from(width) * u64::from(height);
    if pixel_count > 64 && bytes.len() < 100 {
        img_warn!(
            "encode_avif: output is suspiciously small ({} bytes) for a {}×{} image — \
             verify the AVIF is decodable",
            bytes.len(),
            width,
            height
        );
    }

    Ok(())
}

/// Approximate compression ratio: `input_bytes / output_bytes`.
#[cfg(feature = "dev-logging")]
fn compression_ratio(image: &RawImage, output_bytes: usize) -> f64 {
    let input_bytes: u64 = match &image.pixels {
        Pixels::Rgba8(b) => b.len() as u64,
        Pixels::Rgba16(s) => s.len() as u64 * 2,
    };
    if output_bytes == 0 {
        return 0.0;
    }
    // Use u64 → f64; safe for any realistic image size (well under 2^52 bytes).
    #[allow(clippy::cast_precision_loss)]
    {
        input_bytes as f64 / output_bytes as f64
    }
}

/// Encode 8-bit RGBA pixels using `ravif::Encoder::encode_rgba`.
fn encode_8bit(
    width: u32,
    height: u32,
    pixels: &[u8],
    quality: u8,
    speed: u8,
    alpha_quality: u8,
) -> Result<Vec<u8>, Error> {
    use ravif::{EncodedImage, Encoder, Img};
    use rgb::FromSlice;

    img_debug!(
        "encode_8bit: {}×{} RGBA8 → rav1e encode_rgba",
        width,
        height
    );

    let rgba = pixels.as_rgba();
    let img = Img::new(rgba, width as usize, height as usize);

    Encoder::new()
        .with_quality(f32::from(quality.clamp(1, 100)))
        .with_alpha_quality(f32::from(alpha_quality.clamp(1, 100)))
        .with_speed(speed.clamp(1, 10))
        .encode_rgba(img)
        .map(|EncodedImage { avif_file, .. }| avif_file)
        .map_err(|e| {
            img_error!("encode_8bit: rav1e failed: {}", e);
            Error::Encode(e.to_string())
        })
}

/// Encode 16-bit RGBA pixels as 10-bit AVIF using `ravif::Encoder::encode_raw_planes_10_bit`.
///
/// Each 16-bit channel (0 – 65 535) is scaled to 10-bit (0 – 1 023) by
/// discarding the bottom 6 bits, then converted to YCbCr with the BT.601
/// luma matrix to match `ravif`'s standard encoding path.
fn encode_16bit(
    width: u32,
    height: u32,
    pixels: &[u16],
    quality: u8,
    quality_1_10: u8,
    speed: u8,
    alpha_quality: u8,
) -> Result<Vec<u8>, Error> {
    use ravif::{EncodedImage, Encoder, MatrixCoefficients, PixelRange};

    let width_usize = width as usize;
    let height_usize = height as usize;

    img_debug!(
        "encode_16bit: {}×{} RGBA16 → rav1e encode_raw_planes_10_bit (BT.601 YCbCr)",
        width,
        height
    );

    // Each pixel is [R, G, B, A] as u16 (0-65535).
    // Convert to 10-bit YCbCr planes and a separate alpha plane.
    let mut ycbcr_planes: Vec<[u16; 3]> = Vec::with_capacity(width_usize * height_usize);
    let mut alpha_plane: Vec<u16> = Vec::with_capacity(width_usize * height_usize);

    for chunk in pixels.chunks_exact(4) {
        let (r, g, b, a) = (chunk[0], chunk[1], chunk[2], chunk[3]);
        ycbcr_planes.push(rgba16_to_10bit_ycbcr_bt601(r, g, b, quality_1_10));
        // Scale alpha from 16-bit to 10-bit.
        alpha_plane.push(a >> 6);
    }

    Encoder::new()
        .with_quality(f32::from(quality.clamp(1, 100)))
        .with_alpha_quality(f32::from(alpha_quality.clamp(1, 100)))
        .with_speed(speed.clamp(1, 10))
        .encode_raw_planes_10_bit(
            width_usize,
            height_usize,
            ycbcr_planes,
            Some(alpha_plane),
            PixelRange::Full,
            MatrixCoefficients::BT601,
        )
        .map(|EncodedImage { avif_file, .. }| avif_file)
        .map_err(|e| {
            img_error!("encode_16bit: rav1e failed: {}", e);
            Error::Encode(e.to_string())
        })
}

/// Convert a 16-bit RGB triplet (0 – 65 535) to 10-bit YCbCr using the
/// BT.601 luma coefficients (Kr = 0.2990, Kg = 0.5870, Kb = 0.1140).
///
/// This mirrors the formula used inside `ravif`'s `rgb_to_10_bit_ycbcr`
/// function, extended to 16-bit input so the full precision of 16-bit PNG
/// files is preserved in the 10-bit AVIF stream.
///
/// ## Quality-dependent rounding
///
/// The `quality_1_10` parameter (1 – 10) controls how much rounding error is
/// tolerated in the colour conversion step.  Higher quality = smaller error.
///
/// | Quality | Path | Max rounding error |
/// |---------|------|--------------------|
/// | 9 – 10  | f32 (BT.601 exact) | < 0.5 ULP (effectively zero) |
/// | 7 – 8   | integer fixed-point | ±1 LSB |
/// | 5 – 6   | integer + 1 extra rounding bit | ±2 LSB |
/// | 3 – 4   | integer + 2 extra rounding bits | ±4 LSB |
/// | 1 – 2   | integer + 3 extra rounding bits | ±8 LSB |
///
/// At quality 9–10 the small extra cost of f32 is invisible next to the AV1
/// encoder's own work.  At lower qualities the encoder's quantisation step
/// already dominates any colour-conversion error, so coarser arithmetic is
/// acceptable and slightly faster in the conversion loop.
///
/// ## Implementation (integer path)
///
/// Uses integer fixed-point arithmetic to avoid f32↔integer conversions
/// in the per-pixel hot loop:
///
/// * Y  — 20-bit fixed-point scale (`2^20`).
/// * Cb / Cr — 16-bit fixed-point scale (`2^16`).
///
/// The coefficients are derived from the floating-point BT.601 formula and
/// rounded to preserve grey neutrality (Cb = Cr = 512 for any grey input).
///
/// ## Overflow safety
///
/// * `y_fp` accumulates into `u32` — max value is `16368 × 65535 ≈ 1.07 × 10⁹`,
///   well within the `u32` range of `4.29 × 10⁹`.
/// * `chroma_b` / `chroma_r` accumulate into `i32` — extremes are approximately
///   `±33.5 M + 33.6 M ≈ ±67 M`, well within the `i32` range of `±2.1 × 10⁹`.
#[inline]
fn rgba16_to_10bit_ycbcr_bt601(r: u16, g: u16, b: u16, quality_1_10: u8) -> [u16; 3] {
    // Maximum value representable in 10-bit (2¹⁰ − 1 = 1023).
    const MAX_10BIT: u32 = 1023;
    const MAX_10BIT_I32: i32 = 1023; // same value; avoids a u32→i32 cast in clamp

    // ── Y (luma) ─────────────────────────────────────────────────────────
    // Scale: 2^20.  Coefficients = round(Kr/Kg/Kb × (1023/65535) × 2^20).
    // 4894 + 9608 + 1866 = 16368 → for R=G=B=65535:
    //   Y = round((16368 × 65535 + 2^19) / 2^20) = round(1023.5) = 1023. ✓
    const KR_Y: u32 = 4894;
    const KG_Y: u32 = 9608;
    const KB_Y: u32 = 1866;
    const HALF_Y: u32 = 1 << 19; // 0.5 in fixed-point for rounding

    // ── Cb / Cr (chroma) ─────────────────────────────────────────────────
    // Scale: 2^16.  Coefficients = round(channel_weight × (1023/65535) × scale_c × 2^16).
    // scale_cb = 0.5/(1−Kb) ≈ 0.5643;  scale_cr = 0.5/(1−Kr) ≈ 0.7133.
    // Grey-balance constraint: Cb_R + Cb_G + Cb_B = 0  (−173 − 339 + 512 = 0).
    //                          Cr_R + Cr_G + Cr_B = 0  ( 511 − 428 −  83 = 0).
    const CB_R: i32 = -173;
    const CB_G: i32 = -339;
    const CB_B: i32 = 512;
    const CR_R: i32 = 511;
    const CR_G: i32 = -428;
    const CR_B: i32 = -83;
    // 512 (chroma midpoint) pre-shifted by 2^16 and combined with rounding (2^15).
    const CHROMA_OFFSET: i32 = 512 * (1 << 16) + (1 << 15);

    // Quality 9–10: use the f32 path for near-exact conversion (no rounding error).
    if quality_1_10 >= 9 {
        return rgba16_to_10bit_ycbcr_bt601_f32(r, g, b);
    }

    // Number of extra bits to round the 10-bit output by, based on quality tier.
    // This controls how much rounding error is tolerated beyond the inherent ±1 LSB
    // from the integer fixed-point coefficients.
    let extra_bits: u32 = match quality_1_10 {
        7..=8 => 0, // ±1 LSB (minimal — coefficient error only)
        5..=6 => 1, // ±2 LSB
        3..=4 => 2, // ±4 LSB
        _ => 3,     // quality 1–2: ±8 LSB
    };

    let (r32, g32, b32) = (u32::from(r), u32::from(g), u32::from(b));
    let (ri, gi, bi) = (i32::from(r), i32::from(g), i32::from(b));

    // Luma
    let y_fp = KR_Y * r32 + KG_Y * g32 + KB_Y * b32;
    // SAFETY: `(y_fp + HALF_Y) >> 20` is at most `(16368×65535 + 2^19) >> 20`
    // ≈ 1023 = MAX_10BIT, which always fits in u16.
    #[allow(clippy::cast_possible_truncation)]
    let y = ((y_fp + HALF_Y) >> 20).min(MAX_10BIT) as u16;

    // Chroma Cb
    let chroma_b = CB_R * ri + CB_G * gi + CB_B * bi + CHROMA_OFFSET;
    // SAFETY: `clamp(0, MAX_10BIT as i32)` guarantees the i32 is in [0, 1023],
    // which is non-negative and fits in u16.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    let cb = (chroma_b >> 16).clamp(0, MAX_10BIT_I32) as u16;

    // Chroma Cr
    let chroma_r = CR_R * ri + CR_G * gi + CR_B * bi + CHROMA_OFFSET;
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    let cr = (chroma_r >> 16).clamp(0, MAX_10BIT_I32) as u16;

    [
        apply_extra_rounding(y, extra_bits),
        apply_extra_rounding(cb, extra_bits),
        apply_extra_rounding(cr, extra_bits),
    ]
}

/// Round a 10-bit value to the nearest multiple of `1 << extra_bits`.
///
/// `extra_bits = 0` is a no-op.  The result is clamped to [0, 1023].
/// Used to apply quality-dependent rounding in [`rgba16_to_10bit_ycbcr_bt601`].
#[inline]
fn apply_extra_rounding(v: u16, extra_bits: u32) -> u16 {
    if extra_bits == 0 {
        return v;
    }
    let step = 1u32 << extra_bits;
    let half = step >> 1;
    // Round to nearest multiple of `step`, then clamp to 10-bit range.
    let rounded = (u32::from(v) + half) & !(step - 1);
    #[allow(clippy::cast_possible_truncation)]
    {
        rounded.min(1023) as u16
    }
}

/// f32 BT.601 reference path used for quality 9–10 (no significant rounding error).
///
/// Each channel is computed with f32 precision; the result is rounded to the
/// nearest integer and clamped to [0, 1023].  For grey inputs (`R = G = B`)
/// the chroma values are exactly 512 within f32 precision.
#[inline]
fn rgba16_to_10bit_ycbcr_bt601_f32(r: u16, g: u16, b: u16) -> [u16; 3] {
    const MAX10: f32 = 1023.0;
    const SCALE: f32 = 1023.0 / 65535.0;
    const SHIFT: f32 = 512.0;
    const KR: f32 = 0.2990;
    const KG: f32 = 0.5870;
    const KB: f32 = 0.1140;
    let (rf, gf, bf) = (f32::from(r), f32::from(g), f32::from(b));
    let y = SCALE * (KR * rf + KG * gf + KB * bf);
    let cb = (SCALE * bf - y) * (0.5 / (1.0 - KB)) + SHIFT;
    let cr = (SCALE * rf - y) * (0.5 / (1.0 - KR)) + SHIFT;
    #[allow(
        clippy::cast_sign_loss,
        clippy::cast_possible_truncation,
        clippy::cast_precision_loss
    )]
    let c10 = |v: f32| v.round().clamp(0.0, MAX10) as u32 as u16;
    [c10(y), c10(cb), c10(cr)]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decoder::Pixels;
    use std::sync::Arc;

    fn solid_rgba8(width: u32, height: u32, r: u8, g: u8, b: u8, a: u8) -> RawImage {
        let pixel = [r, g, b, a];
        let pixels = pixel.repeat(width as usize * height as usize);
        RawImage {
            width,
            height,
            pixels: Pixels::Rgba8(Arc::from(pixels)),
        }
    }

    #[test]
    fn encode_and_validate_small_image() {
        let img = solid_rgba8(8, 8, 255, 0, 0, 255);
        let avif = encode_avif(&img, 80, 6, 80).expect("encode failed");
        assert!(avif.len() >= MIN_AVIF_BYTES);
        assert_eq!(&avif[4..8], b"ftyp");
    }

    #[test]
    fn validate_rejects_empty() {
        let err = validate_avif_output(&[], 4, 4).unwrap_err();
        assert!(matches!(err, Error::Encode(_)));
    }

    #[test]
    fn validate_rejects_too_short() {
        let err = validate_avif_output(&[0u8; 10], 4, 4).unwrap_err();
        assert!(matches!(err, Error::Encode(_)));
    }

    #[test]
    fn validate_rejects_missing_ftyp() {
        // 20 bytes but not an ftyp box
        let mut fake = vec![0u8; 20];
        fake[4..8].copy_from_slice(b"moov");
        let err = validate_avif_output(&fake, 4, 4).unwrap_err();
        assert!(matches!(err, Error::Encode(ref msg) if msg.contains("ftyp")));
    }

    #[test]
    fn validate_accepts_valid_ftyp() {
        let mut valid = vec![0u8; 24];
        // Set box size (big-endian u32) to 24 — the full buffer length.
        valid[0..4].copy_from_slice(&24u32.to_be_bytes());
        valid[4..8].copy_from_slice(b"ftyp");
        valid[8..12].copy_from_slice(b"avif");
        assert!(validate_avif_output(&valid, 4, 4).is_ok());
    }

    #[test]
    fn validate_rejects_invalid_major_brand() {
        let mut fake = vec![0u8; 24];
        fake[0..4].copy_from_slice(&24u32.to_be_bytes());
        fake[4..8].copy_from_slice(b"ftyp");
        fake[8..12].copy_from_slice(b"mp41"); // Not an AVIF brand
        let err = validate_avif_output(&fake, 4, 4).unwrap_err();
        assert!(matches!(err, Error::Encode(ref msg) if msg.contains("major brand")));
    }

    #[test]
    fn validate_rejects_invalid_box_size() {
        let mut fake = vec![0u8; 24];
        fake[0..4].copy_from_slice(&5u32.to_be_bytes()); // Too small
        fake[4..8].copy_from_slice(b"ftyp");
        fake[8..12].copy_from_slice(b"avif");
        let err = validate_avif_output(&fake, 4, 4).unwrap_err();
        assert!(matches!(err, Error::Encode(ref msg) if msg.contains("box size")));
    }

    #[test]
    fn validate_accepts_avis_brand() {
        let mut valid = vec![0u8; 24];
        valid[0..4].copy_from_slice(&24u32.to_be_bytes());
        valid[4..8].copy_from_slice(b"ftyp");
        valid[8..12].copy_from_slice(b"avis");
        assert!(validate_avif_output(&valid, 4, 4).is_ok());
    }

    /// Verify that the quality-dependent rounding tiers work as documented.
    ///
    /// * Quality 9–10 (f32 path): output equals the f32 reference exactly.
    /// * Quality 7–8 (integer path): max error ≤ ±1 LSB vs. the f32 reference.
    /// * Quality 5–6: max error ≤ ±2 LSB.
    /// * Quality 3–4: max error ≤ ±4 LSB.
    /// * Quality 1–2: max error ≤ ±8 LSB.
    #[test]
    fn ycbcr_quality_dependent_rounding() {
        // f32 reference — the canonical BT.601 implementation.
        let float_ref = |r: u16, g: u16, b: u16| rgba16_to_10bit_ycbcr_bt601_f32(r, g, b);

        // Representative test vectors.
        let cases: &[(u16, u16, u16)] = &[
            (65535, 65535, 65535), // white  — Y=1023, Cb=Cr=512
            (0, 0, 0),             // black  — Y=0,    Cb=Cr=512
            (65535, 0, 0),         // red
            (0, 65535, 0),         // green
            (0, 0, 65535),         // blue
            (32768, 32768, 32768), // mid grey
            (32768, 0, 0),         // mid red
            (0, 0, 32768),         // mid blue
            (1000, 800, 600),      // arbitrary dark colour
        ];

        let tiers: &[(u8, u16)] = &[
            (10, 0), // f32 path — exact
            (9, 0),
            (8, 1), // integer fixed-point, ±1 LSB
            (7, 1),
            (6, 2), // integer + 1 extra bit, ±2 LSB
            (5, 2),
            (4, 4), // integer + 2 extra bits, ±4 LSB
            (3, 4),
            (2, 8), // integer + 3 extra bits, ±8 LSB
            (1, 8),
        ];

        for &(quality, max_allowed_diff) in tiers {
            for &(r, g, b) in cases {
                let out = rgba16_to_10bit_ycbcr_bt601(r, g, b, quality);
                let ref_out = float_ref(r, g, b);
                let max_diff = out
                    .iter()
                    .zip(ref_out.iter())
                    .map(|(&a, &b)| a.abs_diff(b))
                    .max()
                    .unwrap();
                assert!(
                    max_diff <= max_allowed_diff,
                    "quality={quality} rgb=({r},{g},{b}): \
                     out={out:?} ref={ref_out:?} diff={max_diff} allowed={max_allowed_diff}"
                );
            }
        }

        // Grey-neutrality: any grey input must produce exactly Cb = Cr = 512
        // at every quality tier (the chroma midpoint is a power-of-2-aligned value
        // and is preserved by every rounding step).
        for &(quality, _) in tiers {
            for level in [0u16, 1024, 16384, 32768, 65535] {
                let [_y, cb, cr] = rgba16_to_10bit_ycbcr_bt601(level, level, level, quality);
                assert_eq!(
                    cb, 512,
                    "quality={quality} grey level {level}: expected Cb=512, got {cb}"
                );
                assert_eq!(
                    cr, 512,
                    "quality={quality} grey level {level}: expected Cr=512, got {cr}"
                );
            }
        }
    }
}