Skip to main content

linear_srgb/
lib.rs

1//! Fast linear↔sRGB color space conversion.
2//!
3//! This crate provides efficient conversion between linear light values and
4//! sRGB gamma-encoded values, with multiple implementation strategies for
5//! different accuracy/performance tradeoffs.
6//!
7//! # Module Organization
8//!
9//! - [`default`] — **Start here.** Rational polynomial for f32, LUT for integers, SIMD for slices.
10//! - [`precise`] — Exact `powf()` with C0-continuous constants. f32/f64, extended range. Slower.
11//! - [`tokens`] — Inlineable `#[rite]` functions for embedding in your own `#[arcane]` SIMD code.
12//! - [`lut`] — Lookup tables for custom bit depths (10-bit, 12-bit, 16-bit).
13//! - **`tf`** — Transfer functions beyond sRGB: BT.709, PQ, HLG. Requires `transfer` feature.
14//! - **`iec`** — IEC 61966-2-1 textbook constants (legacy interop). Requires `iec` feature.
15//!
16//! # Quick Start
17//!
18//! ```rust
19//! use linear_srgb::default::{srgb_to_linear, linear_to_srgb};
20//!
21//! // Convert sRGB 0.5 to linear
22//! let linear = srgb_to_linear(0.5);
23//! assert!((linear - 0.214).abs() < 0.001);
24//!
25//! // Convert back to sRGB
26//! let srgb = linear_to_srgb(linear);
27//! assert!((srgb - 0.5).abs() < 0.001);
28//! ```
29//!
30//! # Batch Processing (SIMD)
31//!
32//! For maximum throughput on slices:
33//!
34//! ```rust
35//! use linear_srgb::default::{srgb_to_linear_slice, linear_to_srgb_slice};
36//!
37//! let mut values = vec![0.5f32; 10000];
38//! srgb_to_linear_slice(&mut values);  // SIMD-accelerated
39//! linear_to_srgb_slice(&mut values);
40//! ```
41//!
42//! # Custom Gamma
43//!
44//! For non-sRGB gamma (pure power function without linear segment):
45//!
46//! ```rust
47//! use linear_srgb::default::{gamma_to_linear, linear_to_gamma};
48//!
49//! let linear = gamma_to_linear(0.5, 2.2);  // gamma 2.2
50//! let encoded = linear_to_gamma(linear, 2.2);
51//! ```
52//!
53//! # LUT-based Conversion
54//!
55//! For batch processing with pre-computed lookup tables:
56//!
57//! ```rust
58//! use linear_srgb::default::SrgbConverter;
59//!
60//! let conv = SrgbConverter::new();  // Zero-cost, const tables
61//!
62//! // Fast 8-bit conversions
63//! let linear = conv.srgb_u8_to_linear(128);
64//! let srgb = conv.linear_to_srgb_u8(linear);
65//! ```
66//!
67//! # Choosing the Right API
68//!
69//! | Use Case | Recommended Function |
70//! |----------|---------------------|
71//! | Single f32 value | [`default::srgb_to_linear`] |
72//! | Single u8 value | [`default::srgb_u8_to_linear`] |
73//! | f32 slice (in-place) | [`default::srgb_to_linear_slice`] |
74//! | RGBA f32 slice (alpha-preserving) | [`default::srgb_to_linear_rgba_slice`] |
75//! | u8 slice → f32 slice | [`default::srgb_u8_to_linear_slice`] |
76//! | RGBA u8 → f32 (alpha-preserving) | [`default::srgb_u8_to_linear_rgba_slice`] |
77//! | u16 slice → f32 slice | [`default::srgb_u16_to_linear_slice`] |
78//! | Exact f32/f64 (powf) | [`precise::srgb_to_linear`] |
79//! | Extended range (HDR) | [`precise::srgb_to_linear_extended`] |
80//! | Inside `#[arcane]` | `tokens::x8::srgb_to_linear_v3` |
81//! | Custom bit depth LUT | [`lut::LinearTable16`] |
82//!
83//! # Clamping and Extended Range
84//!
85//! The f32↔f32 conversion functions come in two flavors: **clamped** (default)
86//! and **extended** (unclamped). Integer paths (u8, u16) always clamp since
87//! out-of-range values can't be represented in the output format.
88//!
89//! ## Clamped (default) — use for same-gamut pipelines
90//!
91//! All functions except the `_extended` variants clamp inputs to \[0, 1\]:
92//! negatives become 0, values above 1 become 1.
93//!
94//! This is correct whenever the source and destination share the same color
95//! space (gamut + transfer function). The typical pipeline:
96//!
97//! 1. Decode sRGB image (u8 → linear f32 via LUT, or f32 via TRC)
98//! 2. Process in linear light (resize, blur, blend, composite)
99//! 3. Re-encode to sRGB (linear f32 → sRGB f32 or u8)
100//!
101//! In this pipeline, out-of-range values only come from processing artifacts:
102//! resize filters with negative lobes (Lanczos, Mitchell, etc.) produce small
103//! negatives near dark edges and values slightly above 1.0 near bright edges.
104//! These are ringing artifacts, not real colors — clamping is correct.
105//!
106//! Float decoders like jpegli can also produce small out-of-range values from
107//! YCbCr quantization noise. When the image is sRGB, these are compression
108//! artifacts and clamping is correct — gives the same result as decoding to
109//! u8 first.
110//!
111//! ## Extended (unclamped) — use for cross-gamut pipelines
112//!
113//! [`precise::srgb_to_linear_extended`] and [`precise::linear_to_srgb_extended`]
114//! do not clamp. They follow the mathematical sRGB transfer function for all
115//! inputs: negatives pass through the linear segment, values above 1.0 pass
116//! through the power segment.
117//!
118//! Use these when the sRGB transfer function is applied to values from a
119//! **different, wider gamut**. A 3×3 matrix converting Rec. 2020 linear or
120//! Display P3 linear to sRGB linear can produce values well outside \[0, 1\]:
121//! a saturated Rec. 2020 green maps to deeply negative sRGB red and blue.
122//! These are real out-of-gamut colors, not artifacts — clamping destroys
123//! information that downstream gamut mapping or compositing may need.
124//!
125//! This matters in practice: JPEG and JPEG XL images can carry Rec. 2020 or
126//! Display P3 ICC profiles. Phones shoot Rec. 2020 HLG, cameras embed
127//! wide-gamut profiles. Decoding such an image and converting to sRGB for
128//! display produces out-of-gamut values that should survive until final
129//! output.
130//!
131//! If a float decoder (jpegli, libjxl) outputs wide-gamut data directly to
132//! f32, the output contains both small compression artifacts and real
133//! out-of-gamut values. The artifacts are tiny; the gamut excursions
134//! dominate. Using `_extended` preserves both — the artifacts are harmless
135//! noise that vanishes at quantization.
136//!
137//! The `_extended` variants also cover **scRGB** (float sRGB with values
138//! outside \[0, 1\] for HDR and wide color) and any pipeline where
139//! intermediate f32 values are not yet at the final output stage.
140//!
141//! ## Summary
142//!
143//! | Function | Range | Pipeline |
144//! |----------|-------|----------|
145//! | All `default::*_slice`, `tokens::*`, `lut::*` | \[0, 1\] | Same-gamut batch processing |
146//! | [`default::srgb_to_linear`] | \[0, 1\] | Same-gamut single values |
147//! | [`default::linear_to_srgb`] | \[0, 1\] | Same-gamut single values |
148//! | [`precise::srgb_to_linear_extended`] | Unbounded | Cross-gamut, scRGB, HDR |
149//! | [`precise::linear_to_srgb_extended`] | Unbounded | Cross-gamut, scRGB, HDR |
150//! | All u8/u16 paths | \[0, 1\] | Final quantization (clamp inherent) |
151//!
152//! **No SIMD extended-range variants exist yet.** The fast polynomial
153//! approximation is fitted to \[0, 1\] and produces garbage outside that
154//! domain. Extended-range SIMD would use `pow` instead of the polynomial
155//! (~3× slower, still faster than scalar for `linear_to_srgb`). For batch
156//! extended-range conversion today, loop over the [`precise`] `_extended`
157//! functions.
158//!
159//! # Feature Flags
160//!
161//! - **`std`** (default) — Enable runtime SIMD dispatch. Required for slice functions.
162//! - **`avx512`** (default) — Enable AVX-512 code paths and `tokens::x16` module.
163//! - **`transfer`** — BT.709, PQ, and HLG transfer functions in `tf` and [`tokens`].
164//! - **`iec`** — IEC 61966-2-1 textbook sRGB functions for legacy interop.
165//! - **`alt`** — Alternative implementations for benchmarking (not stable API).
166//! - **`unsafe_simd`** — No-op (kept for backward compatibility, will be removed in 0.7).
167//!
168//! # `no_std` Support
169//!
170//! This crate is `no_std` compatible (requires `alloc` for LUT generation).
171//! Disable the `std` feature:
172//!
173//! ```toml
174//! linear-srgb = { version = "0.6", default-features = false }
175//! ```
176
177#![cfg_attr(not(feature = "std"), no_std)]
178#![forbid(unsafe_code)]
179#![warn(missing_docs)]
180
181#[cfg(not(feature = "std"))]
182extern crate alloc;
183
184#[cfg(all(test, not(feature = "std")))]
185extern crate std;
186
187// ============================================================================
188// Public modules
189// ============================================================================
190
191/// Recommended API with optimal implementations for each use case.
192///
193/// Uses a rational polynomial for single f32 values (≤14 ULP, perfectly
194/// monotonic), LUT for integer types, and SIMD-dispatched batch processing
195/// for slices.
196pub mod default;
197
198/// Exact `powf()`-based conversions with C0-continuous constants.
199///
200/// Uses C0-continuous constants (from the moxcms reference implementation) that
201/// eliminate the IEC 61966-2-1 piecewise discontinuity. ~6 ULP max error
202/// vs f64 reference. See the module docs for the constant comparison table.
203///
204/// Also provides f64, extended-range (unclamped), and custom gamma functions.
205/// For faster alternatives, use [`default`].
206pub mod precise;
207
208/// Lookup table types for sRGB conversion.
209///
210/// Provides both build-time const tables ([`SrgbConverter`](lut::SrgbConverter))
211/// and runtime-generated tables for custom bit depths (10-bit, 12-bit, 16-bit).
212pub mod lut;
213
214/// Inlineable `#[rite]` functions for embedding in your own `#[arcane]` code.
215///
216/// These carry `#[target_feature]` + `#[inline]` directly — no wrapper, no
217/// dispatch. When called from a matching `#[arcane]` context, LLVM inlines
218/// them fully. Organized by SIMD width; suffixed by required token tier.
219///
220/// Also re-exports token types for convenience: `X64V3Token`, `X64V4Token`,
221/// `NeonToken`, `Wasm128Token` (each gated to its target architecture).
222///
223/// When the `transfer` feature is enabled, each width module also provides
224/// rites for BT.709, PQ, and HLG (prefixed with `tf_` for sRGB to avoid
225/// name collisions with the rational polynomial sRGB rites).
226pub mod tokens;
227
228/// Transfer functions: sRGB, BT.709, PQ (ST 2084), HLG (ARIB STD-B67).
229///
230/// Provides scalar functions for all four transfer curves. SIMD `#[rite]`
231/// versions live in [`tokens`] (x4/x8/x16).
232///
233/// Requires the `transfer` feature.
234#[cfg(feature = "transfer")]
235pub mod tf;
236
237/// IEC 61966-2-1:1999 textbook sRGB transfer functions.
238///
239/// Provides the original specification constants (threshold 0.04045, offset 0.055)
240/// for interoperability with software that implements IEC 61966-2-1 verbatim.
241/// The default module uses C0-continuous constants that eliminate the spec's
242/// ~2.3e-9 piecewise discontinuity.
243///
244/// Requires the `iec` feature.
245#[cfg(feature = "iec")]
246pub mod iec;
247
248// ============================================================================
249// Internal modules
250// ============================================================================
251
252pub(crate) mod scalar;
253pub(crate) mod simd;
254
255mod mlaf;
256
257// Rational polynomial sRGB approximation (shared coefficients + scalar evaluator)
258pub(crate) mod rational_poly;
259
260// Pre-computed const lookup tables (embedded in binary)
261mod const_luts;
262mod const_luts_u16;
263
264// Alternative/experimental implementations (for benchmarking, not stable API)
265#[cfg(feature = "alt")]
266#[doc(hidden)]
267pub mod alt;
268
269// ============================================================================
270// Tests
271// ============================================================================
272
273#[cfg(test)]
274mod tests {
275    use crate::default::*;
276
277    #[cfg(not(feature = "std"))]
278    use alloc::vec::Vec;
279
280    #[test]
281    fn test_api_consistency() {
282        // Ensure direct and LUT-based conversions are consistent
283        let conv = SrgbConverter::new();
284
285        for i in 0..=255u8 {
286            let direct = srgb_u8_to_linear(i);
287            let lut = conv.srgb_u8_to_linear(i);
288            assert!(
289                (direct - lut).abs() < 1e-5,
290                "Mismatch at {}: direct={}, lut={}",
291                i,
292                direct,
293                lut
294            );
295        }
296    }
297
298    #[test]
299    fn test_slice_conversion() {
300        let mut values: Vec<f32> = (0..=10).map(|i| i as f32 / 10.0).collect();
301        let original = values.clone();
302
303        srgb_to_linear_slice(&mut values);
304        linear_to_srgb_slice(&mut values);
305
306        for (i, (orig, conv)) in original.iter().zip(values.iter()).enumerate() {
307            assert!(
308                (orig - conv).abs() < 1e-5,
309                "Slice roundtrip failed at {}: {} -> {}",
310                i,
311                orig,
312                conv
313            );
314        }
315    }
316}