webpx 0.2.3

Complete WebP encoding/decoding with ICC profiles, streaming, and animation support
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
//! WebP decoding functionality.
//!
//! # Stride Convention
//!
//! Functions with `_into` suffix that accept a stride parameter follow this convention:
//! **The stride unit matches the output buffer type:**
//!
//! | Buffer type | Stride unit | Example |
//! |-------------|-------------|---------|
//! | `&mut [u8]` (raw bytes) | bytes | `decode_rgba_into(..., stride_bytes)` |
//! | `&mut [P]` (typed pixels) | pixels | `decode_into::<P>(..., stride_pixels)` |
//!
//! Stride must always be >= width (in the appropriate unit).

use crate::config::DecoderConfig;
use crate::error::{DecodingError, Error, Result};
use crate::types::{DecodePixel, ImageInfo, YuvPlanes};
use alloc::vec::Vec;
use imgref::ImgVec;
use rgb::alt::{BGR8, BGRA8};
use rgb::{RGB8, RGBA8};
use whereat::*;

/// Decode WebP data to RGBA pixels.
///
/// Returns the decoded pixels and dimensions.
///
/// # Example
///
/// ```rust,no_run
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let (pixels, width, height) = webpx::decode_rgba(webp_data)?;
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode_rgba(data: &[u8]) -> Result<(Vec<u8>, u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    let ptr =
        unsafe { libwebp_sys::WebPDecodeRGBA(data.as_ptr(), data.len(), &mut width, &mut height) };

    if ptr.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    let size = (width as usize)
        .saturating_mul(height as usize)
        .saturating_mul(4);
    let pixels = unsafe {
        let slice = core::slice::from_raw_parts(ptr, size);
        let vec = slice.to_vec();
        libwebp_sys::WebPFree(ptr as *mut _);
        vec
    };

    Ok((pixels, width as u32, height as u32))
}

/// Decode WebP data to RGB pixels (no alpha).
///
/// Returns the decoded pixels and dimensions.
pub fn decode_rgb(data: &[u8]) -> Result<(Vec<u8>, u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    let ptr =
        unsafe { libwebp_sys::WebPDecodeRGB(data.as_ptr(), data.len(), &mut width, &mut height) };

    if ptr.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    let size = (width as usize)
        .saturating_mul(height as usize)
        .saturating_mul(3);
    let pixels = unsafe {
        let slice = core::slice::from_raw_parts(ptr, size);
        let vec = slice.to_vec();
        libwebp_sys::WebPFree(ptr as *mut _);
        vec
    };

    Ok((pixels, width as u32, height as u32))
}

/// Decode WebP data to BGRA pixels.
///
/// BGRA is the native format on Windows and some GPU APIs.
/// Returns the decoded pixels and dimensions.
pub fn decode_bgra(data: &[u8]) -> Result<(Vec<u8>, u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    let ptr =
        unsafe { libwebp_sys::WebPDecodeBGRA(data.as_ptr(), data.len(), &mut width, &mut height) };

    if ptr.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    let size = (width as usize)
        .saturating_mul(height as usize)
        .saturating_mul(4);
    let pixels = unsafe {
        let slice = core::slice::from_raw_parts(ptr, size);
        let vec = slice.to_vec();
        libwebp_sys::WebPFree(ptr as *mut _);
        vec
    };

    Ok((pixels, width as u32, height as u32))
}

/// Decode WebP data to BGR pixels (no alpha).
///
/// BGR is common in OpenCV and some image libraries.
/// Returns the decoded pixels and dimensions.
pub fn decode_bgr(data: &[u8]) -> Result<(Vec<u8>, u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    let ptr =
        unsafe { libwebp_sys::WebPDecodeBGR(data.as_ptr(), data.len(), &mut width, &mut height) };

    if ptr.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    let size = (width as usize)
        .saturating_mul(height as usize)
        .saturating_mul(3);
    let pixels = unsafe {
        let slice = core::slice::from_raw_parts(ptr, size);
        let vec = slice.to_vec();
        libwebp_sys::WebPFree(ptr as *mut _);
        vec
    };

    Ok((pixels, width as u32, height as u32))
}

/// Decode WebP data to typed pixels.
///
/// Returns the decoded pixels as the specified pixel type and dimensions.
/// Supports [`RGBA8`], [`RGB8`], [`BGRA8`], and [`BGR8`].
///
/// # Example
///
/// ```rust,no_run
/// use rgb::RGBA8;
///
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let (pixels, width, height) = webpx::decode::<RGBA8>(webp_data)?;
/// // pixels is Vec<RGBA8>
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode<P: DecodePixel>(data: &[u8]) -> Result<(Vec<P>, u32, u32)> {
    let (ptr, width, height) = P::decode_new(data)
        .ok_or_else(|| at!(Error::DecodeFailed(DecodingError::BitstreamError)))?;

    let bpp = P::LAYOUT.bytes_per_pixel();
    // saturating_mul so 32-bit usize cannot wrap when libwebp returns large dims.
    let pixel_count = (width as usize).saturating_mul(height as usize);
    let byte_size = pixel_count.saturating_mul(bpp);

    let pixels = unsafe {
        // Copy from libwebp buffer to our Vec<P>
        let byte_slice = core::slice::from_raw_parts(ptr, byte_size);
        let mut vec: Vec<P> = Vec::with_capacity(pixel_count);
        core::ptr::copy_nonoverlapping(byte_slice.as_ptr(), vec.as_mut_ptr() as *mut u8, byte_size);
        vec.set_len(pixel_count);
        libwebp_sys::WebPFree(ptr as *mut _);
        vec
    };

    Ok((pixels, width as u32, height as u32))
}

/// Decode WebP data, appending typed pixels to an existing Vec.
///
/// This is useful when you want to reuse an existing buffer or
/// decode multiple images into the same Vec.
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Vec to append decoded pixels to
///
/// # Returns
/// Width and height of the decoded image.
///
/// # Example
///
/// ```rust,no_run
/// use rgb::RGBA8;
///
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let mut pixels: Vec<RGBA8> = Vec::new();
/// let (width, height) = webpx::decode_append::<RGBA8>(webp_data, &mut pixels)?;
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode_append<P: DecodePixel>(data: &[u8], output: &mut Vec<P>) -> Result<(u32, u32)> {
    let (ptr, width, height) = P::decode_new(data)
        .ok_or_else(|| at!(Error::DecodeFailed(DecodingError::BitstreamError)))?;

    let bpp = P::LAYOUT.bytes_per_pixel();
    let pixel_count = (width as usize).saturating_mul(height as usize);
    let byte_size = pixel_count.saturating_mul(bpp);

    unsafe {
        let byte_slice = core::slice::from_raw_parts(ptr, byte_size);
        let start = output.len();
        output.reserve(pixel_count);
        core::ptr::copy_nonoverlapping(
            byte_slice.as_ptr(),
            (output.as_mut_ptr() as *mut u8).add(start * bpp),
            byte_size,
        );
        output.set_len(start + pixel_count);
        libwebp_sys::WebPFree(ptr as *mut _);
    };

    Ok((width as u32, height as u32))
}

/// Decode WebP data to an imgref image.
///
/// Returns the decoded image as an [`ImgVec`] with the specified pixel type.
///
/// # Example
///
/// ```rust,no_run
/// use rgb::RGBA8;
///
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let img: imgref::ImgVec<RGBA8> = webpx::decode_to_img(webp_data)?;
/// // Access via img.pixels(), img.width(), img.height()
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode_to_img<P: DecodePixel>(data: &[u8]) -> Result<ImgVec<P>> {
    let (pixels, width, height) = decode::<P>(data)?;
    Ok(ImgVec::new(pixels, width as usize, height as usize))
}

/// Decode WebP data directly into a typed pixel slice.
///
/// This function decodes directly into the provided buffer, avoiding
/// allocation overhead. The buffer must be pre-allocated with sufficient space.
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Pre-allocated output buffer (must be at least width * height pixels)
/// * `stride_pixels` - Row stride in pixels (must be >= width)
///
/// # Returns
/// Width and height of the decoded image.
///
/// # Example
///
/// ```rust,no_run
/// use rgb::RGBA8;
///
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let info = webpx::ImageInfo::from_webp(&webp_data)?;
/// let mut buffer: Vec<RGBA8> = vec![RGBA8::default(); info.width as usize * info.height as usize];
/// let (w, h) = webpx::decode_into::<RGBA8>(&webp_data, &mut buffer, info.width)?;
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode_into<P: DecodePixel>(
    data: &[u8],
    output: &mut [P],
    stride_pixels: u32,
) -> Result<(u32, u32)> {
    let info = ImageInfo::from_webp(data)?;
    let width = info.width;
    let height = info.height;
    let bpp = P::LAYOUT.bytes_per_pixel();

    // Validate buffer; saturating_mul so 32-bit usize cannot wrap.
    let required_pixels = (stride_pixels as usize).saturating_mul(height as usize);
    if output.len() < required_pixels {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "output buffer too small: got {} pixels, need {} (stride {} × height {})",
            output.len(),
            required_pixels,
            stride_pixels,
            height
        ))));
    }
    if stride_pixels < width {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too small: got {}, minimum {}",
            stride_pixels,
            width
        ))));
    }

    // saturating_mul on 32-bit; range-check before casting to i32 below.
    let stride_bytes = (stride_pixels as usize).saturating_mul(bpp);
    if stride_bytes > i32::MAX as usize {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too large for libwebp i32 stride parameter: {}",
            stride_bytes
        ))));
    }
    let output_bytes = output.len() * bpp;

    // SAFETY: We've validated the buffer size and stride above
    let ok = unsafe {
        P::decode_into(
            data,
            output.as_mut_ptr() as *mut u8,
            output_bytes,
            stride_bytes as i32,
        )
    };

    if !ok {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    Ok((width, height))
}

/// Decode WebP data directly into a pre-allocated RGBA buffer (zero-copy).
///
/// This function decodes directly into the provided buffer, avoiding
/// allocation and copy overhead.
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Pre-allocated output buffer (must be at least stride * height bytes)
/// * `stride_bytes` - Row stride in bytes (must be >= width * 4)
///
/// # Returns
/// Width and height of the decoded image.
///
/// # Example
/// ```rust,no_run
/// let webp_data: &[u8] = &[]; // placeholder
/// let info = webpx::ImageInfo::from_webp(&webp_data)?;
/// let stride = info.width as usize * 4;
/// let mut buffer = vec![0u8; stride * info.height as usize];
/// let (w, h) = webpx::decode_rgba_into(&webp_data, &mut buffer, stride as u32)?;
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub fn decode_rgba_into(data: &[u8], output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    // Get dimensions first
    if unsafe { libwebp_sys::WebPGetInfo(data.as_ptr(), data.len(), &mut width, &mut height) } == 0
    {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    // Validate buffer
    let required = (stride_bytes as usize).saturating_mul(height as usize);
    if output.len() < required {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "output buffer too small: got {}, need {} (stride {} × height {})",
            output.len(),
            required,
            stride_bytes,
            height
        ))));
    }
    if (stride_bytes as i32) < width * 4 {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too small: got {}, minimum {}",
            stride_bytes,
            width * 4
        ))));
    }

    let result = unsafe {
        libwebp_sys::WebPDecodeRGBAInto(
            data.as_ptr(),
            data.len(),
            output.as_mut_ptr(),
            output.len(),
            stride_bytes as i32,
        )
    };

    if result.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    Ok((width as u32, height as u32))
}

/// Decode WebP data directly into a pre-allocated BGRA buffer (zero-copy).
///
/// BGRA is the native format on Windows and some GPU APIs.
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Pre-allocated output buffer (must be at least stride * height bytes)
/// * `stride_bytes` - Row stride in bytes (must be >= width * 4)
///
/// # Returns
/// Width and height of the decoded image.
pub fn decode_bgra_into(data: &[u8], output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    // Get dimensions first
    if unsafe { libwebp_sys::WebPGetInfo(data.as_ptr(), data.len(), &mut width, &mut height) } == 0
    {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    // Validate buffer
    let required = (stride_bytes as usize).saturating_mul(height as usize);
    if output.len() < required {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "output buffer too small: got {}, need {} (stride {} × height {})",
            output.len(),
            required,
            stride_bytes,
            height
        ))));
    }
    if (stride_bytes as i32) < width * 4 {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too small: got {}, minimum {}",
            stride_bytes,
            width * 4
        ))));
    }

    let result = unsafe {
        libwebp_sys::WebPDecodeBGRAInto(
            data.as_ptr(),
            data.len(),
            output.as_mut_ptr(),
            output.len(),
            stride_bytes as i32,
        )
    };

    if result.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    Ok((width as u32, height as u32))
}

/// Decode WebP data directly into a pre-allocated RGB buffer (zero-copy).
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Pre-allocated output buffer (must be at least stride * height bytes)
/// * `stride_bytes` - Row stride in bytes (must be >= width * 3)
///
/// # Returns
/// Width and height of the decoded image.
pub fn decode_rgb_into(data: &[u8], output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    // Get dimensions first
    if unsafe { libwebp_sys::WebPGetInfo(data.as_ptr(), data.len(), &mut width, &mut height) } == 0
    {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    // Validate buffer
    let required = (stride_bytes as usize).saturating_mul(height as usize);
    if output.len() < required {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "output buffer too small: got {}, need {} (stride {} × height {})",
            output.len(),
            required,
            stride_bytes,
            height
        ))));
    }
    if (stride_bytes as i32) < width * 3 {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too small: got {}, minimum {}",
            stride_bytes,
            width * 3
        ))));
    }

    let result = unsafe {
        libwebp_sys::WebPDecodeRGBInto(
            data.as_ptr(),
            data.len(),
            output.as_mut_ptr(),
            output.len(),
            stride_bytes as i32,
        )
    };

    if result.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    Ok((width as u32, height as u32))
}

/// Decode WebP data directly into a pre-allocated BGR buffer (zero-copy).
///
/// BGR is common in OpenCV and some image libraries.
///
/// # Arguments
/// * `data` - WebP encoded data
/// * `output` - Pre-allocated output buffer (must be at least stride * height bytes)
/// * `stride_bytes` - Row stride in bytes (must be >= width * 3)
///
/// # Returns
/// Width and height of the decoded image.
pub fn decode_bgr_into(data: &[u8], output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;

    // Get dimensions first
    if unsafe { libwebp_sys::WebPGetInfo(data.as_ptr(), data.len(), &mut width, &mut height) } == 0
    {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    // Validate buffer
    let required = (stride_bytes as usize).saturating_mul(height as usize);
    if output.len() < required {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "output buffer too small: got {}, need {} (stride {} × height {})",
            output.len(),
            required,
            stride_bytes,
            height
        ))));
    }
    if (stride_bytes as i32) < width * 3 {
        return Err(at!(Error::InvalidInput(alloc::format!(
            "stride too small: got {}, minimum {}",
            stride_bytes,
            width * 3
        ))));
    }

    let result = unsafe {
        libwebp_sys::WebPDecodeBGRInto(
            data.as_ptr(),
            data.len(),
            output.as_mut_ptr(),
            output.len(),
            stride_bytes as i32,
        )
    };

    if result.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    Ok((width as u32, height as u32))
}

/// Decode WebP data to YUV planes.
///
/// Returns YUV420 planar data.
pub fn decode_yuv(data: &[u8]) -> Result<YuvPlanes> {
    let mut width: i32 = 0;
    let mut height: i32 = 0;
    let mut u_ptr: *mut u8 = core::ptr::null_mut();
    let mut v_ptr: *mut u8 = core::ptr::null_mut();
    let mut y_stride: i32 = 0;
    let mut uv_stride: i32 = 0;

    let y_ptr = unsafe {
        libwebp_sys::WebPDecodeYUV(
            data.as_ptr(),
            data.len(),
            &mut width,
            &mut height,
            &mut u_ptr,
            &mut v_ptr,
            &mut y_stride,
            &mut uv_stride,
        )
    };

    if y_ptr.is_null() {
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }

    let _uv_width = (width + 1) / 2;
    let uv_height = (height + 1) / 2;

    // libwebp's strides come back as i32; treat negatives as a malformed
    // response (would wrap to ~4 GB on `as usize`) and saturate the product
    // so 32-bit usize cannot wrap before from_raw_parts.
    if y_stride < 0 || uv_stride < 0 || height < 0 || uv_height < 0 {
        unsafe { libwebp_sys::WebPFree(y_ptr as *mut _) };
        return Err(at!(Error::DecodeFailed(DecodingError::BitstreamError)));
    }
    let y_size = (y_stride as usize).saturating_mul(height as usize);
    let uv_size = (uv_stride as usize).saturating_mul(uv_height as usize);

    let (y, u, v) = unsafe {
        let y = core::slice::from_raw_parts(y_ptr, y_size).to_vec();
        let u = core::slice::from_raw_parts(u_ptr, uv_size).to_vec();
        let v = core::slice::from_raw_parts(v_ptr, uv_size).to_vec();
        libwebp_sys::WebPFree(y_ptr as *mut _);
        // u and v are part of the same allocation as y, don't free separately
        (y, u, v)
    };

    Ok(YuvPlanes {
        y,
        y_stride: y_stride as usize,
        u,
        u_stride: uv_stride as usize,
        v,
        v_stride: uv_stride as usize,
        a: None,
        a_stride: 0,
        width: width as u32,
        height: height as u32,
    })
}

/// WebP decoder with advanced options.
///
/// # Example
///
/// ```rust,no_run
/// use webpx::Decoder;
///
/// let webp_data: &[u8] = &[0u8; 100]; // placeholder
/// let decoder = Decoder::new(webp_data)?;
/// let info = decoder.info();
/// println!("Image: {}x{}, alpha: {}", info.width, info.height, info.has_alpha);
///
/// let img: imgref::ImgVec<rgb::RGBA8> = decoder.decode_rgba()?;
/// # Ok::<(), webpx::At<webpx::Error>>(())
/// ```
pub struct Decoder<'a> {
    data: &'a [u8],
    info: ImageInfo,
    config: DecoderConfig,
}

impl<'a> Decoder<'a> {
    /// Create a new decoder for the given WebP data.
    pub fn new(data: &'a [u8]) -> Result<Self> {
        let info = ImageInfo::from_webp(data)?;
        Ok(Self {
            data,
            info,
            config: DecoderConfig::default(),
        })
    }

    /// Get image information.
    pub fn info(&self) -> &ImageInfo {
        &self.info
    }

    /// Set decoder configuration.
    pub fn config(mut self, config: DecoderConfig) -> Self {
        self.config = config;
        self
    }

    /// Enable cropping.
    pub fn crop(mut self, left: u32, top: u32, width: u32, height: u32) -> Self {
        self.config.use_cropping = true;
        self.config.crop_left = left;
        self.config.crop_top = top;
        self.config.crop_width = width;
        self.config.crop_height = height;
        self
    }

    /// Enable scaling.
    pub fn scale(mut self, width: u32, height: u32) -> Self {
        self.config.use_scaling = true;
        self.config.scaled_width = width;
        self.config.scaled_height = height;
        self
    }

    /// Decode to RGBA ImgVec.
    pub fn decode_rgba(self) -> Result<ImgVec<RGBA8>> {
        let (pixels, width, height) = self.decode_rgba_raw()?;

        // Convert &[u8] to Vec<RGBA8>
        let rgba_pixels: Vec<RGBA8> = pixels
            .chunks_exact(4)
            .map(|c| RGBA8::new(c[0], c[1], c[2], c[3]))
            .collect();

        Ok(ImgVec::new(rgba_pixels, width as usize, height as usize))
    }

    /// Decode to RGB ImgVec (no alpha).
    pub fn decode_rgb(self) -> Result<ImgVec<RGB8>> {
        let (pixels, width, height) = self.decode_rgb_raw()?;

        // Convert &[u8] to Vec<RGB8>
        let rgb_pixels: Vec<RGB8> = pixels
            .chunks_exact(3)
            .map(|c| RGB8::new(c[0], c[1], c[2]))
            .collect();

        Ok(ImgVec::new(rgb_pixels, width as usize, height as usize))
    }

    /// Decode to raw RGBA bytes.
    pub fn decode_rgba_raw(self) -> Result<(Vec<u8>, u32, u32)> {
        if self.config.needs_advanced_api() {
            self.decode_advanced(libwebp_sys::WEBP_CSP_MODE::MODE_RGBA)
        } else {
            decode_rgba(self.data)
        }
    }

    /// Decode to raw RGB bytes.
    pub fn decode_rgb_raw(self) -> Result<(Vec<u8>, u32, u32)> {
        if self.config.needs_advanced_api() {
            self.decode_advanced(libwebp_sys::WEBP_CSP_MODE::MODE_RGB)
        } else {
            decode_rgb(self.data)
        }
    }

    /// Decode to BGRA ImgVec.
    ///
    /// BGRA is the native format on Windows and some GPU APIs.
    pub fn decode_bgra(self) -> Result<ImgVec<BGRA8>> {
        let (pixels, width, height) = self.decode_bgra_raw()?;

        // Convert &[u8] to Vec<BGRA8>
        let bgra_pixels: Vec<BGRA8> = pixels
            .chunks_exact(4)
            .map(|c| BGRA8 {
                b: c[0],
                g: c[1],
                r: c[2],
                a: c[3],
            })
            .collect();

        Ok(ImgVec::new(bgra_pixels, width as usize, height as usize))
    }

    /// Decode to BGR ImgVec (no alpha).
    ///
    /// BGR is common in OpenCV and some image libraries.
    pub fn decode_bgr(self) -> Result<ImgVec<BGR8>> {
        let (pixels, width, height) = self.decode_bgr_raw()?;

        // Convert &[u8] to Vec<BGR8>
        let bgr_pixels: Vec<BGR8> = pixels
            .chunks_exact(3)
            .map(|c| BGR8 {
                b: c[0],
                g: c[1],
                r: c[2],
            })
            .collect();

        Ok(ImgVec::new(bgr_pixels, width as usize, height as usize))
    }

    /// Decode to raw BGRA bytes.
    pub fn decode_bgra_raw(self) -> Result<(Vec<u8>, u32, u32)> {
        if self.config.needs_advanced_api() {
            self.decode_advanced(libwebp_sys::WEBP_CSP_MODE::MODE_BGRA)
        } else {
            decode_bgra(self.data)
        }
    }

    /// Decode to raw BGR bytes.
    pub fn decode_bgr_raw(self) -> Result<(Vec<u8>, u32, u32)> {
        if self.config.needs_advanced_api() {
            self.decode_advanced(libwebp_sys::WEBP_CSP_MODE::MODE_BGR)
        } else {
            decode_bgr(self.data)
        }
    }

    /// Decode RGBA into a pre-allocated buffer (zero-copy).
    ///
    /// # Arguments
    /// * `output` - Pre-allocated buffer (must be at least width * height * 4 bytes)
    /// * `stride_bytes` - Row stride in bytes (must be >= width * 4)
    ///
    /// # Note
    /// Cropping and scaling are not supported with `_into` methods.
    /// Use `decode_rgba()` for those features.
    pub fn decode_rgba_into(self, output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
        if self.config.use_cropping || self.config.use_scaling {
            return Err(at!(Error::InvalidConfig(
                "cropping/scaling not supported with decode_into; use decode_rgba() instead".into()
            )));
        }
        decode_rgba_into(self.data, output, stride_bytes)
    }

    /// Decode RGB into a pre-allocated buffer (zero-copy).
    ///
    /// See [`Self::decode_rgba_into`] for details.
    pub fn decode_rgb_into(self, output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
        if self.config.use_cropping || self.config.use_scaling {
            return Err(at!(Error::InvalidConfig(
                "cropping/scaling not supported with decode_into; use decode_rgb() instead".into()
            )));
        }
        decode_rgb_into(self.data, output, stride_bytes)
    }

    /// Decode BGRA into a pre-allocated buffer (zero-copy).
    ///
    /// See [`Self::decode_rgba_into`] for details.
    pub fn decode_bgra_into(self, output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
        if self.config.use_cropping || self.config.use_scaling {
            return Err(at!(Error::InvalidConfig(
                "cropping/scaling not supported with decode_into; use decode_bgra() instead".into()
            )));
        }
        decode_bgra_into(self.data, output, stride_bytes)
    }

    /// Decode BGR into a pre-allocated buffer (zero-copy).
    ///
    /// See [`Self::decode_rgba_into`] for details.
    pub fn decode_bgr_into(self, output: &mut [u8], stride_bytes: u32) -> Result<(u32, u32)> {
        if self.config.use_cropping || self.config.use_scaling {
            return Err(at!(Error::InvalidConfig(
                "cropping/scaling not supported with decode_into; use decode_bgr() instead".into()
            )));
        }
        decode_bgr_into(self.data, output, stride_bytes)
    }

    /// Decode to YUV planes.
    pub fn decode_yuv(self) -> Result<YuvPlanes> {
        // For YUV, we use the simple API since advanced YUV decoding
        // requires more complex buffer management
        decode_yuv(self.data)
    }

    /// Advanced decode with cropping/scaling support.
    fn decode_advanced(self, mode: libwebp_sys::WEBP_CSP_MODE) -> Result<(Vec<u8>, u32, u32)> {
        // Reject zero-sized scale/crop targets up front: libwebp may accept
        // them and return a 0×N or N×0 buffer, which then panics inside
        // imgref's `ImgVec::new` (asserts stride > 0). Surfacing as a clean
        // error keeps `decode_rgba()` panic-free for any caller-supplied
        // builder configuration.
        if self.config.use_scaling
            && (self.config.scaled_width == 0 || self.config.scaled_height == 0)
        {
            return Err(at!(Error::InvalidInput(alloc::format!(
                "scale dimensions must be non-zero: got {}x{}",
                self.config.scaled_width,
                self.config.scaled_height
            ))));
        }
        if self.config.use_cropping && (self.config.crop_width == 0 || self.config.crop_height == 0)
        {
            return Err(at!(Error::InvalidInput(alloc::format!(
                "crop dimensions must be non-zero: got {}x{}",
                self.config.crop_width,
                self.config.crop_height
            ))));
        }

        // Input-size cap is the cheapest gate — reject before even creating
        // the decoder config / probing features.
        if let Err(e) = self
            .config
            .get_limits()
            .check_input_size(self.data.len() as u64)
        {
            return Err(at!(Error::LimitExceeded(e)));
        }

        let mut dec_config = libwebp_sys::WebPDecoderConfig::new()
            .map_err(|_| at!(Error::InvalidConfig("failed to init decoder config".into())))?;

        // Get features
        let status = unsafe {
            libwebp_sys::WebPGetFeatures(self.data.as_ptr(), self.data.len(), &mut dec_config.input)
        };
        if status != libwebp_sys::VP8StatusCode::VP8_STATUS_OK {
            return Err(at!(Error::DecodeFailed(DecodingError::from(status as i32))));
        }
        // Limits checks happen after features are read but before libwebp
        // allocates the output buffer in WebPDecode. The pre-scale check
        // is the cheap upfront gate; if a scale is configured, also check
        // the post-scale dimensions so the produced canvas honors the cap.
        self.config.check_still_image(
            dec_config.input.width as u32,
            dec_config.input.height as u32,
        )?;
        if self.config.use_scaling {
            self.config
                .check_still_image(self.config.scaled_width, self.config.scaled_height)?;
        }

        // Configure output
        dec_config.output.colorspace = mode;

        // Configure options
        if self.config.use_cropping {
            dec_config.options.use_cropping = 1;
            dec_config.options.crop_left = self.config.crop_left as i32;
            dec_config.options.crop_top = self.config.crop_top as i32;
            dec_config.options.crop_width = self.config.crop_width as i32;
            dec_config.options.crop_height = self.config.crop_height as i32;
        }

        if self.config.use_scaling {
            dec_config.options.use_scaling = 1;
            dec_config.options.scaled_width = self.config.scaled_width as i32;
            dec_config.options.scaled_height = self.config.scaled_height as i32;
        }

        dec_config.options.bypass_filtering = self.config.bypass_filtering as i32;
        dec_config.options.no_fancy_upsampling = self.config.no_fancy_upsampling as i32;
        dec_config.options.use_threads = self.config.use_threads as i32;
        dec_config.options.flip = self.config.flip as i32;
        dec_config.options.alpha_dithering_strength = self.config.alpha_dithering as i32;

        // Decode
        let status = unsafe {
            libwebp_sys::WebPDecode(self.data.as_ptr(), self.data.len(), &mut dec_config)
        };

        if status != libwebp_sys::VP8StatusCode::VP8_STATUS_OK {
            // libwebp's internal WebPDecode frees its own buffer on failure,
            // but call WebPFreeDecBuffer defensively — it is a safe no-op when
            // private_memory is null and protects against future libwebp paths
            // that might leave the buffer allocated.
            unsafe { libwebp_sys::WebPFreeDecBuffer(&mut dec_config.output) };
            return Err(at!(Error::DecodeFailed(DecodingError::from(status as i32))));
        }

        // Get output dimensions
        let width = if self.config.use_scaling {
            self.config.scaled_width
        } else if self.config.use_cropping {
            self.config.crop_width
        } else {
            dec_config.input.width as u32
        };

        let height = if self.config.use_scaling {
            self.config.scaled_height
        } else if self.config.use_cropping {
            self.config.crop_height
        } else {
            dec_config.input.height as u32
        };

        // Use libwebp's reported allocation size rather than recomputing it
        // from width*height*bpp. The recomputed size assumes a tightly-packed
        // stride, which is currently the case but not guaranteed — and a
        // mismatch would make the slice over-read libwebp's allocation.
        let pixels = unsafe {
            if dec_config.output.u.RGBA.rgba.is_null() {
                libwebp_sys::WebPFreeDecBuffer(&mut dec_config.output);
                return Err(at!(Error::DecodeFailed(DecodingError::OutOfMemory)));
            }
            let size = dec_config.output.u.RGBA.size;
            let slice = core::slice::from_raw_parts(dec_config.output.u.RGBA.rgba, size);
            let vec = slice.to_vec();
            libwebp_sys::WebPFreeDecBuffer(&mut dec_config.output);
            vec
        };

        Ok((pixels, width, height))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Test with a minimal valid WebP (would need actual test data)
    #[test]
    fn test_image_info_invalid() {
        let invalid_data = b"not a webp";
        assert!(ImageInfo::from_webp(invalid_data).is_err());
    }
}