wagahai_lut 0.1.0

CUBE LUT parser and image processing library with SIMD
Documentation
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
 * SPDX-FileCopyrightText: © 2026 Jinwoo Park (pmnxis@gmail.com)
 *
 * SPDX-License-Identifier: MIT
 */

//! LUT data structures

pub mod common;
pub mod lut_1d;
pub mod lut_1d_processing;
pub mod lut_3d;
pub mod lut_3d_processing;

use crate::error::Result;
use image::{DynamicImage, ImageBuffer};

// Re-export main LUT types
pub use common::Rgb;
pub use lut_1d::Lut1D;
pub use lut_3d::Lut3D;

// Re-export ImageBuffer processing functions for 1D LUT
pub use lut_1d_processing::{
    apply_to_image_buffer_luma, apply_to_image_buffer_luma_a,
    apply_to_image_buffer_rgb as apply_1d_to_image_buffer_rgb,
    apply_to_image_buffer_rgb_mut as apply_1d_to_image_buffer_rgb_mut,
    apply_to_image_buffer_rgba as apply_1d_to_image_buffer_rgba,
    apply_to_image_buffer_rgba_mut as apply_1d_to_image_buffer_rgba_mut,
};

// Re-export ImageBuffer processing functions for 3D LUT
pub use lut_3d_processing::{
    apply_to_image_buffer_rgb_mut as apply_3d_to_image_buffer_rgb_mut,
    apply_to_image_buffer_rgb_unchecked as apply_3d_to_image_buffer_rgb,
    apply_to_image_buffer_rgba_mut as apply_3d_to_image_buffer_rgba_mut,
    apply_to_image_buffer_rgba_unchecked as apply_3d_to_image_buffer_rgba,
};

// Re-export SoA 3D LUT (alias in lut_3d.rs)
pub use lut_3d::Lut3DSoA;

/// Apply LUT to ImageBuffer<Rgb<u8>> (auto-detects 1D/3D)
/// This is most convenient function for ImageBuffer processing
pub fn apply_rgb(
    cube_lut: &CubeLut,
    image: &ImageBuffer<image::Rgb<u8>, Vec<u8>>,
) -> ImageBuffer<image::Rgb<u8>, Vec<u8>> {
    match &cube_lut.lut {
        LutData::Lut1D(lut) => lut_1d_processing::apply_to_image_buffer_rgb(cube_lut, image, lut),
        LutData::Lut3D(lut) => {
            lut_3d_processing::apply_to_image_buffer_rgb_unchecked(cube_lut, image, lut)
        }
    }
}

/// Apply LUT to ImageBuffer<Rgb<u8>> in-place (auto-detects 1D/3D)
/// Zero-allocation in-place modification with maximum performance:
/// - Direct byte slice access instead of get_pixel/put_pixel
/// - Pre-computed inverse domain ranges
/// - Linear memory access pattern for cache efficiency
#[inline]
pub fn apply_rgb_mut(cube_lut: &CubeLut, image: &mut ImageBuffer<image::Rgb<u8>, Vec<u8>>) {
    match &cube_lut.lut {
        LutData::Lut1D(lut) => {
            lut_1d_processing::apply_to_image_buffer_rgb_mut(cube_lut, image, lut)
        }
        LutData::Lut3D(lut) => {
            lut_3d_processing::apply_to_image_buffer_rgb_mut(cube_lut, image, lut)
        }
    }
}

/// Apply LUT to ImageBuffer<Rgba<u8>> (auto-detects 1D/3D)
/// This is most convenient function for ImageBuffer processing
pub fn apply_rgba(
    cube_lut: &CubeLut,
    image: &ImageBuffer<image::Rgba<u8>, Vec<u8>>,
) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> {
    match &cube_lut.lut {
        LutData::Lut1D(lut) => lut_1d_processing::apply_to_image_buffer_rgba(cube_lut, image, lut),
        LutData::Lut3D(lut) => {
            lut_3d_processing::apply_to_image_buffer_rgba_unchecked(cube_lut, image, lut)
        }
    }
}

/// Apply LUT to ImageBuffer<Rgba<u8>> in-place (auto-detects 1D/3D)
/// Zero-allocation in-place modification with maximum performance:
/// - Direct byte slice access instead of get_pixel/put_pixel
/// - Pre-computed inverse domain ranges
/// - Linear memory access pattern for cache efficiency
/// - Alpha channel preserved without modification
#[inline]
pub fn apply_rgba_mut(cube_lut: &CubeLut, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) {
    match &cube_lut.lut {
        LutData::Lut1D(lut) => {
            lut_1d_processing::apply_to_image_buffer_rgba_mut(cube_lut, image, lut)
        }
        LutData::Lut3D(lut) => {
            lut_3d_processing::apply_to_image_buffer_rgba_mut(cube_lut, image, lut)
        }
    }
}

// Re-export processing functions for testing
#[cfg(test)]
pub use lut_1d_processing::{__normal_test_apply_1d_lut, __normal_test_interpolate_1d};

/// Type of LUT (1D Fixed, 1D Other, or 3D)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LutType {
    Lut1DFixed,
    Lut1DOther,
    Lut3DFixed,
    Lut3DOther,
}

impl std::fmt::Display for LutType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LutType::Lut1DFixed => write!(f, "1D LUT (Fixed)"),
            LutType::Lut1DOther => write!(f, "1D LUT (Other)"),
            LutType::Lut3DFixed => write!(f, "3D LUT (Fixed)"),
            LutType::Lut3DOther => write!(f, "3D LUT (Other)"),
        }
    }
}

/// LUT data - exactly one of these is always present
#[derive(Debug, Clone)]
pub enum LutData {
    Lut1D(Lut1D),
    Lut3D(Lut3D),
}

impl LutData {
    /// Get LUT type
    pub fn get_type(&self) -> LutType {
        match self {
            LutData::Lut1D(lut_1d) => {
                // Fixed sizes: 1024 (10-bit), 4096 (12-bit), 16384 (14-bit), 65536 (16-bit)
                match lut_1d {
                    lut_1d::Lut1D::Bit10 { .. } => LutType::Lut1DFixed,
                    lut_1d::Lut1D::Bit12 { .. } => LutType::Lut1DFixed,
                    lut_1d::Lut1D::Bit14 { .. } => LutType::Lut1DFixed,
                    lut_1d::Lut1D::Bit16 { .. } => LutType::Lut1DFixed,
                    lut_1d::Lut1D::Other { .. } => LutType::Lut1DOther,
                }
            }
            LutData::Lut3D(_lut_3d) => {
                // All 3D LUTs are now SoA (cache-optimized)
                LutType::Lut3DFixed
            }
        }
    }

    /// Check if this is a 1D LUT
    pub fn is_1d(&self) -> bool {
        matches!(self, LutData::Lut1D(_))
    }

    /// Check if this is a 3D LUT
    pub fn is_3d(&self) -> bool {
        matches!(self, LutData::Lut3D(_))
    }

    /// Get 1D LUT reference
    pub fn as_1d(&self) -> Option<&Lut1D> {
        match self {
            LutData::Lut1D(lut) => Some(lut),
            LutData::Lut3D(_) => None,
        }
    }

    /// Get 1D LUT mutable reference
    pub fn as_1d_mut(&mut self) -> Option<&mut Lut1D> {
        match self {
            LutData::Lut1D(lut) => Some(lut),
            LutData::Lut3D(_) => None,
        }
    }

    /// Get 3D LUT reference
    pub fn as_3d(&self) -> Option<&Lut3D> {
        match self {
            LutData::Lut1D(_) => None,
            LutData::Lut3D(lut) => Some(lut),
        }
    }

    /// Get 3D LUT mutable reference
    pub fn as_3d_mut(&mut self) -> Option<&mut Lut3D> {
        match self {
            LutData::Lut1D(_) => None,
            LutData::Lut3D(lut) => Some(lut),
        }
    }
}

/// Main CUBE LUT structure
#[derive(Debug, Clone)]
pub struct CubeLut {
    /// Optional title from file
    pub title: Option<String>,
    /// Input domain minimum values for R, G, B
    pub domain_min: Rgb,
    /// Input domain maximum values for R, G, B
    pub domain_max: Rgb,
    /// LUT data (exactly one is always present)
    pub lut: LutData,
}

impl CubeLut {
    /// Create a new CUBE LUT with 1D LUT data
    pub fn with_1d(lut_1d: Lut1D) -> Self {
        CubeLut {
            title: None,
            domain_min: [0.0, 0.0, 0.0],
            domain_max: [1.0, 1.0, 1.0],
            lut: LutData::Lut1D(lut_1d),
        }
    }

    /// Create a new CUBE LUT with 3D LUT data
    pub fn with_3d(lut_3d: Lut3D) -> Self {
        CubeLut {
            title: None,
            domain_min: [0.0, 0.0, 0.0],
            domain_max: [1.0, 1.0, 1.0],
            lut: LutData::Lut3D(lut_3d),
        }
    }

    /// Validate LUT structure
    pub fn validate(&self) -> crate::error::Result<()> {
        // Check domain bounds
        for i in 0..3 {
            if self.domain_min[i] >= self.domain_max[i] {
                return Err(crate::error::CubeError::DomainBoundsReversed);
            }
        }

        // LUT data is always present (enum enforces this)
        // No need to check for both/none scenarios

        Ok(())
    }

    /// Get LUT type
    pub fn get_lut_type(&self) -> LutType {
        self.lut.get_type()
    }

    /// Check if this is a 1D LUT
    pub fn is_1d(&self) -> bool {
        self.lut.is_1d()
    }

    /// Check if this is a 3D LUT
    pub fn is_3d(&self) -> bool {
        self.lut.is_3d()
    }

    /// Get 1D LUT reference
    pub fn lut_1d(&self) -> Option<&Lut1D> {
        self.lut.as_1d()
    }

    /// Get 3D LUT reference
    pub fn lut_3d(&self) -> Option<&Lut3D> {
        self.lut.as_3d()
    }

    /// Apply LUT to a color value using SIMD-optimized implementation
    pub fn apply_to_color(&self, color: Rgb) -> Result<Rgb> {
        // Normalize input to [0, 1] based on domain
        let normalized_r = self.normalize(color[0], 0);
        let normalized_g = self.normalize(color[1], 1);
        let normalized_b = self.normalize(color[2], 2);

        let lut_type = self.get_lut_type();

        let output = match lut_type {
            LutType::Lut1DFixed | LutType::Lut1DOther => {
                if let Some(lut_1d) = self.lut_1d() {
                    lut_1d_processing::apply_1d_lut_simd(
                        lut_1d,
                        normalized_r,
                        normalized_g,
                        normalized_b,
                    )
                } else {
                    return Err(crate::error::CubeError::InvalidFormat(
                        "1D LUT not available".to_string(),
                    ));
                }
            }
            LutType::Lut3DFixed | LutType::Lut3DOther => {
                if let Some(lut_3d) = self.lut_3d() {
                    // All 3D LUTs use SoA implementation
                    let (r_ptr, g_ptr, b_ptr) = unsafe { lut_3d.channel_pointers() };
                    let size = lut_3d.size();
                    lut_3d_processing::apply_3d_lut_soa(
                        r_ptr,
                        g_ptr,
                        b_ptr,
                        normalized_r,
                        normalized_g,
                        normalized_b,
                        size,
                        (size - 1) as f32,
                        size * size,
                    )
                } else {
                    return Err(crate::error::CubeError::InvalidFormat(
                        "3D LUT not available".to_string(),
                    ));
                }
            }
        };

        Ok(output)
    }

    /// Apply LUT to an image with optimized branching
    /// LUT type is checked once outside the loop to avoid per-pixel overhead
    pub fn apply_to_image(&self, image: &DynamicImage) -> Result<DynamicImage> {
        match &self.lut {
            LutData::Lut1D(lut) => lut_1d_processing::apply_to_image_1d(self, image, lut),
            LutData::Lut3D(lut) => lut_3d_processing::apply_to_image_3d(self, image, lut),
        }
    }

    /// Normalize a value from the input domain to [0, 1]
    #[inline]
    fn normalize(&self, value: f32, channel: usize) -> f32 {
        let min = self.domain_min[channel];
        let max = self.domain_max[channel];
        (value - min) / (max - min)
    }
}

impl Default for CubeLut {
    fn default() -> Self {
        // Create a default 1D LUT (most common case)
        let lut_1d = Lut1D::new(256).unwrap_or_else(|_| Lut1D::new(2).unwrap());
        CubeLut::with_1d(lut_1d)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test that SIMD and scalar 1D LUT implementations produce identical results
    #[test]
    fn test_simd_vs_scalar_1d_lut() {
        // Create a simple 1D LUT
        let mut lut_1d = Lut1D::new(256).unwrap();
        for i in 0..256 {
            let value = i as f32 / 255.0;
            lut_1d.set_rgb(i, [value, value, value]).unwrap();
        }

        let cube_lut = CubeLut::with_1d(lut_1d);

        // Test various color values
        let test_colors = [
            [0.0, 0.0, 0.0],
            [0.5, 0.5, 0.5],
            [1.0, 1.0, 1.0],
            [0.25, 0.75, 0.5],
            [0.1, 0.9, 0.3],
            [0.33, 0.66, 0.99],
        ];

        for color in test_colors {
            // Normalize
            let normalized_r = cube_lut.normalize(color[0], 0);
            let normalized_g = cube_lut.normalize(color[1], 1);
            let normalized_b = cube_lut.normalize(color[2], 2);

            // Get SIMD result
            let simd_result = lut_1d_processing::apply_1d_lut_simd(
                cube_lut.lut_1d().unwrap(),
                normalized_r,
                normalized_g,
                normalized_b,
            );

            // Get scalar result
            let scalar_result = __normal_test_apply_1d_lut(
                cube_lut.lut_1d().unwrap(),
                normalized_r,
                normalized_g,
                normalized_b,
            );

            // Compare results with tolerance for floating point precision
            for c in 0..3 {
                let diff = (simd_result[c] - scalar_result[c]).abs();
                assert!(
                    diff < f32::EPSILON,
                    "SIMD and scalar results differ at channel {}: SIMD={:.10}, Scalar={:.10}, Diff={:.10}",
                    c, simd_result[c], scalar_result[c], diff
                );
            }
        }
    }

    /// Test that SIMD and scalar 3D LUT implementations produce identical results
    #[test]
    fn test_simd_vs_scalar_3d_lut() {
        // Create a simple 3D LUT
        let mut lut_3d = Lut3D::new(17).unwrap();
        for r in 0..17 {
            for g in 0..17 {
                for b in 0..17 {
                    let v_r = r as f32 / 16.0;
                    let v_g = g as f32 / 16.0;
                    let v_b = b as f32 / 16.0;
                    lut_3d.set_rgb(r, g, b, [v_r, v_g, v_b]).unwrap();
                }
            }
        }

        let cube_lut = CubeLut::with_3d(lut_3d);

        // Test that 3D LUT produces consistent results
        let test_colors = [
            [0.0, 0.0, 0.0],
            [0.5, 0.5, 0.5],
            [1.0, 1.0, 1.0],
            [0.25, 0.75, 0.5],
            [0.1, 0.9, 0.3],
            [0.33, 0.66, 0.99],
        ];

        for color in test_colors {
            // Get result using SoA implementation
            let result = cube_lut.apply_to_color(color).unwrap();

            // Verify result is in valid range [0, 1]
            #[allow(clippy::needless_range_loop)]
            for c in 0..3 {
                assert!(
                    result[c] >= 0.0 && result[c] <= 1.0,
                    "3D LUT result out of range at channel {}: Result={:.10}",
                    c,
                    result[c]
                );
            }
        }
    }
}