Skip to main content

linear_srgb/
lut.rs

1//! Lookup table (LUT) based sRGB conversions.
2//!
3//! ## For u8 and u16 data
4//!
5//! Use the functions in [`crate::default`] instead of this module — they're
6//! faster and easier:
7//! - u8: [`srgb_u8_to_linear`](crate::default::srgb_u8_to_linear), [`linear_to_srgb_u8`](crate::default::linear_to_srgb_u8)
8//! - u16: [`srgb_u16_to_linear`](crate::default::srgb_u16_to_linear), [`linear_to_srgb_u16`](crate::default::linear_to_srgb_u16)
9//!
10//! ## For non-standard bit depths (10-bit, 12-bit)
11//!
12//! This module provides generic `LinearizationTable<N>` and `EncodingTable<N>`
13//! for arbitrary bit depths, plus interpolation helpers. Use these when working
14//! with 10-bit HDR, 12-bit medical imaging, or other non-standard formats.
15//!
16//! ## `SrgbConverter`
17//!
18//! A zero-sized type wrapping const 8-bit tables. Largely superseded by the
19//! free functions in [`crate::default`], but kept for API compatibility.
20
21#[cfg(not(feature = "std"))]
22use alloc::{boxed::Box, vec};
23
24use crate::mlaf::{mlaf, neg_mlaf};
25use crate::scalar::{linear_to_srgb_f64, srgb_to_linear_f64};
26#[allow(unused_imports)]
27use num_traits::Float; // provides ceil/floor via libm in no_std
28
29/// Pre-computed linearization table for sRGB to linear conversion.
30pub struct LinearizationTable<const N: usize> {
31    table: Box<[f32; N]>,
32}
33
34impl<const N: usize> LinearizationTable<N> {
35    /// Create a linearization table for the given bit depth.
36    ///
37    /// N must equal 2^BIT_DEPTH (e.g., N=256 for 8-bit, N=65536 for 16-bit).
38    pub fn new() -> Self {
39        let mut table = vec![0.0f32; N].into_boxed_slice();
40        let max_value = (N - 1) as f64;
41
42        for (i, entry) in table.iter_mut().enumerate() {
43            let srgb = i as f64 / max_value;
44            *entry = srgb_to_linear_f64(srgb) as f32;
45        }
46
47        // Convert boxed slice to boxed array (safe - size is guaranteed by const N)
48        let table: Box<[f32; N]> = table.try_into().expect("size mismatch");
49
50        Self { table }
51    }
52
53    /// Direct lookup (no interpolation) - for exact bit-depth matches.
54    #[inline]
55    pub fn lookup(&self, index: usize) -> f32 {
56        self.table[index.min(N - 1)]
57    }
58
59    /// Get the raw table for custom interpolation.
60    #[inline]
61    pub fn as_slice(&self) -> &[f32] {
62        &self.table[..]
63    }
64}
65
66impl<const N: usize> Default for LinearizationTable<N> {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72/// Pre-computed encoding table for linear to sRGB conversion.
73pub struct EncodingTable<const N: usize> {
74    table: Box<[f32; N]>,
75}
76
77impl<const N: usize> EncodingTable<N> {
78    /// Create an encoding table for the given resolution.
79    ///
80    /// Higher N means finer granularity for interpolation.
81    pub fn new() -> Self {
82        let mut table = vec![0.0f32; N].into_boxed_slice();
83        let max_value = (N - 1) as f64;
84
85        for (i, entry) in table.iter_mut().enumerate() {
86            let linear = i as f64 / max_value;
87            *entry = linear_to_srgb_f64(linear) as f32;
88        }
89
90        // Convert boxed slice to boxed array (safe - size is guaranteed by const N)
91        let table: Box<[f32; N]> = table.try_into().expect("size mismatch");
92
93        Self { table }
94    }
95
96    /// Direct lookup (no interpolation).
97    #[inline]
98    pub fn lookup(&self, index: usize) -> f32 {
99        self.table[index.min(N - 1)]
100    }
101
102    /// Get the raw table for custom interpolation.
103    #[inline]
104    pub fn as_slice(&self) -> &[f32] {
105        &self.table[..]
106    }
107}
108
109impl<const N: usize> Default for EncodingTable<N> {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115/// Linear interpolation in a float LUT.
116///
117/// `x` should be in [0, 1]. Values outside are clamped.
118/// Uses FMA for the interpolation calculation.
119#[inline]
120pub fn lut_interp_linear_float(x: f32, table: &[f32]) -> f32 {
121    let x = x.clamp(0.0, 1.0);
122    let value = x * (table.len() - 1) as f32;
123
124    let upper = value.ceil() as usize;
125    let lower = value.floor() as usize;
126
127    // Safety: upper and lower are bounded by table.len() - 1 due to clamping
128    let tu = table[upper.min(table.len() - 1)];
129    let tl = table[lower];
130
131    let diff = upper as f32 - value;
132
133    // result = tl * diff + tu * (1 - diff)
134    // Using FMA: neg_mlaf(tu, tu, diff) = tu - tu*diff = tu*(1-diff)
135    // Then: mlaf(tu*(1-diff), tl, diff) = tu*(1-diff) + tl*diff
136    mlaf(neg_mlaf(tu, tu, diff), tl, diff)
137}
138
139/// Linear interpolation in a u16 LUT using fixed-point arithmetic.
140///
141/// Avoids floating-point entirely for integer-only pipelines.
142#[inline]
143pub fn lut_interp_linear_u16(input_value: u16, table: &[u16]) -> u16 {
144    let table_len = table.len() as u32;
145    let mut value: u32 = input_value as u32 * (table_len - 1);
146
147    let upper = value.div_ceil(65535) as usize;
148    let lower = (value / 65535) as usize;
149    let interp: u32 = value % 65535;
150
151    // Safety: upper and lower are bounded
152    let upper = upper.min(table.len() - 1);
153    let lower = lower.min(table.len() - 1);
154
155    value = (table[upper] as u32 * interp + table[lower] as u32 * (65535 - interp)) / 65535;
156    value as u16
157}
158
159/// Pre-computed 8-bit linearization table (256 entries).
160pub type LinearTable8 = LinearizationTable<256>;
161
162/// Pre-computed 10-bit linearization table (1024 entries).
163pub type LinearTable10 = LinearizationTable<1024>;
164
165/// Pre-computed 12-bit linearization table (4096 entries).
166pub type LinearTable12 = LinearizationTable<4096>;
167
168/// Pre-computed 16-bit linearization table (65536 entries).
169///
170/// **Deprecated:** Use [`crate::default::srgb_u16_to_linear`] instead — it's
171/// faster (shared OnceLock LUT, SIMD-generated) and doesn't add 1+ seconds
172/// of compile time from const evaluation.
173#[deprecated(
174    since = "0.7.0",
175    note = "use default::srgb_u16_to_linear instead (faster, shared LUT)"
176)]
177pub type LinearTable16 = LinearizationTable<65536>;
178
179/// Pre-computed 8-bit encoding table (256 entries).
180pub type EncodeTable8 = EncodingTable<256>;
181
182/// Pre-computed 12-bit encoding table (4096 entries).
183pub type EncodeTable12 = EncodingTable<4096>;
184
185/// Pre-computed 16-bit encoding table (65536 entries).
186///
187/// **Deprecated:** Use [`crate::default::linear_to_srgb_u16`] (exact) or
188/// [`crate::default::linear_to_srgb_u16_fast`] (10×, ±1 max error) instead.
189#[deprecated(
190    since = "0.7.0",
191    note = "use default::linear_to_srgb_u16 or linear_to_srgb_u16_fast instead"
192)]
193pub type EncodeTable16 = EncodingTable<65536>;
194
195/// Converter using pre-computed const LUTs for fast batch conversion.
196///
197/// This is a **zero-sized type** - the tables are embedded in the binary at
198/// compile time with no runtime initialization cost. This is the recommended
199/// approach for standard 8-bit sRGB workflows.
200///
201/// # Example
202///
203/// ```rust
204/// use linear_srgb::lut::SrgbConverter;
205///
206/// let conv = SrgbConverter::new();  // No allocation, just a marker type
207///
208/// // Fast 8-bit lookups
209/// let linear = conv.srgb_u8_to_linear(128);
210/// let srgb = conv.linear_to_srgb_u8(linear);
211/// ```
212///
213/// # Implementation Details
214///
215/// - Uses a 256-entry const table for sRGB u8 → linear f32 (direct lookup)
216/// - Uses a 4096-entry const table for linear f32 → sRGB f32 (linear interpolation)
217pub struct SrgbConverter;
218
219impl SrgbConverter {
220    /// Create a new converter.
221    ///
222    /// This is a no-op since tables are const and embedded in binary.
223    #[inline]
224    pub const fn new() -> Self {
225        Self
226    }
227
228    /// Convert 8-bit sRGB to linear using direct table lookup.
229    #[inline]
230    pub fn srgb_u8_to_linear(&self, value: u8) -> f32 {
231        crate::const_luts::LINEAR_TABLE_8[value as usize]
232    }
233
234    /// Convert linear to sRGB using table interpolation.
235    #[inline]
236    pub fn linear_to_srgb(&self, linear: f32) -> f32 {
237        lut_interp_linear_float(linear, &crate::const_luts::ENCODE_TABLE_12)
238    }
239
240    /// Convert linear to 8-bit sRGB using direct LUT lookup.
241    ///
242    /// Uses a 4096-entry const u8 table — no interpolation or transcendental math.
243    #[inline]
244    pub fn linear_to_srgb_u8(&self, linear: f32) -> u8 {
245        crate::scalar::linear_to_srgb_u8(linear)
246    }
247
248    /// Batch convert sRGB u8 values to linear f32.
249    #[inline]
250    pub fn batch_srgb_to_linear(&self, input: &[u8], output: &mut [f32]) {
251        assert_eq!(input.len(), output.len());
252        for (i, o) in input.iter().zip(output.iter_mut()) {
253            *o = self.srgb_u8_to_linear(*i);
254        }
255    }
256
257    /// Batch convert linear f32 values to sRGB u8.
258    ///
259    /// Uses [`crate::default::linear_to_srgb_u8_slice`] for SIMD-accelerated
260    /// index computation with LUT lookup.
261    #[inline]
262    pub fn batch_linear_to_srgb(&self, input: &[f32], output: &mut [u8]) {
263        crate::simd::linear_to_srgb_u8_slice(input, output);
264    }
265}
266
267impl Default for SrgbConverter {
268    fn default() -> Self {
269        Self::new()
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[cfg(not(feature = "std"))]
278    use alloc::{vec, vec::Vec};
279
280    #[test]
281    fn test_linearization_table_8bit() {
282        let table = LinearTable8::new();
283
284        // Check boundaries
285        assert_eq!(table.lookup(0), 0.0);
286        assert!((table.lookup(255) - 1.0).abs() < 1e-6);
287
288        // Check middle value
289        let mid = table.lookup(128);
290        assert!(mid > 0.0 && mid < 1.0);
291    }
292
293    #[test]
294    fn test_encoding_table() {
295        let table = EncodeTable12::new();
296
297        assert_eq!(table.lookup(0), 0.0);
298        assert!((table.lookup(4095) - 1.0).abs() < 1e-5);
299    }
300
301    #[test]
302    fn test_lut_interpolation() {
303        let table = EncodeTable12::new();
304
305        // Test interpolation at exact points
306        let result = lut_interp_linear_float(0.0, table.as_slice());
307        assert!((result - 0.0).abs() < 1e-6);
308
309        let result = lut_interp_linear_float(1.0, table.as_slice());
310        assert!((result - 1.0).abs() < 1e-5);
311    }
312
313    #[test]
314    fn test_converter_roundtrip() {
315        let conv = SrgbConverter::new();
316
317        for i in 0..=255u8 {
318            let linear = conv.srgb_u8_to_linear(i);
319            let back = conv.linear_to_srgb_u8(linear);
320            assert!(
321                (i as i32 - back as i32).abs() <= 1,
322                "Roundtrip failed for {}: {} -> {} -> {}",
323                i,
324                i,
325                linear,
326                back
327            );
328        }
329    }
330
331    #[test]
332    fn test_lut_vs_direct() {
333        use crate::scalar::srgb_to_linear;
334
335        let table = LinearTable8::new();
336
337        // Compare LUT to direct computation
338        for i in 0..=255u8 {
339            let lut_result = table.lookup(i as usize);
340            let direct_result = srgb_to_linear(i as f32 / 255.0);
341            assert!(
342                (lut_result - direct_result).abs() < 1e-5,
343                "Mismatch at {}: LUT={}, direct={}",
344                i,
345                lut_result,
346                direct_result
347            );
348        }
349    }
350
351    #[test]
352    fn test_u16_interpolation() {
353        // Create a simple linear ramp table
354        let table: Vec<u16> = (0..=255).map(|i| (i * 257) as u16).collect();
355
356        // Input 0 should give 0
357        assert_eq!(lut_interp_linear_u16(0, &table), 0);
358
359        // Input max should give max
360        assert_eq!(lut_interp_linear_u16(65535, &table), 65535);
361    }
362
363    #[test]
364    fn test_batch_conversion() {
365        let conv = SrgbConverter::new();
366
367        let input: Vec<u8> = (0..=255).collect();
368        let mut linear = vec![0.0f32; 256];
369        let mut back = vec![0u8; 256];
370
371        conv.batch_srgb_to_linear(&input, &mut linear);
372        conv.batch_linear_to_srgb(&linear, &mut back);
373
374        for i in 0..256 {
375            assert!(
376                (input[i] as i32 - back[i] as i32).abs() <= 1,
377                "Batch roundtrip failed at {}",
378                i
379            );
380        }
381    }
382}