forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

cube.rs382 lines, 15.4 KiBHistoryRawDownload
1//! `.cube` look-up tables: the file format, the sampler, and the process-wide
2//! table of loaded files a grade names its LUT through.
3//!
4//! The format is Adobe's Cube 1.0 as every grading tool writes it: optional
5//! `TITLE`, one of `LUT_1D_SIZE N` / `LUT_3D_SIZE N`, optional `DOMAIN_MIN r g b`
6//! and `DOMAIN_MAX r g b` (or Resolve's `LUT_1D_INPUT_RANGE lo hi` /
7//! `LUT_3D_INPUT_RANGE lo hi`), `#` comments, then the table as one `r g b`
8//! line per entry with red changing fastest. A 3D table is sampled
9//! tetrahedrally (the interpolation `ffmpeg -vf lut3d=interp=tetrahedral` and the
10//! grading suites use), a 1D table linearly per channel.
11//!
12//! A grade holds a [`LutRef`], not the table: a small `Copy` handle into the
13//! registry below, so [`crate::color::ColorParams`] stays plain data that every
14//! render path can copy per frame. The registry maps a handle to the path it was
15//! made from and to the parsed table -- or to why there is none, which is how a
16//! missing or broken file becomes a warning and an ungraded-by-LUT picture
17//! instead of a failed render.
18
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex};
21
22/// The largest 3D table edge a file may declare (65 is the biggest any tool writes).
23pub const MAX_3D_SIZE: usize = 65;
24/// The largest 1D table a file may declare.
25pub const MAX_1D_SIZE: usize = 65_536;
26/// The largest `.cube` file read: a 65-edge table is ~10 MB of text.
27const MAX_FILE_BYTES: u64 = 64 << 20;
28
29/// One parsed `.cube` file.
30#[derive(Debug, Clone, PartialEq)]
31pub struct Cube {
32 /// The `TITLE`, if the file gave one.
33 pub title: Option<String>,
34 /// Whether this is a 3D table (`LUT_3D_SIZE`) rather than a 1D one.
35 pub three_d: bool,
36 /// Entries per axis (3D) or entries (1D).
37 pub size: usize,
38 /// The input value mapped to the first entry, per channel.
39 pub domain_min: [f32; 3],
40 /// The input value mapped to the last entry, per channel.
41 pub domain_max: [f32; 3],
42 /// The table, red fastest: `size` entries for 1D, `size^3` for 3D.
43 pub data: Vec<[f32; 3]>,
44}
45
46fn nums<const N: usize>(rest: &[&str], line: usize, what: &str) -> Result<[f32; N], String> {
47 if rest.len() != N {
48 return Err(format!("line {line}: {what} wants {N} numbers, found {}", rest.len()));
49 }
50 let mut out = [0f32; N];
51 for (o, t) in out.iter_mut().zip(rest) {
52 *o = t
53 .parse::<f32>()
54 .ok()
55 .filter(|v| v.is_finite())
56 .ok_or_else(|| format!("line {line}: {what}: '{t}' is not a number"))?;
57 }
58 Ok(out)
59}
60
61fn size_of(rest: &[&str], line: usize, what: &str, max: usize) -> Result<usize, String> {
62 let [t] = rest else {
63 return Err(format!("line {line}: {what} wants one size"));
64 };
65 let n: usize = t.parse().map_err(|_| format!("line {line}: {what}: '{t}' is not a size"))?;
66 if !(2..=max).contains(&n) {
67 return Err(format!("line {line}: {what} {n} is outside 2..={max}"));
68 }
69 Ok(n)
70}
71
72/// Parses the text of a `.cube` file. Every refusal names the line and what is
73/// wrong with it, so the message can be shown as it is.
74pub fn parse(text: &str) -> Result<Cube, String> {
75 let mut title = None;
76 let (mut size1, mut size3) = (None, None);
77 let (mut min, mut max) = ([0f32; 3], [1f32; 3]);
78 let mut data: Vec<[f32; 3]> = Vec::new();
79 let mut want = 0usize;
80 for (i, raw) in text.lines().enumerate() {
81 let n = i + 1;
82 let line = raw.split('#').next().unwrap_or("").trim();
83 if line.is_empty() {
84 continue;
85 }
86 let words: Vec<&str> = line.split_whitespace().collect();
87 let head = words[0];
88 let starts_alpha = head.starts_with(|c: char| c.is_ascii_alphabetic());
89 if !starts_alpha {
90 if want == 0 {
91 return Err(format!("line {n}: table data before LUT_1D_SIZE or LUT_3D_SIZE"));
92 }
93 if data.len() == want {
94 return Err(format!("line {n}: more table entries than the declared {want}"));
95 }
96 data.push(nums::<3>(&words, n, "a table entry")?);
97 continue;
98 }
99 if !data.is_empty() {
100 return Err(format!("line {n}: keyword '{head}' after the table data began"));
101 }
102 let rest = &words[1..];
103 match head {
104 "TITLE" => {
105 let t = line["TITLE".len()..].trim();
106 title = Some(t.trim_matches('"').to_string());
107 }
108 "LUT_1D_SIZE" => size1 = Some(size_of(rest, n, head, MAX_1D_SIZE)?),
109 "LUT_3D_SIZE" => size3 = Some(size_of(rest, n, head, MAX_3D_SIZE)?),
110 "DOMAIN_MIN" => min = nums::<3>(rest, n, head)?,
111 "DOMAIN_MAX" => max = nums::<3>(rest, n, head)?,
112 "LUT_1D_INPUT_RANGE" | "LUT_3D_INPUT_RANGE" => {
113 let [lo, hi] = nums::<2>(rest, n, head)?;
114 min = [lo; 3];
115 max = [hi; 3];
116 }
117 // Other tools' own keywords (Resolve's LUT_IN_VIDEO_RANGE and the
118 // like) carry nothing this sampler reads.
119 _ => {}
120 }
121 want = match (size1, size3) {
122 (Some(_), Some(_)) => {
123 return Err(format!("line {n}: both LUT_1D_SIZE and LUT_3D_SIZE; one table per file"));
124 }
125 (Some(s), None) => s,
126 (None, Some(s)) => s * s * s,
127 (None, None) => 0,
128 };
129 }
130 if want == 0 {
131 return Err("no LUT_1D_SIZE or LUT_3D_SIZE line: not a .cube table".into());
132 }
133 if data.len() != want {
134 return Err(format!("the table has {} entries, the size line declares {want}", data.len()));
135 }
136 if (0..3).any(|c| min[c] >= max[c]) {
137 return Err("DOMAIN_MIN must be below DOMAIN_MAX on every channel".into());
138 }
139 Ok(Cube {
140 title,
141 three_d: size3.is_some(),
142 size: size3.or(size1).unwrap_or(0),
143 domain_min: min,
144 domain_max: max,
145 data,
146 })
147}
148
149/// Reads and parses a `.cube` file.
150pub fn load(path: &Path) -> Result<Cube, String> {
151 let meta = std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
152 if meta.len() > MAX_FILE_BYTES {
153 return Err(format!("{} is {} bytes, more than a .cube table can be", path.display(), meta.len()));
154 }
155 let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
156 let text = String::from_utf8(bytes).map_err(|_| format!("{} is not a text file", path.display()))?;
157 parse(&text).map_err(|e| format!("{}: {e}", path.display()))
158}
159
160impl Cube {
161 /// The table at `rgb` (non-linear R'G'B', 0..1 for the default domain).
162 /// Inputs outside the domain are held at its edge.
163 pub fn sample(&self, rgb: [f32; 3]) -> [f32; 3] {
164 let edge = (self.size - 1) as f32;
165 let mut p = [0f32; 3];
166 for c in 0..3 {
167 let t = (rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c]);
168 p[c] = t.clamp(0.0, 1.0) * edge;
169 }
170 if !self.three_d {
171 let mut out = [0f32; 3];
172 for c in 0..3 {
173 let i = (p[c] as usize).min(self.size - 2);
174 let d = p[c] - i as f32;
175 out[c] = self.data[i][c] * (1.0 - d) + self.data[i + 1][c] * d;
176 }
177 return out;
178 }
179 let s = self.size;
180 let i = [0, 1, 2].map(|c| (p[c] as usize).min(s - 2));
181 let d = [0, 1, 2].map(|c| p[c] - i[c] as f32);
182 let at = |r: usize, g: usize, b: usize| self.data[(i[0] + r) + (i[1] + g) * s + (i[2] + b) * s * s];
183 let c000 = at(0, 0, 0);
184 let c111 = at(1, 1, 1);
185 let (dr, dg, db) = (d[0], d[1], d[2]);
186 // The six tetrahedra of the unit cube, picked by the order of the
187 // fractions: each output is four corners weighted by their differences.
188 let (w, a, b) = if dr > dg {
189 if dg > db {
190 ([1.0 - dr, dr - dg, dg - db, db], at(1, 0, 0), at(1, 1, 0))
191 } else if dr > db {
192 ([1.0 - dr, dr - db, db - dg, dg], at(1, 0, 0), at(1, 0, 1))
193 } else {
194 ([1.0 - db, db - dr, dr - dg, dg], at(0, 0, 1), at(1, 0, 1))
195 }
196 } else if db > dg {
197 ([1.0 - db, db - dg, dg - dr, dr], at(0, 0, 1), at(0, 1, 1))
198 } else if db > dr {
199 ([1.0 - dg, dg - db, db - dr, dr], at(0, 1, 0), at(0, 1, 1))
200 } else {
201 ([1.0 - dg, dg - dr, dr - db, db], at(0, 1, 0), at(1, 1, 0))
202 };
203 [0, 1, 2].map(|c| w[0] * c000[c] + w[1] * a[c] + w[2] * b[c] + w[3] * c111[c])
204 }
205}
206
207/// A grade's handle on a `.cube` file: an index into the process-wide table of
208/// loaded files. Equal paths share a handle, so a grade compares equal to
209/// another naming the same file.
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
211pub struct LutRef(u32);
212
213struct Entry {
214 path: PathBuf,
215 table: Result<Arc<Cube>, String>,
216}
217
218static TABLE: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
219
220fn table() -> std::sync::MutexGuard<'static, Vec<Entry>> {
221 TABLE.lock().unwrap_or_else(|e| e.into_inner())
222}
223
224impl LutRef {
225 /// The handle for `path`, reading the file the first time it is named and
226 /// again whenever an earlier read failed (so a file that turns up later is
227 /// picked up). Never fails: a file that cannot be read gets a handle whose
228 /// [`table`](Self::table) says why.
229 pub fn open(path: &Path) -> Self {
230 let mut t = table();
231 if let Some(i) = t.iter().position(|e| e.path == path) {
232 if t[i].table.is_err() {
233 t[i].table = load(path).map(Arc::new);
234 }
235 return Self(i as u32);
236 }
237 t.push(Entry {
238 path: path.to_path_buf(),
239 table: load(path).map(Arc::new),
240 });
241 Self((t.len() - 1) as u32)
242 }
243
244 /// [`open`](Self::open), re-reading the file even when it loaded before: what a
245 /// relink to the same path (an edited file) asks for.
246 pub fn reload(path: &Path) -> Self {
247 let r = Self::open(path);
248 let fresh = load(path).map(Arc::new);
249 table()[r.0 as usize].table = fresh;
250 r
251 }
252
253 /// The path this handle was made from.
254 pub fn path(self) -> PathBuf {
255 table().get(self.0 as usize).map(|e| e.path.clone()).unwrap_or_default()
256 }
257
258 /// The parsed table, or why there is none (missing file, malformed file).
259 pub fn table(self) -> Result<Arc<Cube>, String> {
260 match table().get(self.0 as usize) {
261 Some(e) => e.table.clone(),
262 None => Err("unknown LUT".into()),
263 }
264 }
265
266 /// Why the table cannot be used, or `None` when it can.
267 pub fn problem(self) -> Option<String> {
268 self.table().err()
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 /// A 3D table of `size` whose entries are `f` of the grid point.
277 pub(crate) fn cube_text(size: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> String {
278 let mut s = format!("TITLE \"t\"\nLUT_3D_SIZE {size}\n");
279 let e = (size - 1) as f32;
280 for b in 0..size {
281 for g in 0..size {
282 for r in 0..size {
283 let o = f([r as f32 / e, g as f32 / e, b as f32 / e]);
284 s.push_str(&format!("{} {} {}\n", o[0], o[1], o[2]));
285 }
286 }
287 }
288 s
289 }
290
291 #[test]
292 fn identity_3d_samples_back_its_input() {
293 for size in [2, 17, 33] {
294 let c = parse(&cube_text(size, |p| p)).expect("parses");
295 assert!(c.three_d && c.size == size);
296 for p in [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.3, 0.71, 0.02], [0.5, 0.25, 0.9]] {
297 let o = c.sample(p);
298 for k in 0..3 {
299 assert!((o[k] - p[k]).abs() < 1e-5, "{size} {p:?} -> {o:?}");
300 }
301 }
302 }
303 }
304
305 /// Tetrahedral interpolation is exact for any function linear in r, g and b,
306 /// whatever the cell -- a channel swap and an affine mix are both.
307 #[test]
308 fn tetrahedral_is_exact_for_linear_tables() {
309 let f = |p: [f32; 3]| [p[2], 0.5 * p[0] + 0.25 * p[1], 1.0 - p[1]];
310 let c = parse(&cube_text(9, f)).expect("parses");
311 for p in [[0.13, 0.77, 0.5], [0.9, 0.1, 0.45], [0.33, 0.33, 0.34]] {
312 let (o, w) = (c.sample(p), f(p));
313 for k in 0..3 {
314 assert!((o[k] - w[k]).abs() < 1e-5, "{p:?}: {o:?} vs {w:?}");
315 }
316 }
317 }
318
319 #[test]
320 fn one_d_and_domain() {
321 let c = parse("LUT_1D_SIZE 3\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n0 0 0\n0.5 0.25 1\n1 1 1\n").expect("1D");
322 assert!(!c.three_d);
323 // 1.0 is the middle entry of a 0..2 domain.
324 assert_eq!(c.sample([1.0, 1.0, 1.0]), [0.5, 0.25, 1.0]);
325 let o = c.sample([0.5, 0.5, 0.5]);
326 assert!((o[0] - 0.25).abs() < 1e-6 && (o[2] - 0.5).abs() < 1e-6);
327 // Outside the domain is held at its edge.
328 assert_eq!(c.sample([-3.0, 9.0, 2.0]), [0.0, 1.0, 1.0]);
329 let r = parse("LUT_3D_INPUT_RANGE -0.5 1.5\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").expect("range");
330 assert_eq!((r.domain_min, r.domain_max), ([-0.5; 3], [1.5; 3]));
331 }
332
333 /// The fuzz corpus: every malformed file is a named refusal, never a panic.
334 #[test]
335 fn malformed_files_are_refused_by_name() {
336 let ok = cube_text(2, |p| p);
337 let cases: Vec<(String, &str)> = vec![
338 (String::new(), "no LUT_1D_SIZE"),
339 ("# only a comment\n".into(), "no LUT_1D_SIZE"),
340 ("0 0 0\nLUT_3D_SIZE 2\n".into(), "before LUT_1D_SIZE"),
341 ("LUT_3D_SIZE 66\n".into(), "outside 2..=65"),
342 ("LUT_3D_SIZE 1\n0 0 0\n".into(), "outside 2..=65"),
343 ("LUT_3D_SIZE x\n".into(), "not a size"),
344 ("LUT_3D_SIZE 2 3\n".into(), "one size"),
345 ("LUT_3D_SIZE 99999999999999999999\n".into(), "not a size"),
346 ("LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n".into(), "both"),
347 ("LUT_1D_SIZE 2\n0 0 0\n".into(), "has 1 entries"),
348 ("LUT_1D_SIZE 2\n0 0 0\n1 1 1\n1 1 1\n".into(), "more table entries"),
349 ("LUT_1D_SIZE 2\n0 0\n1 1 1\n".into(), "wants 3 numbers"),
350 ("LUT_1D_SIZE 2\n0 nan 0\n1 1 1\n".into(), "not a number"),
351 ("LUT_1D_SIZE 2\n0 inf 0\n1 1 1\n".into(), "not a number"),
352 ("LUT_1D_SIZE 2\n0 0 0\nTITLE late\n1 1 1\n".into(), "after the table"),
353 ("DOMAIN_MIN 1 0 0\nDOMAIN_MAX 0 1 1\nLUT_1D_SIZE 2\n0 0 0\n1 1 1\n".into(), "below DOMAIN_MAX"),
354 ("DOMAIN_MIN 0 0\nLUT_1D_SIZE 2\n".into(), "wants 3 numbers"),
355 (ok[..ok.len() - 7].to_string(), "entries"),
356 ("\u{0}\u{1}\u{2}garbage\n".into(), "before LUT_1D_SIZE"),
357 ];
358 for (text, want) in cases {
359 let e = parse(&text).expect_err(&text);
360 assert!(e.contains(want), "{text:?}: {e}");
361 }
362 // Random bytes never panic.
363 let mut seed = 0x9e37_79b9u32;
364 for _ in 0..300 {
365 let mut s = String::from("LUT_3D_SIZE 2\n");
366 for _ in 0..40 {
367 seed ^= seed << 13;
368 seed ^= seed >> 17;
369 seed ^= seed << 5;
370 s.push(b"0123456789 .-e\nLUT_ #x"[(seed % 22) as usize] as char);
371 }
372 let _ = parse(&s);
373 }
374 }
375
376 #[test]
377 fn a_missing_file_is_a_handle_with_a_reason() {
378 let r = LutRef::open(Path::new("/nonexistent/edith/look.cube"));
379 assert!(r.problem().expect("missing").contains("cannot read"));
380 assert_eq!(r, LutRef::open(Path::new("/nonexistent/edith/look.cube")), "one handle per path");
381 }
382}