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