Skip to main content

mcraw_tui/
thumbnail.rs

1use std::num::NonZeroUsize;
2use std::path::PathBuf;
3use std::sync::Mutex;
4use std::time::Instant;
5
6use anyhow::Result;
7use lru::LruCache;
8
9use crate::preview::pipeline::pipeline::{GpuPreviewPipeline, Ready};
10use crate::preview::pipeline::params::PreviewParams;
11use crate::preview::pipeline::params::{color_space_to_u32, transfer_to_u32};
12use crate::terminal::{protocol, TerminalProtocol};
13
14pub const THUMBNAIL_WIDTH: u32 = 320;
15pub const THUMBNAIL_HEIGHT: u32 = 180;
16pub const CACHE_MAX_ENTRIES: usize = 1000;
17pub const CACHE_MAX_BYTES: usize = 50 * 1024 * 1024;
18
19/// Compute aspect-ratio-preserving output dims that fit inside THUMBNAIL_WIDTH × THUMBNAIL_HEIGHT.
20/// This is the same logic as build_preview_params in app.rs — keep in sync.
21pub fn aspect_fit(raw_w: u32, raw_h: u32) -> (u32, u32) {
22    let raw_aspect = raw_w as f64 / raw_h as f64;
23    let target_aspect = THUMBNAIL_WIDTH as f64 / THUMBNAIL_HEIGHT as f64;
24    if raw_aspect > target_aspect {
25        let h = (THUMBNAIL_WIDTH as f64 / raw_aspect) as u32;
26        (THUMBNAIL_WIDTH, h.max(1))
27    } else {
28        let w = (THUMBNAIL_HEIGHT as f64 * raw_aspect) as u32;
29        (w.max(1), THUMBNAIL_HEIGHT)
30    }
31}
32
33fn build_params(
34    width: u32,
35    height: u32,
36    raw_width: u32,
37    raw_height: u32,
38    black_level: f32,
39    white_level: f32,
40    bayer_phase: u32,
41) -> PreviewParams {
42    PreviewParams {
43        width,
44        height,
45        bayer_width: raw_width,
46        bayer_height: raw_height,
47        black_level,
48        white_level,
49        exposure: 0.0,
50        wb_r: 1.0, wb_g: 1.0, wb_b: 1.0,
51        contrast: 1.0,
52        saturation: 1.0,
53        shadows: 0.0,
54        highlights: 0.0,
55        _align0: 0.0, _align1: 0.0,
56        ccm_row0: [1.0, 0.0, 0.0, 0.0],
57        ccm_row1: [0.0, 1.0, 0.0, 0.0],
58        ccm_row2: [0.0, 0.0, 1.0, 0.0],
59        color_space: color_space_to_u32(&crate::color::ColorSpace::Rec709),
60        transfer: transfer_to_u32(&crate::color::TransferFunction::Gamma24),
61        adjust_enabled: 0,
62        bayer_phase,
63        compute_histogram: 0,
64        _pad0: 0, _pad1: 0, _pad2: 0, _pad3: 0, _pad4: 0, _pad5: 0, _pad6: 0,
65    }
66}
67
68static FALLBACK_PLACEHOLDER: &[u8] = include_bytes!("../assets/placeholder.sixel");
69
70#[derive(Clone)]
71pub struct CachedThumbnail {
72    pub sixel: Vec<u8>,
73    pub width: u32,
74    pub height: u32,
75    pub encode_time: Instant,
76}
77
78impl CachedThumbnail {
79    pub fn byte_size(&self) -> usize {
80        self.sixel.len()
81    }
82}
83
84pub struct ThumbnailCache {
85    inner: Mutex<LruCache<PathBuf, CachedThumbnail>>,
86    current_bytes: std::sync::atomic::AtomicUsize,
87    pub placeholder: Vec<u8>,
88}
89
90impl ThumbnailCache {
91    pub fn new() -> Self {
92        Self::new_with_placeholder(None)
93    }
94
95    pub fn new_with_placeholder(custom_path: Option<&std::path::Path>) -> Self {
96        let placeholder = match custom_path {
97            Some(p) => match std::fs::read(p) {
98                Ok(data) => {
99                    tracing::info!("loaded custom placeholder from {}", p.display());
100                    data
101                }
102                Err(e) => {
103                    tracing::warn!("failed to load custom placeholder {}: {}; using bundled", p.display(), e);
104                    FALLBACK_PLACEHOLDER.to_vec()
105                }
106            }
107            None => FALLBACK_PLACEHOLDER.to_vec(),
108        };
109
110        Self {
111            inner: Mutex::new(LruCache::new(NonZeroUsize::new(CACHE_MAX_ENTRIES).unwrap())),
112            current_bytes: std::sync::atomic::AtomicUsize::new(0),
113            placeholder,
114        }
115    }
116
117    pub fn get(&self, path: &PathBuf) -> Option<CachedThumbnail> {
118        let mut cache = self.inner.lock().unwrap();
119        cache.get(path).cloned()
120    }
121
122    pub fn insert(&self, path: PathBuf, thumbnail: CachedThumbnail) {
123        let size = thumbnail.byte_size();
124        let mut cache = self.inner.lock().unwrap();
125
126        // Enforce byte cap: evict until we fit
127        let mut evict_bytes = 0usize;
128        while self.current_bytes.load(std::sync::atomic::Ordering::Relaxed) + size > CACHE_MAX_BYTES && !cache.is_empty() {
129            if let Some((_, evicted)) = cache.pop_lru() {
130                evict_bytes += evicted.byte_size();
131            }
132        }
133
134        if let Some(old) = cache.put(path, thumbnail) {
135            self.current_bytes.fetch_sub(old.byte_size(), std::sync::atomic::Ordering::Relaxed);
136        }
137
138        self.current_bytes.fetch_add(size, std::sync::atomic::Ordering::Relaxed);
139        if evict_bytes > 0 {
140            self.current_bytes.fetch_sub(evict_bytes, std::sync::atomic::Ordering::Relaxed);
141        }
142    }
143
144    pub fn clear(&self) {
145        let mut cache = self.inner.lock().unwrap();
146        cache.clear();
147        self.current_bytes.store(0, std::sync::atomic::Ordering::Relaxed);
148    }
149
150    pub fn len(&self) -> usize {
151        self.inner.lock().unwrap().len()
152    }
153}
154
155impl Default for ThumbnailCache {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161/// Strip alpha channel from RGBA for Kitty f=24 raw RGB.
162fn rgba_to_rgb(rgba: &[u8]) -> Vec<u8> {
163    let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
164    for chunk in rgba.chunks(4) {
165        rgb.push(chunk[0]);
166        rgb.push(chunk[1]);
167        rgb.push(chunk[2]);
168    }
169    rgb
170}
171
172/// Encode an RGBA buffer as Kitty graphics protocol raw RGB (`f=24`).
173///
174/// Uses `a=t` (transmit only, image ID=0, replace=1) to send the pixel
175/// data without displaying. The caller must emit a subsequent `a=p` (place)
176/// command to display the image at the cursor position — this two-step
177/// approach works around WezTerm on Windows where `a=T` (transmit+display)
178/// ignores the cursor position and snaps to pixel (0,0).
179fn kitty_encode(rgba: &[u8], width: usize, height: usize) -> Vec<u8> {
180    use base64::Engine;
181    let rgb = rgba_to_rgb(rgba);
182    let b64 = base64::engine::general_purpose::STANDARD.encode(&rgb);
183    let header = format!("\x1b_Ga=t,i=0,r=1,f=24,s={},v={},m=0;", width, height);
184    let mut out = header.into_bytes();
185    out.extend_from_slice(b64.as_bytes());
186    out.extend_from_slice(b"\x1b\\");
187    out
188}
189
190/// Encode an RGBA buffer to the terminal's image protocol (sixel or Kitty).
191/// Returns raw bytes ready to write directly to stdout.
192fn encode_rgba_to_terminal(rgba: &[u8], width: usize, height: usize) -> Result<Vec<u8>> {
193    match protocol() {
194        TerminalProtocol::Kitty => Ok(kitty_encode(rgba, width, height)),
195        TerminalProtocol::Sixel => {
196            let s = icy_sixel::sixel_encode(rgba, width, height, &icy_sixel::EncodeOptions::default())
197                .map_err(|e| anyhow::anyhow!("sixel encode: {}", e))?;
198            Ok(s.into_bytes())
199        }
200        TerminalProtocol::TextFallback => {
201            // Best-effort sixel. Terminals that don't support it silently
202            // ignore the escape sequences — harmless.
203            let s = icy_sixel::sixel_encode(rgba, width, height, &icy_sixel::EncodeOptions::default())
204                .map_err(|e| anyhow::anyhow!("sixel encode: {}", e))?;
205            Ok(s.into_bytes())
206        }
207    }
208}
209
210pub fn compute_thumbnail(
211    pipeline: &mut GpuPreviewPipeline<Ready>,
212    bayer: &[u16],
213    raw_width: u32,
214    raw_height: u32,
215    black_level: f32,
216    white_level: f32,
217    bayer_phase: u32,
218) -> Result<CachedThumbnail> {
219    let (width, height) = aspect_fit(raw_width, raw_height);
220
221    let params = build_params(width, height, raw_width, raw_height, black_level, white_level, bayer_phase);
222
223    let (rgba, w, h) = pipeline.process_and_readback(bayer, &params)?;
224
225    let encoded = encode_rgba_to_terminal(&rgba, w as usize, h as usize)?;
226
227    Ok(CachedThumbnail {
228        sixel: encoded,
229        width: w,
230        height: h,
231        encode_time: Instant::now(),
232    })
233}
234
235// ═══════════════════════════════════════════════════════════════════════════════
236// CPU thumbnail pipeline — pixel-exact port of shaders/preview.wgsl
237// ═══════════════════════════════════════════════════════════════════════════════
238
239fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
240    let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
241    t * t * (3.0 - 2.0 * t)
242}
243
244fn load_bayer(bayer: &[u16], raw_w: u32, x: i32, y: i32) -> f32 {
245    let cx = x.clamp(0, raw_w as i32 - 1);
246    let cy = y.clamp(0, (bayer.len() as u32 / raw_w).saturating_sub(1) as i32);
247    bayer[(cy as u32 * raw_w + cx as u32) as usize] as f32
248}
249
250fn bayer_color(x: i32, y: i32, phase: u32) -> i32 {
251    let even_row = (y & 1) == 0;
252    let even_col = (x & 1) == 0;
253    match phase {
254        0 => { // RGGB
255            if even_row { if even_col { 0 } else { 1 } }
256            else        { if even_col { 1 } else { 2 } }
257        }
258        1 => { // GRBG
259            if even_row { if even_col { 1 } else { 0 } }
260            else        { if even_col { 2 } else { 1 } }
261        }
262        2 => { // GBRG
263            if even_row { if even_col { 1 } else { 2 } }
264            else        { if even_col { 0 } else { 1 } }
265        }
266        _ => { // BGGR
267            if even_row { if even_col { 2 } else { 1 } }
268            else        { if even_col { 1 } else { 0 } }
269        }
270    }
271}
272
273fn demosaic_bilinear(bayer: &[u16], raw_w: u32, _raw_h: u32, phase: u32, x: i32, y: i32) -> [f32; 3] {
274    let c = bayer_color(x, y, phase);
275    let center = load_bayer(bayer, raw_w, x, y);
276    let n  = load_bayer(bayer, raw_w, x, y - 1);
277    let s  = load_bayer(bayer, raw_w, x, y + 1);
278    let w  = load_bayer(bayer, raw_w, x - 1, y);
279    let e  = load_bayer(bayer, raw_w, x + 1, y);
280    let nw = load_bayer(bayer, raw_w, x - 1, y - 1);
281    let ne = load_bayer(bayer, raw_w, x + 1, y - 1);
282    let sw = load_bayer(bayer, raw_w, x - 1, y + 1);
283    let se = load_bayer(bayer, raw_w, x + 1, y + 1);
284
285    let (r, g, b) = if c == 0 { // R site
286        (center, (n + s + w + e) * 0.25, (nw + ne + sw + se) * 0.25)
287    } else if c == 2 { // B site
288        ((nw + ne + sw + se) * 0.25, (n + s + w + e) * 0.25, center)
289    } else { // G site
290        let horiz_color = bayer_color(x - 1, y, phase);
291        let _vert_color = bayer_color(x, y - 1, phase);
292        if horiz_color == 0 { // R is horizontal
293            ((w + e) * 0.5, center, (n + s) * 0.5)
294        } else { // B is horizontal
295            ((n + s) * 0.5, center, (w + e) * 0.5)
296        }
297    };
298    [r, g, b]
299}
300
301fn apply_oetf(r: f32, g: f32, b: f32, tf: u32) -> [f32; 3] {
302    let oetf_ch = |x: f32| -> f32 {
303        match tf {
304            0 => x,
305            14 => x.max(0.0).powf(1.0 / 2.4),
306            1 => {
307                if x < 0.018 { 4.5 * x }
308                else { 1.099 * x.max(0.0).powf(0.45) - 0.099 }
309            }
310            2 => {
311                if x >= 0.01 { 0.432699 * (10.0 * x + 1.0).log10() + 0.037584 }
312                else { (x * 261.5 + 10.23) / 1023.0 }
313            }
314            3 => {
315                if x < 0.01 { 5.6 * x + 0.125 }
316                else { 0.241514 * (x + 0.00873).log10() + 0.598206 }
317            }
318            4 => {
319                if x > 0.010591 { 0.247190 * (5.555556 * x + 0.052272).log10() + 0.385537 }
320                else { 5.367655 * x + 0.092809 }
321            }
322            5 => {
323                let a: f32 = (262144.0 - 16.0) / 117.45;
324                let b_rev: f32 = (1023.0 - 95.0) / 1023.0;
325                let c_rev: f32 = 95.0 / 1023.0;
326                let s_rev = (7.0 * 0.6931471805599453 * f32::exp2(7.0 - 14.0 * c_rev / b_rev)) / (a * b_rev);
327                let t_rev = (f32::exp2(14.0 * (-c_rev / b_rev) + 6.0) - 64.0) / a;
328                if x >= t_rev {
329                    ((a * x + 64.0).log2() - 6.0) / 14.0 * b_rev + c_rev
330                } else {
331                    (x - t_rev) / s_rev
332                }
333            }
334            6 => {
335                let neg_graft = (0.097465473 - 0.12512219) / 1.9754798;
336                let pos_graft = (0.15277891 - 0.12512219) / 1.9754798;
337                if x < neg_graft {
338                    -0.36726845 * ((-x * 14.98325 + 1.0).max(1e-10)).log10() + 0.12783901
339                } else if x <= pos_graft {
340                    1.9754798 * x + 0.12512219
341                } else {
342                    0.36726845 * (x * 14.98325 + 1.0).log10() + 0.12240537
343                }
344            }
345            7 => {
346                if x >= 0.000889 { 0.245281 * (5.555556 * x + 0.064829).log10() + 0.384316 }
347                else { 8.799461 * x + 0.092864 }
348            }
349            8 | 9 => {
350                if x < -0.05641088 { 0.0 }
351                else if x < 0.01 { 47.28711236 * (x + 0.05641088) * (x + 0.05641088) }
352                else { 0.08550479 * (x + 0.00964052).log2() + 0.69336945 }
353            }
354            10 => {
355                if x > 0.0078125 { (x.log2() + 9.72) / 17.52 }
356                else { 10.5402377416545 * x + 0.0729055341958355 }
357            }
358            11 => {
359                let m1 = 0.1593017578125;
360                let m2 = 78.84375;
361                let c1 = 0.8359375;
362                let c2 = 18.8515625;
363                let c3 = 18.6875;
364                let x_m1 = x.max(0.0).powf(m1);
365                (c1 + c2 * x_m1).max(0.0) / (1.0 + c3 * x_m1).max(1e-10).powf(m2)
366            }
367            12 => {
368                if x < 1.0 / 12.0 { (3.0 * x.max(0.0)).sqrt() }
369                else { 0.17883277 * (12.0 * x - 0.28466892).max(1e-10).ln() + 0.55991073 }
370            }
371            13 => {
372                if x <= 0.00262409 { x * 10.44426855 }
373                else { 0.07329248 * ((x + 0.0075).log2() + 7.0) }
374            }
375            _ => x,
376        }
377    };
378    [oetf_ch(r), oetf_ch(g), oetf_ch(b)]
379}
380
381fn inverse_oetf(r: f32, g: f32, b: f32, tf: u32) -> [f32; 3] {
382    let inv_ch = |y: f32| -> f32 {
383        match tf {
384            0 => y,
385            14 => y.max(0.0).powf(2.4),
386            1 => {
387                if y < 0.081 { y / 4.5 }
388                else { ((y + 0.099) / 1.099).powf(1.0 / 0.45) }
389            }
390            2 => {
391                let knee_val = (0.01 * 261.5 + 10.23) / 1023.0;
392                if y >= knee_val { ((10.0f32).powf((y - 0.037584) / 0.432699) - 1.0) / 10.0 }
393                else { (y * 1023.0 - 10.23) / 261.5 }
394            }
395            3 => {
396                if y < 0.181 { (y - 0.125) / 5.6 }
397                else { (10.0f32).powf((y - 0.598206) / 0.241514) - 0.00873 }
398            }
399            4 => {
400                let knee_val = 5.367655 * 0.010591 + 0.092809;
401                if y >= knee_val { ((10.0f32).powf((y - 0.385537) / 0.247190) - 0.052272) / 5.555556 }
402                else { (y - 0.092809) / 5.367655 }
403            }
404            5 => {
405                let a: f32 = (262144.0 - 16.0) / 117.45;
406                let b_rev: f32 = (1023.0 - 95.0) / 1023.0;
407                let c_rev: f32 = 95.0 / 1023.0;
408                let s_rev = (7.0 * 0.6931471805599453 * f32::exp2(7.0 - 14.0 * c_rev / b_rev)) / (a * b_rev);
409                let t_rev = (f32::exp2(14.0 * (-c_rev / b_rev) + 6.0) - 64.0) / a;
410                if y >= 0.0 { (f32::exp2(14.0 * ((y - c_rev) / b_rev) + 6.0) - 64.0) / a }
411                else { y * s_rev + t_rev }
412            }
413            6 => {
414                let neg_graft = (0.097465473 - 0.12512219) / 1.9754798;
415                let pos_graft = (0.15277891 - 0.12512219) / 1.9754798;
416                let knee_lo = 0.12512219 + neg_graft * 1.9754798;
417                let knee_hi = 0.12512219 + pos_graft * 1.9754798;
418                if y < knee_lo {
419                    ((10.0f32).powf(-(y - 0.12783901) / 0.36726845) - 1.0) / (-14.98325)
420                } else if y <= knee_hi {
421                    (y - 0.12512219) / 1.9754798
422                } else {
423                    ((10.0f32).powf((y - 0.12240537) / 0.36726845) - 1.0) / 14.98325
424                }
425            }
426            7 => {
427                let knee_val = 8.799461 * 0.000889 + 0.092864;
428                if y >= knee_val { ((10.0f32).powf((y - 0.384316) / 0.245281) - 0.064829) / 5.555556 }
429                else { (y - 0.092864) / 8.799461 }
430            }
431            8 | 9 => {
432                if y <= 0.0 { -0.05641088 }
433                else {
434                    let knee_val = 47.28711236 * (0.01 + 0.05641088) * (0.01 + 0.05641088);
435                    if y < knee_val { (y / 47.28711236).sqrt() - 0.05641088 }
436                    else { (2.0f32).powf((y - 0.69336945) / 0.08550479) - 0.00964052 }
437                }
438            }
439            10 => {
440                let cutoff = 10.5402377416545 * 0.0078125 + 0.0729055341958355;
441                if y > cutoff { (2.0f32).powf(y * 17.52 - 9.72) }
442                else { (y - 0.0729055341958355) / 10.5402377416545 }
443            }
444            11 => {
445                let m1 = 0.1593017578125;
446                let m2 = 78.84375;
447                let c1 = 0.8359375;
448                let c2 = 18.8515625;
449                let c3 = 18.6875;
450                let v = y.max(0.0);
451                let v_m2 = v.powf(1.0 / m2);
452                let num = (v_m2 - c1).max(0.0);
453                let den = c2 - c3 * v_m2;
454                if den > 0.0 { (num / den).powf(1.0 / m1) }
455                else { 0.0 }
456            }
457            12 => {
458                let knee_out: f32 = f32::sqrt(3.0 / 12.0);
459                if y <= knee_out { y * y / 3.0 }
460                else { ((y - 0.55991073) / 0.17883277).exp() + 0.28466892 / 12.0 }
461            }
462            13 => {
463                let cut_out = 0.00262409 * 10.44426855;
464                if y <= cut_out { y / 10.44426855 }
465                else { (2.0f32).powf(y / 0.07329248 - 7.0) - 0.0075 }
466            }
467            _ => y,
468        }
469    };
470    [inv_ch(r), inv_ch(g), inv_ch(b)]
471}
472
473fn srgb_oetf(r: f32, g: f32, b: f32) -> [f32; 3] {
474    let srgb_ch = |x: f32| -> f32 {
475        if x <= 0.0031308 { x * 12.92 }
476        else { 1.055 * x.max(0.0).powf(1.0 / 2.4) - 0.055 }
477    };
478    [srgb_ch(r), srgb_ch(g), srgb_ch(b)]
479}
480
481fn apply_tone_curve(r: f32, g: f32, b: f32, shadows: f32, highlights: f32) -> [f32; 3] {
482    let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
483    let shadow_weight = 1.0 - smoothstep(0.0, 0.35, luma);
484    let mut rt = r + shadows * shadow_weight;
485    let mut gt = g + shadows * shadow_weight;
486    let mut bt = b + shadows * shadow_weight;
487    let hi_weight = smoothstep(0.5, 1.0, luma);
488    rt = rt + highlights * hi_weight * rt;
489    gt = gt + highlights * hi_weight * gt;
490    bt = bt + highlights * hi_weight * bt;
491    [rt.max(0.0), gt.max(0.0), bt.max(0.0)]
492}
493
494fn xyz_to_rec709(x: f32, y: f32, z: f32) -> [f32; 3] {
495    [
496        3.2404542 * x + -1.9692660 * y + 0.0556434 * z,
497        -1.5371385 * x + 1.8760108 * y + -0.2040259 * z,
498        -0.4985314 * x + 0.0415560 * y + 1.0572252 * z,
499    ]
500}
501
502fn working_to_xyz(r: f32, g: f32, b: f32, cs: u32) -> [f32; 3] {
503    match cs {
504        0 => [ // ACESAP1
505            0.6954522414 * r + 0.1406786965 * g + 0.1638690622 * b,
506            0.0447945634 * r + 0.8596711185 * g + 0.0955343182 * b,
507            -0.0055258826 * r + 0.0040252104 * g + 1.0015006723 * b,
508        ],
509        1 => [ // Apple Wide Gamut
510            1.99650669 * r + -0.04380294 * g + 0.04729625 * b,
511            0.50573456 * r + 0.86522867 * g + -0.37096323 * b,
512            0.00612684 * r + -0.00089651 * g + 0.99476967 * b,
513        ],
514        2 => [ // ARRIWideGamut3
515            0.688161 * r + 0.150181 * g + 0.161658 * b,
516            0.047434 * r + 0.807529 * g + 0.145037 * b,
517            -0.002103 * r + -0.004533 * g + 1.006636 * b,
518        ],
519        3 => [ // ARRIWideGamut4
520            0.732690 * r + 0.143327 * g + 0.123983 * b,
521            0.044200 * r + 0.878486 * g + 0.077314 * b,
522            -0.001988 * r + -0.003142 * g + 1.005130 * b,
523        ],
524        5 => [ // DaVinciWideGamut
525            0.8000 * r + 0.3130 * g + -0.1130 * b,
526            0.1682 * r + 0.9877 * g + -0.1559 * b,
527            0.0790 * r + -0.1155 * g + 1.0365 * b,
528        ],
529        6 | 7 => [ // DciP3 / DisplayP3
530            0.4865709 * r + 0.2656677 * g + 0.1982242 * b,
531            0.2289746 * r + 0.6917385 * g + 0.0792869 * b,
532            0.0 * r + 0.0451136 * g + 1.0439444 * b,
533        ],
534        11 => [ // Rec2020
535            0.6369580 * r + 0.1446169 * g + 0.1688810 * b,
536            0.2627002 * r + 0.6779981 * g + 0.0593017 * b,
537            0.0 * r + 0.0280727 * g + 1.0609052 * b,
538        ],
539        _ => [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)],
540    }
541}
542
543fn gamut_clip_to_srgb(r: f32, g: f32, b: f32, cs: u32) -> [f32; 3] {
544    if cs == 12 || cs == 15 { // Rec709 or Srgb
545        [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)]
546    } else {
547        let xyz = working_to_xyz(r, g, b, cs);
548        let srgb = xyz_to_rec709(xyz[0], xyz[1], xyz[2]);
549        [srgb[0].clamp(0.0, 1.0), srgb[1].clamp(0.0, 1.0), srgb[2].clamp(0.0, 1.0)]
550    }
551}
552
553/// Generate a thumbnail on the CPU, producing sixel-encoded RGBA bytes.
554/// This is a pixel-exact port of the WGSL preview shader — same pipeline order,
555/// same constants, same bilinear demosaic. Use for outputs ≤ 800×600 where the
556/// GPU dispatch + readback overhead dominates.
557pub fn cpu_thumbnail(
558    bayer: &[u16],
559    params: &PreviewParams,
560) -> Result<(Vec<u8>, u32, u32)> {
561    let out_w = params.width;
562    let out_h = params.height;
563    let raw_w = params.bayer_width;
564    let raw_h = params.bayer_height;
565    let black = params.black_level;
566    let range = (params.white_level - black).max(0.001);
567    let exp_gain = (2.0f32).powf(params.exposure);
568    let adjust = params.adjust_enabled != 0;
569    let phase = params.bayer_phase;
570
571    let mut rgba = vec![0u8; (out_w * out_h * 4) as usize];
572
573    // Single-pass: for each output pixel, map to bayer coordinate and process
574    // the full color pipeline in the exact same order as the WGSL shader.
575    for y in 0..out_h {
576        for x in 0..out_w {
577            let src_x = (x * raw_w) / out_w;
578            let src_y = (y * raw_h) / out_h;
579
580            // 1. Bilinear demosaic
581            let mut rgb = demosaic_bilinear(bayer, raw_w, raw_h, phase, src_x as i32, src_y as i32);
582
583            // 2. Normalize
584            rgb[0] = (rgb[0] - black) / range;
585            rgb[1] = (rgb[1] - black) / range;
586            rgb[2] = (rgb[2] - black) / range;
587
588            // 3. Exposure
589            rgb[0] *= exp_gain;
590            rgb[1] *= exp_gain;
591            rgb[2] *= exp_gain;
592
593            // 4. White balance
594            rgb[0] *= params.wb_r;
595            rgb[1] *= params.wb_g;
596            rgb[2] *= params.wb_b;
597
598            // 5. Camera Color Matrix (CCM)
599            // NOTE: WGSL mat3x3(ccm_row0, ccm_row1, ccm_row2) is column-major:
600            //   column 0 = ccm_row0, column 1 = ccm_row1, column 2 = ccm_row2
601            // So ccm_row0[0] * r + ccm_row1[0] * g + ccm_row2[0] * b
602            let (cr, cg, cb) = (rgb[0], rgb[1], rgb[2]);
603            rgb[0] = params.ccm_row0[0] * cr + params.ccm_row1[0] * cg + params.ccm_row2[0] * cb;
604            rgb[1] = params.ccm_row0[1] * cr + params.ccm_row1[1] * cg + params.ccm_row2[1] * cb;
605            rgb[2] = params.ccm_row0[2] * cr + params.ccm_row1[2] * cg + params.ccm_row2[2] * cb;
606
607            // 6. Grading adjustments (only if adjust_enabled)
608            if adjust {
609                rgb = apply_tone_curve(rgb[0], rgb[1], rgb[2], params.shadows, params.highlights);
610                // Contrast pivot at 0.18 mid-grey
611                rgb[0] = ((rgb[0] - 0.18) * params.contrast + 0.18).max(0.0);
612                rgb[1] = ((rgb[1] - 0.18) * params.contrast + 0.18).max(0.0);
613                rgb[2] = ((rgb[2] - 0.18) * params.contrast + 0.18).max(0.0);
614                // Saturation
615                let luma = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
616                rgb[0] = luma + (rgb[0] - luma) * params.saturation;
617                rgb[1] = luma + (rgb[1] - luma) * params.saturation;
618                rgb[2] = luma + (rgb[2] - luma) * params.saturation;
619            }
620
621            // 7. Apply selected OETF
622            let encoded = apply_oetf(rgb[0], rgb[1], rgb[2], params.transfer);
623
624            // 8. Display compensation: decode OETF → linear
625            let linear_for_display = inverse_oetf(encoded[0], encoded[1], encoded[2], params.transfer);
626
627            // 9. Gamut clip to sRGB
628            let srgb_linear = gamut_clip_to_srgb(linear_for_display[0], linear_for_display[1], linear_for_display[2], params.color_space);
629
630            // 10. sRGB OETF for display
631            let display = srgb_oetf(srgb_linear[0], srgb_linear[1], srgb_linear[2]);
632
633            // 11. Pack to RGBA8
634            let idx = ((y * out_w + x) * 4) as usize;
635            rgba[idx] = (display[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
636            rgba[idx + 1] = (display[1].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
637            rgba[idx + 2] = (display[2].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
638            rgba[idx + 3] = 255;
639        }
640    }
641
642    // 12. Encode to terminal protocol
643    let encoded = encode_rgba_to_terminal(&rgba, out_w as usize, out_h as usize)?;
644
645    Ok((encoded, out_w, out_h))
646}