1use 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
66const MODE_BPP: [u8; WEBP_CSP_MODE::MODE_LAST.0 as usize] = [
72 3, 4, 3, 4, 4, 2, 2, 4, 4, 4, 2, 1, 1,
75];
76
77fn mode_bpp(mode: WEBP_CSP_MODE) -> u8 {
79 MODE_BPP[mode.0 as usize]
80}
81
82#[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
92fn colorspace_int(mode: WEBP_CSP_MODE) -> i32 {
94 mode.0.cast_signed()
95}
96
97fn 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
107fn to_u64(value: i32) -> u64 {
109 i64::from(value).cast_unsigned()
110}
111
112#[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
123fn 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 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; }
161 } else {
162 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; }
173 }
174 if ok {
175 Ok(())
176 } else {
177 Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM)
178 }
179}
180
181#[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 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 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 buffer.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
232 rgba: plane(0),
233 stride,
234 size: size as usize,
235 });
236 } else {
237 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
266fn 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
280pub 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
317pub 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 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); }
353 width = cw;
354 height = ch;
355 }
356
357 if options.use_scaling != 0 {
358 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 allocate_buffer(buffer)?;
378
379 if options.is_some_and(|options| options.flip != 0) {
381 webp_flip_buffer(buffer)?;
382 }
383 Ok(())
384}
385
386#[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; }
400 *buffer = WebPDecBuffer::default();
401 true
402}
403
404pub fn webp_free_dec_buffer(buffer: &mut WebPDecBuffer<'_>) {
410 if let PlaneStorage::Internal(memory) = &mut buffer.storage {
411 *memory = Vec::new();
412 }
413}
414
415pub 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 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
437pub 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
459fn 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
470fn 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#[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
508pub 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#[must_use]
604pub fn webp_avoid_slow_memory(
605 output: &WebPDecBuffer<'_>,
606 features: Option<&WebPBitstreamFeatures>,
607) -> bool {
608 output.slow_memory
610 && webp_is_premultiplied_mode(output.colorspace)
611 && features.is_some_and(|features| features.has_alpha != 0)
612}