oxideav-webp 0.1.5

Pure-Rust WebP image codec for oxideav — RIFF VP8 lossy + VP8L lossless + VP8X extended + ALPH + animation decode, plus VP8 lossy and VP8L lossless single-frame encode
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
//! WebP container demuxer.
//!
//! WebP is a RIFF file whose top-level form-type is `WEBP`. Inside the
//! form we find one of three layouts:
//!
//! ```text
//! RIFF <size> WEBP VP8  <size> <VP8 keyframe bytes>       — simple lossy
//! RIFF <size> WEBP VP8L <size> <VP8L bytes>               — simple lossless
//! RIFF <size> WEBP VP8X <size> <flags+size hdr>
//!                 [ICCP|ANIM|ALPH|VP8 |VP8L|ANMF|EXIF|XMP ]* — extended
//! ```
//!
//! Chunks are even-padded the same way as other RIFF formats: if the payload
//! length is odd, one zero byte follows. All multi-byte integers are
//! little-endian.
//!
//! The demuxer emits each still frame (or each animation frame from an
//! `ANMF` chunk) as a single `Packet` on stream 0, with `codec_id = "webp"`
//! (a synthetic codec id local to this crate — the decoder handles all
//! three flavours transparently).

#[cfg(feature = "registry")]
use std::io::{Read, SeekFrom};

#[cfg(feature = "registry")]
use oxideav_core::{
    CodecId, CodecParameters, CodecResolver, MediaType, Packet, PixelFormat, StreamInfo, TimeBase,
};
#[cfg(feature = "registry")]
use oxideav_core::{ContainerRegistry, Demuxer, ProbeData, ReadSeek};

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

/// Codec id we attach to every packet emitted by this demuxer. The decoder
/// registered under the same id dispatches to the VP8, VP8L, or extended
/// path based on the chunk layout.
pub const WEBP_CODEC_ID: &str = "webp";

#[cfg(feature = "registry")]
pub fn register(reg: &mut ContainerRegistry) {
    reg.register_demuxer("webp", open);
    reg.register_extension("webp", "webp");
    reg.register_probe("webp", probe);
}

#[cfg(feature = "registry")]
fn probe(p: &ProbeData) -> u8 {
    if p.buf.len() < 12 {
        return 0;
    }
    if &p.buf[0..4] != b"RIFF" {
        return 0;
    }
    if &p.buf[8..12] != b"WEBP" {
        return 0;
    }
    // `VeryHigh` — the RIFF magic + WEBP form-type is unambiguous.
    100
}

/// Public wrapper over `open` so the decoder-side convenience API can
/// instantiate a demuxer without duplicating the boxing dance.
#[cfg(feature = "registry")]
pub fn open_boxed(input: Box<dyn ReadSeek>) -> oxideav_core::Result<Box<dyn Demuxer>> {
    open(input, &oxideav_core::NullCodecResolver)
}

#[cfg(feature = "registry")]
fn open(
    mut input: Box<dyn ReadSeek>,
    _codecs: &dyn CodecResolver,
) -> oxideav_core::Result<Box<dyn Demuxer>> {
    // Read the whole file into memory. WebP stills are inherently small
    // (max 16384x16384 lossless / 16383x16383 VP8) and a full-buffer pass
    // simplifies chunk iteration + random access over the `ANMF` loop.
    let mut buf = Vec::new();
    input.seek(SeekFrom::Start(0))?;
    input.read_to_end(&mut buf)?;
    drop(input);

    if buf.len() < 12 || &buf[0..4] != b"RIFF" || &buf[8..12] != b"WEBP" {
        return Err(oxideav_core::Error::invalid("WebP: bad RIFF/WEBP magic"));
    }
    let riff_size = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
    // `riff_size` excludes the "RIFF" FourCC + the 4-byte size field, so
    // the total file is 8 + riff_size bytes. Clamp to the actual buffer to
    // survive files whose size field lies (we'd rather keep decoding).
    let end = (8 + riff_size).min(buf.len());
    // Own the body bytes so the lazy `(offset, length)` ranges in
    // `parsed.frames` stay valid for the lifetime of the demuxer. This
    // is the same allocation strategy `WebpAnimDecoder` uses.
    let body: Vec<u8> = buf[12..end].to_vec();

    let parsed = parse_webp_body_lazy(&body)?;
    // Width/height default to the dimensions declared by the first image
    // chunk (VP8/VP8L) or the VP8X canvas, whichever we saw first.
    let (w, h) = parsed.canvas;

    let mut params = CodecParameters::video(CodecId::new(WEBP_CODEC_ID));
    params.media_type = MediaType::Video;
    params.width = Some(w);
    params.height = Some(h);
    params.pixel_format = Some(PixelFormat::Rgba);

    // Time base: milliseconds. Animation chunk durations are already in ms.
    let time_base = TimeBase::new(1, 1000);
    let stream = StreamInfo {
        index: 0,
        time_base,
        duration: Some(parsed.total_duration_ms as i64),
        start_time: Some(0),
        params,
    };

    Ok(Box::new(WebpDemuxer {
        stream,
        body,
        parsed,
        time_base,
        pos: 0,
        pts: 0,
    }))
}

/// Result of parsing a `WEBP` form body.
#[derive(Debug)]
pub(crate) struct ParsedContainer {
    /// (width, height) — final rendered canvas size.
    pub canvas: (u32, u32),
    /// Frames in presentation order. Each frame has an already-extracted
    /// payload chunk (VP8 or VP8L) plus optional ALPH and offset/disposal
    /// info for animations. Static files produce exactly one entry.
    pub frames: Vec<ParsedFrame>,
    /// Sum of all per-frame durations in milliseconds. Currently
    /// unread because the framework `Demuxer` impl uses the lazy
    /// container's parallel field for `StreamInfo::duration`; the
    /// standalone `decode_webp` path also doesn't surface a
    /// container-level duration. Kept for parity with the lazy struct
    /// + so a future eager-side caller doesn't have to re-scan.
    #[allow(dead_code)]
    pub total_duration_ms: u32,
    /// Optional auxiliary metadata chunks (ICCP / EXIF / XMP). Empty for
    /// simple-layout files that omitted them; populated whenever the
    /// container carries the matching FourCC.
    pub metadata: WebpFileMetadata,
    /// Animated-WebP background colour as parsed from the `ANIM` chunk
    /// (RFC 9649 §2.5). Stored exactly as the spec lays it down — `[B,
    /// G, R, A]` byte order — so callers that want to surface the raw
    /// chunk see the original bytes. `None` for non-animated files (no
    /// `ANIM` chunk).
    ///
    /// The decoder converts these to RGBA when initialising the canvas
    /// and when filling dispose-to-background regions; see
    /// [`bgra_to_rgba`] for the conversion.
    pub anim_background_bgra: Option<[u8; 4]>,
    /// `loop_count` from the ANIM chunk (`0` = infinite). `None` for
    /// non-animated files.
    pub anim_loop_count: Option<u16>,
}

/// Convert a 4-byte ANIM-chunk background colour from the spec's `[B,
/// G, R, A]` byte order to row-major RGBA. The decoder uses this to
/// initialise the rendering canvas + fill dispose-to-background
/// regions per RFC 9649 §2.5. Centralised so both the standalone
/// [`crate::decode_webp`] path and the registry-side `WebpDecoder`
/// agree on the byte order.
pub(crate) fn bgra_to_rgba(bgra: [u8; 4]) -> [u8; 4] {
    [bgra[2], bgra[1], bgra[0], bgra[3]]
}

/// Auxiliary `.webp` file-level metadata chunks. Values are the raw
/// chunk payloads — ICC profile bytes, EXIF binary blob, XMP UTF-8
/// XML — exactly as written by the encoder. Per the WebP container
/// spec §3 these are file-global (not per-frame) and may appear in
/// any order after the `VP8X` header.
#[derive(Debug, Clone, Default)]
pub struct WebpFileMetadata {
    /// Raw `ICCP` chunk payload (an ICC colour profile). `None` when the
    /// file omitted the chunk.
    pub icc: Option<Vec<u8>>,
    /// Raw `EXIF` chunk payload. `None` when absent.
    pub exif: Option<Vec<u8>>,
    /// Raw `XMP ` chunk payload (UTF-8 XML, typically). `None` when absent.
    pub xmp: Option<Vec<u8>>,
}

impl WebpFileMetadata {
    /// True if any of the three metadata fields is populated. Useful for
    /// `decode_webp` callers that want to skip work when the file is
    /// metadata-free.
    pub fn any(&self) -> bool {
        self.icc.is_some() || self.exif.is_some() || self.xmp.is_some()
    }
}

/// Parse only the auxiliary metadata chunks (`ICCP`, `EXIF`, `XMP `)
/// out of a complete `.webp` file. Useful for callers that want to
/// inspect the colour profile or sidecar metadata without decoding any
/// pixels.
///
/// Returns `Ok(default)` (all fields `None`) for simple-layout files
/// that don't carry a `VP8X` header — those layouts can't carry
/// metadata by definition. Returns an error only for malformed
/// containers (bad RIFF header, truncated chunks); unknown auxiliary
/// chunks are skipped silently per the WebP container spec.
pub fn extract_metadata(buf: &[u8]) -> Result<WebpFileMetadata> {
    if buf.len() < 12 || &buf[0..4] != b"RIFF" || &buf[8..12] != b"WEBP" {
        return Err(Error::invalid("WebP: bad RIFF/WEBP magic"));
    }
    let riff_size = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
    let end = (8 + riff_size).min(buf.len());
    let body = &buf[12..end];
    let mut chunks = RiffChunks::new(body);
    // Peek the first chunk: only VP8X-extended layouts can carry metadata.
    let Some(first) = chunks.next().transpose()? else {
        return Ok(WebpFileMetadata::default());
    };
    if &first.id != b"VP8X" {
        // Simple lossy/lossless layout — no metadata possible.
        return Ok(WebpFileMetadata::default());
    }
    let mut meta = WebpFileMetadata::default();
    while let Some(c) = chunks.next().transpose()? {
        match &c.id {
            b"ICCP" => meta.icc = Some(c.data.to_vec()),
            b"EXIF" => meta.exif = Some(c.data.to_vec()),
            b"XMP " => meta.xmp = Some(c.data.to_vec()),
            _ => {}
        }
    }
    Ok(meta)
}

#[derive(Debug)]
pub(crate) struct ParsedFrame {
    /// Raw payload of the image chunk — VP8 keyframe or VP8L bitstream.
    pub image: ImagePayload,
    /// Optional ALPH chunk (extended-format alpha plane).
    pub alph: Option<AlphChunk>,
    pub x_offset: u32,
    pub y_offset: u32,
    pub width: u32,
    pub height: u32,
    pub duration_ms: u32,
    /// True → dispose to background colour before rendering the next frame.
    pub dispose_to_background: bool,
    /// True → blend with the canvas (false = overwrite).
    pub blend_with_previous: bool,
}

#[derive(Debug)]
pub(crate) enum ImagePayload {
    Vp8(Vec<u8>),
    Vp8l(Vec<u8>),
}

#[derive(Debug)]
pub(crate) struct AlphChunk {
    /// Pre-processing nibble of the ALPH header byte (RFC 9649 §3.4).
    /// libwebp's encoder doesn't emit any pre-processing other than 0,
    /// so the decoder ignores it; kept on the struct for parity with
    /// [`LazyAlphRef`] + so a future implementation can pick it up
    /// without re-walking chunks.
    #[allow(dead_code)]
    pub pre_processing: u8,
    pub filtering: u8,
    pub compression: u8,
    pub data: Vec<u8>,
}

/// Memory-tight counterpart to [`ParsedContainer`] used by
/// [`crate::WebpAnimDecoder`]. Per-frame VP8/VP8L bitstreams + ALPH
/// payloads are recorded as `(start_offset, length)` ranges into the
/// buffer the decoder owns, instead of being copied into per-frame
/// `Vec<u8>`s up front. For a 1000-frame animation that's ~1000 saved
/// allocations + the file size's worth of memcpy traffic.
///
/// The decoder keeps the body buffer alive for the lifetime of the
/// `WebpAnimDecoder` (it copies the caller's bytes once at
/// construction), so the offsets stay valid until the decoder is
/// dropped. This is the WebP analogue to libwebp's `WebPAnimDecoder`
/// holding the file blob and resolving frame ranges lazily.
#[derive(Debug)]
pub(crate) struct LazyParsedContainer {
    pub canvas: (u32, u32),
    pub frames: Vec<LazyParsedFrame>,
    /// Sum of all `duration_ms` fields across `frames`. Used by the
    /// streaming `Demuxer` impl to populate `StreamInfo::duration` at
    /// `open` time without re-walking the frames. The animated
    /// `WebpAnimDecoder` still surfaces duration on a per-frame basis
    /// and ignores this field.
    pub total_duration_ms: u32,
    pub metadata: WebpFileMetadata,
    pub anim_background_bgra: Option<[u8; 4]>,
    pub anim_loop_count: Option<u16>,
}

/// Per-frame entry in [`LazyParsedContainer`]. `image` and `alph` carry
/// only the kind tag + a `(offset, length)` pair into the body buffer
/// — the actual VP8/VP8L/ALPH bytes stay in the buffer until the
/// decoder slices them on demand.
#[derive(Debug, Clone)]
pub(crate) struct LazyParsedFrame {
    pub image: LazyImageRef,
    pub alph: Option<LazyAlphRef>,
    pub x_offset: u32,
    pub y_offset: u32,
    pub width: u32,
    pub height: u32,
    pub duration_ms: u32,
    pub dispose_to_background: bool,
    pub blend_with_previous: bool,
}

/// Image-payload reference into the owning buffer. Same semantics as
/// [`ImagePayload`] but byte-range instead of owned `Vec`.
#[derive(Debug, Clone, Copy)]
pub(crate) enum LazyImageRef {
    Vp8 { offset: usize, len: usize },
    Vp8l { offset: usize, len: usize },
}

/// ALPH-chunk reference into the owning buffer — the 3 header nibbles
/// (`pre_processing` / `filtering` / `compression`) are still parsed
/// eagerly because the VP8X parser uses them, but the (potentially
/// large) compressed alpha plane stays in the body buffer.
#[derive(Debug, Clone, Copy)]
pub(crate) struct LazyAlphRef {
    /// Pre-processing nibble of the ALPH header byte (RFC 9649 §3.4).
    /// Currently unused by the decoder (libwebp's encoder doesn't emit
    /// any pre-processing other than 0); kept for parity with
    /// [`AlphChunk`] so a future implementation can pick it up without
    /// re-walking the chunks.
    #[allow(dead_code)]
    pub pre_processing: u8,
    pub filtering: u8,
    pub compression: u8,
    pub data_offset: usize,
    pub data_len: usize,
}

/// Streaming `OWEB` payload builder used by [`WebpDemuxer::next_packet`].
/// Materialises one frame's payload at a time directly from a
/// [`LazyParsedFrame`] + the owning body buffer, so the demuxer never
/// needs to pre-compute the full `Vec<Packet>` up front. The on-wire
/// layout is the small TLV the decoder side (`decode_frame_payload`)
/// already understands — magic `OWEB` + version + flags + canvas/bbox
/// scalars + image bytes + optional ALPH block + optional ANIM bg
/// trailer (RFC 9649 §2.5 byte order).
#[cfg(feature = "registry")]
pub(crate) fn encode_lazy_frame_payload(
    f: &LazyParsedFrame,
    body: &[u8],
    canvas: (u32, u32),
    anim_background_bgra: Option<[u8; 4]>,
) -> Result<Vec<u8>> {
    let (img_bytes, is_vp8l) = match f.image {
        LazyImageRef::Vp8 { offset, len } => {
            if offset + len > body.len() {
                return Err(Error::invalid("WebP: VP8 ref out of bounds"));
            }
            (&body[offset..offset + len], false)
        }
        LazyImageRef::Vp8l { offset, len } => {
            if offset + len > body.len() {
                return Err(Error::invalid("WebP: VP8L ref out of bounds"));
            }
            (&body[offset..offset + len], true)
        }
    };
    let alph_bytes = if let Some(a) = &f.alph {
        if a.data_offset + a.data_len > body.len() {
            return Err(Error::invalid("WebP: ALPH ref out of bounds"));
        }
        Some(&body[a.data_offset..a.data_offset + a.data_len])
    } else {
        None
    };

    let mut out = Vec::with_capacity(
        64 + img_bytes.len() + f.alph.as_ref().map(|a| a.data_len + 16).unwrap_or(0) + 8,
    );
    out.extend_from_slice(b"OWEB");
    out.push(2);
    let mut flags = 0u8;
    if f.alph.is_some() {
        flags |= 0x01;
    }
    if is_vp8l {
        flags |= 0x02;
    }
    if f.dispose_to_background {
        flags |= 0x04;
    }
    if f.blend_with_previous {
        flags |= 0x08;
    }
    if anim_background_bgra.is_some() {
        flags |= 0x10;
    }
    out.push(flags);
    for v in [
        canvas.0, canvas.1, f.x_offset, f.y_offset, f.width, f.height,
    ] {
        out.extend_from_slice(&v.to_le_bytes());
    }
    out.extend_from_slice(&f.duration_ms.to_le_bytes());
    out.extend_from_slice(&(img_bytes.len() as u32).to_le_bytes());
    out.extend_from_slice(img_bytes);
    if let (Some(a), Some(ab)) = (&f.alph, alph_bytes) {
        out.push(a.pre_processing);
        out.push(a.filtering);
        out.push(a.compression);
        out.extend_from_slice(&(ab.len() as u32).to_le_bytes());
        out.extend_from_slice(ab);
    }
    if let Some(bgra) = anim_background_bgra {
        out.extend_from_slice(&bgra);
    }
    Ok(out)
}

/// Counterpart to `encode_lazy_frame_payload`. Used by the decoder.
pub(crate) fn decode_frame_payload(buf: &[u8]) -> Result<DecodedPayload<'_>> {
    if buf.len() < 4 + 1 + 1 + 6 * 4 + 4 + 4 {
        return Err(Error::invalid("WebP: frame payload too short"));
    }
    if &buf[0..4] != b"OWEB" {
        return Err(Error::invalid("WebP: bad frame payload magic"));
    }
    let version = buf[4];
    if version != 1 && version != 2 {
        return Err(Error::invalid("WebP: unknown frame payload version"));
    }
    let flags = buf[5];
    let mut p = 6usize;
    let read_u32 = |p: &mut usize, buf: &[u8]| -> u32 {
        let v = u32::from_le_bytes([buf[*p], buf[*p + 1], buf[*p + 2], buf[*p + 3]]);
        *p += 4;
        v
    };
    let canvas_w = read_u32(&mut p, buf);
    let canvas_h = read_u32(&mut p, buf);
    let x_off = read_u32(&mut p, buf);
    let y_off = read_u32(&mut p, buf);
    let frame_w = read_u32(&mut p, buf);
    let frame_h = read_u32(&mut p, buf);
    let duration_ms = read_u32(&mut p, buf);
    let img_len = read_u32(&mut p, buf) as usize;
    if p + img_len > buf.len() {
        return Err(Error::invalid("WebP: image chunk extends past payload"));
    }
    let image = &buf[p..p + img_len];
    p += img_len;
    let alph = if flags & 0x01 != 0 {
        if p + 3 + 4 > buf.len() {
            return Err(Error::invalid("WebP: truncated ALPH header"));
        }
        let pre = buf[p];
        let filt = buf[p + 1];
        let comp = buf[p + 2];
        p += 3;
        let alen = read_u32(&mut p, buf) as usize;
        if p + alen > buf.len() {
            return Err(Error::invalid("WebP: ALPH data extends past payload"));
        }
        let a = &buf[p..p + alen];
        p += alen;
        Some(DecodedAlph {
            pre_processing: pre,
            filtering: filt,
            compression: comp,
            data: a,
        })
    } else {
        None
    };
    // v2 trailing ANIM-background block. Bit 4 of `flags` gates it; v1
    // payloads always have the bit clear.
    let anim_background_bgra = if version >= 2 && (flags & 0x10) != 0 {
        if p + 4 > buf.len() {
            return Err(Error::invalid("WebP: truncated ANIM bg in payload"));
        }
        Some([buf[p], buf[p + 1], buf[p + 2], buf[p + 3]])
    } else {
        None
    };
    Ok(DecodedPayload {
        is_vp8l: flags & 0x02 != 0,
        dispose_to_background: flags & 0x04 != 0,
        blend_with_previous: flags & 0x08 != 0,
        canvas: (canvas_w, canvas_h),
        x_offset: x_off,
        y_offset: y_off,
        width: frame_w,
        height: frame_h,
        duration_ms,
        image,
        alph,
        anim_background_bgra,
    })
}

pub(crate) struct DecodedPayload<'a> {
    pub is_vp8l: bool,
    pub dispose_to_background: bool,
    pub blend_with_previous: bool,
    pub canvas: (u32, u32),
    pub x_offset: u32,
    pub y_offset: u32,
    pub width: u32,
    pub height: u32,
    #[allow(dead_code)]
    pub duration_ms: u32,
    pub image: &'a [u8],
    pub alph: Option<DecodedAlph<'a>>,
    /// ANIM background colour as parsed from the file's `ANIM` chunk
    /// (`[B, G, R, A]` byte order; `None` for non-animated files).
    /// The decoder converts this to RGBA when initialising the canvas
    /// + filling dispose-to-background regions.
    pub anim_background_bgra: Option<[u8; 4]>,
}

pub(crate) struct DecodedAlph<'a> {
    #[allow(dead_code)]
    pub pre_processing: u8,
    pub filtering: u8,
    pub compression: u8,
    pub data: &'a [u8],
}

pub(crate) fn parse_webp_body(body: &[u8]) -> Result<ParsedContainer> {
    let mut chunks = RiffChunks::new(body);
    // Peek the first chunk to distinguish simple vs extended layout.
    let first = chunks
        .next()
        .transpose()?
        .ok_or_else(|| Error::invalid("WebP: empty RIFF body"))?;

    match &first.id {
        b"VP8 " => {
            // Simple lossy still.
            let (w, h) = parse_vp8_keyframe_dims(first.data)?;
            let frame = ParsedFrame {
                image: ImagePayload::Vp8(first.data.to_vec()),
                alph: None,
                x_offset: 0,
                y_offset: 0,
                width: w,
                height: h,
                duration_ms: 0,
                dispose_to_background: false,
                blend_with_previous: false,
            };
            Ok(ParsedContainer {
                canvas: (w, h),
                frames: vec![frame],
                total_duration_ms: 0,
                metadata: WebpFileMetadata::default(),
                anim_background_bgra: None,
                anim_loop_count: None,
            })
        }
        b"VP8L" => {
            let (w, h) = parse_vp8l_dims(first.data)?;
            let frame = ParsedFrame {
                image: ImagePayload::Vp8l(first.data.to_vec()),
                alph: None,
                x_offset: 0,
                y_offset: 0,
                width: w,
                height: h,
                duration_ms: 0,
                dispose_to_background: false,
                blend_with_previous: false,
            };
            Ok(ParsedContainer {
                canvas: (w, h),
                frames: vec![frame],
                total_duration_ms: 0,
                metadata: WebpFileMetadata::default(),
                anim_background_bgra: None,
                anim_loop_count: None,
            })
        }
        b"VP8X" => parse_extended(first.data, &mut chunks),
        other => Err(Error::invalid(format!(
            "WebP: unexpected first chunk {:?}",
            std::str::from_utf8(other).unwrap_or("???")
        ))),
    }
}

fn parse_extended(vp8x: &[u8], chunks: &mut RiffChunks<'_>) -> Result<ParsedContainer> {
    if vp8x.len() < 10 {
        return Err(Error::invalid("WebP: VP8X chunk too short"));
    }
    // VP8X layout: 1 byte flags, 3 bytes reserved, 3 bytes canvas_w-1, 3 bytes canvas_h-1.
    let flags = vp8x[0];
    let has_anim = flags & 0x02 != 0;
    let canvas_w = (u32::from_le_bytes([vp8x[4], vp8x[5], vp8x[6], 0]) & 0x00FF_FFFF) + 1;
    let canvas_h = (u32::from_le_bytes([vp8x[7], vp8x[8], vp8x[9], 0]) & 0x00FF_FFFF) + 1;

    let mut frames: Vec<ParsedFrame> = Vec::new();
    // Static extended WebP state — we accumulate the VP8/VP8L chunk and
    // optional ALPH, and emit one frame when we've seen an image.
    let mut pending_alph: Option<AlphChunk> = None;
    let mut pending_image: Option<ImagePayload> = None;
    let mut metadata = WebpFileMetadata::default();
    // ANIM chunk state (RFC 9649 §2.5). Only meaningful when the VP8X
    // ANIM flag is set; we still capture it on flag-mismatch files
    // (the spec says "MUST be ignored" on flag-clear, but a strict
    // ignore would also drop a benign chunk on a malformed file —
    // gating on `has_anim` below preserves the spec's "ignore" while
    // still reading the chunk so a future loose-mode could surface it).
    let mut anim_background_bgra: Option<[u8; 4]> = None;
    let mut anim_loop_count: Option<u16> = None;

    let mut total_duration = 0u32;

    while let Some(c) = chunks.next().transpose()? {
        match &c.id {
            b"VP8 " => {
                pending_image = Some(ImagePayload::Vp8(c.data.to_vec()));
            }
            b"VP8L" => {
                pending_image = Some(ImagePayload::Vp8l(c.data.to_vec()));
            }
            b"ALPH" => {
                if c.data.is_empty() {
                    return Err(Error::invalid("WebP: ALPH chunk empty"));
                }
                let hdr = c.data[0];
                let pre = (hdr >> 4) & 0x3;
                let filt = (hdr >> 2) & 0x3;
                let comp = hdr & 0x3;
                pending_alph = Some(AlphChunk {
                    pre_processing: pre,
                    filtering: filt,
                    compression: comp,
                    data: c.data[1..].to_vec(),
                });
            }
            b"ANMF" => {
                let anmf = parse_anmf(c.data)?;
                let f = anmf.into_frame();
                total_duration = total_duration.saturating_add(f.duration_ms);
                frames.push(f);
            }
            // Auxiliary metadata chunks — captured into `metadata` so
            // callers can read them off `WebpImage::metadata` after
            // decode. Unknown auxiliary FourCCs (and `ANIM` whose flags
            // are already represented in the per-frame state) are
            // skipped silently per the WebP container spec.
            b"ICCP" => metadata.icc = Some(c.data.to_vec()),
            b"EXIF" => metadata.exif = Some(c.data.to_vec()),
            b"XMP " => metadata.xmp = Some(c.data.to_vec()),
            // ANIM chunk: 4 bytes [B, G, R, A] background colour +
            // 2 bytes little-endian loop count (RFC 9649 §2.5,
            // "ANIM Chunk"). Per spec: "This chunk MUST appear if
            // the Animation flag in the VP8X Chunk is set. If the
            // Animation flag is not set and this chunk is present,
            // it MUST be ignored." We capture it unconditionally
            // and gate exposure on `has_anim` after the loop so a
            // file with the flag clear still parses cleanly.
            b"ANIM" if c.data.len() >= 6 => {
                anim_background_bgra = Some([c.data[0], c.data[1], c.data[2], c.data[3]]);
                anim_loop_count = Some(u16::from_le_bytes([c.data[4], c.data[5]]));
            }
            b"ANIM" => {
                // Truncated ANIM payload — leave fields at None.
            }
            _ => {
                // Unknown chunk — skip silently per the spec.
            }
        }
    }
    // Per RFC 9649 §2.5, the ANIM chunk is meaningful only when the
    // VP8X ANIM flag is set. Drop it when the flag is clear so callers
    // see `None` — matches "MUST be ignored" wording.
    if !has_anim {
        anim_background_bgra = None;
        anim_loop_count = None;
    }

    if !has_anim {
        let image = pending_image
            .ok_or_else(|| Error::invalid("WebP: extended file has no image chunk"))?;
        let (w, h) = match &image {
            ImagePayload::Vp8(v) => parse_vp8_keyframe_dims(v).unwrap_or((canvas_w, canvas_h)),
            ImagePayload::Vp8l(v) => parse_vp8l_dims(v).unwrap_or((canvas_w, canvas_h)),
        };
        let frame = ParsedFrame {
            image,
            alph: pending_alph.take(),
            x_offset: 0,
            y_offset: 0,
            width: w,
            height: h,
            duration_ms: 0,
            dispose_to_background: false,
            blend_with_previous: false,
        };
        frames.push(frame);
    }

    Ok(ParsedContainer {
        canvas: (canvas_w, canvas_h),
        frames,
        total_duration_ms: total_duration,
        metadata,
        anim_background_bgra,
        anim_loop_count,
    })
}

struct AnmfBundle {
    x_offset: u32,
    y_offset: u32,
    width: u32,
    height: u32,
    duration_ms: u32,
    dispose_to_background: bool,
    blend_with_previous: bool,
    image: ImagePayload,
    alph: Option<AlphChunk>,
}

impl AnmfBundle {
    fn into_frame(self) -> ParsedFrame {
        ParsedFrame {
            image: self.image,
            alph: self.alph,
            x_offset: self.x_offset,
            y_offset: self.y_offset,
            width: self.width,
            height: self.height,
            duration_ms: self.duration_ms,
            dispose_to_background: self.dispose_to_background,
            blend_with_previous: self.blend_with_previous,
        }
    }
}

fn parse_anmf(data: &[u8]) -> Result<AnmfBundle> {
    // ANMF: 3 bytes X/2, 3 bytes Y/2, 3 bytes w-1, 3 bytes h-1, 3 bytes duration,
    //       1 byte flags (bit0 = blending=overwrite, bit1 = dispose-to-bg).
    //       Then nested sub-chunks (ALPH? + VP8/VP8L).
    if data.len() < 16 {
        return Err(Error::invalid("WebP: ANMF header too short"));
    }
    let x_off = u32::from_le_bytes([data[0], data[1], data[2], 0]) & 0x00FF_FFFF;
    let y_off = u32::from_le_bytes([data[3], data[4], data[5], 0]) & 0x00FF_FFFF;
    let w = (u32::from_le_bytes([data[6], data[7], data[8], 0]) & 0x00FF_FFFF) + 1;
    let h = (u32::from_le_bytes([data[9], data[10], data[11], 0]) & 0x00FF_FFFF) + 1;
    let dur = u32::from_le_bytes([data[12], data[13], data[14], 0]) & 0x00FF_FFFF;
    let flags = data[15];
    // Spec (WebP container, ANMF flags byte):
    //   bit 0 = blending_method (0 = alpha-blend with canvas,
    //                            1 = no blend / overwrite)
    //   bit 1 = disposal_method (0 = do nothing,
    //                            1 = dispose to background after rendering)
    // The flag we keep internally is the *positive* sense — true means
    // "blend onto the canvas using the source alpha". So invert bit 0.
    let blend_with_previous = flags & 0x01 == 0;
    let dispose_to_background = flags & 0x02 != 0;

    let mut chunks = RiffChunks::new(&data[16..]);
    let mut image: Option<ImagePayload> = None;
    let mut alph: Option<AlphChunk> = None;
    while let Some(c) = chunks.next().transpose()? {
        match &c.id {
            b"VP8 " => image = Some(ImagePayload::Vp8(c.data.to_vec())),
            b"VP8L" => image = Some(ImagePayload::Vp8l(c.data.to_vec())),
            b"ALPH" if !c.data.is_empty() => {
                let hdr = c.data[0];
                alph = Some(AlphChunk {
                    pre_processing: (hdr >> 4) & 0x3,
                    filtering: (hdr >> 2) & 0x3,
                    compression: hdr & 0x3,
                    data: c.data[1..].to_vec(),
                });
            }
            _ => {}
        }
    }
    let image = image.ok_or_else(|| Error::invalid("WebP: ANMF has no image chunk"))?;
    Ok(AnmfBundle {
        x_offset: x_off * 2, // spec: multiples of 2 → stored /2
        y_offset: y_off * 2,
        width: w,
        height: h,
        duration_ms: dur,
        dispose_to_background,
        blend_with_previous,
        image,
        alph,
    })
}

fn parse_vp8_keyframe_dims(vp8: &[u8]) -> Result<(u32, u32)> {
    // Bare VP8 keyframe tag: 3 byte frame tag + 3 byte start code + 4 byte hdr.
    if vp8.len() < 10 {
        return Err(Error::invalid("WebP: VP8 chunk too short"));
    }
    if vp8[3] != 0x9d || vp8[4] != 0x01 || vp8[5] != 0x2a {
        return Err(Error::invalid("WebP: missing VP8 keyframe start code"));
    }
    let w = u16::from_le_bytes([vp8[6], vp8[7]]) as u32 & 0x3FFF;
    let h = u16::from_le_bytes([vp8[8], vp8[9]]) as u32 & 0x3FFF;
    Ok((w, h))
}

fn parse_vp8l_dims(vp8l: &[u8]) -> Result<(u32, u32)> {
    // VP8L: signature byte 0x2f then 14 bit width-1, 14 bit height-1, ...
    if vp8l.len() < 5 {
        return Err(Error::invalid("WebP: VP8L chunk too short"));
    }
    if vp8l[0] != 0x2f {
        return Err(Error::invalid("WebP: bad VP8L signature"));
    }
    let bits = u32::from_le_bytes([vp8l[1], vp8l[2], vp8l[3], vp8l[4]]);
    let w = (bits & 0x3FFF) + 1;
    let h = ((bits >> 14) & 0x3FFF) + 1;
    Ok((w, h))
}

/// Memory-tight counterpart to [`parse_webp_body`]. Walks the RIFF
/// chunk tree once and returns a [`LazyParsedContainer`] whose frames
/// reference VP8/VP8L/ALPH bytes via `(offset, len)` ranges into
/// `body` instead of cloning each chunk into an owned `Vec<u8>`.
///
/// Returned offsets are relative to `body` (i.e. the slice the caller
/// passed in), not the full RIFF file. Consumers that own the file
/// buffer (e.g. [`crate::WebpAnimDecoder`]) need to remember the
/// `body` start offset (it's always the byte after the 12-byte
/// `RIFF/<size>/WEBP` preamble) when slicing.
///
/// This function is lossless w.r.t. [`parse_webp_body`] — the same set
/// of frames in the same order, the same metadata, the same ANIM bg /
/// loop-count, the same total duration. Only the per-frame storage
/// shape changes from owned to borrowed-via-offset.
pub(crate) fn parse_webp_body_lazy(body: &[u8]) -> Result<LazyParsedContainer> {
    let mut chunks = RiffChunks::new(body);
    let first = chunks
        .next()
        .transpose()?
        .ok_or_else(|| Error::invalid("WebP: empty RIFF body"))?;

    match &first.id {
        b"VP8 " => {
            let (w, h) = parse_vp8_keyframe_dims(first.data)?;
            let frame = LazyParsedFrame {
                image: LazyImageRef::Vp8 {
                    offset: first.payload_offset,
                    len: first.data.len(),
                },
                alph: None,
                x_offset: 0,
                y_offset: 0,
                width: w,
                height: h,
                duration_ms: 0,
                dispose_to_background: false,
                blend_with_previous: false,
            };
            Ok(LazyParsedContainer {
                canvas: (w, h),
                frames: vec![frame],
                total_duration_ms: 0,
                metadata: WebpFileMetadata::default(),
                anim_background_bgra: None,
                anim_loop_count: None,
            })
        }
        b"VP8L" => {
            let (w, h) = parse_vp8l_dims(first.data)?;
            let frame = LazyParsedFrame {
                image: LazyImageRef::Vp8l {
                    offset: first.payload_offset,
                    len: first.data.len(),
                },
                alph: None,
                x_offset: 0,
                y_offset: 0,
                width: w,
                height: h,
                duration_ms: 0,
                dispose_to_background: false,
                blend_with_previous: false,
            };
            Ok(LazyParsedContainer {
                canvas: (w, h),
                frames: vec![frame],
                total_duration_ms: 0,
                metadata: WebpFileMetadata::default(),
                anim_background_bgra: None,
                anim_loop_count: None,
            })
        }
        b"VP8X" => parse_extended_lazy(first.data, &mut chunks),
        other => Err(Error::invalid(format!(
            "WebP: unexpected first chunk {:?}",
            std::str::from_utf8(other).unwrap_or("???")
        ))),
    }
}

fn parse_extended_lazy(vp8x: &[u8], chunks: &mut RiffChunks<'_>) -> Result<LazyParsedContainer> {
    if vp8x.len() < 10 {
        return Err(Error::invalid("WebP: VP8X chunk too short"));
    }
    let flags = vp8x[0];
    let has_anim = flags & 0x02 != 0;
    let canvas_w = (u32::from_le_bytes([vp8x[4], vp8x[5], vp8x[6], 0]) & 0x00FF_FFFF) + 1;
    let canvas_h = (u32::from_le_bytes([vp8x[7], vp8x[8], vp8x[9], 0]) & 0x00FF_FFFF) + 1;

    let mut frames: Vec<LazyParsedFrame> = Vec::new();
    let mut pending_alph: Option<LazyAlphRef> = None;
    let mut pending_image: Option<LazyImageRef> = None;
    let mut metadata = WebpFileMetadata::default();
    let mut anim_background_bgra: Option<[u8; 4]> = None;
    let mut anim_loop_count: Option<u16> = None;
    let mut total_duration = 0u32;

    while let Some(c) = chunks.next().transpose()? {
        match &c.id {
            b"VP8 " => {
                pending_image = Some(LazyImageRef::Vp8 {
                    offset: c.payload_offset,
                    len: c.data.len(),
                });
            }
            b"VP8L" => {
                pending_image = Some(LazyImageRef::Vp8l {
                    offset: c.payload_offset,
                    len: c.data.len(),
                });
            }
            b"ALPH" => {
                if c.data.is_empty() {
                    return Err(Error::invalid("WebP: ALPH chunk empty"));
                }
                let hdr = c.data[0];
                pending_alph = Some(LazyAlphRef {
                    pre_processing: (hdr >> 4) & 0x3,
                    filtering: (hdr >> 2) & 0x3,
                    compression: hdr & 0x3,
                    // Skip the 1-byte ALPH header — `data_offset`
                    // points at the compressed alpha plane proper.
                    data_offset: c.payload_offset + 1,
                    data_len: c.data.len() - 1,
                });
            }
            b"ANMF" => {
                let f = parse_anmf_lazy(c.data, c.payload_offset)?;
                total_duration = total_duration.saturating_add(f.duration_ms);
                frames.push(f);
            }
            // The auxiliary metadata chunks are typically small (a few
            // hundred bytes for ICCP, ~tens of KB for EXIF/XMP); we
            // continue cloning them eagerly because consumers of
            // `WebpAnimInfo` expect owned `Vec<u8>` and the savings
            // wouldn't change the asymptotic memory shape (animations
            // dwarf metadata).
            b"ICCP" => metadata.icc = Some(c.data.to_vec()),
            b"EXIF" => metadata.exif = Some(c.data.to_vec()),
            b"XMP " => metadata.xmp = Some(c.data.to_vec()),
            b"ANIM" if c.data.len() >= 6 => {
                anim_background_bgra = Some([c.data[0], c.data[1], c.data[2], c.data[3]]);
                anim_loop_count = Some(u16::from_le_bytes([c.data[4], c.data[5]]));
            }
            b"ANIM" => {}
            _ => {}
        }
    }
    if !has_anim {
        anim_background_bgra = None;
        anim_loop_count = None;
    }
    if !has_anim {
        let image = pending_image
            .ok_or_else(|| Error::invalid("WebP: extended file has no image chunk"))?;
        // Compute width/height from the image bitstream, falling back
        // to the canvas dims if the parse fails (matches the eager
        // path's tolerance).
        let body_full_view = chunks.body;
        let (w, h) = match image {
            LazyImageRef::Vp8 { offset, len } => {
                parse_vp8_keyframe_dims(&body_full_view[offset..offset + len])
                    .unwrap_or((canvas_w, canvas_h))
            }
            LazyImageRef::Vp8l { offset, len } => {
                parse_vp8l_dims(&body_full_view[offset..offset + len])
                    .unwrap_or((canvas_w, canvas_h))
            }
        };
        frames.push(LazyParsedFrame {
            image,
            alph: pending_alph.take(),
            x_offset: 0,
            y_offset: 0,
            width: w,
            height: h,
            duration_ms: 0,
            dispose_to_background: false,
            blend_with_previous: false,
        });
    }
    Ok(LazyParsedContainer {
        canvas: (canvas_w, canvas_h),
        frames,
        total_duration_ms: total_duration,
        metadata,
        anim_background_bgra,
        anim_loop_count,
    })
}

fn parse_anmf_lazy(data: &[u8], anmf_payload_offset: usize) -> Result<LazyParsedFrame> {
    if data.len() < 16 {
        return Err(Error::invalid("WebP: ANMF header too short"));
    }
    let x_off = u32::from_le_bytes([data[0], data[1], data[2], 0]) & 0x00FF_FFFF;
    let y_off = u32::from_le_bytes([data[3], data[4], data[5], 0]) & 0x00FF_FFFF;
    let w = (u32::from_le_bytes([data[6], data[7], data[8], 0]) & 0x00FF_FFFF) + 1;
    let h = (u32::from_le_bytes([data[9], data[10], data[11], 0]) & 0x00FF_FFFF) + 1;
    let dur = u32::from_le_bytes([data[12], data[13], data[14], 0]) & 0x00FF_FFFF;
    let flags = data[15];
    let blend_with_previous = flags & 0x01 == 0;
    let dispose_to_background = flags & 0x02 != 0;

    // The nested-chunk iterator walks `data[16..]`; offsets it produces
    // are relative to that sub-slice. We add `anmf_payload_offset + 16`
    // to translate them back to body-buffer offsets.
    let mut chunks = RiffChunks::new(&data[16..]);
    let mut image: Option<LazyImageRef> = None;
    let mut alph: Option<LazyAlphRef> = None;
    while let Some(c) = chunks.next().transpose()? {
        let abs_offset = anmf_payload_offset + 16 + c.payload_offset;
        match &c.id {
            b"VP8 " => {
                image = Some(LazyImageRef::Vp8 {
                    offset: abs_offset,
                    len: c.data.len(),
                });
            }
            b"VP8L" => {
                image = Some(LazyImageRef::Vp8l {
                    offset: abs_offset,
                    len: c.data.len(),
                });
            }
            b"ALPH" if !c.data.is_empty() => {
                let hdr = c.data[0];
                alph = Some(LazyAlphRef {
                    pre_processing: (hdr >> 4) & 0x3,
                    filtering: (hdr >> 2) & 0x3,
                    compression: hdr & 0x3,
                    data_offset: abs_offset + 1,
                    data_len: c.data.len() - 1,
                });
            }
            _ => {}
        }
    }
    let image = image.ok_or_else(|| Error::invalid("WebP: ANMF has no image chunk"))?;
    Ok(LazyParsedFrame {
        image,
        alph,
        x_offset: x_off * 2,
        y_offset: y_off * 2,
        width: w,
        height: h,
        duration_ms: dur,
        dispose_to_background,
        blend_with_previous,
    })
}

/// Iterator over RIFF chunks inside a body. Borrows the body slice.
struct RiffChunks<'a> {
    body: &'a [u8],
    pos: usize,
}

impl<'a> RiffChunks<'a> {
    fn new(body: &'a [u8]) -> Self {
        Self { body, pos: 0 }
    }
}

struct ChunkRef<'a> {
    id: [u8; 4],
    data: &'a [u8],
    /// Offset of `data[0]` inside the iterator's `body` slice. Used by
    /// the lazy demuxer to record `(offset, len)` ranges into the
    /// owning buffer instead of cloning chunks.
    payload_offset: usize,
}

impl<'a> Iterator for RiffChunks<'a> {
    type Item = Result<ChunkRef<'a>>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.pos + 8 > self.body.len() {
            // Dangling trailing bytes <8 bytes long — treat as clean EOF
            // to survive tolerant muxers.
            return None;
        }
        let id = [
            self.body[self.pos],
            self.body[self.pos + 1],
            self.body[self.pos + 2],
            self.body[self.pos + 3],
        ];
        let size = u32::from_le_bytes([
            self.body[self.pos + 4],
            self.body[self.pos + 5],
            self.body[self.pos + 6],
            self.body[self.pos + 7],
        ]) as usize;
        let payload_start = self.pos + 8;
        let payload_end = payload_start.saturating_add(size);
        if payload_end > self.body.len() {
            return Some(Err(Error::invalid("WebP: chunk extends past RIFF body")));
        }
        let data = &self.body[payload_start..payload_end];
        let payload_offset = payload_start;
        let padded = (size + (size & 1)).min(self.body.len().saturating_sub(payload_start));
        self.pos = payload_start + padded;
        Some(Ok(ChunkRef {
            id,
            data,
            payload_offset,
        }))
    }
}

/// Streaming WebP `Demuxer` impl. Owns the full RIFF body buffer once
/// (so `parse_webp_body_lazy`'s per-frame `(offset, len)` ranges stay
/// valid), then yields one `Packet` per [`Demuxer::next_packet`] call
/// — the OWEB payload is materialised on demand via
/// [`encode_lazy_frame_payload`] instead of being precomputed for every
/// frame at `open` time.
///
/// For long animations (1000+ frames) this trades a one-time
/// `Vec<Packet>` allocation (size ~ sum of all OWEB blobs) for
/// per-frame allocations totalling the same size — but the working
/// set at any moment is one packet's worth, not all of them. Same
/// shape as libwebp's `WebPAnimDecoder` API, where each
/// `WebPAnimDecoderGetNext` call materialises the next frame's
/// composite without pre-computing all frames up front.
#[cfg(feature = "registry")]
struct WebpDemuxer {
    stream: StreamInfo,
    /// Owned RIFF body buffer; sliced by `parsed.frames` ranges.
    body: Vec<u8>,
    /// Lazily-walked container metadata + frame `(offset, len)` ranges.
    parsed: LazyParsedContainer,
    /// Time base used to construct each `Packet` (millisecond units —
    /// matches the WebP ANMF native time scale).
    time_base: TimeBase,
    /// Index of the next frame to emit. Bumped by `next_packet`.
    pos: usize,
    /// Cumulative PTS in time-base units; bumped by each frame's
    /// `max(duration_ms, 1)` so we mirror the eager
    /// `ParsedContainer::into_packets` arithmetic exactly.
    pts: i64,
}

#[cfg(feature = "registry")]
impl Demuxer for WebpDemuxer {
    fn format_name(&self) -> &str {
        "webp"
    }

    fn streams(&self) -> &[StreamInfo] {
        std::slice::from_ref(&self.stream)
    }

    fn next_packet(&mut self) -> oxideav_core::Result<Packet> {
        if self.pos >= self.parsed.frames.len() {
            return Err(oxideav_core::Error::Eof);
        }
        let i = self.pos;
        let f = &self.parsed.frames[i];
        let duration = f.duration_ms;
        let data = encode_lazy_frame_payload(
            f,
            &self.body,
            self.parsed.canvas,
            self.parsed.anim_background_bgra,
        )?;
        let mut pkt = Packet::new(0, self.time_base, data);
        pkt.pts = Some(self.pts);
        pkt.dts = Some(self.pts);
        pkt.duration = Some(duration.max(1) as i64);
        pkt.flags.keyframe = i == 0;
        self.pts += duration.max(1) as i64;
        self.pos += 1;
        Ok(pkt)
    }

    fn duration_micros(&self) -> Option<i64> {
        self.stream.duration.map(|d| d * 1000)
    }
}

#[cfg(all(test, feature = "registry"))]
mod tests {
    use super::*;

    #[test]
    fn probe_recognises_webp() {
        let mut buf = vec![0u8; 16];
        buf[..4].copy_from_slice(b"RIFF");
        buf[8..12].copy_from_slice(b"WEBP");
        let p = ProbeData {
            buf: &buf,
            ext: None,
        };
        assert_eq!(probe(&p), 100);
    }

    #[test]
    fn probe_rejects_non_webp_riff() {
        let mut buf = vec![0u8; 16];
        buf[..4].copy_from_slice(b"RIFF");
        buf[8..12].copy_from_slice(b"AVI ");
        let p = ProbeData {
            buf: &buf,
            ext: None,
        };
        assert_eq!(probe(&p), 0);
    }

    /// Build a tiny 3-frame animated WebP for the streaming Demuxer
    /// tests. Mirrors the inline `three_frame_anim` in
    /// `anim_decoder.rs::tests`.
    fn three_frame_anim_blob() -> Vec<u8> {
        use crate::encoder_anim::{build_animated_webp, AnimFrame};
        const W: u32 = 8;
        const H: u32 = 8;
        let solid = |rgba: [u8; 4]| -> Vec<u8> {
            let n = (W as usize) * (H as usize);
            let mut v = Vec::with_capacity(n * 4);
            for _ in 0..n {
                v.extend_from_slice(&rgba);
            }
            v
        };
        let red = solid([0xff, 0, 0, 0xff]);
        let green = solid([0, 0xff, 0, 0xff]);
        let blue = solid([0, 0, 0xff, 0xff]);
        let frames = [
            AnimFrame {
                width: W,
                height: H,
                x_offset: 0,
                y_offset: 0,
                duration_ms: 30,
                blend: false,
                dispose_to_background: false,
                rgba: &red,
            },
            AnimFrame {
                width: W,
                height: H,
                x_offset: 0,
                y_offset: 0,
                duration_ms: 40,
                blend: false,
                dispose_to_background: false,
                rgba: &green,
            },
            AnimFrame {
                width: W,
                height: H,
                x_offset: 0,
                y_offset: 0,
                duration_ms: 50,
                blend: false,
                dispose_to_background: false,
                rgba: &blue,
            },
        ];
        build_animated_webp(W, H, [0, 0, 0, 0], 0, &frames).expect("encode")
    }

    #[test]
    fn streaming_demuxer_yields_frames_in_order_with_pts() {
        // The streaming Demuxer materialises one packet at a time —
        // `pos` advances per `next_packet`, PTS arithmetic mirrors the
        // anim-decoder's `pts_ms` (cumulative `max(duration_ms, 1)`).
        let blob = three_frame_anim_blob();
        let cursor = std::io::Cursor::new(blob);
        let mut demux = open_boxed(Box::new(cursor)).expect("open");
        // Streams metadata is available before any packet is pulled.
        assert_eq!(demux.streams().len(), 1);
        let p0 = demux.next_packet().expect("first");
        assert_eq!(p0.pts, Some(0));
        assert_eq!(p0.duration, Some(30));
        assert!(p0.flags.keyframe);
        let p1 = demux.next_packet().expect("second");
        assert_eq!(p1.pts, Some(30));
        assert_eq!(p1.duration, Some(40));
        assert!(!p1.flags.keyframe);
        let p2 = demux.next_packet().expect("third");
        assert_eq!(p2.pts, Some(70));
        assert_eq!(p2.duration, Some(50));
        // Subsequent calls report Eof.
        assert!(matches!(demux.next_packet(), Err(oxideav_core::Error::Eof)));
    }

    #[test]
    fn streaming_demuxer_packet_payload_round_trips_through_decoder() {
        // Each packet's OWEB payload must decode through the same
        // `decode_frame_payload` reader the registry decoder uses —
        // proving the streaming `encode_lazy_frame_payload` is
        // byte-for-byte equivalent to the eager helper it replaced.
        let blob = three_frame_anim_blob();
        let cursor = std::io::Cursor::new(blob);
        let mut demux = open_boxed(Box::new(cursor)).expect("open");
        for i in 0..3 {
            let pkt = demux.next_packet().expect("ok");
            let parsed = decode_frame_payload(pkt.data.as_slice()).expect("OWEB parse");
            assert_eq!(parsed.canvas, (8, 8), "frame {i} canvas");
            assert_eq!(parsed.width, 8);
            assert_eq!(parsed.height, 8);
            // Image bytes are non-empty (a real VP8L bitstream).
            assert!(!parsed.image.is_empty());
        }
    }

    #[test]
    fn streaming_demuxer_does_not_pre_allocate_packet_vec() {
        // Sanity-check the streaming shape: opening doesn't materialise
        // every packet up front — we can construct the demuxer for a
        // 3-frame blob and immediately drop it without any cost beyond
        // the (small) lazy-parse + body buffer. Best signal we can
        // reasonably observe in a unit test: the type doesn't expose a
        // `Vec<Packet>` surface, and `next_packet` is the only way to
        // get one out.
        let blob = three_frame_anim_blob();
        let cursor = std::io::Cursor::new(blob);
        let demux = open_boxed(Box::new(cursor)).expect("open");
        // We never call `next_packet`; the demuxer holds only the body
        // + the lazy frame ranges. Drop and check no panic.
        drop(demux);
    }

    #[test]
    fn streaming_demuxer_eof_is_repeatable() {
        // After draining, every subsequent `next_packet` returns Eof
        // — not a panic, not a re-emit of the last packet.
        let blob = three_frame_anim_blob();
        let cursor = std::io::Cursor::new(blob);
        let mut demux = open_boxed(Box::new(cursor)).expect("open");
        for _ in 0..3 {
            let _ = demux.next_packet().expect("ok");
        }
        for _ in 0..5 {
            assert!(matches!(demux.next_packet(), Err(oxideav_core::Error::Eof)));
        }
    }
}