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