Skip to main content

webp/dec/
buffer_dec.rs

1// libwebp v1.6.0, src/dec/buffer_dec.c:
2//
3// Copyright 2011 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// Everything about WebPDecBuffer
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16//! Translation of `src/dec/buffer_dec.c` from libwebp v1.6.0.
17//!
18//! Work package: WP12 (decoder integration).
19//!
20//! The samples of a buffer are one [`PlaneStorage`] (ADR 0003, buffers and
21//! planes): `Internal` is C's `private_memory`, `External` the caller's memory of
22//! `is_external_memory`. A C plane pointer is `NULL` here when the buffer holds
23//! no memory of its own (an empty `Internal` storage is C's
24//! `private_memory == NULL`) or when its region does not exist in the caller's
25//! storage (the C ABI gives a `NULL` plane no region); an empty caller slice is
26//! a pointer to no bytes, as in C. The
27//! member of the `u` union that C reads is the one that the colorspace selects;
28//! a Rust buffer whose `u` holds the other member describes no valid plane, and
29//! `CheckDecBuffer` rejects it (`# Deviations from upstream`, item 2).
30//!
31//! C's `is_external_memory >= 2`, slow external memory, is the buffer's
32//! `slow_memory` flag (ADR 0003, amended 2026-11-07).
33//!
34//! # Deviations from upstream
35//!
36//! Changes of representation that the ADRs allow, or behavior that the Rust
37//! side cannot reproduce exactly. Each records the reason.
38//!
39//! 1. **Freeing.** `WebPFreeDecBuffer` drops library memory;
40//!    `WebPInitDecBuffer` and `WebPInitDecoderConfig` drop the old storage,
41//!    where C zeroes the structure without freeing it.
42//! 2. **Mismatched union member.** A Rust buffer whose `u` holds the member
43//!    that the colorspace does not select reads as a zeroed member (ADR 0003),
44//!    so `CheckDecBuffer` rejects it and the incremental getters write zeros,
45//!    as C does for its zeroed union before allocation. C would reinterpret
46//!    arbitrary bytes of the other member; only Rust callers can build such a
47//!    buffer, and the C ABI reads the member that the colorspace selects.
48//!
49//! # Checks not applicable
50//!
51//! These checks do not apply, or cannot be made, with the reason:
52//!
53//! 1. **`WebPGrabDecBuffer`** has no caller in libwebp v1.6.0 and is not
54//!    exported (`webpi_dec.h` is internal); it is translated and not compared.
55
56use crate::dec::webp_dec::webp_check_crop_dimensions;
57use crate::utils::rescaler_utils::webp_rescaler_get_scaled_dimensions;
58use crate::utils::utils::{webp_copy_plane, webp_safe_malloc};
59use crate::webp::decode::{
60    VP8StatusCode, WEBP_CSP_MODE, WEBP_DECODER_ABI_VERSION, WebPBitstreamFeatures, WebPDecBuffer,
61    WebPDecBufferPlanes, WebPDecoderOptions, WebPRGBABuffer, WebPYUVABuffer, webp_is_alpha_mode,
62    webp_is_premultiplied_mode, webp_is_rgb_mode,
63};
64use crate::webp::types::{PlaneOffset, PlaneStorage, webp_abi_is_incompatible};
65
66//------------------------------------------------------------------------------
67// WebPDecBuffer
68
69// upstream: src/dec/buffer_dec.c kModeBpp
70/// Number of bytes per pixel for the different color-spaces.
71const MODE_BPP: [u8; WEBP_CSP_MODE::MODE_LAST.0 as usize] = [
72    3, 4, 3, 4, 4, 2, 2, //
73    4, 4, 4, 2, // pre-multiplied modes
74    1, 1,
75];
76
77/// `kModeBpp[mode]` for a valid colorspace.
78fn mode_bpp(mode: WEBP_CSP_MODE) -> u8 {
79    MODE_BPP[mode.0 as usize]
80}
81
82// upstream: src/dec/buffer_dec.c IsValidColorspace
83/// Converts to an integer to handle both the unsigned and the signed enum
84/// cases, as C does: callers pass the colorspace as an `int` (C declares the
85/// function in `src/dec/common_dec.h`).
86#[must_use]
87pub fn is_valid_colorspace(webp_csp_mode: i32) -> bool {
88    webp_csp_mode >= WEBP_CSP_MODE::MODE_RGB.0.cast_signed()
89        && webp_csp_mode < WEBP_CSP_MODE::MODE_LAST.0.cast_signed()
90}
91
92/// The colorspace as the `int` that C passes to `IsValidColorspace`.
93fn colorspace_int(mode: WEBP_CSP_MODE) -> i32 {
94    mode.0.cast_signed()
95}
96
97// upstream: src/dec/buffer_dec.c MIN_BUFFER_SIZE
98/// Strictly speaking, the very last (or first, if flipped) row doesn't require
99/// padding. C computes `(uint64_t)(STRIDE) * ((HEIGHT) - 1) + (WIDTH)`, with
100/// the `int` operands converted to `uint64_t`.
101fn min_buffer_size(width: u64, height: i32, stride: i32) -> u64 {
102    u64::from(stride.cast_unsigned())
103        .wrapping_mul(i64::from(height - 1).cast_unsigned())
104        .wrapping_add(width)
105}
106
107/// An `int` widened to `uint64_t`, as the C conversion does.
108fn to_u64(value: i32) -> u64 {
109    i64::from(value).cast_unsigned()
110}
111
112/// Whether the plane is C's `NULL` pointer (see the module documentation).
113#[must_use]
114pub fn is_null_plane(storage: &PlaneStorage<'_, u8>, plane: PlaneOffset) -> bool {
115    match storage {
116        PlaneStorage::Internal(memory) => memory.is_empty(),
117        PlaneStorage::External(_) | PlaneStorage::Shared(_) => {
118            storage.region(plane.region).is_none()
119        }
120    }
121}
122
123// upstream: src/dec/buffer_dec.c CheckDecBuffer
124fn check_dec_buffer(buffer: &WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
125    let mut ok = true;
126    let mode = buffer.colorspace;
127    let width = buffer.width;
128    let height = buffer.height;
129    if !is_valid_colorspace(colorspace_int(mode)) {
130        ok = false;
131    } else if !webp_is_rgb_mode(mode) {
132        // YUV checks
133        if let WebPDecBufferPlanes::YUVA(buf) = &buffer.u {
134            let uv_width = (width + 1) / 2;
135            let uv_height = (height + 1) / 2;
136            let y_stride = buf.y_stride.abs();
137            let u_stride = buf.u_stride.abs();
138            let v_stride = buf.v_stride.abs();
139            let a_stride = buf.a_stride.abs();
140            let y_size = min_buffer_size(to_u64(width), height, y_stride);
141            let u_size = min_buffer_size(to_u64(uv_width), uv_height, u_stride);
142            let v_size = min_buffer_size(to_u64(uv_width), uv_height, v_stride);
143            let a_size = min_buffer_size(to_u64(width), height, a_stride);
144            ok &= y_size <= buf.y_size as u64;
145            ok &= u_size <= buf.u_size as u64;
146            ok &= v_size <= buf.v_size as u64;
147            ok &= y_stride >= width;
148            ok &= u_stride >= uv_width;
149            ok &= v_stride >= uv_width;
150            ok &= !is_null_plane(&buffer.storage, buf.y);
151            ok &= !is_null_plane(&buffer.storage, buf.u);
152            ok &= !is_null_plane(&buffer.storage, buf.v);
153            if mode == WEBP_CSP_MODE::MODE_YUVA {
154                ok &= a_stride >= width;
155                ok &= a_size <= buf.a_size as u64;
156                ok &= buf.a.is_some_and(|a| !is_null_plane(&buffer.storage, a));
157            }
158        } else {
159            ok = false; // the RGBA member describes no YUVA plane
160        }
161    } else {
162        // RGB checks
163        if let WebPDecBufferPlanes::RGBA(buf) = &buffer.u {
164            let bpp = mode_bpp(mode);
165            let stride = buf.stride.abs();
166            let size = min_buffer_size(to_u64(width).wrapping_mul(u64::from(bpp)), height, stride);
167            ok &= size <= buf.size as u64;
168            ok &= stride >= width * i32::from(bpp);
169            ok &= !is_null_plane(&buffer.storage, buf.rgba);
170        } else {
171            ok = false; // the YUVA member describes no RGBA plane
172        }
173    }
174    if ok {
175        Ok(())
176    } else {
177        Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM)
178    }
179}
180
181// upstream: src/dec/buffer_dec.c AllocateBuffer
182#[expect(
183    clippy::cast_possible_truncation,
184    reason = "C converts the uint64_t sizes to size_t, which holds them after WebPSafeMalloc"
185)]
186fn allocate_buffer(buffer: &mut WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
187    let w = buffer.width;
188    let h = buffer.height;
189    let mode = buffer.colorspace;
190
191    if w <= 0 || h <= 0 || !is_valid_colorspace(colorspace_int(mode)) {
192        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
193    }
194
195    if matches!(&buffer.storage, PlaneStorage::Internal(memory) if memory.is_empty()) {
196        let mut uv_stride = 0;
197        let mut a_stride = 0;
198        let mut uv_size: u64 = 0;
199        let mut a_size: u64 = 0;
200        // We need memory and it hasn't been allocated yet.
201        // => initialize output buffer, now that dimensions are known.
202        let bpp = mode_bpp(mode);
203        if to_u64(w) * u64::from(bpp) >= (1u64 << 31) {
204            return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
205        }
206        let stride = w * i32::from(bpp);
207        let size = to_u64(stride) * to_u64(h);
208        if !webp_is_rgb_mode(mode) {
209            uv_stride = (w + 1) / 2;
210            uv_size = to_u64(uv_stride) * to_u64((h + 1) / 2);
211            if mode == WEBP_CSP_MODE::MODE_YUVA {
212                a_stride = w;
213                a_size = to_u64(a_stride) * to_u64(h);
214            }
215        }
216        let total_size = size + 2 * uv_size + a_size;
217
218        let Some(mut output) = webp_safe_malloc::<u8>(total_size, 1) else {
219            return Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY);
220        };
221        // Rust initializes the allocation (ADR 0003, allocation limits).
222        output.resize(total_size as usize, 0);
223        buffer.storage = PlaneStorage::Internal(output);
224
225        let plane = |offset: u64| PlaneOffset {
226            region: 0,
227            offset: offset as usize,
228        };
229        if webp_is_rgb_mode(mode) {
230            // RGBA initialization
231            buffer.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
232                rgba: plane(0),
233                stride,
234                size: size as usize,
235            });
236        } else {
237            // YUVA initialization. C leaves `a` alone for MODE_YUV; the RGBA
238            // member that the union held before has no `a`, which reads as NULL.
239            let a = match &buffer.u {
240                WebPDecBufferPlanes::YUVA(buf) => buf.a,
241                WebPDecBufferPlanes::RGBA(_) => None,
242            };
243            buffer.u = WebPDecBufferPlanes::YUVA(WebPYUVABuffer {
244                y: plane(0),
245                y_stride: stride,
246                y_size: size as usize,
247                u: plane(size),
248                u_stride: uv_stride,
249                u_size: uv_size as usize,
250                v: plane(size + uv_size),
251                v_stride: uv_stride,
252                v_size: uv_size as usize,
253                a: if mode == WEBP_CSP_MODE::MODE_YUVA {
254                    Some(plane(size + 2 * uv_size))
255                } else {
256                    a
257                },
258                a_size: a_size as usize,
259                a_stride,
260            });
261        }
262    }
263    check_dec_buffer(buffer)
264}
265
266/// `pointer += delta` for a plane, as C moves a plane pointer by a signed
267/// number of bytes.
268///
269/// # Panics
270///
271/// Panics when the plane would start before its region, where the C pointer
272/// would leave the buffer.
273fn move_plane(plane: &mut PlaneOffset, delta: i64) {
274    plane.offset = plane
275        .offset
276        .checked_add_signed(isize::try_from(delta).expect("the plane offset fits"))
277        .expect("the flipped plane starts inside its region");
278}
279
280// upstream: src/dec/buffer_dec.c WebPFlipBuffer
281/// Flips the buffer vertically by negating the various strides. C returns
282/// `VP8_STATUS_INVALID_PARAM` for a `NULL` buffer, which exists only at the C
283/// ABI.
284///
285/// # Errors
286///
287/// None: the result is always `Ok`, as C returns `VP8_STATUS_OK` for every
288/// buffer.
289///
290/// # Panics
291///
292/// Panics when a plane would start before its region, where C would compute a
293/// pointer outside the buffer.
294pub fn webp_flip_buffer(buffer: &mut WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
295    let height = i64::from(buffer.height);
296    if webp_is_rgb_mode(buffer.colorspace) {
297        if let WebPDecBufferPlanes::RGBA(buf) = &mut buffer.u {
298            move_plane(&mut buf.rgba, (height - 1) * i64::from(buf.stride));
299            buf.stride = -buf.stride;
300        }
301    } else if let WebPDecBufferPlanes::YUVA(buf) = &mut buffer.u {
302        let h = height;
303        move_plane(&mut buf.y, (h - 1) * i64::from(buf.y_stride));
304        buf.y_stride = -buf.y_stride;
305        move_plane(&mut buf.u, ((h - 1) >> 1) * i64::from(buf.u_stride));
306        buf.u_stride = -buf.u_stride;
307        move_plane(&mut buf.v, ((h - 1) >> 1) * i64::from(buf.v_stride));
308        buf.v_stride = -buf.v_stride;
309        if let Some(a) = &mut buf.a {
310            move_plane(a, (h - 1) * i64::from(buf.a_stride));
311            buf.a_stride = -buf.a_stride;
312        }
313    }
314    Ok(())
315}
316
317// upstream: src/dec/buffer_dec.c WebPAllocateDecBuffer
318/// Prepares `buffer` with the requested initial dimensions `width` and
319/// `height`. If no external storage is supplied, initializes the buffer by
320/// allocating output memory and setting up the stride information. Validates
321/// the parameters. If `options` is not `None`, also verifies that the options'
322/// parameters are valid and applies them to the width and height of the output
323/// buffer: cropping, scaling and the vertical flip. C returns
324/// `VP8_STATUS_INVALID_PARAM` for a `NULL` buffer, which exists only at the C
325/// ABI.
326///
327/// # Errors
328///
329/// Returns `VP8_STATUS_INVALID_PARAM` for invalid dimensions, options, strides
330/// or sizes and `VP8_STATUS_OUT_OF_MEMORY` when the allocation fails. The width
331/// and height are written before the buffer is checked, as in C.
332pub fn webp_allocate_dec_buffer(
333    width: i32,
334    height: i32,
335    options: Option<&WebPDecoderOptions>,
336    buffer: &mut WebPDecBuffer<'_>,
337) -> Result<(), VP8StatusCode> {
338    let mut width = width;
339    let mut height = height;
340    if width <= 0 || height <= 0 {
341        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
342    }
343    if let Some(options) = options {
344        // First, apply options if there is any.
345        if options.use_cropping != 0 {
346            let cw = options.crop_width;
347            let ch = options.crop_height;
348            let x = options.crop_left & !1;
349            let y = options.crop_top & !1;
350            if !webp_check_crop_dimensions(width, height, x, y, cw, ch) {
351                return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM); // out of frame boundary.
352            }
353            width = cw;
354            height = ch;
355        }
356
357        if options.use_scaling != 0 {
358            // WEBP_REDUCE_SIZE is not defined in the reference configuration.
359            let mut scaled_width = options.scaled_width;
360            let mut scaled_height = options.scaled_height;
361            if !webp_rescaler_get_scaled_dimensions(
362                width,
363                height,
364                &mut scaled_width,
365                &mut scaled_height,
366            ) {
367                return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
368            }
369            width = scaled_width;
370            height = scaled_height;
371        }
372    }
373    buffer.width = width;
374    buffer.height = height;
375
376    // Then, allocate buffer for real.
377    allocate_buffer(buffer)?;
378
379    // Use the stride trick if vertical flip is needed.
380    if options.is_some_and(|options| options.flip != 0) {
381        webp_flip_buffer(buffer)?;
382    }
383    Ok(())
384}
385
386//------------------------------------------------------------------------------
387// constructors / destructors
388
389// upstream: src/dec/buffer_dec.c WebPInitDecBufferInternal
390/// Internal, version-checked, entry point of `WebPInitDecBuffer`: resets the
391/// buffer to empty unless the ABI versions are incompatible. Returns false in
392/// case of version mismatch. C also returns 0 for a `NULL` buffer, which exists
393/// only at the C ABI. C zeroes the structure without freeing it; here the old
394/// storage is dropped.
395#[must_use]
396pub fn webp_init_dec_buffer_internal(buffer: &mut WebPDecBuffer<'_>, version: i32) -> bool {
397    if webp_abi_is_incompatible(version, WEBP_DECODER_ABI_VERSION) {
398        return false; // version mismatch
399    }
400    *buffer = WebPDecBuffer::default();
401    true
402}
403
404// upstream: src/dec/buffer_dec.c WebPFreeDecBuffer
405/// Frees any memory associated with the buffer: the memory that the buffer
406/// allocated itself. External memory stays the caller's, and the buffer keeps
407/// describing it, as C keeps the plane pointers. C accepts a `NULL` buffer,
408/// which exists only at the C ABI.
409pub fn webp_free_dec_buffer(buffer: &mut WebPDecBuffer<'_>) {
410    if let PlaneStorage::Internal(memory) = &mut buffer.storage {
411        *memory = Vec::new();
412    }
413}
414
415// upstream: src/dec/buffer_dec.c WebPCopyDecBuffer
416/// Copies `src` into `dst`, making sure `dst` does not own the memory, which
417/// `src` still holds. No pixels are copied: `dst` gets a shared view of every
418/// region of `src`, with the same plane offsets, where C copies the pointers
419/// and marks `dst` as external. C accepts `NULL` buffers, which exist only at
420/// the C ABI.
421pub fn webp_copy_dec_buffer<'s>(src: &'s WebPDecBuffer<'_>, dst: &mut WebPDecBuffer<'s>) {
422    dst.colorspace = src.colorspace;
423    dst.width = src.width;
424    dst.height = src.height;
425    // C copies `is_external_memory`; the view is not external storage, so the
426    // flag that only external storage carries is false.
427    dst.slow_memory = false;
428    dst.u = src.u;
429    dst.pad = src.pad;
430    dst.storage = PlaneStorage::Shared(match &src.storage {
431        PlaneStorage::Internal(memory) => vec![memory.as_slice()],
432        PlaneStorage::External(slices) => slices.iter().map(|slice| &**slice).collect(),
433        PlaneStorage::Shared(slices) => slices.clone(),
434    });
435}
436
437// upstream: src/dec/buffer_dec.c WebPGrabDecBuffer
438/// Copies and transfers ownership from `src` to `dst` (beware of the parameter
439/// order). `dst` receives the storage of `src`. In C, `src` keeps pointers to
440/// the memory, now marked external; safe Rust cannot keep a second view of
441/// memory that `dst` owns or borrows mutably, so `src` keeps its plane
442/// descriptions with an empty storage of the same kind. C accepts `NULL`
443/// buffers, which exist only at the C ABI.
444pub fn webp_grab_dec_buffer<'a>(src: &mut WebPDecBuffer<'a>, dst: &mut WebPDecBuffer<'a>) {
445    dst.colorspace = src.colorspace;
446    dst.width = src.width;
447    dst.height = src.height;
448    dst.slow_memory = src.slow_memory;
449    dst.u = src.u;
450    dst.pad = src.pad;
451    let empty = match &src.storage {
452        PlaneStorage::Internal(_) => PlaneStorage::Internal(Vec::new()),
453        PlaneStorage::External(_) => PlaneStorage::External(Vec::new()),
454        PlaneStorage::Shared(_) => PlaneStorage::Shared(Vec::new()),
455    };
456    dst.storage = std::mem::replace(&mut src.storage, empty);
457}
458
459/// The samples of `plane` for reading.
460///
461/// # Panics
462///
463/// Panics when the region does not exist.
464fn region<'b>(storage: &'b PlaneStorage<'_, u8>, plane: PlaneOffset) -> &'b [u8] {
465    storage
466        .region(plane.region)
467        .expect("the plane's region exists")
468}
469
470/// The samples of `plane` for writing.
471///
472/// # Panics
473///
474/// Panics when the region does not exist or is shared.
475fn region_mut<'b>(storage: &'b mut PlaneStorage<'_, u8>, plane: PlaneOffset) -> &'b mut [u8] {
476    storage
477        .region_mut(plane.region)
478        .expect("the plane's region exists")
479}
480
481/// One plane copy of `WebPCopyDecBufferPixels`.
482#[expect(
483    clippy::too_many_arguments,
484    reason = "the arguments of WebPCopyPlane with the two storages"
485)]
486fn copy_plane(
487    src: &PlaneStorage<'_, u8>,
488    src_plane: PlaneOffset,
489    src_stride: i32,
490    dst: &mut PlaneStorage<'_, u8>,
491    dst_plane: PlaneOffset,
492    dst_stride: i32,
493    width: i32,
494    height: i32,
495) {
496    webp_copy_plane(
497        region(src, src_plane),
498        src_plane.offset,
499        src_stride,
500        region_mut(dst, dst_plane),
501        dst_plane.offset,
502        dst_stride,
503        width,
504        height,
505    );
506}
507
508// upstream: src/dec/buffer_dec.c WebPCopyDecBufferPixels
509/// Copies the pixels of `src_buf` into the preallocated `dst_buf`.
510///
511/// # Errors
512///
513/// Returns `VP8_STATUS_INVALID_PARAM` if `dst_buf` is not set up correctly for
514/// the copy; its width and height are set to those of `src_buf` first, as in C.
515///
516/// # Panics
517///
518/// Debug builds panic when the colorspaces differ, as C asserts. A plane of
519/// `src_buf` outside its region panics, where C would read outside the buffer.
520pub fn webp_copy_dec_buffer_pixels(
521    src_buf: &WebPDecBuffer<'_>,
522    dst_buf: &mut WebPDecBuffer<'_>,
523) -> Result<(), VP8StatusCode> {
524    debug_assert_eq!(src_buf.colorspace, dst_buf.colorspace);
525
526    dst_buf.width = src_buf.width;
527    dst_buf.height = src_buf.height;
528    if check_dec_buffer(dst_buf).is_err() {
529        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
530    }
531    match (&src_buf.u, &dst_buf.u) {
532        (WebPDecBufferPlanes::RGBA(src), WebPDecBufferPlanes::RGBA(dst))
533            if webp_is_rgb_mode(src_buf.colorspace) =>
534        {
535            let (src, dst) = (*src, *dst);
536            copy_plane(
537                &src_buf.storage,
538                src.rgba,
539                src.stride,
540                &mut dst_buf.storage,
541                dst.rgba,
542                dst.stride,
543                src_buf.width * i32::from(mode_bpp(src_buf.colorspace)),
544                src_buf.height,
545            );
546        }
547        (WebPDecBufferPlanes::YUVA(src), WebPDecBufferPlanes::YUVA(dst))
548            if !webp_is_rgb_mode(src_buf.colorspace) =>
549        {
550            let (src, dst) = (*src, *dst);
551            copy_plane(
552                &src_buf.storage,
553                src.y,
554                src.y_stride,
555                &mut dst_buf.storage,
556                dst.y,
557                dst.y_stride,
558                src_buf.width,
559                src_buf.height,
560            );
561            copy_plane(
562                &src_buf.storage,
563                src.u,
564                src.u_stride,
565                &mut dst_buf.storage,
566                dst.u,
567                dst.u_stride,
568                (src_buf.width + 1) / 2,
569                (src_buf.height + 1) / 2,
570            );
571            copy_plane(
572                &src_buf.storage,
573                src.v,
574                src.v_stride,
575                &mut dst_buf.storage,
576                dst.v,
577                dst.v_stride,
578                (src_buf.width + 1) / 2,
579                (src_buf.height + 1) / 2,
580            );
581            if webp_is_alpha_mode(src_buf.colorspace) {
582                copy_plane(
583                    &src_buf.storage,
584                    src.a.expect("a YUVA buffer has an alpha plane"),
585                    src.a_stride,
586                    &mut dst_buf.storage,
587                    dst.a.expect("the checked YUVA buffer has an alpha plane"),
588                    dst.a_stride,
589                    src_buf.width,
590                    src_buf.height,
591                );
592            }
593        }
594        _ => panic!("the source buffer's member matches its colorspace"),
595    }
596    Ok(())
597}
598
599// upstream: src/dec/buffer_dec.c WebPAvoidSlowMemory
600/// Returns true if decoding will be slow with the current configuration and
601/// bitstream features: slow external memory, a premultiplied colorspace and an
602/// image with alpha.
603#[must_use]
604pub fn webp_avoid_slow_memory(
605    output: &WebPDecBuffer<'_>,
606    features: Option<&WebPBitstreamFeatures>,
607) -> bool {
608    // C: output->is_external_memory >= 2.
609    output.slow_memory
610        && webp_is_premultiplied_mode(output.colorspace)
611        && features.is_some_and(|features| features.has_alpha != 0)
612}