edgefirst-tensor 0.34.1

Zero-copy tensor memory management with DMA, shared memory, and heap backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! Colorimetry metadata for image/video tensors.
//!
//! Four orthogonal axes mirroring V4L2's `struct v4l2_format` colorimetry
//! fields and `libcamera::ColorSpace`, named to match the EdgeFirst
//! `CameraFrame.msg` schema so values round-trip through the ROS layer.
//! Each enum is `#[non_exhaustive]`; unknown/`_DEFAULT` values map to `None`.

use core::fmt;
use serde::{Deserialize, Serialize};

// V4L2 UAPI constants (stable kernel ABI) — mirrored from <linux/videodev2.h>.
const V4L2_COLORSPACE_SMPTE170M: u32 = 1;
const V4L2_COLORSPACE_REC709: u32 = 3;
const V4L2_COLORSPACE_470_SYSTEM_M: u32 = 5;
const V4L2_COLORSPACE_470_SYSTEM_BG: u32 = 6;
const V4L2_COLORSPACE_JPEG: u32 = 7;
const V4L2_COLORSPACE_SRGB: u32 = 8;
const V4L2_COLORSPACE_BT2020: u32 = 10;
const V4L2_XFER_FUNC_709: u32 = 1;
const V4L2_XFER_FUNC_SRGB: u32 = 2;
const V4L2_XFER_FUNC_NONE: u32 = 5;
const V4L2_XFER_FUNC_SMPTE2084: u32 = 7;
const V4L2_YCBCR_ENC_DEFAULT: u32 = 0;
const V4L2_YCBCR_ENC_601: u32 = 1;
const V4L2_YCBCR_ENC_709: u32 = 2;
const V4L2_YCBCR_ENC_BT2020: u32 = 6;
const V4L2_QUANTIZATION_DEFAULT: u32 = 0;
const V4L2_QUANTIZATION_FULL_RANGE: u32 = 1;
const V4L2_QUANTIZATION_LIM_RANGE: u32 = 2;

/// Color primaries (`color_space` in the EdgeFirst schema).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ColorSpace {
    Bt709,
    Bt2020,
    Srgb,
    Smpte170m,
}

/// Transfer function (`color_transfer` in the EdgeFirst schema).
///
/// **Limitation:** this axis is stored, propagated, and round-tripped, but it is
/// **not applied** by any conversion backend. All YUV↔RGB paths operate only on
/// the matrix ([`ColorEncoding`]) and range ([`ColorRange`]); the transfer
/// function (gamma / TRC) is assumed to be the platform-native curve and is left
/// unchanged. HDR transfer curves ([`Self::Pq`] / [`Self::Hlg`]) are therefore
/// *not* tone-mapped — consumers needing linear-light or HDR handling must apply
/// the curve themselves.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ColorTransfer {
    Bt709,
    Srgb,
    Pq,
    /// Hybrid Log-Gamma. Present for EdgeFirst-schema / libcamera parity; the
    /// V4L2 UAPI defines no `V4L2_XFER_FUNC_HLG`, so `from_v4l2` never yields
    /// this variant.
    Hlg,
    Linear,
}

/// YCbCr encoding matrix (`color_encoding` in the EdgeFirst schema).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ColorEncoding {
    Bt601,
    Bt709,
    Bt2020,
}

/// Quantization range (`color_range` in the EdgeFirst schema).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ColorRange {
    Full,
    Limited,
}

impl ColorSpace {
    /// Parse the schema's short string label — the inverse of [`Self::as_str`].
    ///
    /// Returns `None` for `""` and for any label this build does not know.
    /// Colorimetry is descriptive metadata: a consumer that cannot name one
    /// axis can still use the pixels, so an unknown label degrades to
    /// "unspecified" rather than failing the whole import.
    pub fn from_str_code(s: &str) -> Option<Self> {
        match s {
            "bt709" => Some(Self::Bt709),
            "bt2020" => Some(Self::Bt2020),
            "srgb" => Some(Self::Srgb),
            "smpte170m" => Some(Self::Smpte170m),
            _ => None,
        }
    }

    /// Short string label matching the EdgeFirst schema.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Bt709 => "bt709",
            Self::Bt2020 => "bt2020",
            Self::Srgb => "srgb",
            Self::Smpte170m => "smpte170m",
        }
    }

    /// Map a raw V4L2 `colorspace` field to a [`ColorSpace`].
    ///
    /// Returns `None` for `V4L2_COLORSPACE_DEFAULT` (0) and any
    /// unrecognised value.
    pub fn from_v4l2(v: u32) -> Option<Self> {
        match v {
            V4L2_COLORSPACE_SMPTE170M => Some(Self::Smpte170m),
            V4L2_COLORSPACE_REC709 => Some(Self::Bt709),
            // legacy NTSC (470M) / PAL-SECAM (470BG): close enough to SMPTE 170M primaries for conversion
            V4L2_COLORSPACE_470_SYSTEM_M | V4L2_COLORSPACE_470_SYSTEM_BG => Some(Self::Smpte170m),
            V4L2_COLORSPACE_JPEG | V4L2_COLORSPACE_SRGB => Some(Self::Srgb),
            V4L2_COLORSPACE_BT2020 => Some(Self::Bt2020),
            _ => None,
        }
    }
}

impl ColorTransfer {
    /// Parse the schema's short string label — the inverse of [`Self::as_str`].
    ///
    /// Returns `None` for `""` and for any label this build does not know.
    /// Colorimetry is descriptive metadata: a consumer that cannot name one
    /// axis can still use the pixels, so an unknown label degrades to
    /// "unspecified" rather than failing the whole import.
    pub fn from_str_code(s: &str) -> Option<Self> {
        match s {
            "bt709" => Some(Self::Bt709),
            "srgb" => Some(Self::Srgb),
            "pq" => Some(Self::Pq),
            "hlg" => Some(Self::Hlg),
            "linear" => Some(Self::Linear),
            _ => None,
        }
    }

    /// Short string label matching the EdgeFirst schema.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Bt709 => "bt709",
            Self::Srgb => "srgb",
            Self::Pq => "pq",
            Self::Hlg => "hlg",
            Self::Linear => "linear",
        }
    }

    /// Map a raw V4L2 `xfer_func` field to a [`ColorTransfer`].
    ///
    /// Returns `None` for `V4L2_XFER_FUNC_DEFAULT` (0) and any
    /// unrecognised value.
    ///
    /// Note: OPRGB (3), SMPTE240M (4), and DCI_P3 (6) have no HAL equivalent
    /// and map to `None`. [`ColorTransfer::Hlg`] is never produced because the
    /// V4L2 UAPI defines no `V4L2_XFER_FUNC_HLG` value.
    pub fn from_v4l2(v: u32) -> Option<Self> {
        match v {
            V4L2_XFER_FUNC_709 => Some(Self::Bt709),
            V4L2_XFER_FUNC_SRGB => Some(Self::Srgb),
            V4L2_XFER_FUNC_NONE => Some(Self::Linear),
            V4L2_XFER_FUNC_SMPTE2084 => Some(Self::Pq),
            _ => None,
        }
    }
}

impl ColorEncoding {
    /// Parse the schema's short string label — the inverse of [`Self::as_str`].
    ///
    /// Returns `None` for `""` and for any label this build does not know.
    /// Colorimetry is descriptive metadata: a consumer that cannot name one
    /// axis can still use the pixels, so an unknown label degrades to
    /// "unspecified" rather than failing the whole import.
    pub fn from_str_code(s: &str) -> Option<Self> {
        match s {
            "bt601" => Some(Self::Bt601),
            "bt709" => Some(Self::Bt709),
            "bt2020" => Some(Self::Bt2020),
            _ => None,
        }
    }

    /// Short string label matching the EdgeFirst schema.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Bt601 => "bt601",
            Self::Bt709 => "bt709",
            Self::Bt2020 => "bt2020",
        }
    }

    /// Map a raw V4L2 `ycbcr_enc` field to a [`ColorEncoding`].
    ///
    /// Returns `None` for `V4L2_YCBCR_ENC_DEFAULT` (0) and any
    /// unrecognised value.
    pub fn from_v4l2(v: u32) -> Option<Self> {
        match v {
            V4L2_YCBCR_ENC_601 => Some(Self::Bt601),
            V4L2_YCBCR_ENC_709 => Some(Self::Bt709),
            V4L2_YCBCR_ENC_BT2020 => Some(Self::Bt2020),
            _ => None,
        }
    }
}

impl ColorRange {
    /// Parse the schema's short string label — the inverse of [`Self::as_str`].
    ///
    /// Returns `None` for `""` and for any label this build does not know.
    /// Colorimetry is descriptive metadata: a consumer that cannot name one
    /// axis can still use the pixels, so an unknown label degrades to
    /// "unspecified" rather than failing the whole import.
    pub fn from_str_code(s: &str) -> Option<Self> {
        match s {
            "full" => Some(Self::Full),
            "limited" => Some(Self::Limited),
            _ => None,
        }
    }

    /// Short string label matching the EdgeFirst schema.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Limited => "limited",
        }
    }

    /// Map a raw V4L2 `quantization` field to a [`ColorRange`].
    ///
    /// Returns `None` for `V4L2_QUANTIZATION_DEFAULT` (0) and any
    /// unrecognised value.
    pub fn from_v4l2(v: u32) -> Option<Self> {
        match v {
            V4L2_QUANTIZATION_FULL_RANGE => Some(Self::Full),
            V4L2_QUANTIZATION_LIM_RANGE => Some(Self::Limited),
            _ => None,
        }
    }
}

macro_rules! display_via_as_str {
    ($($t:ty),*) => {$(
        impl fmt::Display for $t {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
    )*};
}
display_via_as_str!(ColorSpace, ColorTransfer, ColorEncoding, ColorRange);

/// YCbCr matrix luma weights `(kr, kb)`; the green weight is `kg = 1 - kr - kb`.
///
/// This is the single source of the BT.601/709/2020 coefficients. Every
/// YUV↔RGB path (the in-shader GL coefficients and the hand-rolled fixed-point
/// CPU encoders) derives its matrix from here so a coefficient change is made
/// in exactly one place.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MatrixWeights {
    pub kr: f64,
    pub kb: f64,
}

impl MatrixWeights {
    /// Green luma weight, `1 - kr - kb`.
    pub fn kg(self) -> f64 {
        1.0 - self.kr - self.kb
    }
}

impl ColorEncoding {
    /// The matrix luma weights `(kr, kb)` for this encoding — the canonical
    /// BT.601/709/2020 coefficients shared by every YUV↔RGB conversion path.
    pub fn luma_weights(self) -> MatrixWeights {
        match self {
            Self::Bt601 => MatrixWeights {
                kr: 0.299,
                kb: 0.114,
            },
            Self::Bt709 => MatrixWeights {
                kr: 0.2126,
                kb: 0.0722,
            },
            Self::Bt2020 => MatrixWeights {
                kr: 0.2627,
                kb: 0.0593,
            },
        }
    }
}

/// Quantization swings (out of 255) for a YCbCr range: the luma black offset and
/// the luma/chroma excursions. Full range is `0 / 255 / 255`; limited (studio)
/// range is `16 / 219 / 224`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RangeScaling {
    /// Luma black level (0 for full range, 16 for limited).
    pub y_offset: f64,
    /// Luma excursion (255 for full range, 219 for limited).
    pub y_swing: f64,
    /// Chroma excursion (255 for full range, 224 for limited).
    pub c_swing: f64,
}

impl ColorRange {
    /// The luma/chroma quantization swings for this range — the canonical
    /// 0/255/255 (full) or 16/219/224 (limited) studio-swing constants shared
    /// by every YUV↔RGB conversion path.
    pub fn scaling(self) -> RangeScaling {
        match self {
            Self::Full => RangeScaling {
                y_offset: 0.0,
                y_swing: 255.0,
                c_swing: 255.0,
            },
            Self::Limited => RangeScaling {
                y_offset: 16.0,
                y_swing: 219.0,
                c_swing: 224.0,
            },
        }
    }
}

/// Full 4-axis colorimetry. Each axis is `Option`; `None` means "undefined"
/// and is never auto-filled — consumers (e.g. `convert()`) resolve missing
/// axes at use-time without mutating the value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct Colorimetry {
    pub space: Option<ColorSpace>,
    pub transfer: Option<ColorTransfer>,
    pub encoding: Option<ColorEncoding>,
    pub range: Option<ColorRange>,
}

impl Colorimetry {
    /// JPEG/JFIF colorimetry: sRGB primaries, sRGB transfer, BT.601
    /// encoding, full range.
    pub fn jfif() -> Self {
        Self {
            space: Some(ColorSpace::Srgb),
            transfer: Some(ColorTransfer::Srgb),
            encoding: Some(ColorEncoding::Bt601),
            range: Some(ColorRange::Full),
        }
    }

    /// Build from the four raw V4L2 colorimetry integers.
    ///
    /// Explicit values map directly. For `ycbcr_enc`/`quantization`, the V4L2
    /// `DEFAULT` (0) sentinel does NOT mean "unknown" — it means "derive from
    /// the colorspace" (kernel `V4L2_MAP_YCBCR_ENC_DEFAULT` /
    /// `V4L2_MAP_QUANTIZATION_DEFAULT`). So a recognised colorspace resolves
    /// those axes here (e.g. `V4L2_COLORSPACE_JPEG` → BT.601 full-range) rather
    /// than leaving them `None` and falling through to the at-use height
    /// heuristic (which would wrongly pick BT.709/limited for an HD JPEG frame).
    /// A `DEFAULT`/unrecognised colorspace still yields `None` (deferred to the
    /// heuristic); unrecognised non-default values also map to `None`.
    pub fn from_v4l2(colorspace: u32, xfer: u32, ycbcr_enc: u32, quant: u32) -> Self {
        let encoding = ColorEncoding::from_v4l2(ycbcr_enc).or_else(|| {
            if ycbcr_enc == V4L2_YCBCR_ENC_DEFAULT {
                Self::default_encoding_for_colorspace(colorspace)
            } else {
                None
            }
        });
        let range = ColorRange::from_v4l2(quant).or_else(|| {
            if quant == V4L2_QUANTIZATION_DEFAULT {
                Self::default_range_for_colorspace(colorspace)
            } else {
                None
            }
        });
        Self {
            space: ColorSpace::from_v4l2(colorspace),
            transfer: ColorTransfer::from_v4l2(xfer),
            encoding,
            range,
        }
    }

    /// V4L2 `ycbcr_enc=DEFAULT` → encoding implied by the colorspace
    /// (`V4L2_MAP_YCBCR_ENC_DEFAULT`). `None` for default/unrecognised.
    fn default_encoding_for_colorspace(colorspace: u32) -> Option<ColorEncoding> {
        match colorspace {
            V4L2_COLORSPACE_REC709 => Some(ColorEncoding::Bt709),
            V4L2_COLORSPACE_BT2020 => Some(ColorEncoding::Bt2020),
            V4L2_COLORSPACE_SMPTE170M
            | V4L2_COLORSPACE_470_SYSTEM_M
            | V4L2_COLORSPACE_470_SYSTEM_BG
            | V4L2_COLORSPACE_JPEG
            | V4L2_COLORSPACE_SRGB => Some(ColorEncoding::Bt601),
            _ => None,
        }
    }

    /// V4L2 `quantization=DEFAULT` → range implied by the colorspace
    /// (`V4L2_MAP_QUANTIZATION_DEFAULT` for the YUV case: only JPEG is full,
    /// every other recognised colorspace is limited). `None` for
    /// default/unrecognised.
    fn default_range_for_colorspace(colorspace: u32) -> Option<ColorRange> {
        match colorspace {
            V4L2_COLORSPACE_JPEG => Some(ColorRange::Full),
            V4L2_COLORSPACE_SMPTE170M
            | V4L2_COLORSPACE_REC709
            | V4L2_COLORSPACE_BT2020
            | V4L2_COLORSPACE_470_SYSTEM_M
            | V4L2_COLORSPACE_470_SYSTEM_BG
            | V4L2_COLORSPACE_SRGB => Some(ColorRange::Limited),
            _ => None,
        }
    }

    /// Set color primaries (consuming builder).
    pub fn with_space(mut self, s: ColorSpace) -> Self {
        self.space = Some(s);
        self
    }

    /// Set transfer function (consuming builder).
    pub fn with_transfer(mut self, t: ColorTransfer) -> Self {
        self.transfer = Some(t);
        self
    }

    /// Set YCbCr encoding matrix (consuming builder).
    pub fn with_encoding(mut self, e: ColorEncoding) -> Self {
        self.encoding = Some(e);
        self
    }

    /// Set quantization range (consuming builder).
    pub fn with_range(mut self, r: ColorRange) -> Self {
        self.range = Some(r);
        self
    }

    /// Pack all four axes into one `u32` for
    /// [`crate::protocol::TensorDesc::colorimetry`].
    ///
    /// One byte per axis, `space` in the low byte through `range` in the
    /// high byte; `0` on an axis means "undefined", so an all-`None`
    /// `Colorimetry` packs to `0`. The per-axis codes are the same "stable
    /// HAL constants" the C API's `ef_colorimetry` documents
    /// — duplicated rather than shared
    /// because the C leaves depend on this crate, not the reverse, but kept in
    /// sync deliberately so a value means the same thing on both
    /// boundaries. This crosses a package boundary like `TensorDesc`
    /// itself: codes are appended, never renumbered.
    pub fn pack(&self) -> u32 {
        let space: u32 = match self.space {
            None => 0,
            Some(ColorSpace::Bt709) => 1,
            Some(ColorSpace::Bt2020) => 2,
            Some(ColorSpace::Srgb) => 3,
            Some(ColorSpace::Smpte170m) => 4,
        };
        let transfer: u32 = match self.transfer {
            None => 0,
            Some(ColorTransfer::Bt709) => 1,
            Some(ColorTransfer::Srgb) => 2,
            Some(ColorTransfer::Pq) => 3,
            Some(ColorTransfer::Hlg) => 4,
            Some(ColorTransfer::Linear) => 5,
        };
        let encoding: u32 = match self.encoding {
            None => 0,
            Some(ColorEncoding::Bt601) => 1,
            Some(ColorEncoding::Bt709) => 2,
            Some(ColorEncoding::Bt2020) => 3,
        };
        let range: u32 = match self.range {
            None => 0,
            Some(ColorRange::Full) => 1,
            Some(ColorRange::Limited) => 2,
        };
        space | (transfer << 8) | (encoding << 16) | (range << 24)
    }

    /// Inverse of [`Self::pack`]: rebuild a `Colorimetry` from a packed
    /// `u32`, e.g. [`crate::protocol::TensorDesc::colorimetry`] on
    /// import. `0` on an axis byte (undefined, including a build that
    /// predates the axis) maps to `None` rather than erroring, the same
    /// forward-compatibility rule [`crate::protocol::dtype_to_dtype`]
    /// applies to another wire-coded axis -- a code this build does not
    /// recognise (e.g. one a newer producer added) also maps to `None`
    /// instead of guessing.
    pub fn unpack(bits: u32) -> Self {
        let space = match bits & 0xFF {
            1 => Some(ColorSpace::Bt709),
            2 => Some(ColorSpace::Bt2020),
            3 => Some(ColorSpace::Srgb),
            4 => Some(ColorSpace::Smpte170m),
            _ => None,
        };
        let transfer = match (bits >> 8) & 0xFF {
            1 => Some(ColorTransfer::Bt709),
            2 => Some(ColorTransfer::Srgb),
            3 => Some(ColorTransfer::Pq),
            4 => Some(ColorTransfer::Hlg),
            5 => Some(ColorTransfer::Linear),
            _ => None,
        };
        let encoding = match (bits >> 16) & 0xFF {
            1 => Some(ColorEncoding::Bt601),
            2 => Some(ColorEncoding::Bt709),
            3 => Some(ColorEncoding::Bt2020),
            _ => None,
        };
        let range = match (bits >> 24) & 0xFF {
            1 => Some(ColorRange::Full),
            2 => Some(ColorRange::Limited),
            _ => None,
        };
        Colorimetry {
            space,
            transfer,
            encoding,
            range,
        }
    }
}

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

    #[test]
    fn from_v4l2_known_and_default() {
        assert_eq!(ColorEncoding::from_v4l2(1), Some(ColorEncoding::Bt601));
        assert_eq!(ColorEncoding::from_v4l2(2), Some(ColorEncoding::Bt709));
        assert_eq!(ColorEncoding::from_v4l2(6), Some(ColorEncoding::Bt2020));
        assert_eq!(ColorEncoding::from_v4l2(0), None); // DEFAULT
        assert_eq!(ColorEncoding::from_v4l2(3), None); // XV601 (unsurfaced)
        assert_eq!(ColorRange::from_v4l2(1), Some(ColorRange::Full));
        assert_eq!(ColorRange::from_v4l2(2), Some(ColorRange::Limited));
        assert_eq!(ColorSpace::from_v4l2(7), Some(ColorSpace::Srgb)); // JPEG→sRGB
        assert_eq!(ColorTransfer::from_v4l2(5), Some(ColorTransfer::Linear)); // NONE→linear

        // ColorSpace: additional arms
        assert_eq!(ColorSpace::from_v4l2(1), Some(ColorSpace::Smpte170m)); // SMPTE170M
        assert_eq!(ColorSpace::from_v4l2(3), Some(ColorSpace::Bt709)); // REC709
        assert_eq!(ColorSpace::from_v4l2(10), Some(ColorSpace::Bt2020)); // BT2020
        assert_eq!(ColorSpace::from_v4l2(5), Some(ColorSpace::Smpte170m)); // 470_SYSTEM_M
        assert_eq!(ColorSpace::from_v4l2(6), Some(ColorSpace::Smpte170m)); // 470_SYSTEM_BG

        // ColorTransfer: additional arms and unmapped values
        assert_eq!(ColorTransfer::from_v4l2(1), Some(ColorTransfer::Bt709)); // XFER_FUNC_709
        assert_eq!(ColorTransfer::from_v4l2(2), Some(ColorTransfer::Srgb)); // XFER_FUNC_SRGB
        assert_eq!(ColorTransfer::from_v4l2(7), Some(ColorTransfer::Pq)); // XFER_FUNC_SMPTE2084
        assert_eq!(ColorTransfer::from_v4l2(3), None); // OPRGB — no HAL equivalent
        assert_eq!(ColorTransfer::from_v4l2(6), None); // DCI_P3 — no HAL equivalent

        // Hlg is never produced by from_v4l2 — no V4L2_XFER_FUNC_HLG exists in the kernel UAPI
        for v in 0u32..=10 {
            assert_ne!(ColorTransfer::from_v4l2(v), Some(ColorTransfer::Hlg));
        }
    }

    #[test]
    fn jfif_is_bt601_full_srgb() {
        let c = Colorimetry::jfif();
        assert_eq!(c.space, Some(ColorSpace::Srgb));
        assert_eq!(c.transfer, Some(ColorTransfer::Srgb));
        assert_eq!(c.encoding, Some(ColorEncoding::Bt601));
        assert_eq!(c.range, Some(ColorRange::Full));
    }

    #[test]
    fn from_v4l2_struct_maps_all_axes_and_unknown_to_none() {
        let c = Colorimetry::from_v4l2(3, 1, 2, 1); // REC709, XFER709, ENC709, FULL
        assert_eq!(c.space, Some(ColorSpace::Bt709));
        assert_eq!(c.transfer, Some(ColorTransfer::Bt709));
        assert_eq!(c.encoding, Some(ColorEncoding::Bt709));
        assert_eq!(c.range, Some(ColorRange::Full));
        let d = Colorimetry::from_v4l2(0, 0, 0, 0); // all DEFAULT
        assert_eq!(d, Colorimetry::default()); // all None
    }

    #[test]
    fn from_v4l2_default_enc_quant_derive_from_colorspace() {
        // COLORSPACE_JPEG (7) with DEFAULT ycbcr_enc/quant must resolve to
        // BT.601 full-range per V4L2_MAP_*_DEFAULT — NOT be left None (which
        // would let the height heuristic wrongly pick BT.709/limited for HD).
        let jpeg = Colorimetry::from_v4l2(7, 0, 0, 0);
        assert_eq!(jpeg.encoding, Some(ColorEncoding::Bt601));
        assert_eq!(jpeg.range, Some(ColorRange::Full));

        // REC709 colorspace, DEFAULT enc/quant → BT.709 limited.
        let rec709 = Colorimetry::from_v4l2(3, 0, 0, 0);
        assert_eq!(rec709.encoding, Some(ColorEncoding::Bt709));
        assert_eq!(rec709.range, Some(ColorRange::Limited));

        // Explicit ycbcr_enc/quant still win over the colorspace default.
        let explicit = Colorimetry::from_v4l2(7, 0, 2, 2); // JPEG but enc=709, quant=limited
        assert_eq!(explicit.encoding, Some(ColorEncoding::Bt709));
        assert_eq!(explicit.range, Some(ColorRange::Limited));

        // Unrecognised non-default values stay None (not derived).
        let unknown_enc = Colorimetry::from_v4l2(7, 0, 99, 0);
        assert_eq!(unknown_enc.encoding, None);
        assert_eq!(unknown_enc.range, Some(ColorRange::Full)); // quant still defaulted from JPEG
    }

    #[test]
    fn luma_weights_are_the_canonical_bt_constants() {
        assert_eq!(
            ColorEncoding::Bt601.luma_weights(),
            MatrixWeights {
                kr: 0.299,
                kb: 0.114
            }
        );
        assert_eq!(
            ColorEncoding::Bt709.luma_weights(),
            MatrixWeights {
                kr: 0.2126,
                kb: 0.0722
            }
        );
        assert_eq!(
            ColorEncoding::Bt2020.luma_weights(),
            MatrixWeights {
                kr: 0.2627,
                kb: 0.0593
            }
        );
        // kg = 1 - kr - kb (BT.709 green weight ≈ 0.7152).
        assert!((ColorEncoding::Bt709.luma_weights().kg() - 0.7152).abs() < 1e-9);
    }

    #[test]
    fn range_scaling_is_full_or_studio_swing() {
        let full = ColorRange::Full.scaling();
        assert_eq!(
            full,
            RangeScaling {
                y_offset: 0.0,
                y_swing: 255.0,
                c_swing: 255.0
            }
        );
        let limited = ColorRange::Limited.scaling();
        assert_eq!(
            limited,
            RangeScaling {
                y_offset: 16.0,
                y_swing: 219.0,
                c_swing: 224.0
            }
        );
    }

    #[test]
    fn as_str_and_from_str_code_are_inverses_for_every_variant() {
        // The wire round-trip depends on this, and `as_str` alone cannot show
        // it: a parser missing one arm silently degrades that axis to None.
        for v in [
            ColorSpace::Bt709,
            ColorSpace::Bt2020,
            ColorSpace::Srgb,
            ColorSpace::Smpte170m,
        ] {
            assert_eq!(ColorSpace::from_str_code(v.as_str()), Some(v), "{v:?}");
        }
        for v in [
            ColorTransfer::Bt709,
            ColorTransfer::Srgb,
            ColorTransfer::Pq,
            ColorTransfer::Hlg,
            ColorTransfer::Linear,
        ] {
            assert_eq!(ColorTransfer::from_str_code(v.as_str()), Some(v), "{v:?}");
        }
        for v in [
            ColorEncoding::Bt601,
            ColorEncoding::Bt709,
            ColorEncoding::Bt2020,
        ] {
            assert_eq!(ColorEncoding::from_str_code(v.as_str()), Some(v), "{v:?}");
        }
        for v in [ColorRange::Full, ColorRange::Limited] {
            assert_eq!(ColorRange::from_str_code(v.as_str()), Some(v), "{v:?}");
        }
    }

    #[test]
    fn an_unknown_or_empty_label_is_unspecified_not_an_error() {
        assert_eq!(ColorSpace::from_str_code(""), None);
        assert_eq!(ColorSpace::from_str_code("not-a-colour-space"), None);
        assert_eq!(
            ColorRange::from_str_code("FULL"),
            None,
            "labels are case-sensitive"
        );
    }

    #[test]
    fn as_str_matches_schema() {
        assert_eq!(ColorEncoding::Bt601.as_str(), "bt601");
        assert_eq!(ColorRange::Full.as_str(), "full");
        assert_eq!(ColorSpace::Smpte170m.as_str(), "smpte170m");
        assert_eq!(ColorTransfer::Pq.as_str(), "pq");
        assert_eq!(ColorTransfer::Hlg.as_str(), "hlg");
    }

    #[test]
    fn pack_unpack_round_trips() {
        // The exact round trip the cross-package import path relies on:
        // `TensorDyn::import_descriptor` unpacks what `descriptor_pinned`
        // packed. All-None must round-trip through 0, and every populated
        // axis must survive.
        assert_eq!(
            Colorimetry::unpack(Colorimetry::default().pack()),
            Colorimetry::default()
        );
        assert_eq!(Colorimetry::default().pack(), 0);

        let jfif = Colorimetry::jfif();
        assert_eq!(Colorimetry::unpack(jfif.pack()), jfif);

        let full = Colorimetry {
            space: Some(ColorSpace::Bt2020),
            transfer: Some(ColorTransfer::Hlg),
            encoding: Some(ColorEncoding::Bt2020),
            range: Some(ColorRange::Limited),
        };
        assert_eq!(Colorimetry::unpack(full.pack()), full);
    }

    #[test]
    fn unpack_maps_unrecognised_codes_to_none() {
        // A code this build does not recognise (e.g. from a newer producer)
        // must not panic or guess -- same forward-compat rule as
        // `dtype_to_dtype`/`format_from_code`.
        let bits = 0xFFu32 | (0xFFu32 << 8) | (0xFFu32 << 16) | (0xFFu32 << 24);
        assert_eq!(Colorimetry::unpack(bits), Colorimetry::default());
    }

    const SPACES: [(ColorSpace, u32); 4] = [
        (ColorSpace::Bt709, 1),
        (ColorSpace::Bt2020, 2),
        (ColorSpace::Srgb, 3),
        (ColorSpace::Smpte170m, 4),
    ];
    const TRANSFERS: [(ColorTransfer, u32); 5] = [
        (ColorTransfer::Bt709, 1),
        (ColorTransfer::Srgb, 2),
        (ColorTransfer::Pq, 3),
        (ColorTransfer::Hlg, 4),
        (ColorTransfer::Linear, 5),
    ];
    const ENCODINGS: [(ColorEncoding, u32); 3] = [
        (ColorEncoding::Bt601, 1),
        (ColorEncoding::Bt709, 2),
        (ColorEncoding::Bt2020, 3),
    ];
    const RANGES: [(ColorRange, u32); 2] = [(ColorRange::Full, 1), (ColorRange::Limited, 2)];

    #[test]
    fn pack_places_each_axis_code_in_its_own_byte() {
        // The per-axis codes are a cross-package wire contract: pin them.
        for (s, code) in SPACES {
            let c = Colorimetry::default().with_space(s);
            assert_eq!(c.pack(), code, "{s:?}");
            assert_eq!(Colorimetry::unpack(code), c, "{s:?}");
        }
        for (t, code) in TRANSFERS {
            let c = Colorimetry::default().with_transfer(t);
            assert_eq!(c.pack(), code << 8, "{t:?}");
            assert_eq!(Colorimetry::unpack(code << 8), c, "{t:?}");
        }
        for (e, code) in ENCODINGS {
            let c = Colorimetry::default().with_encoding(e);
            assert_eq!(c.pack(), code << 16, "{e:?}");
            assert_eq!(Colorimetry::unpack(code << 16), c, "{e:?}");
        }
        for (r, code) in RANGES {
            let c = Colorimetry::default().with_range(r);
            assert_eq!(c.pack(), code << 24, "{r:?}");
            assert_eq!(Colorimetry::unpack(code << 24), c, "{r:?}");
        }
    }

    #[test]
    fn unpack_decodes_a_fully_populated_word() {
        assert_eq!(
            Colorimetry::unpack(0x02_02_05_04),
            Colorimetry {
                space: Some(ColorSpace::Smpte170m),
                transfer: Some(ColorTransfer::Linear),
                encoding: Some(ColorEncoding::Bt709),
                range: Some(ColorRange::Limited),
            }
        );
    }

    #[test]
    fn every_axis_combination_round_trips_through_pack() {
        for (s, _) in SPACES {
            for (t, _) in TRANSFERS {
                for (e, _) in ENCODINGS {
                    for (r, _) in RANGES {
                        let c = Colorimetry {
                            space: Some(s),
                            transfer: Some(t),
                            encoding: Some(e),
                            range: Some(r),
                        };
                        assert_eq!(Colorimetry::unpack(c.pack()), c);
                    }
                }
            }
        }
    }

    #[test]
    fn builders_set_exactly_their_own_axis() {
        let c = Colorimetry::default()
            .with_space(ColorSpace::Bt2020)
            .with_transfer(ColorTransfer::Pq)
            .with_encoding(ColorEncoding::Bt2020)
            .with_range(ColorRange::Full);
        assert_eq!(
            c,
            Colorimetry {
                space: Some(ColorSpace::Bt2020),
                transfer: Some(ColorTransfer::Pq),
                encoding: Some(ColorEncoding::Bt2020),
                range: Some(ColorRange::Full),
            }
        );
        // Each builder leaves the other axes as they were.
        let base = Colorimetry::jfif();
        assert_eq!(
            base.with_space(ColorSpace::Bt709),
            Colorimetry {
                space: Some(ColorSpace::Bt709),
                ..base
            }
        );
        assert_eq!(
            base.with_transfer(ColorTransfer::Hlg),
            Colorimetry {
                transfer: Some(ColorTransfer::Hlg),
                ..base
            }
        );
        assert_eq!(
            base.with_encoding(ColorEncoding::Bt709),
            Colorimetry {
                encoding: Some(ColorEncoding::Bt709),
                ..base
            }
        );
        assert_eq!(
            base.with_range(ColorRange::Limited),
            Colorimetry {
                range: Some(ColorRange::Limited),
                ..base
            }
        );
    }

    #[test]
    fn from_v4l2_derives_encoding_and_range_for_every_recognised_colorspace() {
        use ColorEncoding as E;
        use ColorRange as R;
        let table = [
            (V4L2_COLORSPACE_SMPTE170M, E::Bt601, R::Limited),
            (V4L2_COLORSPACE_REC709, E::Bt709, R::Limited),
            (V4L2_COLORSPACE_470_SYSTEM_M, E::Bt601, R::Limited),
            (V4L2_COLORSPACE_470_SYSTEM_BG, E::Bt601, R::Limited),
            (V4L2_COLORSPACE_JPEG, E::Bt601, R::Full),
            (V4L2_COLORSPACE_SRGB, E::Bt601, R::Limited),
            (V4L2_COLORSPACE_BT2020, E::Bt2020, R::Limited),
        ];
        for (colorspace, encoding, range) in table {
            let c = Colorimetry::from_v4l2(colorspace, 0, 0, 0);
            assert_eq!(c.encoding, Some(encoding), "colorspace {colorspace}");
            assert_eq!(c.range, Some(range), "colorspace {colorspace}");
        }
        // Unrecognised colorspaces leave both axes to the at-use heuristic.
        for colorspace in [0, 2, 4, 9, 11, 99] {
            let c = Colorimetry::from_v4l2(colorspace, 0, 0, 0);
            assert_eq!(
                (c.encoding, c.range),
                (None, None),
                "colorspace {colorspace}"
            );
        }
    }
}