Skip to main content

rust_motion_cms/
lutfile.rs

1//! Creative 3D LUT files for Image › Adjustments › Color Lookup: `.cube` (Adobe/Resolve), `.3dl`
2//! (Autodesk Lustre / Flame) and `.look` (SpeedGrade XML), plus a few generated (CC0) looks.
3//!
4//! Every table is normalised to [`LutFile`]: `size`³ RGB triplets in 0..=1, **red varying
5//! fastest** (`((b·size + g)·size + r)·3`). Formats follow their public descriptions: the Adobe
6//! "Cube LUT Specification 1.0", the Lustre 3DL layout as documented by OpenColorIO, and the
7//! SpeedGrade `.look` XML (hex-encoded little-endian float32 RGB triplets).
8
9/// A parsed 3D LUT.
10#[derive(Clone, Debug, PartialEq)]
11pub struct LutFile {
12    pub title: String,
13    pub size: usize,
14    /// `size`³ × 3 values, red fastest.
15    pub data: Vec<f32>,
16    /// The input domain the table expects (`.cube` `DOMAIN_MIN`/`DOMAIN_MAX`,
17    /// `LUT_3D_INPUT_RANGE`): an input `c` samples the table at `(c - min) / (max - min)`,
18    /// saturating outside. `[0, 1]` is the identity default; applying a table with any other
19    /// domain is rejected upstream until Color Lookup carries it through.
20    pub domain_min: [f32; 3],
21    pub domain_max: [f32; 3],
22}
23
24/// Largest edge length accepted (64³ is Photoshop's practical maximum; 129 leaves headroom while
25/// keeping the GPU table within texture limits).
26pub const MAX_SIZE: usize = 129;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct LutError(pub String);
30
31impl std::fmt::Display for LutError {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37impl std::error::Error for LutError {}
38
39fn err<T>(msg: impl Into<String>) -> Result<T, LutError> {
40    Err(LutError(msg.into()))
41}
42
43fn checked_data_len(size: usize) -> Result<(usize, usize), LutError> {
44    if !(2..=MAX_SIZE).contains(&size) {
45        return err(format!("unsupported LUT size {size}"));
46    }
47    let entries = size
48        .checked_pow(3)
49        .ok_or_else(|| LutError(format!("unsupported LUT size {size}")))?;
50    let data_len = entries
51        .checked_mul(3)
52        .ok_or_else(|| LutError(format!("unsupported LUT size {size}")))?;
53    Ok((entries, data_len))
54}
55
56impl LutFile {
57    /// The identity table of edge `size`.
58    pub fn identity(size: usize) -> Self {
59        Self::from_fn("Identity", size, |c| c)
60    }
61
62    /// Samples `f` on an `size`³ grid.
63    pub fn from_fn(title: &str, size: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> Self {
64        let m = (size.max(2) - 1) as f32;
65        let mut data = Vec::with_capacity(size * size * size * 3);
66        for b in 0..size {
67            for g in 0..size {
68                for r in 0..size {
69                    let o = f([r as f32 / m, g as f32 / m, b as f32 / m]);
70                    data.extend(o.map(|v| v.clamp(0.0, 1.0)));
71                }
72            }
73        }
74        LutFile {
75            title: title.to_string(),
76            size,
77            data,
78            domain_min: [0.0; 3],
79            domain_max: [1.0; 3],
80        }
81    }
82
83    /// Whether the table expects plain 0..1 inputs (the common case; Photoshop's default).
84    pub fn domain_is_default(&self) -> bool {
85        self.domain_min == [0.0, 0.0, 0.0] && self.domain_max == [1.0, 1.0, 1.0]
86    }
87
88    fn check(self) -> Result<Self, LutError> {
89        let (entries, data_len) = checked_data_len(self.size)?;
90        if self.data.len() != data_len {
91            return err(format!(
92                "expected {entries} entries, found {}",
93                self.data.len() / 3
94            ));
95        }
96        if self.data.iter().any(|v| !v.is_finite()) {
97            return err("non-finite LUT value");
98        }
99        Ok(self)
100    }
101}
102
103/// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing).
104pub fn parse(file_name: &str, bytes: &[u8]) -> Result<LutFile, LutError> {
105    let lower = file_name.to_ascii_lowercase();
106    let text = String::from_utf8_lossy(bytes);
107    if lower.ends_with(".3dl") {
108        parse_3dl(&text)
109    } else if lower.ends_with(".look") || text.trim_start().starts_with('<') {
110        parse_look(&text)
111    } else {
112        parse_cube(&text)
113    }
114}
115
116/// Adobe / Resolve `.cube`. 1D LUTs (`LUT_1D_SIZE`) are expanded to a 33³ table.
117pub fn parse_cube(text: &str) -> Result<LutFile, LutError> {
118    let mut title = String::new();
119    let (mut size3, mut size1) = (0usize, 0usize);
120    let (mut dmin, mut dmax) = ([0.0f32; 3], [1.0f32; 3]);
121    let mut rows: Vec<f32> = Vec::new();
122    for line in text.lines() {
123        let line = line.split('#').next().unwrap_or("").trim();
124        if line.is_empty() {
125            continue;
126        }
127        let mut it = line.split_whitespace();
128        let key = it.next().unwrap_or("");
129        let nums = |it: std::str::SplitWhitespace<'_>| -> Result<[f32; 3], LutError> {
130            let v: Vec<f32> = it.filter_map(|s| s.parse().ok()).collect();
131            if v.len() == 3 {
132                Ok([v[0], v[1], v[2]])
133            } else {
134                err(format!("bad line `{line}`"))
135            }
136        };
137        match key {
138            "TITLE" => title = line[5..].trim().trim_matches('"').to_string(),
139            "LUT_3D_SIZE" => {
140                size3 = it
141                    .next()
142                    .and_then(|s| s.parse().ok())
143                    .ok_or_else(|| LutError("bad LUT_3D_SIZE".into()))?
144            }
145            "LUT_1D_SIZE" => {
146                size1 = it
147                    .next()
148                    .and_then(|s| s.parse().ok())
149                    .ok_or_else(|| LutError("bad LUT_1D_SIZE".into()))?
150            }
151            "DOMAIN_MIN" => dmin = nums(it)?,
152            "DOMAIN_MAX" => dmax = nums(it)?,
153            "LUT_3D_INPUT_RANGE" | "LUT_1D_INPUT_RANGE" => {
154                let v: Vec<f32> = it.filter_map(|s| s.parse().ok()).collect();
155                if v.len() == 2 {
156                    dmin = [v[0]; 3];
157                    dmax = [v[1]; 3];
158                }
159            }
160            k if k
161                .starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+' || c == '.') =>
162            {
163                let mut v = vec![k
164                    .parse::<f32>()
165                    .map_err(|_| LutError(format!("bad number in `{line}`")))?];
166                v.extend(it.filter_map(|s| s.parse::<f32>().ok()));
167                if v.len() != 3 {
168                    return err(format!("bad data line `{line}`"));
169                }
170                rows.extend(v);
171            }
172            // Unknown keywords (e.g. Resolve's LUT_IN_VIDEO_RANGE) are ignored, as the spec allows.
173            _ => {}
174        }
175    }
176    let domain_ok = (0..3).all(|k| dmin[k] < dmax[k] && dmin[k].is_finite() && dmax[k].is_finite());
177    if (size3 > 0 || size1 >= 2) && !domain_ok {
178        return err(format!(
179            "DOMAIN_MIN {:?} must lie below DOMAIN_MAX {:?}",
180            dmin, dmax
181        ));
182    }
183    if size3 > 0 {
184        return LutFile {
185            title,
186            size: size3,
187            data: rows,
188            domain_min: dmin,
189            domain_max: dmax,
190        }
191        .check();
192    }
193    if size1 >= 2 {
194        let expected_rows = size1
195            .checked_mul(3)
196            .ok_or_else(|| LutError(format!("unsupported 1D LUT size {size1}")))?;
197        if rows.len() != expected_rows {
198            return err("no LUT_3D_SIZE in .cube file");
199        }
200        // The 1D table is resampled onto a 0..1 cube anyway, so its input domain
201        // (`DOMAIN_MIN`/`MAX`, `LUT_1D_INPUT_RANGE`) is baked into the resample: an input `v`
202        // reads the table at `(v - min) / (max - min)`, saturating outside.
203        let curve = |ch: usize, v: f32| {
204            let t = (v - dmin[ch]) / (dmax[ch] - dmin[ch]);
205            let x = if t.is_finite() {
206                t.clamp(0.0, 1.0)
207            } else {
208                0.0
209            } * (size1 - 1) as f32;
210            let i = (x.floor() as usize).min(size1 - 2);
211            let f = x - i as f32;
212            rows[i * 3 + ch] * (1.0 - f) + rows[(i + 1) * 3 + ch] * f
213        };
214        let mut l = LutFile::from_fn(&title, 33, |c| {
215            [curve(0, c[0]), curve(1, c[1]), curve(2, c[2])]
216        });
217        l.title = title;
218        return l.check();
219    }
220    err("no LUT_3D_SIZE in .cube file")
221}
222
223/// Lustre `.3dl`: an optional shaper line of input values, then integer RGB rows with **blue**
224/// varying fastest; the output bit depth is inferred from the largest value.
225pub fn parse_3dl(text: &str) -> Result<LutFile, LutError> {
226    let mut rows: Vec<[f64; 3]> = Vec::new();
227    for line in text.lines() {
228        let line = line.split('#').next().unwrap_or("").trim();
229        if line.is_empty() || line.starts_with(|c: char| c.is_ascii_alphabetic()) {
230            continue;
231        }
232        let v: Vec<f64> = line
233            .split_whitespace()
234            .filter_map(|s| s.parse().ok())
235            .collect();
236        if v.len() == 3 {
237            rows.push([v[0], v[1], v[2]]);
238        }
239        // Lines with more than three numbers are the input shaper; it is assumed linear.
240    }
241    let n = (rows.len() as f64).cbrt().round() as usize;
242    if n < 2 || n * n * n != rows.len() {
243        return err(format!("{} rows is not a cube", rows.len()));
244    }
245    let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b));
246    let scale = if max <= 1.0 {
247        1.0
248    } else {
249        [1023.0, 4095.0, 16383.0, 65535.0]
250            .into_iter()
251            .find(|&s| max <= s)
252            .unwrap_or(max)
253    };
254    let mut data = vec![0.0f32; n * n * n * 3];
255    for (i, row) in rows.iter().enumerate() {
256        let (r, g, b) = (i / (n * n), (i / n) % n, i % n);
257        let at = ((b * n + g) * n + r) * 3;
258        for k in 0..3 {
259            data[at + k] = (row[k] / scale) as f32;
260        }
261    }
262    LutFile {
263        title: String::new(),
264        size: n,
265        data,
266        domain_min: [0.0; 3],
267        domain_max: [1.0; 3],
268    }
269    .check()
270}
271
272/// SpeedGrade `.look`: `<size>` and a hex `<data>` string of little-endian float32 RGB triplets
273/// (red fastest).
274pub fn parse_look(text: &str) -> Result<LutFile, LutError> {
275    let tag = |name: &str| -> Option<String> {
276        let open = format!("<{name}>");
277        let start = text.find(&open)? + open.len();
278        let end = text[start..].find(&format!("</{name}>"))? + start;
279        Some(text[start..end].trim().trim_matches('"').trim().to_string())
280    };
281    let size: usize = tag("size")
282        .and_then(|s| s.parse().ok())
283        .ok_or_else(|| LutError("no <size> in .look".into()))?;
284    let (entries, _) = checked_data_len(size)?;
285    let hex: Vec<u8> = tag("data")
286        .ok_or_else(|| LutError("no <data> in .look".into()))?
287        .bytes()
288        .filter(u8::is_ascii_hexdigit)
289        .collect();
290    let nib = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
291    let bytes: Vec<u8> = hex
292        .as_chunks::<2>()
293        .0
294        .iter()
295        .map(|p| nib(p[0]) << 4 | nib(p[1]))
296        .collect();
297    let floats: Vec<f32> = bytes
298        .as_chunks::<4>()
299        .0
300        .iter()
301        .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
302        .collect();
303    let rgba_entries = entries
304        .checked_mul(4)
305        .ok_or_else(|| LutError(format!("unsupported LUT size {size}")))?;
306    let data = if floats.len() == rgba_entries {
307        floats
308            .as_chunks::<4>()
309            .0
310            .iter()
311            .flat_map(|c| [c[0], c[1], c[2]])
312            .collect()
313    } else {
314        floats
315    };
316    LutFile {
317        title: tag("title").unwrap_or_default(),
318        size,
319        data,
320        domain_min: [0.0; 3],
321        domain_max: [1.0; 3],
322    }
323    .check()
324}
325
326/// Writes a `.cube` file (what Photoshop embeds in a Color Lookup layer).
327pub fn write_cube(l: &LutFile) -> String {
328    let mut s = String::new();
329    if !l.title.is_empty() {
330        s.push_str(&format!("TITLE \"{}\"\n", l.title.replace('"', "'")));
331    }
332    s.push_str(&format!("LUT_3D_SIZE {}\n", l.size));
333    for c in l.data.as_chunks::<3>().0 {
334        s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2]));
335    }
336    s
337}
338
339fn luma(c: [f32; 3]) -> f32 {
340    0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
341}
342
343fn smooth(x: f32) -> f32 {
344    let x = x.clamp(0.0, 1.0);
345    x * x * (3.0 - 2.0 * x)
346}
347
348/// Generated looks shipped with Photocraft (procedural, CC0): `(id, label)`.
349pub const BUILTIN: [(&str, &str); 8] = [
350    ("warm", "Warm Filter"),
351    ("cool", "Cool Filter"),
352    ("tealOrange", "Teal & Orange"),
353    ("bleachBypass", "Bleach Bypass"),
354    ("fadedFilm", "Faded Film"),
355    ("dayForNight", "Day for Night"),
356    ("monoContrast", "Mono High Contrast"),
357    ("crossProcess", "Cross Process"),
358];
359
360/// A built-in look by id (33³), or None.
361pub fn builtin(id: &str) -> Option<LutFile> {
362    let label = BUILTIN.iter().find(|b| b.0 == id)?.1;
363    let f: Box<dyn Fn([f32; 3]) -> [f32; 3]> = match id {
364        "warm" => Box::new(|c: [f32; 3]| [c[0] * 0.92 + 0.08, c[1] * 0.97 + 0.02, c[2] * 0.85]),
365        "cool" => Box::new(|c: [f32; 3]| [c[0] * 0.86, c[1] * 0.97 + 0.01, c[2] * 0.9 + 0.1]),
366        "tealOrange" => Box::new(|c: [f32; 3]| {
367            // Shadows toward teal, highlights toward orange, skin-ish midtones kept.
368            let l = luma(c);
369            let t = smooth(l);
370            let teal = [0.0, 0.5, 0.55];
371            let orange = [1.0, 0.62, 0.3];
372            std::array::from_fn(|k| {
373                let tint = teal[k] * (1.0 - t) + orange[k] * t;
374                c[k] * 0.75 + (tint * l * 1.1).min(1.0) * 0.25 + (smooth(c[k]) - c[k]) * 0.3
375            })
376        }),
377        "bleachBypass" => Box::new(|c: [f32; 3]| {
378            let l = luma(c);
379            let s = smooth(l);
380            std::array::from_fn(|k| {
381                let desat = c[k] * 0.45 + l * 0.55;
382                desat * 0.5 + s * 0.5
383            })
384        }),
385        "fadedFilm" => Box::new(|c: [f32; 3]| {
386            let l = luma(c);
387            let tint = [1.0, 0.96, 0.88];
388            std::array::from_fn(|k| (0.08 + (c[k] * 0.8 + l * 0.2) * 0.84) * tint[k] + 0.02)
389        }),
390        "dayForNight" => Box::new(|c: [f32; 3]| {
391            let l = luma(c);
392            [l * 0.35, l * 0.45 + c[1] * 0.05, l * 0.65 + c[2] * 0.15]
393        }),
394        "monoContrast" => Box::new(|c: [f32; 3]| [smooth(smooth(luma(c))); 3]),
395        _ /* crossProcess */ => Box::new(|c: [f32; 3]| [smooth(c[0]) * 1.05, c[1] * 1.1 - 0.03, c[2] * 0.7 + 0.15]),
396    };
397    Some(LutFile::from_fn(label, 33, f))
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn cube_domain_is_kept_and_validated() {
406        let base = "TITLE \"t\"
407LUT_3D_SIZE 2
408";
409        let rows = "0 0 0
4100 0 1
4110 1 0
4120 1 1
4131 0 0
4141 0 1
4151 1 0
4161 1 1
417";
418        // The default domain parses as default.
419        let d = parse_cube(&format!("{base}{rows}")).expect("default domain");
420        assert!(d.domain_is_default());
421        // DOMAIN_MIN/MAX are kept for the caller to act on.
422        let d = parse_cube(&format!(
423            "DOMAIN_MIN 0.1 0.2 0.3
424DOMAIN_MAX 0.9 0.8 0.7
425{base}{rows}"
426        ))
427        .expect("custom domain");
428        assert_eq!(d.domain_min, [0.1, 0.2, 0.3]);
429        assert_eq!(d.domain_max, [0.9, 0.8, 0.7]);
430        assert!(!d.domain_is_default());
431        // A degenerate domain is a parse error, not a division by zero later.
432        let e = parse_cube(&format!(
433            "DOMAIN_MIN 0.5 0.5 0.5
434DOMAIN_MAX 0.5 1 1
435{base}{rows}"
436        ))
437        .unwrap_err();
438        assert!(e.0.contains("below DOMAIN_MAX"), "{e}");
439    }
440
441    #[test]
442    fn cube_1d_domain_is_baked_into_the_resample() {
443        // An identity ramp over the domain 0.25..0.75: 0.25 maps to 0, 0.5 to 0.5, 0.75 to 1.
444        let table = "LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 0.25 0.75\n0 0 0\n1 1 1\n";
445        let l = parse_cube(table).expect("1D with input range");
446        assert!(
447            l.domain_is_default(),
448            "the domain is baked in, so the cube is plain 0..1"
449        );
450        let at = |r: usize| l.data[r * 3];
451        // 33-point grid, red fastest: entry r on the red axis is input r / 32.
452        assert!(at(0).abs() < 1e-6, "below the domain saturates to 0");
453        assert!(
454            (at(16) - 0.5).abs() < 1e-5,
455            "0.5 is the middle of 0.25..0.75: {}",
456            at(16)
457        );
458        assert!((at(8) - 0.0).abs() < 1e-5, "0.25 maps to 0: {}", at(8));
459        assert!((at(24) - 1.0).abs() < 1e-5, "0.75 maps to 1: {}", at(24));
460        assert!(
461            (at(32) - 1.0).abs() < 1e-6,
462            "above the domain saturates to 1"
463        );
464        // Per-channel DOMAIN_MIN/MAX work the same way.
465        let l = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0.5\nDOMAIN_MAX 1 1 1\n0 0 0\n1 1 1\n")
466            .expect("1D domain");
467        let blue_mid = l.data[(16 * 33 * 33) * 3 + 2];
468        assert!(
469            blue_mid.abs() < 1e-5,
470            "blue 0.5 is the bottom of its domain: {blue_mid}"
471        );
472        // A degenerate 1D domain is rejected like the 3D one.
473        let e = parse_cube("LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 1 1\n0 0 0\n1 1 1\n").unwrap_err();
474        assert!(e.0.contains("below DOMAIN_MAX"), "{e}");
475    }
476
477    #[test]
478    fn cube_roundtrip_and_identity() {
479        let id = LutFile::identity(5);
480        let text = write_cube(&LutFile {
481            title: "Id".into(),
482            ..id.clone()
483        });
484        let back = parse_cube(&text).unwrap();
485        assert_eq!(back.size, 5);
486        assert_eq!(back.title, "Id");
487        for (a, b) in back.data.iter().zip(&id.data) {
488            assert!((a - b).abs() < 1e-5);
489        }
490        // Red varies fastest: entry 1 is (0.25, 0, 0).
491        assert_eq!(&back.data[3..6], &[0.25, 0.0, 0.0]);
492    }
493
494    #[test]
495    fn cube_1d_expands() {
496        let text = "LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n";
497        let l = parse_cube(text).unwrap();
498        assert_eq!(l.size, 33);
499        let last = &l.data[l.data.len() - 3..];
500        assert!((last[0] - 0.5).abs() < 1e-6 && (last[1] - 1.0).abs() < 1e-6);
501
502        let mut larger = String::from("LUT_1D_SIZE 256\n");
503        for i in 0..256 {
504            let value = i as f32 / 255.0;
505            larger.push_str(&format!("{value} {value} {value}\n"));
506        }
507        assert_eq!(parse_cube(&larger).unwrap().size, 33);
508    }
509
510    #[test]
511    fn cube_1d_size_multiplication_overflow_is_rejected() {
512        let text = format!("LUT_1D_SIZE {}\n", usize::MAX);
513        assert!(parse_cube(&text).is_err());
514    }
515
516    #[test]
517    fn three_dl_blue_fastest_and_bit_depth() {
518        let mut text = String::from("0 1023\n");
519        for r in 0..2 {
520            for g in 0..2 {
521                for b in 0..2 {
522                    text.push_str(&format!("{} {} {}\n", r * 4095, g * 4095, b * 4095));
523                }
524            }
525        }
526        let l = parse_3dl(&text).unwrap();
527        assert_eq!(l.size, 2);
528        assert_eq!(l.data, LutFile::identity(2).data);
529    }
530
531    #[test]
532    fn look_hex_floats() {
533        let id = LutFile::identity(2);
534        let hex: String = id
535            .data
536            .iter()
537            .flat_map(|v| v.to_le_bytes())
538            .map(|b| format!("{b:02X}"))
539            .collect();
540        let xml = format!("<?xml version=\"1.0\"?><look><LUT><size>\"2\"</size><data>\"{hex}\"</data></LUT></look>");
541        assert_eq!(parse("a.look", xml.as_bytes()).unwrap().data, id.data);
542    }
543
544    #[test]
545    fn look_3d_size_exponent_overflow_is_rejected() {
546        let text = format!("<look><size>{}</size><data>00</data></look>", usize::MAX);
547        assert!(parse_look(&text).is_err());
548    }
549
550    #[test]
551    fn malformed_rejected() {
552        assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());
553        assert!(parse_cube("garbage").is_err());
554        assert!(parse_cube("LUT_3D_SIZE 99999\n").is_err());
555        assert!(parse_3dl("1 2 3\n4 5 6\n").is_err());
556        assert!(parse_look("<look></look>").is_err());
557    }
558
559    #[test]
560    fn builtins_exist_and_are_in_range() {
561        for (id, _) in BUILTIN {
562            let l = builtin(id).unwrap();
563            assert_eq!(l.data.len(), 33 * 33 * 33 * 3);
564            assert!(l.data.iter().all(|v| (0.0..=1.0).contains(v)), "{id}");
565        }
566        assert!(builtin("nope").is_none());
567    }
568}