Skip to main content

libsharpyuv_core/
sharpyuv.rs

1// libwebp v1.6.0, sharpyuv/sharpyuv.c:
2//
3// Copyright 2022 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// Sharp RGB to YUV conversion.
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16// libwebp v1.6.0, sharpyuv/sharpyuv.h:
17//
18// Copyright 2022 Google Inc. All Rights Reserved.
19//
20// Use of this source code is governed by a BSD-style license
21// that can be found in the COPYING file in the root of the source
22// tree. An additional intellectual property rights grant can be found
23// in the file PATENTS. All contributing project authors may
24// be found in the AUTHORS file in the root of the source tree.
25// -----------------------------------------------------------------------------
26//
27// Sharp RGB to YUV conversion.
28
29//! Translation of `sharpyuv/sharpyuv.c` and `sharpyuv/sharpyuv.h` from libwebp v1.6.0.
30//!
31//! Work package: WP5 (`SharpYUV`).
32//!
33//! Pointers into the caller's buffers become slices with a byte offset of their
34//! first sample (ADR 0003). A C `void*` sample buffer is a byte slice: 8-bit
35//! samples are one byte, and samples of 10, 12 or 16 bits are two native-endian
36//! bytes at the byte positions that the C code's `uint16_t` indexing addresses.
37//! Strides and steps keep their C type, in bytes, and rows are addressed from the
38//! offset with a checked signed sum.
39//!
40//! `SharpYuvGetCPUInfo` is translated in `sharpyuv_cpu.rs`. `SharpYuvInit` is not
41//! (see `# Representation`, item 1). Its argument replaces the CPU-information
42//! pointer, which ADR 0003 leaves to the ABI module that exports the pointer, and
43//! its gamma-table work is already done on first use here. The conversion
44//! functions below do not call `SharpYuvInit`, because nothing in the Rust
45//! conversion depends on it: the dispatch functions are direct calls and the gamma
46//! tables are computed on first use.
47//!
48//! # Representation
49//!
50//! 1. **Dispatch and init-once state.** Dispatch pointers are plain functions
51//!    over the portable `_c` implementations (ADR 0003). The functions that
52//!    only assign pointers are absent: `SharpYuvInitDsp`, and the pointer and
53//!    mutex state of `SharpYuvInit`. The runtime selection of the SSE2 and NEON
54//!    variants belongs to the SIMD modules (ADR 0008); see item 1 of
55//!    `# Deviations from upstream`.
56//!    - `SharpYuvInit` stays absent. Forcing the gamma tables is the only part
57//!      the Rust code can keep, and the Rust gamma tables already compute on
58//!      first use. The rest of the function replaces the C pointer
59//!      `SharpYuvGetCPUInfo` with the caller's argument. ADR 0003 gives that
60//!      pointer no Rust state: the query is a function, and the ABI module that
61//!      exports the pointer owns any override, which is the rule ADR 0003
62//!      states for `VP8GetCPUInfo`. Dropping the argument would change what
63//!      `SharpYuvGetCPUInfo` answers after `SharpYuvInit(f)` once the SIMD
64//!      variants consult the query, so the function cannot be translated
65//!      faithfully. No `SharpYUV` C ABI is planned (ADR 0004).
66//!    - `sharpyuv_cpu.rs` translates `SharpYuvGetCPUInfo` as a function with
67//!      that name that calls `vp8_get_cpu_info`, with the `VP8CPUInfo`
68//!      signature. The C file is the re-compilation of `cpu.c` under another
69//!      name, so the answers are the same query. The NULL pointer of the
70//!      reference configuration is item 1 of `# Deviations from upstream` in
71//!      `src/sharpyuv/sharpyuv_cpu.rs`.
72//!
73//! # Deviations from upstream
74//!
75//! Changes of representation that the ADRs allow, or behavior that the Rust
76//! side cannot reproduce exactly. Each records the reason.
77//!
78//! 1. **No `SharpYuvInit` call and no dispatch initialization.** C conversions
79//!    call `SharpYuvInit`, which assigns the dispatch pointers, computes the
80//!    gamma tables and stores the CPU-information function. In Rust the
81//!    dispatch functions are direct calls (ADR 0003), the tables are `LazyLock`
82//!    statics computed on first use. The ported SIMD dispatch (ADR 0008)
83//!    selects kernels independently of `SharpYUV` C initialization; the public
84//!    Rust API does not implement its callback override.
85//! 2. **Negative strides and steps.** Rows and pixels are addressed with a
86//!    checked signed sum from the origin, so a flipped plane works as in C when
87//!    the origin is its last row or pixel (tested, groups `flipped-*`). A row
88//!    that would start before the slice panics, where C reads memory before the
89//!    buffer, which C leaves undefined.
90//! 3. **Predicates return `bool`.** `SharpYuvConvert` and
91//!    `SharpYuvConvertWithOptions` return `bool` in place of `int` 0 and 1
92//!    (ADR 0003, predicate rule), and `SharpYuvOptionsInitInternal` returns an
93//!    `Option`. `SharpYuvGetVersion` keeps its `i32`.
94//! 4. **Integer width of sizes.** Buffer sizes are computed in `usize` and
95//!    `u64`, where the C code multiplies `int` values (`w * 3` and similar)
96//!    that can overflow for widths near `INT_MAX`. The inventory of
97//!    `tests/wp5_convert.rs` has no such size; the allocation fails in both
98//!    (item 3 of `# Checks not applicable` in `tests/wp5_convert.rs`).
99//! 5. **Integer overflow of `RGBToYUVComponent`.** The C `int` products are
100//!    undefined when they overflow; the Rust arithmetic panics in the dev and
101//!    `checked` profiles. No input in the inventory or the seeded cases
102//!    overflows, which the `checked` runs confirm.
103
104use std::mem::size_of;
105
106use super::sharpyuv_dsp::{sharp_yuv_filter_row, sharp_yuv_update_rgb, sharp_yuv_update_y};
107use super::sharpyuv_gamma::GammaContext;
108
109/// Sample access supplied by the caller. The C adapter owns its raw-pointer
110/// safety contract; the WebP adapter checks all access through Rust slices.
111pub trait SampleAccess {
112    fn read(&self, channel: usize, row: usize, column: usize, bit_depth: i32) -> u16;
113    fn write(&mut self, plane: usize, row: usize, column: usize, value: u16, bit_depth: i32);
114}
115
116/// The seven scratch allocations in their original order. Callers own their
117/// allocation and failure policy; conversion only sees initialized storage.
118pub struct Scratch<'a> {
119    pub tmp_buffer: &'a mut [u16],
120    pub best_y_base: &'a mut [u16],
121    pub target_y_base: &'a mut [u16],
122    pub best_rgb_y: &'a mut [u16],
123    pub best_uv_base: &'a mut [i16],
124    pub target_uv_base: &'a mut [i16],
125    pub best_rgb_uv: &'a mut [i16],
126}
127
128/// DSP policy is selected at each package boundary. The AVIF C ABI keeps its
129/// independent callback state; WebP retains its own runtime SIMD dispatch.
130#[derive(Clone, Copy)]
131pub struct Dsp {
132    pub update_y: UpdateY,
133    pub update_rgb: fn(&[i16], &[i16], &mut [i16], i32),
134    pub filter_row: FilterRow,
135}
136
137pub type UpdateY = fn(&[u16], &[u16], &mut [u16], i32, i32) -> u64;
138pub type FilterRow = fn(&[i16], &[i16], i32, &[u16], &mut [u16], i32);
139
140impl Dsp {
141    pub const SCALAR: Self = Self {
142        update_y: sharp_yuv_update_y,
143        update_rgb: sharp_yuv_update_rgb,
144        filter_row: sharp_yuv_filter_row,
145    };
146}
147
148// upstream: sharpyuv/sharpyuv.h SHARPYUV_VERSION_MAJOR
149pub const SHARPYUV_VERSION_MAJOR: i32 = 0;
150// upstream: sharpyuv/sharpyuv.h SHARPYUV_VERSION_MINOR
151pub const SHARPYUV_VERSION_MINOR: i32 = 4;
152// upstream: sharpyuv/sharpyuv.h SHARPYUV_VERSION_PATCH
153pub const SHARPYUV_VERSION_PATCH: i32 = 2;
154
155// upstream: sharpyuv/sharpyuv.h SHARPYUV_MAKE_VERSION
156#[must_use]
157pub const fn sharpyuv_make_version(major: i32, minor: i32, patch: i32) -> i32 {
158    (major << 24) | (minor << 16) | patch
159}
160
161// upstream: sharpyuv/sharpyuv.h SHARPYUV_VERSION
162pub const SHARPYUV_VERSION: i32 = sharpyuv_make_version(
163    SHARPYUV_VERSION_MAJOR,
164    SHARPYUV_VERSION_MINOR,
165    SHARPYUV_VERSION_PATCH,
166);
167
168// upstream: sharpyuv/sharpyuv.c SharpYuvGetVersion
169#[must_use]
170pub const fn sharp_yuv_get_version() -> i32 {
171    SHARPYUV_VERSION
172}
173
174// upstream: sharpyuv/sharpyuv.h SharpYuvConversionMatrix
175/// RGB to YUV conversion matrix, in 16 bit fixed point.
176///
177/// `y_ = rgb_to_y[0] * r + rgb_to_y[1] * g + rgb_to_y[2] * b + rgb_to_y[3]`, and
178/// likewise for `u_` and `v_`; the values are then divided by `1 << 16` and rounded.
179#[repr(C)]
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
181pub struct SharpYuvConversionMatrix {
182    /// Coefficients and offset of the Y component.
183    pub rgb_to_y: [i32; 4],
184    /// Coefficients and offset of the U component.
185    pub rgb_to_u: [i32; 4],
186    /// Coefficients and offset of the V component.
187    pub rgb_to_v: [i32; 4],
188}
189
190// upstream: sharpyuv/sharpyuv.h SharpYuvTransferFunctionType
191/// A transfer function as defined in H.273; a C enumeration stored as its `unsigned int`.
192#[repr(transparent)]
193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub struct SharpYuvTransferFunctionType(pub u32);
195
196impl SharpYuvTransferFunctionType {
197    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt709
198    #[expect(non_upper_case_globals, reason = "C enumerator name")]
199    pub const kSharpYuvTransferFunctionBt709: Self = Self(1);
200    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt470M
201    #[expect(non_upper_case_globals, reason = "C enumerator name")]
202    pub const kSharpYuvTransferFunctionBt470M: Self = Self(4);
203    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt470Bg
204    #[expect(non_upper_case_globals, reason = "C enumerator name")]
205    pub const kSharpYuvTransferFunctionBt470Bg: Self = Self(5);
206    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt601
207    #[expect(non_upper_case_globals, reason = "C enumerator name")]
208    pub const kSharpYuvTransferFunctionBt601: Self = Self(6);
209    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionSmpte240
210    #[expect(non_upper_case_globals, reason = "C enumerator name")]
211    pub const kSharpYuvTransferFunctionSmpte240: Self = Self(7);
212    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionLinear
213    #[expect(non_upper_case_globals, reason = "C enumerator name")]
214    pub const kSharpYuvTransferFunctionLinear: Self = Self(8);
215    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionLog100
216    #[expect(non_upper_case_globals, reason = "C enumerator name")]
217    pub const kSharpYuvTransferFunctionLog100: Self = Self(9);
218    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionLog100_Sqrt10
219    #[expect(non_upper_case_globals, reason = "C enumerator name")]
220    pub const kSharpYuvTransferFunctionLog100_Sqrt10: Self = Self(10);
221    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionIec61966
222    #[expect(non_upper_case_globals, reason = "C enumerator name")]
223    pub const kSharpYuvTransferFunctionIec61966: Self = Self(11);
224    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt1361
225    #[expect(non_upper_case_globals, reason = "C enumerator name")]
226    pub const kSharpYuvTransferFunctionBt1361: Self = Self(12);
227    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionSrgb
228    #[expect(non_upper_case_globals, reason = "C enumerator name")]
229    pub const kSharpYuvTransferFunctionSrgb: Self = Self(13);
230    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt2020_10Bit
231    #[expect(non_upper_case_globals, reason = "C enumerator name")]
232    pub const kSharpYuvTransferFunctionBt2020_10Bit: Self = Self(14);
233    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionBt2020_12Bit
234    #[expect(non_upper_case_globals, reason = "C enumerator name")]
235    pub const kSharpYuvTransferFunctionBt2020_12Bit: Self = Self(15);
236    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionSmpte2084
237    #[expect(non_upper_case_globals, reason = "C enumerator name")]
238    pub const kSharpYuvTransferFunctionSmpte2084: Self = Self(16);
239    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionSmpte428
240    #[expect(non_upper_case_globals, reason = "C enumerator name")]
241    pub const kSharpYuvTransferFunctionSmpte428: Self = Self(17);
242    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionHlg
243    #[expect(non_upper_case_globals, reason = "C enumerator name")]
244    pub const kSharpYuvTransferFunctionHlg: Self = Self(18);
245    // upstream: sharpyuv/sharpyuv.h kSharpYuvTransferFunctionNum
246    /// The number of transfer functions; not a transfer function.
247    #[expect(non_upper_case_globals, reason = "C enumerator name")]
248    pub const kSharpYuvTransferFunctionNum: Self = Self(19);
249}
250
251// upstream: sharpyuv/sharpyuv.h SharpYuvOptions
252/// Conversion options: the matrix, which the caller owns, and the transfer function.
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub struct SharpYuvOptions<'a> {
255    /// The RGB to YUV matrix; it cannot be absent.
256    pub yuv_matrix: &'a SharpYuvConversionMatrix,
257    /// The transfer function of the RGB samples.
258    pub transfer_type: SharpYuvTransferFunctionType,
259}
260
261// upstream: sharpyuv/sharpyuv.c kNumIterations
262const NUM_ITERATIONS: u32 = 4;
263
264// upstream: sharpyuv/sharpyuv.c YUV_FIX
265const YUV_FIX: i32 = 16;
266
267// upstream: sharpyuv/sharpyuv.c kYuvHalf
268const YUV_HALF: i32 = 1 << (YUV_FIX - 1);
269
270// upstream: sharpyuv/sharpyuv.c kMaxBitDepth
271const MAX_BIT_DEPTH: i32 = 14;
272
273// upstream: sharpyuv/sharpyuv.c GetPrecisionShift
274// Returns the precision shift to use based on the input rgb_bit_depth.
275fn get_precision_shift(rgb_bit_depth: i32) -> i32 {
276    // Try to add 2 bits of precision if it fits in kMaxBitDepth. Otherwise remove
277    // bits if needed.
278    if rgb_bit_depth + 2 <= MAX_BIT_DEPTH {
279        2
280    } else {
281        MAX_BIT_DEPTH - rgb_bit_depth
282    }
283}
284
285// upstream: sharpyuv/sharpyuv.c clip_8b
286#[expect(
287    clippy::cast_possible_truncation,
288    clippy::cast_sign_loss,
289    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
290)]
291fn clip_8b(v: i16) -> u8 {
292    if i32::from(v) & !0xff == 0 {
293        v as u8
294    } else if v < 0 {
295        0
296    } else {
297        255
298    }
299}
300
301// upstream: sharpyuv/sharpyuv.c clip
302#[expect(
303    clippy::cast_possible_truncation,
304    clippy::cast_sign_loss,
305    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
306)]
307fn clip(v: i16, max: i32) -> u16 {
308    if v < 0 {
309        0
310    } else if i32::from(v) > max {
311        max as u16
312    } else {
313        v as u16
314    }
315}
316
317// upstream: sharpyuv/sharpyuv.c clip_bit_depth
318#[expect(
319    clippy::cast_possible_truncation,
320    clippy::cast_sign_loss,
321    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
322)]
323fn clip_bit_depth(y: i32, bit_depth: i32) -> u16 {
324    let max = (1 << bit_depth) - 1;
325    if y & !max == 0 {
326        y as u16
327    } else if y < 0 {
328        0
329    } else {
330        max as u16
331    }
332}
333
334// upstream: sharpyuv/sharpyuv.c RGBToGray
335#[expect(
336    clippy::cast_possible_truncation,
337    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
338)]
339fn rgb_to_gray(r: i64, g: i64, b: i64) -> i32 {
340    let luma = 13933 * r + 46871 * g + 4732 * b + i64::from(YUV_HALF);
341    (luma >> YUV_FIX) as i32
342}
343
344// upstream: sharpyuv/sharpyuv.c ScaleDown
345fn scale_down(a: u16, b: u16, c: u16, d: u16, rgb_bit_depth: i32, gamma: &GammaContext) -> u32 {
346    let bit_depth = rgb_bit_depth + get_precision_shift(rgb_bit_depth);
347    let a_lin = gamma.to_linear(a, bit_depth);
348    let b_lin = gamma.to_linear(b, bit_depth);
349    let c_lin = gamma.to_linear(c, bit_depth);
350    let d_lin = gamma.to_linear(d, bit_depth);
351    u32::from(gamma.to_gamma((a_lin + b_lin + c_lin + d_lin + 2) >> 2, bit_depth))
352}
353
354// upstream: sharpyuv/sharpyuv.c UpdateW
355// `src` holds three rows of `w` samples (R, G, B); `dst` receives one row.
356#[expect(
357    clippy::cast_sign_loss,
358    clippy::many_single_char_names,
359    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
360)]
361fn update_w(src: &[u16], dst: &mut [u16], w: usize, rgb_bit_depth: i32, gamma: &GammaContext) {
362    let bit_depth = rgb_bit_depth + get_precision_shift(rgb_bit_depth);
363    for (i, out) in dst[..w].iter_mut().enumerate() {
364        let r = gamma.to_linear(src[i], bit_depth);
365        let g = gamma.to_linear(src[w + i], bit_depth);
366        let b = gamma.to_linear(src[2 * w + i], bit_depth);
367        let y = rgb_to_gray(i64::from(r), i64::from(g), i64::from(b));
368        *out = gamma.to_gamma(y as u32, bit_depth);
369    }
370}
371
372// upstream: sharpyuv/sharpyuv.c UpdateChroma
373// `src1` and `src2` hold the R, G and B rows of two luma rows; `dst` receives the
374// three chroma differences of `uv_w` pixels.
375#[expect(
376    clippy::cast_possible_truncation,
377    clippy::cast_possible_wrap,
378    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
379)]
380fn update_chroma(
381    src1: &[u16],
382    src2: &[u16],
383    dst: &mut [i16],
384    uv_w: usize,
385    rgb_bit_depth: i32,
386    gamma: &GammaContext,
387) {
388    for i in 0..uv_w {
389        let base = 2 * i;
390        let r = scale_down(
391            src1[base],
392            src1[base + 1],
393            src2[base],
394            src2[base + 1],
395            rgb_bit_depth,
396            gamma,
397        ) as i32;
398        let g = scale_down(
399            src1[base + 2 * uv_w],
400            src1[base + 2 * uv_w + 1],
401            src2[base + 2 * uv_w],
402            src2[base + 2 * uv_w + 1],
403            rgb_bit_depth,
404            gamma,
405        ) as i32;
406        let b = scale_down(
407            src1[base + 4 * uv_w],
408            src1[base + 4 * uv_w + 1],
409            src2[base + 4 * uv_w],
410            src2[base + 4 * uv_w + 1],
411            rgb_bit_depth,
412            gamma,
413        ) as i32;
414        let w_gray = rgb_to_gray(i64::from(r), i64::from(g), i64::from(b));
415        dst[i] = (r - w_gray) as i16;
416        dst[i + uv_w] = (g - w_gray) as i16;
417        dst[i + 2 * uv_w] = (b - w_gray) as i16;
418    }
419}
420
421// upstream: sharpyuv/sharpyuv.c StoreGray
422#[expect(
423    clippy::cast_possible_truncation,
424    clippy::cast_sign_loss,
425    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
426)]
427fn store_gray(rgb: &[u16], y: &mut [u16], w: usize) {
428    for (i, out) in y[..w].iter_mut().enumerate() {
429        *out = rgb_to_gray(
430            i64::from(rgb[i]),
431            i64::from(rgb[w + i]),
432            i64::from(rgb[2 * w + i]),
433        ) as u16;
434    }
435}
436
437// upstream: sharpyuv/sharpyuv.c Filter2
438fn filter2(a: i32, b: i32, w0: i32, bit_depth: i32) -> u16 {
439    let v0 = (a * 3 + b + 2) >> 2;
440    clip_bit_depth(v0 + w0, bit_depth)
441}
442
443// upstream: sharpyuv/sharpyuv.c Shift
444fn shift(v: i32, shift_amount: i32) -> i32 {
445    if shift_amount >= 0 {
446        v << shift_amount
447    } else {
448        v >> -shift_amount
449    }
450}
451
452// The byte index of sample `count` of a row that is `step` bytes apart, from
453// `origin`. A negative result would address memory before the buffer, which the
454// C code may do with a negative stride; here it panics, as an index does.
455#[expect(
456    clippy::cast_possible_wrap,
457    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
458)]
459fn sample_index(origin: usize, count: usize, step: i32) -> usize {
460    usize::try_from(origin as isize + count as isize * step as isize)
461        .expect("sample address before the start of the buffer")
462}
463
464// Reads sample `index` of an input plane: one byte for 8 bits, two native-endian
465// bytes otherwise, as the C code reads `uint8_t` and `uint16_t` samples.
466fn read_sample(buf: &[u8], index: usize, bit_depth: i32) -> u16 {
467    if bit_depth == 8 {
468        u16::from(buf[index])
469    } else {
470        u16::from_ne_bytes([buf[index], buf[index + 1]])
471    }
472}
473
474// Writes `value` at byte `index` of an output plane: one byte for 8 bits, two
475// native-endian bytes otherwise.
476#[expect(
477    clippy::cast_possible_truncation,
478    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
479)]
480fn write_sample(buf: &mut [u8], index: usize, value: u16, bit_depth: i32) {
481    if bit_depth <= 8 {
482        buf[index] = value as u8;
483    } else {
484        buf[index..index + 2].copy_from_slice(&value.to_ne_bytes());
485    }
486}
487
488struct SliceAccess<'a> {
489    input: [(&'a [u8], usize); 3],
490    output: [(&'a mut [u8], usize, i32); 3],
491    rgb_step: i32,
492    rgb_stride: i32,
493}
494
495impl SampleAccess for SliceAccess<'_> {
496    fn read(&self, channel: usize, row: usize, column: usize, bit_depth: i32) -> u16 {
497        let (bytes, origin) = self.input[channel];
498        let index = sample_index(
499            sample_index(origin, row, self.rgb_stride),
500            column,
501            self.rgb_step,
502        );
503        read_sample(bytes, index, bit_depth)
504    }
505
506    fn write(&mut self, plane: usize, row: usize, column: usize, value: u16, bit_depth: i32) {
507        let (bytes, origin, stride) = &mut self.output[plane];
508        let unit = if bit_depth <= 8 { 1 } else { 2 };
509        let index = sample_index(*origin, row, *stride) + column * unit;
510        write_sample(bytes, index, value, bit_depth);
511    }
512}
513
514// upstream: sharpyuv/sharpyuv.c ImportOneRow
515#[expect(
516    clippy::cast_possible_truncation,
517    clippy::cast_sign_loss,
518    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
519)]
520fn import_one_row(
521    access: &impl SampleAccess,
522    row: usize,
523    rgb_bit_depth: i32,
524    pic_width: usize,
525    dst: &mut [u16],
526    w: usize,
527) {
528    let shift_amount = get_precision_shift(rgb_bit_depth);
529    for i in 0..pic_width {
530        let r = access.read(0, row, i, rgb_bit_depth);
531        let g = access.read(1, row, i, rgb_bit_depth);
532        let b = access.read(2, row, i, rgb_bit_depth);
533        dst[i] = shift(i32::from(r), shift_amount) as u16;
534        dst[i + w] = shift(i32::from(g), shift_amount) as u16;
535        dst[i + 2 * w] = shift(i32::from(b), shift_amount) as u16;
536    }
537    if pic_width & 1 == 1 {
538        // replicate rightmost pixel
539        dst[pic_width] = dst[pic_width - 1];
540        dst[pic_width + w] = dst[pic_width + w - 1];
541        dst[pic_width + 2 * w] = dst[pic_width + 2 * w - 1];
542    }
543}
544
545// upstream: sharpyuv/sharpyuv.c InterpolateTwoRows
546// `prev_uv`, `cur_uv` and `next_uv` are three chroma rows; `out1` and `out2` hold
547// the R, G and B rows of the two luma rows that they interpolate.
548#[expect(clippy::too_many_arguments, reason = "mirrors the C function")]
549#[expect(
550    clippy::cast_possible_truncation,
551    clippy::cast_possible_wrap,
552    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
553)]
554fn interpolate_two_rows(
555    best_y: &[u16],
556    prev_uv: &[i16],
557    cur_uv: &[i16],
558    next_uv: &[i16],
559    w: usize,
560    out1: &mut [u16],
561    out2: &mut [u16],
562    rgb_bit_depth: i32,
563    dsp: Dsp,
564) {
565    let uv_w = w >> 1;
566    let len = (w - 1) >> 1; // length to filter
567    let bit_depth = rgb_bit_depth + get_precision_shift(rgb_bit_depth);
568    // process each R/G/B segments in turn
569    for k in 0..3 {
570        let p = k * uv_w;
571        let o = k * w;
572        // special boundary case for i==0
573        out1[o] = filter2(
574            i32::from(cur_uv[p]),
575            i32::from(prev_uv[p]),
576            i32::from(best_y[0]),
577            bit_depth,
578        );
579        out2[o] = filter2(
580            i32::from(cur_uv[p]),
581            i32::from(next_uv[p]),
582            i32::from(best_y[w]),
583            bit_depth,
584        );
585
586        (dsp.filter_row)(
587            &cur_uv[p..],
588            &prev_uv[p..],
589            len as i32,
590            &best_y[1..],
591            &mut out1[o + 1..],
592            bit_depth,
593        );
594        (dsp.filter_row)(
595            &cur_uv[p..],
596            &next_uv[p..],
597            len as i32,
598            &best_y[w + 1..],
599            &mut out2[o + 1..],
600            bit_depth,
601        );
602
603        // special boundary case for i == w - 1 when w is even
604        if w & 1 == 0 {
605            out1[o + w - 1] = filter2(
606                i32::from(cur_uv[p + uv_w - 1]),
607                i32::from(prev_uv[p + uv_w - 1]),
608                i32::from(best_y[w - 1]),
609                bit_depth,
610            );
611            out2[o + w - 1] = filter2(
612                i32::from(cur_uv[p + uv_w - 1]),
613                i32::from(next_uv[p + uv_w - 1]),
614                i32::from(best_y[w - 1 + w]),
615                bit_depth,
616            );
617        }
618    }
619}
620
621// upstream: sharpyuv/sharpyuv.c RGBToYUVComponent
622fn rgb_to_yuv_component(r: i32, g: i32, b: i32, coeffs: &[i32; 4], sfix: i32) -> i32 {
623    let srounder = 1 << (YUV_FIX + sfix - 1);
624    let luma = coeffs[0] * r + coeffs[1] * g + coeffs[2] * b + coeffs[3] + srounder;
625    luma >> (YUV_FIX + sfix)
626}
627
628// upstream: sharpyuv/sharpyuv.c ConvertWRGBToYUV
629#[expect(clippy::too_many_arguments, reason = "mirrors the C function")]
630#[expect(
631    clippy::cast_possible_truncation,
632    clippy::many_single_char_names,
633    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
634)]
635fn convert_wrgb_to_yuv(
636    best_y: &[u16],
637    best_uv: &[i16],
638    access: &mut impl SampleAccess,
639    rgb_bit_depth: i32,
640    yuv_bit_depth: i32,
641    width: usize,
642    height: usize,
643    yuv_matrix: &SharpYuvConversionMatrix,
644) -> bool {
645    let w = (width + 1) & !1;
646    let h = (height + 1) & !1;
647    let uv_w = w >> 1;
648    let uv_h = h >> 1;
649    let sfix = get_precision_shift(rgb_bit_depth);
650    let yuv_max = (1 << yuv_bit_depth) - 1;
651
652    let mut best_uv_index = 0_usize;
653    for j in 0..height {
654        for i in 0..width {
655            let off = i >> 1;
656            let w_value = i32::from(best_y[j * w + i]);
657            let r = i32::from(best_uv[best_uv_index + off]) + w_value;
658            let g = i32::from(best_uv[best_uv_index + off + uv_w]) + w_value;
659            let b = i32::from(best_uv[best_uv_index + off + 2 * uv_w]) + w_value;
660            let y = rgb_to_yuv_component(r, g, b, &yuv_matrix.rgb_to_y, sfix);
661            let value = if yuv_bit_depth <= 8 {
662                u16::from(clip_8b(y as i16))
663            } else {
664                clip(y as i16, yuv_max)
665            };
666            access.write(0, j, i, value, yuv_bit_depth);
667        }
668        best_uv_index += (j & 1) * 3 * uv_w;
669    }
670
671    for j in 0..uv_h {
672        let base = j * 3 * uv_w;
673        for i in 0..uv_w {
674            // Note r, g and b values here are off by W, but a constant offset on all
675            // 3 components doesn't change the value of u and v with a YCbCr matrix.
676            let r = i32::from(best_uv[base + i]);
677            let g = i32::from(best_uv[base + i + uv_w]);
678            let b = i32::from(best_uv[base + i + 2 * uv_w]);
679            let u = rgb_to_yuv_component(r, g, b, &yuv_matrix.rgb_to_u, sfix);
680            let v = rgb_to_yuv_component(r, g, b, &yuv_matrix.rgb_to_v, sfix);
681            if yuv_bit_depth <= 8 {
682                access.write(1, j, i, u16::from(clip_8b(u as i16)), yuv_bit_depth);
683                access.write(2, j, i, u16::from(clip_8b(v as i16)), yuv_bit_depth);
684            } else {
685                access.write(1, j, i, clip(u as i16, yuv_max), yuv_bit_depth);
686                access.write(2, j, i, clip(v as i16, yuv_max), yuv_bit_depth);
687            }
688        }
689    }
690    true
691}
692
693// upstream: sharpyuv/sharpyuv.c SafeMalloc, SAFE_ALLOC
694// Allocates `nmemb` zeroed elements of `T`, or returns `None` when the size does not
695// fit in `size_t` or the allocation is refused. Rust initializes the memory that C
696// leaves uninitialized; the C code never reads it before writing it.
697fn safe_malloc<T: Default + Clone>(nmemb: u64) -> Option<Vec<T>> {
698    let total_size = nmemb.checked_mul(size_of::<T>() as u64)?;
699    usize::try_from(total_size).ok()?;
700    let count = usize::try_from(nmemb).ok()?;
701    let mut buffer = Vec::new();
702    buffer.try_reserve_exact(count).ok()?;
703    buffer.resize(count, T::default());
704    Some(buffer)
705}
706
707// upstream: sharpyuv/sharpyuv.c DoSharpArgbToYuv
708#[expect(clippy::too_many_arguments, reason = "mirrors the C function")]
709#[expect(clippy::too_many_lines, reason = "mirrors the C function")]
710#[expect(
711    clippy::cast_possible_truncation,
712    clippy::cast_possible_wrap,
713    clippy::cast_precision_loss,
714    clippy::cast_sign_loss,
715    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
716)]
717fn do_sharp_argb_to_yuv(
718    access: &mut impl SampleAccess,
719    scratch: Scratch<'_>,
720    dsp: Dsp,
721    rgb_bit_depth: i32,
722    yuv_bit_depth: i32,
723    width: usize,
724    height: usize,
725    yuv_matrix: &SharpYuvConversionMatrix,
726    transfer_type: SharpYuvTransferFunctionType,
727) -> bool {
728    // we expand the right/bottom border if needed
729    let w = (width + 1) & !1;
730    let h = (height + 1) & !1;
731    let uv_w = w >> 1;
732    let uv_h = h >> 1;
733    let y_bit_depth = rgb_bit_depth + get_precision_shift(rgb_bit_depth);
734    let gamma = GammaContext::new(transfer_type);
735    let mut prev_diff_y_sum: u64 = u64::MAX;
736
737    let Scratch {
738        tmp_buffer,
739        best_y_base,
740        target_y_base,
741        best_rgb_y,
742        best_uv_base,
743        target_uv_base,
744        best_rgb_uv,
745    } = scratch;
746    if tmp_buffer.len() < w * 6
747        || best_y_base.len() < w * h
748        || target_y_base.len() < w * h
749        || best_rgb_y.len() < w * 2
750        || best_uv_base.len() < uv_w * 3 * uv_h
751        || target_uv_base.len() < uv_w * 3 * uv_h
752        || best_rgb_uv.len() < uv_w * 3
753    {
754        return false;
755    }
756    let diff_y_threshold = (3.0_f64 * w as f64 * h as f64) as u64;
757
758    // Import RGB samples to W/RGB representation.
759    let mut best_y_index = 0_usize;
760    let mut target_y_index = 0_usize;
761    let mut best_uv_index = 0_usize;
762    let mut target_uv_index = 0_usize;
763    let mut j = 0_usize;
764    while j < height {
765        let is_last_row = j == height - 1;
766        let (src1, src2) = tmp_buffer.split_at_mut(3 * w);
767
768        // prepare two rows of input
769        import_one_row(access, j, rgb_bit_depth, width, src1, w);
770        if is_last_row {
771            src2.copy_from_slice(src1);
772        } else {
773            import_one_row(access, j + 1, rgb_bit_depth, width, src2, w);
774        }
775        store_gray(src1, &mut best_y_base[best_y_index..], w);
776        store_gray(src2, &mut best_y_base[best_y_index + w..], w);
777
778        update_w(
779            src1,
780            &mut target_y_base[target_y_index..],
781            w,
782            rgb_bit_depth,
783            &gamma,
784        );
785        update_w(
786            src2,
787            &mut target_y_base[target_y_index + w..],
788            w,
789            rgb_bit_depth,
790            &gamma,
791        );
792        update_chroma(
793            src1,
794            src2,
795            &mut target_uv_base[target_uv_index..],
796            uv_w,
797            rgb_bit_depth,
798            &gamma,
799        );
800        best_uv_base[best_uv_index..best_uv_index + 3 * uv_w]
801            .copy_from_slice(&target_uv_base[target_uv_index..target_uv_index + 3 * uv_w]);
802        best_y_index += 2 * w;
803        best_uv_index += 3 * uv_w;
804        target_y_index += 2 * w;
805        target_uv_index += 3 * uv_w;
806        j += 2;
807    }
808
809    // Iterate and resolve clipping conflicts.
810    for iter in 0..NUM_ITERATIONS {
811        let mut cur_uv_index = 0_usize;
812        let mut prev_uv_index = 0_usize;
813        let mut diff_y_sum: u64 = 0;
814
815        best_y_index = 0;
816        best_uv_index = 0;
817        target_y_index = 0;
818        target_uv_index = 0;
819        j = 0;
820        loop {
821            let next_uv_index = cur_uv_index + if j + 2 < h { 3 * uv_w } else { 0 };
822            {
823                let (src1, src2) = tmp_buffer.split_at_mut(3 * w);
824                interpolate_two_rows(
825                    &best_y_base[best_y_index..],
826                    &best_uv_base[prev_uv_index..],
827                    &best_uv_base[cur_uv_index..],
828                    &best_uv_base[next_uv_index..],
829                    w,
830                    src1,
831                    src2,
832                    rgb_bit_depth,
833                    dsp,
834                );
835                prev_uv_index = cur_uv_index;
836                cur_uv_index = next_uv_index;
837
838                update_w(src1, &mut best_rgb_y[..w], w, rgb_bit_depth, &gamma);
839                update_w(src2, &mut best_rgb_y[w..2 * w], w, rgb_bit_depth, &gamma);
840                update_chroma(src1, src2, best_rgb_uv, uv_w, rgb_bit_depth, &gamma);
841            }
842
843            // update two rows of Y and one row of RGB
844            diff_y_sum += (dsp.update_y)(
845                &target_y_base[target_y_index..],
846                best_rgb_y,
847                &mut best_y_base[best_y_index..],
848                (2 * w) as i32,
849                y_bit_depth,
850            );
851            (dsp.update_rgb)(
852                &target_uv_base[target_uv_index..],
853                best_rgb_uv,
854                &mut best_uv_base[best_uv_index..],
855                (3 * uv_w) as i32,
856            );
857
858            best_y_index += 2 * w;
859            best_uv_index += 3 * uv_w;
860            target_y_index += 2 * w;
861            target_uv_index += 3 * uv_w;
862            j += 2;
863            if j >= h {
864                break;
865            }
866        }
867        // test exit condition
868        if iter > 0 {
869            if diff_y_sum < diff_y_threshold {
870                break;
871            }
872            if diff_y_sum > prev_diff_y_sum {
873                break;
874            }
875        }
876        prev_diff_y_sum = diff_y_sum;
877    }
878
879    // final reconstruction
880    convert_wrgb_to_yuv(
881        best_y_base,
882        best_uv_base,
883        access,
884        rgb_bit_depth,
885        yuv_bit_depth,
886        width,
887        height,
888        yuv_matrix,
889    )
890}
891
892// upstream: sharpyuv/sharpyuv.h SharpYuvOptionsInitInternal
893/// Returns the options for `yuv_matrix`, or `None` when `version` is not the version
894/// of this library in its major and minor numbers (the C function returns 0 and
895/// leaves `options` unchanged). The NULL checks of the C function are not
896/// representable here.
897#[must_use]
898pub fn sharp_yuv_options_init_internal(
899    yuv_matrix: &SharpYuvConversionMatrix,
900    version: i32,
901) -> Option<SharpYuvOptions<'_>> {
902    let major = version >> 24;
903    let minor = (version >> 16) & 0xff;
904    // The C condition is (major == 0 && minor != 4) || major != 0, which is the
905    // same as the condition below.
906    if major != SHARPYUV_VERSION_MAJOR || minor != SHARPYUV_VERSION_MINOR {
907        return None;
908    }
909    Some(SharpYuvOptions {
910        yuv_matrix,
911        transfer_type: SharpYuvTransferFunctionType::kSharpYuvTransferFunctionSrgb,
912    })
913}
914
915// upstream: sharpyuv/sharpyuv.h SharpYuvOptionsInit
916#[must_use]
917pub fn sharp_yuv_options_init(
918    yuv_matrix: &SharpYuvConversionMatrix,
919) -> Option<SharpYuvOptions<'_>> {
920    sharp_yuv_options_init_internal(yuv_matrix, SHARPYUV_VERSION)
921}
922
923/// Lengths of the seven scratch buffers, in elements of their respective type.
924#[must_use]
925pub fn scratch_lengths(width: usize, height: usize) -> [usize; 7] {
926    let w = (width + 1) & !1;
927    let h = (height + 1) & !1;
928    let uv_w = w / 2;
929    let uv_h = h / 2;
930    [
931        w * 6,
932        w * h,
933        w * h,
934        w * 2,
935        uv_w * 3 * uv_h,
936        uv_w * 3 * uv_h,
937        uv_w * 3,
938    ]
939}
940
941/// Arguments rejected by both public boundaries before pixel access.
942#[must_use]
943#[expect(
944    clippy::too_many_arguments,
945    reason = "mirrors the C validation boundary"
946)]
947pub fn valid_arguments(
948    rgb_step: i32,
949    rgb_stride: i32,
950    rgb_bit_depth: i32,
951    y_stride: i32,
952    u_stride: i32,
953    v_stride: i32,
954    yuv_bit_depth: i32,
955    width: i32,
956    height: i32,
957) -> bool {
958    width >= 1
959        && height >= 1
960        && width != i32::MAX
961        && height != i32::MAX
962        && matches!(rgb_bit_depth, 8 | 10 | 12 | 16)
963        && matches!(yuv_bit_depth, 8 | 10 | 12)
964        && (rgb_bit_depth == 8 || (rgb_step % 2 == 0 && rgb_stride % 2 == 0))
965        && (yuv_bit_depth == 8 || (y_stride % 2 == 0 && u_stride % 2 == 0 && v_stride % 2 == 0))
966}
967
968/// One conversion algorithm for the safe slice and raw C adapters. Storage is
969/// already allocated and initialized before this call.
970#[must_use]
971#[expect(clippy::too_many_arguments, reason = "narrow adapter boundary")]
972pub fn convert_with_access(
973    access: &mut impl SampleAccess,
974    scratch: Scratch<'_>,
975    dsp: Dsp,
976    rgb_bit_depth: i32,
977    yuv_bit_depth: i32,
978    width: usize,
979    height: usize,
980    yuv_matrix: &SharpYuvConversionMatrix,
981    transfer_type: SharpYuvTransferFunctionType,
982) -> bool {
983    let rgb_max = (1 << rgb_bit_depth) - 1;
984    let rgb_round = 1 << (rgb_bit_depth - 1);
985    let yuv_max = (1 << yuv_bit_depth) - 1;
986    let sfix = get_precision_shift(rgb_bit_depth);
987    let mut scaled_matrix = *yuv_matrix;
988    if rgb_bit_depth != yuv_bit_depth {
989        for i in 0..3 {
990            scaled_matrix.rgb_to_y[i] = (yuv_matrix.rgb_to_y[i] * yuv_max + rgb_round) / rgb_max;
991            scaled_matrix.rgb_to_u[i] = (yuv_matrix.rgb_to_u[i] * yuv_max + rgb_round) / rgb_max;
992            scaled_matrix.rgb_to_v[i] = (yuv_matrix.rgb_to_v[i] * yuv_max + rgb_round) / rgb_max;
993        }
994    }
995    scaled_matrix.rgb_to_y[3] = shift(yuv_matrix.rgb_to_y[3], sfix);
996    scaled_matrix.rgb_to_u[3] = shift(yuv_matrix.rgb_to_u[3], sfix);
997    scaled_matrix.rgb_to_v[3] = shift(yuv_matrix.rgb_to_v[3], sfix);
998    do_sharp_argb_to_yuv(
999        access,
1000        scratch,
1001        dsp,
1002        rgb_bit_depth,
1003        yuv_bit_depth,
1004        width,
1005        height,
1006        &scaled_matrix,
1007        transfer_type,
1008    )
1009}
1010
1011// upstream: sharpyuv/sharpyuv.c SharpYuvConvertWithOptions
1012/// Converts RGB to YUV with `options`. Returns `false` for the arguments that the C
1013/// function rejects; the output is then unchanged.
1014///
1015/// Each buffer is a slice whose byte `*_origin` is the first sample, and each
1016/// stride is in bytes between rows. The `rgb_step` is in bytes between two
1017/// horizontally adjacent pixels. Both 8-bit and wider samples are read and written
1018/// at these byte positions. As in the original WebP safe API, an undersized
1019/// slice or out-of-range origin panics when indexed; callers must provide the
1020/// storage addressed by their dimensions, strides, and steps.
1021#[must_use]
1022#[expect(clippy::too_many_arguments, reason = "mirrors the C signature")]
1023#[expect(
1024    clippy::cast_sign_loss,
1025    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
1026)]
1027pub fn sharp_yuv_convert_with_options_using(
1028    r_ptr: &[u8],
1029    r_origin: usize,
1030    g_ptr: &[u8],
1031    g_origin: usize,
1032    b_ptr: &[u8],
1033    b_origin: usize,
1034    rgb_step: i32,
1035    rgb_stride: i32,
1036    rgb_bit_depth: i32,
1037    y_ptr: &mut [u8],
1038    y_origin: usize,
1039    y_stride: i32,
1040    u_ptr: &mut [u8],
1041    u_origin: usize,
1042    u_stride: i32,
1043    v_ptr: &mut [u8],
1044    v_origin: usize,
1045    v_stride: i32,
1046    yuv_bit_depth: i32,
1047    width: i32,
1048    height: i32,
1049    options: &SharpYuvOptions<'_>,
1050    dsp: Dsp,
1051) -> bool {
1052    if !valid_arguments(
1053        rgb_step,
1054        rgb_stride,
1055        rgb_bit_depth,
1056        y_stride,
1057        u_stride,
1058        v_stride,
1059        yuv_bit_depth,
1060        width,
1061        height,
1062    ) {
1063        return false;
1064    }
1065    let lengths = scratch_lengths(width as usize, height as usize);
1066    let Some(mut tmp_buffer) = safe_malloc::<u16>(lengths[0] as u64) else {
1067        return false;
1068    };
1069    let Some(mut best_y_base) = safe_malloc::<u16>(lengths[1] as u64) else {
1070        return false;
1071    };
1072    let Some(mut target_y_base) = safe_malloc::<u16>(lengths[2] as u64) else {
1073        return false;
1074    };
1075    let Some(mut best_rgb_y) = safe_malloc::<u16>(lengths[3] as u64) else {
1076        return false;
1077    };
1078    let Some(mut best_uv_base) = safe_malloc::<i16>(lengths[4] as u64) else {
1079        return false;
1080    };
1081    let Some(mut target_uv_base) = safe_malloc::<i16>(lengths[5] as u64) else {
1082        return false;
1083    };
1084    let Some(mut best_rgb_uv) = safe_malloc::<i16>(lengths[6] as u64) else {
1085        return false;
1086    };
1087    let scratch = Scratch {
1088        tmp_buffer: &mut tmp_buffer,
1089        best_y_base: &mut best_y_base,
1090        target_y_base: &mut target_y_base,
1091        best_rgb_y: &mut best_rgb_y,
1092        best_uv_base: &mut best_uv_base,
1093        target_uv_base: &mut target_uv_base,
1094        best_rgb_uv: &mut best_rgb_uv,
1095    };
1096    let mut access = SliceAccess {
1097        input: [(r_ptr, r_origin), (g_ptr, g_origin), (b_ptr, b_origin)],
1098        output: [
1099            (y_ptr, y_origin, y_stride),
1100            (u_ptr, u_origin, u_stride),
1101            (v_ptr, v_origin, v_stride),
1102        ],
1103        rgb_step,
1104        rgb_stride,
1105    };
1106    convert_with_access(
1107        &mut access,
1108        scratch,
1109        dsp,
1110        rgb_bit_depth,
1111        yuv_bit_depth,
1112        width as usize,
1113        height as usize,
1114        options.yuv_matrix,
1115        options.transfer_type,
1116    )
1117}
1118
1119/// Scalar safe entry point for callers without an ISA-specific dispatch.
1120#[must_use]
1121#[expect(clippy::too_many_arguments, reason = "mirrors the C signature")]
1122pub fn sharp_yuv_convert_with_options(
1123    r_ptr: &[u8],
1124    r_origin: usize,
1125    g_ptr: &[u8],
1126    g_origin: usize,
1127    b_ptr: &[u8],
1128    b_origin: usize,
1129    rgb_step: i32,
1130    rgb_stride: i32,
1131    rgb_bit_depth: i32,
1132    y_ptr: &mut [u8],
1133    y_origin: usize,
1134    y_stride: i32,
1135    u_ptr: &mut [u8],
1136    u_origin: usize,
1137    u_stride: i32,
1138    v_ptr: &mut [u8],
1139    v_origin: usize,
1140    v_stride: i32,
1141    yuv_bit_depth: i32,
1142    width: i32,
1143    height: i32,
1144    options: &SharpYuvOptions<'_>,
1145) -> bool {
1146    sharp_yuv_convert_with_options_using(
1147        r_ptr,
1148        r_origin,
1149        g_ptr,
1150        g_origin,
1151        b_ptr,
1152        b_origin,
1153        rgb_step,
1154        rgb_stride,
1155        rgb_bit_depth,
1156        y_ptr,
1157        y_origin,
1158        y_stride,
1159        u_ptr,
1160        u_origin,
1161        u_stride,
1162        v_ptr,
1163        v_origin,
1164        v_stride,
1165        yuv_bit_depth,
1166        width,
1167        height,
1168        options,
1169        Dsp::SCALAR,
1170    )
1171}
1172
1173// upstream: sharpyuv/sharpyuv.c SharpYuvConvert
1174/// Converts RGB to YUV with the sRGB transfer function and `yuv_matrix`; see
1175/// [`sharp_yuv_convert_with_options`] for the buffer conventions.
1176#[must_use]
1177#[expect(clippy::too_many_arguments, reason = "mirrors the C signature")]
1178pub fn sharp_yuv_convert(
1179    r_ptr: &[u8],
1180    r_origin: usize,
1181    g_ptr: &[u8],
1182    g_origin: usize,
1183    b_ptr: &[u8],
1184    b_origin: usize,
1185    rgb_step: i32,
1186    rgb_stride: i32,
1187    rgb_bit_depth: i32,
1188    y_ptr: &mut [u8],
1189    y_origin: usize,
1190    y_stride: i32,
1191    u_ptr: &mut [u8],
1192    u_origin: usize,
1193    u_stride: i32,
1194    v_ptr: &mut [u8],
1195    v_origin: usize,
1196    v_stride: i32,
1197    yuv_bit_depth: i32,
1198    width: i32,
1199    height: i32,
1200    yuv_matrix: &SharpYuvConversionMatrix,
1201) -> bool {
1202    let options = SharpYuvOptions {
1203        yuv_matrix,
1204        transfer_type: SharpYuvTransferFunctionType::kSharpYuvTransferFunctionSrgb,
1205    };
1206    sharp_yuv_convert_with_options(
1207        r_ptr,
1208        r_origin,
1209        g_ptr,
1210        g_origin,
1211        b_ptr,
1212        b_origin,
1213        rgb_step,
1214        rgb_stride,
1215        rgb_bit_depth,
1216        y_ptr,
1217        y_origin,
1218        y_stride,
1219        u_ptr,
1220        u_origin,
1221        u_stride,
1222        v_ptr,
1223        v_origin,
1224        v_stride,
1225        yuv_bit_depth,
1226        width,
1227        height,
1228        &options,
1229    )
1230}