Skip to main content

ad_plugins_rs/
color_convert.rs

1use std::sync::Arc;
2
3#[cfg(feature = "parallel")]
4use crate::par_util;
5#[cfg(feature = "parallel")]
6use rayon::prelude::*;
7
8use ad_core_rs::color::{self, NDBayerPattern, NDColorMode};
9use ad_core_rs::ndarray::{NDArray, NDDataBuffer, NDDataType, NDDimension};
10use ad_core_rs::ndarray_pool::NDArrayPool;
11use ad_core_rs::plugin::runtime::{NDPluginProcess, ProcessResult};
12
13/// Simple Bayer demosaic using bilinear interpolation.
14pub fn bayer_to_rgb1(src: &NDArray, pattern: NDBayerPattern) -> Option<NDArray> {
15    if src.dims.len() != 2 {
16        return None;
17    }
18    let w = src.dims[0].size;
19    let h = src.dims[1].size;
20
21    // Read dimension offsets to adjust the bayer phase when offset is odd
22    let offset_x = src.dims[0].offset;
23    let offset_y = src.dims[1].offset;
24
25    // Pre-compute source values into a flat f64 vec for efficient random access
26    let n = w * h;
27    let src_vals: Vec<f64> = (0..n)
28        .map(|i| src.data.get_as_f64(i).unwrap_or(0.0))
29        .collect();
30    let get_val = |x: usize, y: usize| -> f64 { src_vals[y * w + x] };
31
32    let mut r = vec![0.0f64; n];
33    let mut g = vec![0.0f64; n];
34    let mut b = vec![0.0f64; n];
35
36    // Determine which color each pixel position has, flipping phase for odd offsets
37    let (mut r_row_even, mut r_col_even) = match pattern {
38        NDBayerPattern::RGGB => (true, true),
39        NDBayerPattern::GBRG => (true, false),
40        NDBayerPattern::GRBG => (false, true),
41        NDBayerPattern::BGGR => (false, false),
42    };
43    if offset_x % 2 != 0 {
44        r_col_even = !r_col_even;
45    }
46    if offset_y % 2 != 0 {
47        r_row_even = !r_row_even;
48    }
49
50    // Helper to demosaic a single row into (r, g, b) slices.
51    //
52    // C interpolates only pixels not touching a border
53    // (NDPluginColorConvert.cpp:305): a pixel with x in 0/rowSize-1 or y in
54    // 0/numRows-1 keeps only its native Bayer channel, the other two stay 0.
55    // Interior pixels always have all 8 neighbours, so C's fixed divisors
56    // (/4 for the red/blue arms, /2 for green) apply directly.
57    let demosaic_row = |y: usize, r_row: &mut [f64], g_row: &mut [f64], b_row: &mut [f64]| {
58        let even_row = (y % 2 == 0) == r_row_even;
59        for x in 0..w {
60            let val = get_val(x, y);
61            let even_col = (x % 2 == 0) == r_col_even;
62            let interior = x > 0 && x + 1 < w && y > 0 && y + 1 < h;
63
64            match (even_row, even_col) {
65                (true, true) => {
66                    // Red pixel: green = orthogonal mean, blue = diagonal mean
67                    // (NDPluginColorConvert.cpp:308-309).
68                    r_row[x] = val;
69                    if interior {
70                        g_row[x] = (get_val(x - 1, y)
71                            + get_val(x + 1, y)
72                            + get_val(x, y - 1)
73                            + get_val(x, y + 1))
74                            / 4.0;
75                        b_row[x] = (get_val(x - 1, y - 1)
76                            + get_val(x + 1, y - 1)
77                            + get_val(x - 1, y + 1)
78                            + get_val(x + 1, y + 1))
79                            / 4.0;
80                    }
81                }
82                (true, false) | (false, true) => {
83                    // Green pixel.
84                    g_row[x] = val;
85                    if interior {
86                        if even_row {
87                            // Green next to red: red horizontal, blue vertical
88                            // (NDPluginColorConvert.cpp:313-314).
89                            r_row[x] = (get_val(x - 1, y) + get_val(x + 1, y)) / 2.0;
90                            b_row[x] = (get_val(x, y - 1) + get_val(x, y + 1)) / 2.0;
91                        } else {
92                            // Green next to blue: blue horizontal, red vertical
93                            // (NDPluginColorConvert.cpp:318-319).
94                            b_row[x] = (get_val(x - 1, y) + get_val(x + 1, y)) / 2.0;
95                            r_row[x] = (get_val(x, y - 1) + get_val(x, y + 1)) / 2.0;
96                        }
97                    }
98                }
99                (false, false) => {
100                    // Blue pixel: green = orthogonal mean, red = diagonal mean
101                    // (NDPluginColorConvert.cpp:308-309, blue branch).
102                    b_row[x] = val;
103                    if interior {
104                        g_row[x] = (get_val(x - 1, y)
105                            + get_val(x + 1, y)
106                            + get_val(x, y - 1)
107                            + get_val(x, y + 1))
108                            / 4.0;
109                        r_row[x] = (get_val(x - 1, y - 1)
110                            + get_val(x + 1, y - 1)
111                            + get_val(x - 1, y + 1)
112                            + get_val(x + 1, y + 1))
113                            / 4.0;
114                    }
115                }
116            }
117        }
118    };
119
120    #[cfg(feature = "parallel")]
121    let use_parallel = par_util::should_parallelize(n);
122    #[cfg(not(feature = "parallel"))]
123    let use_parallel = false;
124
125    if use_parallel {
126        #[cfg(feature = "parallel")]
127        {
128            // Split r, g, b into per-row mutable slices and process in parallel
129            let r_rows: Vec<&mut [f64]> = r.chunks_mut(w).collect();
130            let g_rows: Vec<&mut [f64]> = g.chunks_mut(w).collect();
131            let b_rows: Vec<&mut [f64]> = b.chunks_mut(w).collect();
132
133            par_util::thread_pool().install(|| {
134                r_rows
135                    .into_par_iter()
136                    .zip(g_rows.into_par_iter())
137                    .zip(b_rows.into_par_iter())
138                    .enumerate()
139                    .for_each(|(y, ((r_row, g_row), b_row))| {
140                        demosaic_row(y, r_row, g_row, b_row);
141                    });
142            });
143        }
144    } else {
145        for y in 0..h {
146            let row_start = y * w;
147            let row_end = row_start + w;
148            demosaic_row(
149                y,
150                &mut r[row_start..row_end],
151                &mut g[row_start..row_end],
152                &mut b[row_start..row_end],
153            );
154        }
155    }
156
157    // Build RGB1 interleaved output
158    let out_data = match src.data.data_type() {
159        NDDataType::UInt8 => {
160            let mut out = vec![0u8; n * 3];
161            for i in 0..n {
162                out[i * 3] = r[i].clamp(0.0, 255.0) as u8;
163                out[i * 3 + 1] = g[i].clamp(0.0, 255.0) as u8;
164                out[i * 3 + 2] = b[i].clamp(0.0, 255.0) as u8;
165            }
166            NDDataBuffer::U8(out)
167        }
168        NDDataType::UInt16 => {
169            let mut out = vec![0u16; n * 3];
170            for i in 0..n {
171                out[i * 3] = r[i].clamp(0.0, 65535.0) as u16;
172                out[i * 3 + 1] = g[i].clamp(0.0, 65535.0) as u16;
173                out[i * 3 + 2] = b[i].clamp(0.0, 65535.0) as u16;
174            }
175            NDDataBuffer::U16(out)
176        }
177        _ => return None,
178    };
179
180    let dims = vec![
181        NDDimension::new(3),
182        NDDimension::new(w),
183        NDDimension::new(h),
184    ];
185    let mut arr = NDArray::new(dims, src.data.data_type());
186    arr.data = out_data;
187    arr.unique_id = src.unique_id;
188    arr.timestamp = src.timestamp;
189    arr.attributes = src.attributes.clone();
190    Some(arr)
191}
192
193/// Rainbow false-color lookup table (`falseColor == 1`), 256 RGB entries.
194///
195/// Ported verbatim from ADCore `colorMaps.h` (RainbowColorR/G/B). C selects
196/// this table when the FalseColor parameter is 1
197/// (NDPluginColorConvert.cpp:62-66).
198const RAINBOW_COLOR_MAP: [[u8; 3]; 256] = [
199    [0, 0, 0],
200    [0, 0, 4],
201    [0, 0, 8],
202    [0, 0, 12],
203    [0, 0, 16],
204    [0, 0, 20],
205    [0, 0, 24],
206    [0, 0, 28],
207    [0, 0, 32],
208    [0, 0, 36],
209    [0, 0, 40],
210    [0, 0, 45],
211    [0, 0, 49],
212    [0, 0, 53],
213    [0, 0, 57],
214    [0, 0, 61],
215    [0, 0, 65],
216    [0, 0, 69],
217    [0, 0, 73],
218    [0, 0, 77],
219    [0, 0, 81],
220    [0, 0, 85],
221    [0, 0, 89],
222    [0, 0, 93],
223    [0, 0, 97],
224    [0, 0, 101],
225    [0, 0, 105],
226    [0, 0, 109],
227    [0, 0, 113],
228    [0, 0, 117],
229    [0, 0, 121],
230    [0, 0, 125],
231    [0, 0, 130],
232    [0, 0, 134],
233    [0, 0, 138],
234    [0, 0, 142],
235    [0, 0, 146],
236    [0, 0, 150],
237    [0, 0, 154],
238    [0, 0, 158],
239    [0, 0, 162],
240    [0, 0, 166],
241    [0, 0, 170],
242    [0, 0, 174],
243    [0, 0, 178],
244    [0, 0, 182],
245    [0, 0, 186],
246    [0, 0, 190],
247    [0, 0, 194],
248    [0, 0, 198],
249    [0, 0, 202],
250    [0, 0, 206],
251    [0, 0, 210],
252    [0, 0, 215],
253    [0, 0, 219],
254    [0, 0, 223],
255    [0, 0, 227],
256    [0, 0, 231],
257    [0, 0, 235],
258    [0, 0, 239],
259    [0, 0, 243],
260    [0, 0, 247],
261    [0, 0, 251],
262    [0, 0, 255],
263    [0, 4, 255],
264    [0, 8, 255],
265    [0, 12, 255],
266    [0, 16, 255],
267    [0, 20, 255],
268    [0, 24, 255],
269    [0, 28, 255],
270    [0, 32, 255],
271    [0, 36, 255],
272    [0, 40, 255],
273    [0, 44, 255],
274    [0, 48, 255],
275    [0, 52, 255],
276    [0, 56, 255],
277    [0, 60, 255],
278    [0, 64, 255],
279    [0, 68, 255],
280    [0, 72, 255],
281    [0, 76, 255],
282    [0, 80, 255],
283    [0, 84, 255],
284    [0, 88, 255],
285    [0, 92, 255],
286    [0, 96, 255],
287    [0, 100, 255],
288    [0, 104, 255],
289    [0, 108, 255],
290    [0, 112, 255],
291    [0, 116, 255],
292    [0, 120, 255],
293    [0, 124, 255],
294    [0, 128, 255],
295    [0, 131, 255],
296    [0, 135, 255],
297    [0, 139, 255],
298    [0, 143, 255],
299    [0, 147, 255],
300    [0, 151, 255],
301    [0, 155, 255],
302    [0, 159, 255],
303    [0, 163, 255],
304    [0, 167, 255],
305    [0, 171, 255],
306    [0, 175, 255],
307    [0, 179, 255],
308    [0, 183, 255],
309    [0, 187, 255],
310    [0, 191, 255],
311    [0, 195, 255],
312    [0, 199, 255],
313    [0, 203, 255],
314    [0, 207, 255],
315    [0, 211, 255],
316    [0, 215, 255],
317    [0, 219, 255],
318    [0, 223, 255],
319    [0, 227, 255],
320    [0, 231, 255],
321    [0, 235, 255],
322    [0, 239, 255],
323    [0, 243, 255],
324    [0, 247, 255],
325    [0, 251, 255],
326    [0, 255, 255],
327    [4, 255, 251],
328    [8, 255, 247],
329    [12, 255, 243],
330    [16, 255, 239],
331    [20, 255, 235],
332    [24, 255, 231],
333    [28, 255, 227],
334    [32, 255, 223],
335    [36, 255, 219],
336    [40, 255, 215],
337    [44, 255, 211],
338    [48, 255, 207],
339    [52, 255, 203],
340    [56, 255, 199],
341    [60, 255, 195],
342    [64, 255, 191],
343    [68, 255, 187],
344    [72, 255, 183],
345    [76, 255, 179],
346    [80, 255, 175],
347    [84, 255, 171],
348    [88, 255, 167],
349    [92, 255, 163],
350    [96, 255, 159],
351    [100, 255, 155],
352    [104, 255, 151],
353    [108, 255, 147],
354    [112, 255, 143],
355    [116, 255, 139],
356    [120, 255, 135],
357    [124, 255, 131],
358    [128, 255, 128],
359    [131, 255, 124],
360    [135, 255, 120],
361    [139, 255, 116],
362    [143, 255, 112],
363    [147, 255, 108],
364    [151, 255, 104],
365    [155, 255, 100],
366    [159, 255, 96],
367    [163, 255, 92],
368    [167, 255, 88],
369    [171, 255, 84],
370    [175, 255, 80],
371    [179, 255, 76],
372    [183, 255, 72],
373    [187, 255, 68],
374    [191, 255, 64],
375    [195, 255, 60],
376    [199, 255, 56],
377    [203, 255, 52],
378    [207, 255, 48],
379    [211, 255, 44],
380    [215, 255, 40],
381    [219, 255, 36],
382    [223, 255, 32],
383    [227, 255, 28],
384    [231, 255, 24],
385    [235, 255, 20],
386    [239, 255, 16],
387    [243, 255, 12],
388    [247, 255, 8],
389    [251, 255, 4],
390    [255, 255, 0],
391    [255, 251, 0],
392    [255, 247, 0],
393    [255, 243, 0],
394    [255, 239, 0],
395    [255, 235, 0],
396    [255, 231, 0],
397    [255, 227, 0],
398    [255, 223, 0],
399    [255, 219, 0],
400    [255, 215, 0],
401    [255, 211, 0],
402    [255, 207, 0],
403    [255, 203, 0],
404    [255, 199, 0],
405    [255, 195, 0],
406    [255, 191, 0],
407    [255, 187, 0],
408    [255, 183, 0],
409    [255, 179, 0],
410    [255, 175, 0],
411    [255, 171, 0],
412    [255, 167, 0],
413    [255, 163, 0],
414    [255, 159, 0],
415    [255, 155, 0],
416    [255, 151, 0],
417    [255, 147, 0],
418    [255, 143, 0],
419    [255, 139, 0],
420    [255, 135, 0],
421    [255, 131, 0],
422    [255, 128, 0],
423    [255, 124, 0],
424    [255, 120, 0],
425    [255, 116, 0],
426    [255, 112, 0],
427    [255, 108, 0],
428    [255, 104, 0],
429    [255, 100, 0],
430    [255, 96, 0],
431    [255, 92, 0],
432    [255, 88, 0],
433    [255, 84, 0],
434    [255, 80, 0],
435    [255, 76, 0],
436    [255, 72, 0],
437    [255, 68, 0],
438    [255, 64, 0],
439    [255, 60, 0],
440    [255, 56, 0],
441    [255, 52, 0],
442    [255, 48, 0],
443    [255, 44, 0],
444    [255, 40, 0],
445    [255, 36, 0],
446    [255, 32, 0],
447    [255, 28, 0],
448    [255, 24, 0],
449    [255, 20, 0],
450    [255, 16, 0],
451    [255, 12, 0],
452    [255, 8, 0],
453    [255, 4, 0],
454    [255, 255, 255],
455];
456
457/// Iron false-color lookup table (`falseColor == 2`), 256 RGB entries.
458///
459/// Ported verbatim from ADCore `colorMaps.h` (IronColorR/G/B). C selects this
460/// table when the FalseColor parameter is 2
461/// (NDPluginColorConvert.cpp:68-72).
462const IRON_COLOR_MAP: [[u8; 3]; 256] = [
463    [0, 0, 0],
464    [1, 0, 1],
465    [3, 1, 3],
466    [4, 1, 5],
467    [6, 2, 6],
468    [7, 2, 8],
469    [9, 3, 10],
470    [10, 3, 11],
471    [12, 4, 13],
472    [13, 4, 15],
473    [15, 5, 17],
474    [16, 5, 18],
475    [18, 6, 20],
476    [19, 6, 22],
477    [21, 7, 23],
478    [22, 7, 25],
479    [24, 8, 27],
480    [25, 8, 28],
481    [27, 9, 30],
482    [28, 9, 32],
483    [30, 10, 34],
484    [31, 10, 35],
485    [33, 11, 37],
486    [34, 11, 39],
487    [36, 12, 40],
488    [37, 12, 42],
489    [39, 13, 44],
490    [40, 13, 45],
491    [42, 14, 47],
492    [43, 14, 49],
493    [45, 15, 51],
494    [46, 15, 52],
495    [48, 16, 54],
496    [49, 16, 56],
497    [51, 17, 57],
498    [52, 17, 59],
499    [54, 18, 61],
500    [55, 18, 62],
501    [57, 19, 64],
502    [58, 19, 66],
503    [60, 20, 68],
504    [61, 20, 69],
505    [63, 21, 71],
506    [64, 21, 73],
507    [66, 22, 74],
508    [67, 22, 76],
509    [69, 23, 78],
510    [70, 23, 79],
511    [72, 24, 81],
512    [73, 24, 83],
513    [75, 25, 85],
514    [76, 25, 86],
515    [78, 26, 88],
516    [79, 26, 90],
517    [81, 27, 91],
518    [82, 27, 93],
519    [84, 28, 95],
520    [85, 28, 96],
521    [87, 29, 98],
522    [88, 29, 100],
523    [90, 30, 102],
524    [91, 30, 103],
525    [93, 31, 105],
526    [94, 31, 107],
527    [96, 32, 108],
528    [97, 32, 110],
529    [99, 33, 112],
530    [100, 33, 113],
531    [102, 34, 115],
532    [103, 34, 117],
533    [105, 35, 119],
534    [106, 35, 120],
535    [108, 36, 120],
536    [109, 36, 119],
537    [111, 37, 118],
538    [112, 37, 117],
539    [114, 38, 116],
540    [115, 38, 115],
541    [117, 39, 114],
542    [118, 39, 113],
543    [120, 40, 112],
544    [121, 40, 111],
545    [123, 41, 110],
546    [124, 41, 109],
547    [126, 42, 108],
548    [127, 42, 107],
549    [129, 43, 106],
550    [130, 43, 105],
551    [132, 44, 104],
552    [133, 44, 103],
553    [135, 45, 102],
554    [136, 45, 101],
555    [138, 46, 100],
556    [139, 46, 99],
557    [141, 47, 98],
558    [142, 47, 97],
559    [144, 48, 96],
560    [145, 48, 95],
561    [147, 49, 94],
562    [148, 49, 93],
563    [150, 50, 92],
564    [151, 50, 91],
565    [153, 51, 90],
566    [154, 51, 89],
567    [156, 52, 88],
568    [157, 52, 87],
569    [159, 53, 86],
570    [160, 53, 85],
571    [162, 54, 84],
572    [163, 54, 83],
573    [165, 55, 82],
574    [166, 55, 81],
575    [168, 56, 80],
576    [169, 56, 79],
577    [171, 57, 78],
578    [172, 57, 77],
579    [174, 58, 76],
580    [175, 58, 75],
581    [177, 59, 74],
582    [178, 59, 73],
583    [180, 60, 72],
584    [181, 60, 71],
585    [183, 61, 70],
586    [184, 61, 69],
587    [186, 62, 68],
588    [187, 62, 67],
589    [189, 63, 66],
590    [190, 63, 65],
591    [192, 64, 64],
592    [192, 65, 64],
593    [192, 67, 64],
594    [192, 68, 64],
595    [192, 70, 64],
596    [192, 71, 64],
597    [192, 73, 64],
598    [192, 74, 64],
599    [192, 76, 64],
600    [192, 77, 64],
601    [192, 79, 64],
602    [192, 80, 64],
603    [192, 82, 64],
604    [192, 83, 64],
605    [192, 85, 64],
606    [192, 86, 64],
607    [192, 88, 64],
608    [192, 89, 64],
609    [192, 91, 64],
610    [192, 92, 64],
611    [192, 94, 64],
612    [192, 95, 64],
613    [192, 97, 64],
614    [192, 98, 64],
615    [192, 100, 64],
616    [192, 101, 64],
617    [192, 103, 64],
618    [192, 104, 64],
619    [192, 106, 64],
620    [192, 107, 64],
621    [192, 109, 64],
622    [192, 110, 64],
623    [192, 112, 64],
624    [192, 113, 64],
625    [192, 115, 64],
626    [192, 116, 64],
627    [192, 118, 64],
628    [192, 119, 64],
629    [192, 121, 64],
630    [192, 122, 64],
631    [192, 124, 64],
632    [192, 125, 64],
633    [192, 127, 64],
634    [192, 128, 64],
635    [192, 130, 64],
636    [192, 131, 64],
637    [192, 133, 64],
638    [192, 134, 64],
639    [192, 136, 64],
640    [192, 137, 64],
641    [192, 139, 64],
642    [192, 140, 64],
643    [192, 142, 64],
644    [192, 143, 64],
645    [192, 145, 64],
646    [192, 146, 64],
647    [192, 148, 64],
648    [192, 149, 64],
649    [192, 151, 64],
650    [192, 152, 64],
651    [192, 154, 64],
652    [192, 155, 64],
653    [192, 157, 64],
654    [192, 158, 64],
655    [192, 160, 64],
656    [192, 161, 64],
657    [192, 163, 64],
658    [192, 164, 64],
659    [192, 166, 64],
660    [192, 167, 64],
661    [192, 169, 64],
662    [192, 170, 64],
663    [192, 172, 64],
664    [192, 173, 64],
665    [192, 175, 64],
666    [192, 176, 64],
667    [192, 178, 64],
668    [192, 179, 64],
669    [192, 181, 64],
670    [192, 182, 64],
671    [192, 184, 64],
672    [192, 185, 64],
673    [192, 187, 64],
674    [192, 188, 64],
675    [192, 190, 64],
676    [192, 191, 64],
677    [192, 193, 64],
678    [192, 194, 64],
679    [192, 196, 64],
680    [192, 197, 64],
681    [192, 199, 64],
682    [192, 200, 64],
683    [192, 202, 64],
684    [192, 203, 64],
685    [192, 205, 64],
686    [192, 206, 64],
687    [192, 208, 64],
688    [192, 209, 64],
689    [192, 211, 64],
690    [192, 212, 64],
691    [192, 214, 64],
692    [192, 215, 64],
693    [192, 217, 64],
694    [192, 218, 64],
695    [192, 220, 64],
696    [192, 221, 64],
697    [192, 223, 64],
698    [192, 224, 64],
699    [192, 226, 64],
700    [192, 227, 64],
701    [192, 229, 64],
702    [192, 230, 64],
703    [192, 232, 64],
704    [192, 233, 64],
705    [192, 235, 64],
706    [192, 236, 64],
707    [192, 238, 64],
708    [192, 239, 64],
709    [192, 241, 64],
710    [192, 242, 64],
711    [192, 244, 64],
712    [192, 245, 64],
713    [192, 247, 64],
714    [192, 248, 64],
715    [192, 250, 64],
716    [192, 251, 64],
717    [192, 253, 64],
718    [255, 255, 255],
719];
720
721/// Select the false-color LUT for a `falseColor` parameter value.
722///
723/// Matches NDPluginColorConvert.cpp:61-78: 1 => Rainbow, 2 => Iron, any other
724/// value => no false color (C resets `falseColor` to 0 in the `default` arm).
725fn false_color_lut(false_color: i32) -> Option<&'static [[u8; 3]; 256]> {
726    match false_color {
727        1 => Some(&RAINBOW_COLOR_MAP),
728        2 => Some(&IRON_COLOR_MAP),
729        _ => None,
730    }
731}
732
733/// Convert a mono 8-bit image to RGB1 using a false-color LUT.
734///
735/// C reads the `FalseColor` parameter **only** for 8-bit arrays
736/// (NDPluginColorConvert.cpp:59-60: `if (pArray->dataType == NDInt8 ||
737/// pArray->dataType == NDUInt8)`); for every wider type the local `falseColor`
738/// stays at its `0` initializer (`:45`) and the plain grayscale replication runs.
739/// So both `NDInt8` and `NDUInt8` are colormapped, and nothing else is.
740///
741/// The LUT index is the *low byte* of the sample — C writes
742/// `colorMapRGB + 3 * ((unsigned char)*pIn)` (`:108`), so a negative `epicsInt8`
743/// indexes 128..=255. The output keeps the input data type, and for `NDInt8`
744/// C `memcpy`s the LUT's raw bytes into `epicsInt8` cells, so a LUT entry above
745/// 127 lands as a negative sample.
746///
747/// Returns `None` for a non-8-bit or non-2-D input, or a `false_color` value
748/// with no table.
749fn false_color_mono_to_rgb1(src: &NDArray, false_color: i32) -> Option<NDArray> {
750    if src.dims.len() != 2 {
751        return None;
752    }
753    let lut = false_color_lut(false_color)?;
754
755    let w = src.dims[0].size;
756    let h = src.dims[1].size;
757    let n = w * h;
758
759    // Map each sample through the LUT by its low byte, keeping the input type.
760    let (data, data_type) = match &src.data {
761        NDDataBuffer::U8(src_slice) => {
762            let mut out = vec![0u8; n * 3];
763            for i in 0..n {
764                let [r, g, b] = lut[src_slice[i] as usize];
765                out[i * 3] = r;
766                out[i * 3 + 1] = g;
767                out[i * 3 + 2] = b;
768            }
769            (NDDataBuffer::U8(out), NDDataType::UInt8)
770        }
771        NDDataBuffer::I8(src_slice) => {
772            let mut out = vec![0i8; n * 3];
773            for i in 0..n {
774                let [r, g, b] = lut[src_slice[i] as u8 as usize];
775                out[i * 3] = r as i8;
776                out[i * 3 + 1] = g as i8;
777                out[i * 3 + 2] = b as i8;
778            }
779            (NDDataBuffer::I8(out), NDDataType::Int8)
780        }
781        _ => return None,
782    };
783
784    let dims = vec![
785        NDDimension::new(3),
786        NDDimension::new(w),
787        NDDimension::new(h),
788    ];
789    let mut arr = NDArray::new(dims, data_type);
790    arr.data = data;
791    arr.unique_id = src.unique_id;
792    arr.timestamp = src.timestamp;
793    arr.attributes = src.attributes.clone();
794    Some(arr)
795}
796
797/// Color convert plugin configuration.
798#[derive(Debug, Clone)]
799pub struct ColorConvertConfig {
800    pub target_mode: NDColorMode,
801    pub bayer_pattern: NDBayerPattern,
802    /// False color mode: 0=off, 1=Rainbow, 2=Iron. Nonzero is treated as enabled.
803    pub false_color: i32,
804}
805
806/// Pure color conversion processing logic.
807pub struct ColorConvertProcessor {
808    config: ColorConvertConfig,
809    color_mode_out_idx: Option<usize>,
810    false_color_idx: Option<usize>,
811}
812
813impl ColorConvertProcessor {
814    pub fn new(config: ColorConvertConfig) -> Self {
815        Self {
816            config,
817            color_mode_out_idx: None,
818            false_color_idx: None,
819        }
820    }
821}
822
823impl NDPluginProcess for ColorConvertProcessor {
824    fn register_params(
825        &mut self,
826        base: &mut asyn_rs::port::PortDriverBase,
827    ) -> asyn_rs::error::AsynResult<()> {
828        use asyn_rs::param::ParamType;
829        base.create_param("COLOR_MODE_OUT", ParamType::Int32)?;
830        base.create_param("FALSE_COLOR", ParamType::Int32)?;
831        self.color_mode_out_idx = base.find_param("COLOR_MODE_OUT");
832        self.false_color_idx = base.find_param("FALSE_COLOR");
833        Ok(())
834    }
835
836    fn on_param_change(
837        &mut self,
838        reason: usize,
839        params: &ad_core_rs::plugin::runtime::PluginParamSnapshot,
840    ) -> ad_core_rs::plugin::runtime::ParamChangeResult {
841        if Some(reason) == self.color_mode_out_idx {
842            self.config.target_mode = NDColorMode::from_i32(params.value.as_i32());
843        } else if Some(reason) == self.false_color_idx {
844            self.config.false_color = params.value.as_i32();
845        }
846        ad_core_rs::plugin::runtime::ParamChangeResult::updates(vec![])
847    }
848
849    fn process_array(&mut self, array: &NDArray, _pool: &NDArrayPool) -> ProcessResult {
850        // C `convertColor` (NDPluginColorConvert.cpp:44,54-55) starts from
851        // `int colorMode = NDColorModeMono` and overwrites it only from the
852        // `ColorMode` attribute; it never infers a layout from the dimensions.
853        // `NDArray::info()` owns that rule for the whole workspace.
854        let src_mode = array.info().color_mode;
855        let target = self.config.target_mode;
856
857        // C:584 — `if (!pArrayOut) pArrayOut = this->pNDArrayPool->copy(pArray, NULL, 1);`
858        // Every arm that does not convert (same mode, unsupported pair, or a shape the
859        // arm rejects, e.g. Mono with `ndims != 2` at :84) leaves `pArrayOut` NULL and
860        // the untouched input is forwarded — with its own ColorMode, since
861        // `changedColorMode` stayed 0 (:589). A frame is never dropped.
862        let passthrough = || ProcessResult::arrays(vec![Arc::new(array.clone())]);
863
864        if src_mode == target {
865            return passthrough();
866        }
867
868        // Step 1: Convert source to RGB1 intermediate
869        let rgb1 = match src_mode {
870            NDColorMode::RGB1 => Some(array.clone()),
871            NDColorMode::Mono => {
872                if self.config.false_color != 0 {
873                    false_color_mono_to_rgb1(array, self.config.false_color)
874                        .or_else(|| color::mono_to_rgb1(array).ok())
875                } else {
876                    color::mono_to_rgb1(array).ok()
877                }
878            }
879            NDColorMode::Bayer => bayer_to_rgb1(array, self.config.bayer_pattern),
880            NDColorMode::RGB2 | NDColorMode::RGB3 => {
881                color::convert_rgb_layout(array, src_mode, NDColorMode::RGB1).ok()
882            }
883            NDColorMode::YUV444 => color::yuv444_to_rgb1(array).ok(),
884            NDColorMode::YUV422 => color::yuv422_to_rgb1(array).ok(),
885            NDColorMode::YUV411 => color::yuv411_to_rgb1(array).ok(),
886        };
887
888        let rgb1 = match rgb1 {
889            Some(r) => r,
890            None => return passthrough(),
891        };
892
893        // Step 2: Convert RGB1 intermediate to target
894        let result = match target {
895            NDColorMode::RGB1 => Some(rgb1),
896            NDColorMode::Mono => color::rgb1_to_mono(&rgb1).ok(),
897            NDColorMode::Bayer => None,
898            NDColorMode::RGB2 | NDColorMode::RGB3 => {
899                color::convert_rgb_layout(&rgb1, NDColorMode::RGB1, target).ok()
900            }
901            NDColorMode::YUV444 => color::rgb1_to_yuv444(&rgb1).ok(),
902            NDColorMode::YUV422 => color::rgb1_to_yuv422(&rgb1).ok(),
903            NDColorMode::YUV411 => color::rgb1_to_yuv411(&rgb1).ok(),
904        };
905
906        match result {
907            Some(mut out) => {
908                // C++: set ColorMode attribute on output array
909                let color_mode_val = match target {
910                    NDColorMode::Mono => 0i32,
911                    NDColorMode::Bayer => 1,
912                    NDColorMode::RGB1 => 2,
913                    NDColorMode::RGB2 => 3,
914                    NDColorMode::RGB3 => 4,
915                    NDColorMode::YUV444 => 5,
916                    NDColorMode::YUV422 => 6,
917                    NDColorMode::YUV411 => 7,
918                };
919                use ad_core_rs::attributes::{NDAttrSource, NDAttrValue, NDAttribute};
920                out.attributes.add(NDAttribute::new_static(
921                    "ColorMode",
922                    "Color Mode",
923                    NDAttrSource::Driver,
924                    NDAttrValue::Int32(color_mode_val),
925                ));
926                ProcessResult::arrays(vec![Arc::new(out)])
927            }
928            None => passthrough(),
929        }
930    }
931
932    fn plugin_type(&self) -> &str {
933        "NDPluginColorConvert"
934    }
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    #[test]
942    fn test_bayer_to_rgb1_basic() {
943        // 4x4 RGGB bayer pattern
944        let mut arr = NDArray::new(
945            vec![NDDimension::new(4), NDDimension::new(4)],
946            NDDataType::UInt8,
947        );
948        if let NDDataBuffer::U8(ref mut v) = arr.data {
949            // Simple pattern: all pixels = 128
950            for i in 0..16 {
951                v[i] = 128;
952            }
953        }
954
955        let rgb = bayer_to_rgb1(&arr, NDBayerPattern::RGGB).unwrap();
956        assert_eq!(rgb.dims.len(), 3);
957        assert_eq!(rgb.dims[0].size, 3); // color
958        assert_eq!(rgb.dims[1].size, 4); // x
959        assert_eq!(rgb.dims[2].size, 4); // y
960    }
961
962    // RGB1 pixel (x,y) channel c lives at out[(y*w + x)*3 + c].
963    fn rgb1_pixel(arr: &NDArray, w: usize, x: usize, y: usize) -> [u8; 3] {
964        let i = (y * w + x) * 3;
965        if let NDDataBuffer::U8(ref v) = arr.data {
966            [v[i], v[i + 1], v[i + 2]]
967        } else {
968            panic!("expected UInt8 RGB1 output");
969        }
970    }
971
972    #[test]
973    fn test_adp4_bayer_border_keeps_native_channel_only() {
974        // 4x4 RGGB, all pixels = 100. C interpolates only interior pixels
975        // (NDPluginColorConvert.cpp:305); border pixels keep only their native
976        // Bayer channel, the other two stay 0. Previously the Rust border was
977        // interpolated from available neighbours (e.g. corner -> (100,100,100)).
978        let mut arr = NDArray::new(
979            vec![NDDimension::new(4), NDDimension::new(4)],
980            NDDataType::UInt8,
981        );
982        if let NDDataBuffer::U8(ref mut v) = arr.data {
983            v.iter_mut().for_each(|p| *p = 100);
984        }
985        let rgb = bayer_to_rgb1(&arr, NDBayerPattern::RGGB).unwrap();
986
987        // Border pixels: native channel only.
988        assert_eq!(rgb1_pixel(&rgb, 4, 0, 0), [100, 0, 0]); // corner, red
989        assert_eq!(rgb1_pixel(&rgb, 4, 1, 0), [0, 100, 0]); // top edge, green
990        assert_eq!(rgb1_pixel(&rgb, 4, 0, 1), [0, 100, 0]); // left edge, green
991        assert_eq!(rgb1_pixel(&rgb, 4, 3, 3), [0, 0, 100]); // corner, blue
992
993        // Interior pixels: fully interpolated (all neighbours = 100).
994        assert_eq!(rgb1_pixel(&rgb, 4, 1, 1), [100, 100, 100]); // blue
995        assert_eq!(rgb1_pixel(&rgb, 4, 1, 2), [100, 100, 100]); // green
996        assert_eq!(rgb1_pixel(&rgb, 4, 2, 2), [100, 100, 100]); // red
997    }
998
999    #[test]
1000    fn test_adp4_bayer_interior_uses_fixed_quarter_divisor() {
1001        // 3x3 RGGB: the only interior pixel is the blue centre (1,1). Its red is
1002        // the diagonal mean /4 and green the orthogonal mean /4
1003        // (NDPluginColorConvert.cpp:308-309). Distinct neighbour values pin the
1004        // divisor: diagonals all 200 -> red 200; orthogonals 40,40,80,80 ->
1005        // green 60.
1006        let mut arr = NDArray::new(
1007            vec![NDDimension::new(3), NDDimension::new(3)],
1008            NDDataType::UInt8,
1009        );
1010        if let NDDataBuffer::U8(ref mut v) = arr.data {
1011            // row0: 200 40 200 / row1: 80 128 80 / row2: 200 40 200
1012            v.copy_from_slice(&[200, 40, 200, 80, 128, 80, 200, 40, 200]);
1013        }
1014        let rgb = bayer_to_rgb1(&arr, NDBayerPattern::RGGB).unwrap();
1015
1016        // Interior blue centre: red = (200*4)/4 = 200, green = (40+40+80+80)/4 = 60.
1017        assert_eq!(rgb1_pixel(&rgb, 3, 1, 1), [200, 60, 128]);
1018        // All eight surrounding pixels are border: native channel only.
1019        assert_eq!(rgb1_pixel(&rgb, 3, 0, 0), [200, 0, 0]); // red
1020        assert_eq!(rgb1_pixel(&rgb, 3, 1, 0), [0, 40, 0]); // green
1021    }
1022
1023    #[test]
1024    fn test_color_convert_processor_bayer() {
1025        let config = ColorConvertConfig {
1026            target_mode: NDColorMode::RGB1,
1027            bayer_pattern: NDBayerPattern::RGGB,
1028            false_color: 0,
1029        };
1030        let mut proc = ColorConvertProcessor::new(config);
1031        let pool = NDArrayPool::new(1_000_000);
1032
1033        let mut arr = NDArray::new(
1034            vec![NDDimension::new(4), NDDimension::new(4)],
1035            NDDataType::UInt8,
1036        );
1037        if let NDDataBuffer::U8(ref mut v) = arr.data {
1038            for i in 0..16 {
1039                v[i] = 128;
1040            }
1041        }
1042
1043        let result = proc.process_array(&arr, &pool);
1044        assert_eq!(result.output_arrays.len(), 1);
1045        assert_eq!(result.output_arrays[0].dims[0].size, 3); // RGB color dim
1046    }
1047
1048    #[test]
1049    fn test_false_color_conversion() {
1050        let config = ColorConvertConfig {
1051            target_mode: NDColorMode::RGB1,
1052            bayer_pattern: NDBayerPattern::RGGB,
1053            false_color: 1,
1054        };
1055        let mut proc = ColorConvertProcessor::new(config);
1056        let pool = NDArrayPool::new(1_000_000);
1057
1058        // Create a 4x4 mono UInt8 image with a gradient
1059        let mut arr = NDArray::new(
1060            vec![NDDimension::new(4), NDDimension::new(4)],
1061            NDDataType::UInt8,
1062        );
1063        if let NDDataBuffer::U8(ref mut v) = arr.data {
1064            for i in 0..16 {
1065                v[i] = (i * 17) as u8; // 0, 17, 34, ... 255
1066            }
1067        }
1068
1069        let result = proc.process_array(&arr, &pool);
1070        assert_eq!(result.output_arrays.len(), 1);
1071        let out = &result.output_arrays[0];
1072        assert_eq!(out.dims.len(), 3);
1073        assert_eq!(out.dims[0].size, 3); // color
1074        assert_eq!(out.dims[1].size, 4); // x
1075        assert_eq!(out.dims[2].size, 4); // y
1076
1077        // false_color=1 selects the Rainbow LUT (NDPluginColorConvert.cpp:62-66).
1078        // Pixel 0 (value=0) -> Rainbow[0]=(0,0,0); the old jet LUT gave B=127 here.
1079        if let NDDataBuffer::U8(ref v) = out.data {
1080            assert_eq!([v[0], v[1], v[2]], RAINBOW_COLOR_MAP[0]);
1081            assert_eq!([v[0], v[1], v[2]], [0, 0, 0]);
1082            // Last pixel (value=255) -> Rainbow[255]=(255,255,255).
1083            let last = 15 * 3;
1084            assert_eq!([v[last], v[last + 1], v[last + 2]], RAINBOW_COLOR_MAP[255]);
1085        } else {
1086            panic!("expected UInt8 output");
1087        }
1088    }
1089
1090    #[test]
1091    fn test_false_color_iron_table() {
1092        let config = ColorConvertConfig {
1093            target_mode: NDColorMode::RGB1,
1094            bayer_pattern: NDBayerPattern::RGGB,
1095            false_color: 2,
1096        };
1097        let mut proc = ColorConvertProcessor::new(config);
1098        let pool = NDArrayPool::new(1_000_000);
1099
1100        // 2x1 mono image with values 0 and 192 to probe distinct Iron entries.
1101        let mut arr = NDArray::new(
1102            vec![NDDimension::new(2), NDDimension::new(1)],
1103            NDDataType::UInt8,
1104        );
1105        if let NDDataBuffer::U8(ref mut v) = arr.data {
1106            v[0] = 0;
1107            v[1] = 192;
1108        }
1109
1110        let result = proc.process_array(&arr, &pool);
1111        let out = &result.output_arrays[0];
1112        if let NDDataBuffer::U8(ref v) = out.data {
1113            // false_color=2 selects Iron (NDPluginColorConvert.cpp:68-72).
1114            assert_eq!([v[0], v[1], v[2]], IRON_COLOR_MAP[0]);
1115            assert_eq!([v[3], v[4], v[5]], IRON_COLOR_MAP[192]);
1116            // Iron[192]=(192,160,64) differs from the Rainbow table at the same index.
1117            assert_eq!([v[3], v[4], v[5]], [192, 160, 64]);
1118            assert_ne!(IRON_COLOR_MAP[192], RAINBOW_COLOR_MAP[192]);
1119        } else {
1120            panic!("expected UInt8 output");
1121        }
1122    }
1123
1124    #[test]
1125    fn test_r6_66_false_color_int8_uses_low_byte_index() {
1126        // R6-66 / NDPluginColorConvert.cpp:59-60 — C reads the FalseColor
1127        // parameter for NDInt8 as well as NDUInt8, and indexes the map with
1128        // `(unsigned char)*pIn` (:108), so a negative epicsInt8 selects entries
1129        // 128..=255. The LUT bytes are memcpy'd into epicsInt8 cells, so an
1130        // entry above 127 lands as a negative sample.
1131        let config = ColorConvertConfig {
1132            target_mode: NDColorMode::RGB1,
1133            bayer_pattern: NDBayerPattern::RGGB,
1134            false_color: 2,
1135        };
1136        let mut proc = ColorConvertProcessor::new(config);
1137        let pool = NDArrayPool::new(1_000_000);
1138
1139        let mut arr = NDArray::new(
1140            vec![NDDimension::new(2), NDDimension::new(1)],
1141            NDDataType::Int8,
1142        );
1143        if let NDDataBuffer::I8(ref mut v) = arr.data {
1144            v[0] = 0;
1145            v[1] = -64; // (unsigned char)(-64) == 192
1146        }
1147
1148        let result = proc.process_array(&arr, &pool);
1149        let out = &result.output_arrays[0];
1150        let NDDataBuffer::I8(ref v) = out.data else {
1151            panic!("Int8 input must stay Int8 (C allocates with pArray->dataType)");
1152        };
1153        let e0 = IRON_COLOR_MAP[0];
1154        let e192 = IRON_COLOR_MAP[192]; // (192, 160, 64)
1155        assert_eq!(
1156            [v[0], v[1], v[2]],
1157            [e0[0] as i8, e0[1] as i8, e0[2] as i8],
1158            "Int8 mono must be colormapped, not replicated to grayscale"
1159        );
1160        assert_eq!(
1161            [v[3], v[4], v[5]],
1162            [e192[0] as i8, e192[1] as i8, e192[2] as i8]
1163        );
1164        assert_eq!(v[3], -64, "LUT byte 192 reinterpreted as epicsInt8");
1165    }
1166
1167    #[test]
1168    fn test_r6_66_false_color_ignored_for_uint16() {
1169        // C only reads FalseColor for 8-bit arrays (NDPluginColorConvert.cpp:59);
1170        // for a UInt16 mono frame the local `falseColor` stays 0 (:45) and the
1171        // grayscale replication runs. Rust must match — no colormap here.
1172        let config = ColorConvertConfig {
1173            target_mode: NDColorMode::RGB1,
1174            bayer_pattern: NDBayerPattern::RGGB,
1175            false_color: 1,
1176        };
1177        let mut proc = ColorConvertProcessor::new(config);
1178        let pool = NDArrayPool::new(1_000_000);
1179
1180        let mut arr = NDArray::new(
1181            vec![NDDimension::new(2), NDDimension::new(1)],
1182            NDDataType::UInt16,
1183        );
1184        if let NDDataBuffer::U16(ref mut v) = arr.data {
1185            v[0] = 1000;
1186            v[1] = 2000;
1187        }
1188
1189        let result = proc.process_array(&arr, &pool);
1190        let out = &result.output_arrays[0];
1191        let NDDataBuffer::U16(ref v) = out.data else {
1192            panic!("expected UInt16 output");
1193        };
1194        assert_eq!(v[..6], [1000, 1000, 1000, 2000, 2000, 2000]);
1195    }
1196
1197    #[test]
1198    fn test_rgb1_to_rgb2_conversion() {
1199        let config = ColorConvertConfig {
1200            target_mode: NDColorMode::RGB2,
1201            bayer_pattern: NDBayerPattern::RGGB,
1202            false_color: 0,
1203        };
1204        let mut proc = ColorConvertProcessor::new(config);
1205        let pool = NDArrayPool::new(1_000_000);
1206
1207        // Create RGB1 image: dims [3, 4, 4]
1208        let mut arr = NDArray::new(
1209            vec![
1210                NDDimension::new(3),
1211                NDDimension::new(4),
1212                NDDimension::new(4),
1213            ],
1214            NDDataType::UInt8,
1215        );
1216        if let NDDataBuffer::U8(ref mut v) = arr.data {
1217            for i in 0..v.len() {
1218                v[i] = (i % 256) as u8;
1219            }
1220        }
1221        // The layout is declared, not guessed from the size-3 dimension
1222        // (NDPluginColorConvert.cpp:54-55).
1223        set_color_mode_attr(&mut arr, NDColorMode::RGB1);
1224
1225        let result = proc.process_array(&arr, &pool);
1226        assert_eq!(result.output_arrays.len(), 1);
1227        let out = &result.output_arrays[0];
1228        assert_eq!(out.dims.len(), 3);
1229        // RGB2 has color dim in position 1
1230        assert_eq!(out.dims[1].size, 3);
1231    }
1232
1233    #[test]
1234    fn test_rgb2_to_mono_conversion() {
1235        let config = ColorConvertConfig {
1236            target_mode: NDColorMode::Mono,
1237            bayer_pattern: NDBayerPattern::RGGB,
1238            false_color: 0,
1239        };
1240        let mut proc = ColorConvertProcessor::new(config);
1241        let pool = NDArrayPool::new(1_000_000);
1242
1243        // Create RGB2 image: dims [4, 3, 4]
1244        let mut arr = NDArray::new(
1245            vec![
1246                NDDimension::new(4),
1247                NDDimension::new(3),
1248                NDDimension::new(4),
1249            ],
1250            NDDataType::UInt8,
1251        );
1252        if let NDDataBuffer::U8(ref mut v) = arr.data {
1253            for i in 0..v.len() {
1254                v[i] = 128;
1255            }
1256        }
1257        // The layout is declared, not guessed from the size-3 dimension
1258        // (NDPluginColorConvert.cpp:54-55).
1259        set_color_mode_attr(&mut arr, NDColorMode::RGB2);
1260
1261        let result = proc.process_array(&arr, &pool);
1262        assert_eq!(result.output_arrays.len(), 1);
1263        let out = &result.output_arrays[0];
1264        // Mono output should be 2D
1265        assert_eq!(out.dims.len(), 2);
1266    }
1267
1268    /// A size-3 dimension is not a color mode. C reads the source mode from the
1269    /// `ColorMode` attribute alone (NDPluginColorConvert.cpp:54-55); with none
1270    /// present the mode is the initialiser, `NDColorModeMono` (:44), whatever the
1271    /// dimensions look like.
1272    #[test]
1273    fn r9_80_dims_never_imply_a_color_mode() {
1274        for dims in [
1275            vec![
1276                NDDimension::new(3),
1277                NDDimension::new(4),
1278                NDDimension::new(4),
1279            ],
1280            vec![
1281                NDDimension::new(4),
1282                NDDimension::new(3),
1283                NDDimension::new(4),
1284            ],
1285            vec![
1286                NDDimension::new(4),
1287                NDDimension::new(4),
1288                NDDimension::new(3),
1289            ],
1290            vec![NDDimension::new(4), NDDimension::new(4)],
1291        ] {
1292            let arr = NDArray::new(dims, NDDataType::UInt8);
1293            assert_eq!(
1294                arr.info().color_mode,
1295                NDColorMode::Mono,
1296                "no ColorMode attribute -> Mono, never an RGB layout guessed from a \
1297                 size-3 dimension"
1298            );
1299        }
1300    }
1301
1302    #[test]
1303    fn test_same_mode_passthrough() {
1304        let config = ColorConvertConfig {
1305            target_mode: NDColorMode::Mono,
1306            bayer_pattern: NDBayerPattern::RGGB,
1307            false_color: 0,
1308        };
1309        let mut proc = ColorConvertProcessor::new(config);
1310        let pool = NDArrayPool::new(1_000_000);
1311
1312        // 2D mono input with Mono target -> passthrough
1313        let mut arr = NDArray::new(
1314            vec![NDDimension::new(4), NDDimension::new(4)],
1315            NDDataType::UInt8,
1316        );
1317        arr.unique_id = 42;
1318        if let NDDataBuffer::U8(ref mut v) = arr.data {
1319            for i in 0..16 {
1320                v[i] = i as u8;
1321            }
1322        }
1323
1324        let result = proc.process_array(&arr, &pool);
1325        assert_eq!(result.output_arrays.len(), 1);
1326        assert_eq!(result.output_arrays[0].unique_id, 42);
1327        assert_eq!(result.output_arrays[0].dims.len(), 2);
1328    }
1329
1330    fn set_color_mode_attr(arr: &mut NDArray, mode: NDColorMode) {
1331        use ad_core_rs::attributes::{NDAttrSource, NDAttrValue, NDAttribute};
1332        arr.attributes.add(NDAttribute::new_static(
1333            "ColorMode",
1334            String::new(),
1335            NDAttrSource::Driver,
1336            NDAttrValue::Int32(mode as i32),
1337        ));
1338    }
1339
1340    #[test]
1341    fn test_bayer_to_mono_via_rgb1() {
1342        let config = ColorConvertConfig {
1343            target_mode: NDColorMode::Mono,
1344            bayer_pattern: NDBayerPattern::RGGB,
1345            false_color: 0,
1346        };
1347        let mut proc = ColorConvertProcessor::new(config);
1348        let pool = NDArrayPool::new(1_000_000);
1349
1350        let mut arr = NDArray::new(
1351            vec![NDDimension::new(4), NDDimension::new(4)],
1352            NDDataType::UInt8,
1353        );
1354        set_color_mode_attr(&mut arr, NDColorMode::Bayer);
1355        if let NDDataBuffer::U8(ref mut v) = arr.data {
1356            for i in 0..16 {
1357                v[i] = 128;
1358            }
1359        }
1360
1361        let result = proc.process_array(&arr, &pool);
1362        assert_eq!(result.output_arrays.len(), 1);
1363        assert_eq!(result.output_arrays[0].dims.len(), 2);
1364    }
1365
1366    #[test]
1367    fn test_rgb1_to_yuv444_conversion() {
1368        let config = ColorConvertConfig {
1369            target_mode: NDColorMode::YUV444,
1370            bayer_pattern: NDBayerPattern::RGGB,
1371            false_color: 0,
1372        };
1373        let mut proc = ColorConvertProcessor::new(config);
1374        let pool = NDArrayPool::new(1_000_000);
1375
1376        let mut arr = NDArray::new(
1377            vec![
1378                NDDimension::new(3),
1379                NDDimension::new(4),
1380                NDDimension::new(4),
1381            ],
1382            NDDataType::UInt8,
1383        );
1384        if let NDDataBuffer::U8(ref mut v) = arr.data {
1385            for i in 0..v.len() {
1386                v[i] = (i % 256) as u8;
1387            }
1388        }
1389
1390        let result = proc.process_array(&arr, &pool);
1391        assert_eq!(result.output_arrays.len(), 1);
1392        let out = &result.output_arrays[0];
1393        assert_eq!(out.dims.len(), 3);
1394        assert_eq!(out.dims[0].size, 3);
1395    }
1396
1397    #[test]
1398    fn test_yuv422_to_rgb1_conversion() {
1399        let config = ColorConvertConfig {
1400            target_mode: NDColorMode::RGB1,
1401            bayer_pattern: NDBayerPattern::RGGB,
1402            false_color: 0,
1403        };
1404        let mut proc = ColorConvertProcessor::new(config);
1405        let pool = NDArrayPool::new(1_000_000);
1406
1407        // packed_x=8 means 4 pixels wide, 2 rows
1408        let mut arr = NDArray::new(
1409            vec![NDDimension::new(8), NDDimension::new(2)],
1410            NDDataType::UInt8,
1411        );
1412        set_color_mode_attr(&mut arr, NDColorMode::YUV422);
1413        if let NDDataBuffer::U8(ref mut v) = arr.data {
1414            // UYVY pattern: U Y0 V Y1
1415            let uyvy: [u8; 16] = [
1416                128, 100, 128, 150, 128, 200, 128, 50, 128, 128, 128, 128, 128, 64, 128, 192,
1417            ];
1418            v[..16].copy_from_slice(&uyvy);
1419        }
1420
1421        let result = proc.process_array(&arr, &pool);
1422        assert_eq!(result.output_arrays.len(), 1);
1423        let out = &result.output_arrays[0];
1424        assert_eq!(out.dims[0].size, 3);
1425        assert_eq!(out.dims[1].size, 4);
1426        assert_eq!(out.dims[2].size, 2);
1427    }
1428
1429    #[test]
1430    fn test_mono_to_yuv422_conversion() {
1431        let config = ColorConvertConfig {
1432            target_mode: NDColorMode::YUV422,
1433            bayer_pattern: NDBayerPattern::RGGB,
1434            false_color: 0,
1435        };
1436        let mut proc = ColorConvertProcessor::new(config);
1437        let pool = NDArrayPool::new(1_000_000);
1438
1439        let mut arr = NDArray::new(
1440            vec![NDDimension::new(4), NDDimension::new(2)],
1441            NDDataType::UInt8,
1442        );
1443        if let NDDataBuffer::U8(ref mut v) = arr.data {
1444            for i in 0..8 {
1445                v[i] = (i * 30) as u8;
1446            }
1447        }
1448
1449        let result = proc.process_array(&arr, &pool);
1450        assert_eq!(result.output_arrays.len(), 1);
1451        let out = &result.output_arrays[0];
1452        assert_eq!(out.dims.len(), 2);
1453        assert_eq!(out.dims[0].size, 8); // packed_x = 4*2
1454    }
1455
1456    #[test]
1457    fn test_yuv444_to_mono_conversion() {
1458        let config = ColorConvertConfig {
1459            target_mode: NDColorMode::Mono,
1460            bayer_pattern: NDBayerPattern::RGGB,
1461            false_color: 0,
1462        };
1463        let mut proc = ColorConvertProcessor::new(config);
1464        let pool = NDArrayPool::new(1_000_000);
1465
1466        let mut arr = NDArray::new(
1467            vec![
1468                NDDimension::new(3),
1469                NDDimension::new(4),
1470                NDDimension::new(4),
1471            ],
1472            NDDataType::UInt8,
1473        );
1474        set_color_mode_attr(&mut arr, NDColorMode::YUV444);
1475        if let NDDataBuffer::U8(ref mut v) = arr.data {
1476            for i in 0..v.len() {
1477                v[i] = 128;
1478            }
1479        }
1480
1481        let result = proc.process_array(&arr, &pool);
1482        assert_eq!(result.output_arrays.len(), 1);
1483        let out = &result.output_arrays[0];
1484        assert_eq!(out.dims.len(), 2);
1485        assert_eq!(out.dims[0].size, 4);
1486        assert_eq!(out.dims[1].size, 4);
1487    }
1488
1489    #[test]
1490    fn test_color_mode_comes_from_the_attribute() {
1491        let mut arr = NDArray::new(
1492            vec![NDDimension::new(8), NDDimension::new(2)],
1493            NDDataType::UInt8,
1494        );
1495        assert_eq!(arr.info().color_mode, NDColorMode::Mono);
1496
1497        set_color_mode_attr(&mut arr, NDColorMode::YUV422);
1498        assert_eq!(arr.info().color_mode, NDColorMode::YUV422);
1499    }
1500
1501    #[test]
1502    fn test_false_color_table_endpoints() {
1503        // Both ADCore tables start at black and end at white (colorMaps.h).
1504        // The previous jet generator gave (0,0,127) at index 0 — the divergence
1505        // this fix closes.
1506        assert_eq!(RAINBOW_COLOR_MAP[0], [0, 0, 0]);
1507        assert_eq!(RAINBOW_COLOR_MAP[255], [255, 255, 255]);
1508        assert_eq!(IRON_COLOR_MAP[0], [0, 0, 0]);
1509        assert_eq!(IRON_COLOR_MAP[255], [255, 255, 255]);
1510
1511        // Mid-table sample pins the exact ported bytes (RainbowColor at 128,
1512        // IronColor at 128 per colorMaps.h).
1513        assert_eq!(RAINBOW_COLOR_MAP[128], [4, 255, 251]);
1514        assert_eq!(IRON_COLOR_MAP[128], [192, 64, 64]);
1515
1516        // falseColor selector matches NDPluginColorConvert.cpp:61-78.
1517        assert_eq!(false_color_lut(1), Some(&RAINBOW_COLOR_MAP));
1518        assert_eq!(false_color_lut(2), Some(&IRON_COLOR_MAP));
1519        assert_eq!(false_color_lut(0), None);
1520        assert_eq!(false_color_lut(3), None);
1521    }
1522}