Skip to main content

libsharpyuv_core/
sharpyuv_csp.rs

1// libwebp v1.6.0, sharpyuv/sharpyuv_csp.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// Colorspace utilities.
13
14// libwebp v1.6.0, sharpyuv/sharpyuv_csp.h:
15//
16// Copyright 2022 Google Inc. All Rights Reserved.
17//
18// Use of this source code is governed by a BSD-style license
19// that can be found in the COPYING file in the root of the source
20// tree. An additional intellectual property rights grant can be found
21// in the file PATENTS. All contributing project authors may
22// be found in the AUTHORS file in the root of the source tree.
23// -----------------------------------------------------------------------------
24//
25// Colorspace utilities.
26
27//! Translation of `sharpyuv/sharpyuv_csp.c` and `sharpyuv/sharpyuv_csp.h` from libwebp v1.6.0.
28//!
29//! Work package: WP5 (`SharpYUV`).
30//!
31//! # Deviations from upstream
32//!
33//! Changes of representation that the ADRs allow, or behavior that the Rust
34//! side cannot reproduce exactly. Each records the reason.
35//!
36//! 1. **Out-of-range float conversions.** C converts a float that is out of
37//!    range for an integer type with an undefined conversion. Rust `as`
38//!    saturates. This is reachable only in the excluded cases of
39//!    `# Excluded undefined behavior`: item 2 here and item 1 of
40//!    `src/sharpyuv/sharpyuv_gamma.rs`.
41//!
42//! # Excluded undefined behavior
43//!
44//! Inputs that are undefined behavior (or assertion failures) in C and are
45//! therefore excluded from the oracle comparison (PORTING rule 8):
46//!
47//! 1. **Seeded color spaces (`csp.c`, `wp5_matrix.rs`).** The seeded color
48//!    spaces draw `kr` and `kb` from `[0, 0.5)` and the bit depth from 8 to 15.
49//!    In `SharpYuvComputeConversionMatrix`, `ToFixed16` converts
50//!    `f * 65536 + 0.5` to `int`, which is undefined when `|f| >= 32768`. With
51//!    these bounds every scale factor is at most 1 and every coefficient is at
52//!    most 1 in magnitude, so every intermediate fits `int`.
53//! 2. **Bit depth 16 in `SharpYuvComputeConversionMatrix`.** The offset
54//!    `128 << (bit_depth - 8)` is `2^15` at 16 bits, and `ToFixed16` of
55//!    `2^15 * 65536` overflows `int`, for every color space. The C result is
56//!    undefined: an oracle run observed `INT_MIN`, and the Rust function
57//!    saturates to `i32::MAX`. The bit depth 16 is excluded from the seeded
58//!    color spaces. The computed matrices of the inventory (see
59//!    `tests/wp5_matrix.rs`) use 8, 10 and 12 bits. `SharpYuvConvert` does not
60//!    use computed matrices, so no conversion reaches this case.
61//!
62//! # Checks not applicable
63//!
64//! These checks do not apply, or cannot be made, with the reason:
65//!
66//! 1. **Floating point across hosts.** The matrix computation uses `float`; the
67//!    full text is in `# Checks not applicable` (item 1) of
68//!    `src/sharpyuv/sharpyuv_gamma.rs`.
69
70use super::sharpyuv::SharpYuvConversionMatrix;
71
72// upstream: sharpyuv/sharpyuv_csp.h SharpYuvRange
73/// The value range of a color space; a C enumeration stored as its `unsigned int`.
74#[repr(transparent)]
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct SharpYuvRange(pub u32);
77
78impl SharpYuvRange {
79    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvRangeFull
80    /// YUV values between [0;255] (for 8 bit).
81    #[expect(non_upper_case_globals, reason = "C enumerator name")]
82    pub const kSharpYuvRangeFull: Self = Self(0);
83    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvRangeLimited
84    /// Y in [16;235], YUV in [16;240] (for 8 bit).
85    #[expect(non_upper_case_globals, reason = "C enumerator name")]
86    pub const kSharpYuvRangeLimited: Self = Self(1);
87}
88
89// upstream: sharpyuv/sharpyuv_csp.h SharpYuvColorSpace
90/// A color space, from which `sharp_yuv_compute_conversion_matrix` derives a matrix.
91#[repr(C)]
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub struct SharpYuvColorSpace {
94    /// Kr and Kb are defined such that: Y = Kr * r + Kg * g + Kb * b where Kg = 1 - Kr - Kb.
95    pub kr: f32,
96    /// See `kr`.
97    pub kb: f32,
98    /// 8, 10 or 12.
99    pub bit_depth: i32,
100    /// The value range.
101    pub range: SharpYuvRange,
102}
103
104// upstream: sharpyuv/sharpyuv_csp.h SharpYuvMatrixType
105/// A predefined conversion matrix; a C enumeration stored as its `unsigned int`.
106#[repr(transparent)]
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct SharpYuvMatrixType(pub u32);
109
110impl SharpYuvMatrixType {
111    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixWebp
112    /// WebP's matrix, similar but not identical to kSharpYuvMatrixRec601Limited.
113    #[expect(non_upper_case_globals, reason = "C enumerator name")]
114    pub const kSharpYuvMatrixWebp: Self = Self(0);
115    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixRec601Limited
116    /// Kr=0.2990f, Kb=0.1140f, 8 bits, range `kSharpYuvRangeLimited`.
117    #[expect(non_upper_case_globals, reason = "C enumerator name")]
118    pub const kSharpYuvMatrixRec601Limited: Self = Self(1);
119    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixRec601Full
120    /// Kr=0.2990f, Kb=0.1140f, 8 bits, range `kSharpYuvRangeFull`.
121    #[expect(non_upper_case_globals, reason = "C enumerator name")]
122    pub const kSharpYuvMatrixRec601Full: Self = Self(2);
123    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixRec709Limited
124    /// Kr=0.2126f, Kb=0.0722f, 8 bits, range `kSharpYuvRangeLimited`.
125    #[expect(non_upper_case_globals, reason = "C enumerator name")]
126    pub const kSharpYuvMatrixRec709Limited: Self = Self(3);
127    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixRec709Full
128    /// Kr=0.2126f, Kb=0.0722f, 8 bits, range `kSharpYuvRangeFull`.
129    #[expect(non_upper_case_globals, reason = "C enumerator name")]
130    pub const kSharpYuvMatrixRec709Full: Self = Self(4);
131    // upstream: sharpyuv/sharpyuv_csp.h kSharpYuvMatrixNum
132    /// The number of predefined matrices; not a matrix.
133    #[expect(non_upper_case_globals, reason = "C enumerator name")]
134    pub const kSharpYuvMatrixNum: Self = Self(5);
135}
136
137// upstream: sharpyuv/sharpyuv_csp.c ToFixed16
138#[expect(
139    clippy::cast_possible_truncation,
140    reason = "C integer and float conversions, kept as in the source (ADR 0003)"
141)]
142fn to_fixed16(f: f32) -> i32 {
143    (f64::from(f * 65536.0 + 0.5)).floor() as i32
144}
145
146// upstream: sharpyuv/sharpyuv_csp.c SharpYuvComputeConversionMatrix
147/// Computes the RGB to YUV matrix of `yuv_color_space`.
148#[must_use]
149#[expect(
150    clippy::cast_precision_loss,
151    reason = "C int to float conversions of the scale factors"
152)]
153pub fn sharp_yuv_compute_conversion_matrix(
154    yuv_color_space: &SharpYuvColorSpace,
155) -> SharpYuvConversionMatrix {
156    let kr = yuv_color_space.kr;
157    let kb = yuv_color_space.kb;
158    let kg = 1.0_f32 - kr - kb;
159    let cb = 0.5_f32 / (1.0_f32 - kb);
160    let cr = 0.5_f32 / (1.0_f32 - kr);
161
162    let shift = yuv_color_space.bit_depth - 8;
163    debug_assert!(yuv_color_space.bit_depth >= 8);
164
165    let denom = ((1 << yuv_color_space.bit_depth) - 1) as f32;
166    let mut scale_y = 1.0_f32;
167    let mut add_y = 0.0_f32;
168    let mut scale_u = cb;
169    let mut scale_v = cr;
170    let add_uv = (128 << shift) as f32;
171
172    if yuv_color_space.range == SharpYuvRange::kSharpYuvRangeLimited {
173        scale_y *= (219 << shift) as f32 / denom;
174        scale_u *= (224 << shift) as f32 / denom;
175        scale_v *= (224 << shift) as f32 / denom;
176        add_y = (16 << shift) as f32;
177    }
178
179    SharpYuvConversionMatrix {
180        rgb_to_y: [
181            to_fixed16(kr * scale_y),
182            to_fixed16(kg * scale_y),
183            to_fixed16(kb * scale_y),
184            to_fixed16(add_y),
185        ],
186        rgb_to_u: [
187            to_fixed16(-kr * scale_u),
188            to_fixed16(-kg * scale_u),
189            to_fixed16((1.0 - kb) * scale_u),
190            to_fixed16(add_uv),
191        ],
192        rgb_to_v: [
193            to_fixed16((1.0 - kr) * scale_v),
194            to_fixed16(-kg * scale_v),
195            to_fixed16(-kb * scale_v),
196            to_fixed16(add_uv),
197        ],
198    }
199}
200
201// upstream: sharpyuv/sharpyuv_csp.c kWebpMatrix
202/// WebP's predefined matrix, the first of the `SharpYuvMatrixType` values.
203const WEBP_MATRIX: SharpYuvConversionMatrix = SharpYuvConversionMatrix {
204    rgb_to_y: [16839, 33059, 6420, 16 << 16],
205    rgb_to_u: [-9719, -19081, 28800, 128 << 16],
206    rgb_to_v: [28800, -24116, -4684, 128 << 16],
207};
208// upstream: sharpyuv/sharpyuv_csp.c kRec601LimitedMatrix
209const REC601_LIMITED_MATRIX: SharpYuvConversionMatrix = SharpYuvConversionMatrix {
210    rgb_to_y: [16829, 33039, 6416, 16 << 16],
211    rgb_to_u: [-9714, -19071, 28784, 128 << 16],
212    rgb_to_v: [28784, -24103, -4681, 128 << 16],
213};
214// upstream: sharpyuv/sharpyuv_csp.c kRec601FullMatrix
215const REC601_FULL_MATRIX: SharpYuvConversionMatrix = SharpYuvConversionMatrix {
216    rgb_to_y: [19595, 38470, 7471, 0],
217    rgb_to_u: [-11058, -21710, 32768, 128 << 16],
218    rgb_to_v: [32768, -27439, -5329, 128 << 16],
219};
220// upstream: sharpyuv/sharpyuv_csp.c kRec709LimitedMatrix
221const REC709_LIMITED_MATRIX: SharpYuvConversionMatrix = SharpYuvConversionMatrix {
222    rgb_to_y: [11966, 40254, 4064, 16 << 16],
223    rgb_to_u: [-6596, -22189, 28784, 128 << 16],
224    rgb_to_v: [28784, -26145, -2639, 128 << 16],
225};
226// upstream: sharpyuv/sharpyuv_csp.c kRec709FullMatrix
227const REC709_FULL_MATRIX: SharpYuvConversionMatrix = SharpYuvConversionMatrix {
228    rgb_to_y: [13933, 46871, 4732, 0],
229    rgb_to_u: [-7509, -25259, 32768, 128 << 16],
230    rgb_to_v: [32768, -29763, -3005, 128 << 16],
231};
232
233// upstream: sharpyuv/sharpyuv_csp.c SharpYuvGetConversionMatrix
234/// Returns the predefined matrix of `matrix_type`, or `None` when the value is not one of
235/// the five predefined matrices (the C function returns `NULL`).
236#[must_use]
237pub fn sharp_yuv_get_conversion_matrix(
238    matrix_type: SharpYuvMatrixType,
239) -> Option<&'static SharpYuvConversionMatrix> {
240    match matrix_type {
241        SharpYuvMatrixType::kSharpYuvMatrixWebp => Some(&WEBP_MATRIX),
242        SharpYuvMatrixType::kSharpYuvMatrixRec601Limited => Some(&REC601_LIMITED_MATRIX),
243        SharpYuvMatrixType::kSharpYuvMatrixRec601Full => Some(&REC601_FULL_MATRIX),
244        SharpYuvMatrixType::kSharpYuvMatrixRec709Limited => Some(&REC709_LIMITED_MATRIX),
245        SharpYuvMatrixType::kSharpYuvMatrixRec709Full => Some(&REC709_FULL_MATRIX),
246        _ => None,
247    }
248}