pixon 0.8.0

SIMD-dispatched color conversion for the FFmpeg AVPixelFormat space: one-call decode of validated source frames to RGB / RGBA / Luma / HSV, fused resampling while converting, colorimetry-honest matrices and chroma siting, no_std-friendly.
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
//! Reference cross-checks for the BT.2020 constant-luminance (`YcCbcCrc`)
//! non-affine decode.
//!
//! The decode is pinned against `colour-science` 0.4.7 — the authoritative
//! BT.2020 CL implementation (`colour.models.rgb.ycbcr.YcCbcCrc_to_RGB` /
//! `oetf_BT2020`) — plus ITU-R BT.2020-2 structural anchors (gray-axis
//! neutrality, OETF round-trip, weight-derivation consistency) that hold
//! independently of any library.
//!
//! Domain convention: `colour-science`'s `YcCbcCrc_to_RGB` returns **linear**
//! RGB (the stage before pixon's transfer-preserving OETF re-encode), so the
//! reference vectors below pin [`cl_norm_to_rgb_linear`] (the linear stage);
//! the re-encode to `R'G'B'` and the integer narrow are pinned separately.
//! Studio (`legal`) range corresponds to `full_range = false`; full range to
//! `full_range = true` — the same correspondence
//! [`crate::row::scalar::ictcp`] uses. All reference values were generated by
//! `colour.models.rgb.ycbcr.YcCbcCrc_to_RGB(..., in_int=True)` with the
//! matching `in_bits` / `in_legal` / `is_12_bits_system`.

use super::*;

use crate::resample::bt2020_oetf;

/// Re-encode a logical `u16` sample as LE wire storage, so a `BE = false`
/// kernel recovers it via `u16::from_le` on both little- and big-endian hosts.
/// The `cl_444p_*` kernels read wire-ordered samples (like the bayer/xv36
/// kernels); a bare `[v]` plane only decodes correctly on little-endian.
fn le_wire_u16(v: u16) -> u16 {
  u16::from_ne_bytes(v.to_le_bytes())
}

/// f32 tolerance for the linear-RGB reference cross-check: the decode is f32
/// throughout and `colour-science` is f64, so the gap is a few ULP after the
/// transcendental inverse-OETF + the green solve.
const LIN_TOL: f32 = 5e-6;

/// Helper: full integer-input → linear-RGB decode at 12-bit, mirroring the
/// kernel's `dequant_cl` + `cl_norm_to_rgb_linear` (the `colour-science`
/// comparison stage).
fn decode_linear<const BITS: u32>(
  yc: u16,
  cbc: u16,
  crc: u16,
  full_range: bool,
  system: ClSystem,
) -> [f32; 3] {
  cl_norm_to_rgb_linear(dequant_cl::<BITS>(yc, cbc, crc, full_range), system)
}

fn assert_close(got: [f32; 3], want: [f32; 3], tol: f32, what: &str) {
  for i in 0..3 {
    assert!(
      (got[i] - want[i]).abs() <= tol,
      "{what}: channel {i} = {} (want {}, |Δ| = {})",
      got[i],
      want[i],
      (got[i] - want[i]).abs()
    );
  }
}

// ---- colour-science `YcCbcCrc_to_RGB` linear-RGB reference vectors -------

/// 12-bit studio-range mid-code: `colour.YcCbcCrc_to_RGB([2048, 2148, 1948],
/// in_bits=12, in_legal=True, in_int=True, is_12_bits_system=True)`.
#[test]
fn decode_matches_colour_science_12bit_studio_midcode() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  let got = decode_linear::<12>(2048, 2148, 1948, false, system);
  assert_close(
    got,
    [0.225_844, 0.284_305, 0.316_264],
    LIN_TOL,
    "12-bit studio mid-code",
  );
}

/// 12-bit studio-range saturated code (blue clips above linear `1.0`):
/// `colour.YcCbcCrc_to_RGB([3000, 2600, 1500], in_bits=12, in_legal=True,
/// in_int=True, is_12_bits_system=True)`.
#[test]
fn decode_matches_colour_science_12bit_studio_saturated() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  let got = decode_linear::<12>(3000, 2600, 1500, false, system);
  assert_close(
    got,
    [0.279_735, 0.704_389, 1.054_776],
    LIN_TOL,
    "12-bit studio saturated",
  );
}

/// 10-bit studio-range mid-code (10-bit OETF constants `α = 1.099`,
/// `β = 0.018`): `colour.YcCbcCrc_to_RGB([512, 540, 480], in_bits=10,
/// in_legal=True, in_int=True, is_12_bits_system=False)`.
#[test]
fn decode_matches_colour_science_10bit_studio_midcode() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_10Bit).unwrap();
  assert!(!system.is_12_bit(), "Bt2020_10Bit must select 10-bit OETF");
  let got = decode_linear::<10>(512, 540, 480, false, system);
  assert_close(
    got,
    [0.213_916, 0.288_245, 0.321_845],
    LIN_TOL,
    "10-bit studio mid-code",
  );
}

// ---- Gray-axis neutrality (BT.2020-2 structural anchor) ------------------

/// On the gray axis (`Cbc = Crc = chroma-zero`) the decode must yield a
/// **neutral** linear triple `R = G = B` for every luma — the defining
/// invariant of any YCbCr-family system. Checked full-range across the luma
/// span; the green solve `(Yc − Kb·B − Kr·R)/Kg` collapses to `Yc` when
/// `R = B = Yc` because `Kr + Kg + Kb = 1`.
#[test]
fn gray_axis_is_neutral_full_range() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  for yc in [0u16, 1024, 2048, 3072, 4095] {
    let [r, g, b] = decode_linear::<12>(yc, 2048, 2048, true, system);
    assert!(
      (r - g).abs() <= 1e-6 && (g - b).abs() <= 1e-6,
      "gray axis Yc={yc}: linear ({r}, {g}, {b}) not neutral"
    );
  }
}

/// Full-range gray-axis end-to-end round-trip: a neutral `Y'c` with zero
/// chroma decodes to `R'G'B'` that narrows back to the **same** native-depth
/// code (`R' = G' = B' = Y'c/in_max` re-encoded), since the OETF/inverse-OETF
/// are exact inverses and the green solve is neutral. Pinned at 12-bit full
/// range against `colour-science` (`Y'c = 3760` → linear `0.842107`).
#[test]
fn gray_axis_full_range_round_trips_to_native_code() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  let lin = decode_linear::<12>(3760, 2048, 2048, true, system);
  assert_close(
    lin,
    [0.842_107, 0.842_107, 0.842_107],
    LIN_TOL,
    "gray linear",
  );
  let mut out = [0u16; 3];
  cl_444p_n_to_rgb_u16_row::<12, false>(
    &[le_wire_u16(3760)],
    &[le_wire_u16(2048)],
    &[le_wire_u16(2048)],
    &mut out,
    1,
    true,
    system,
  );
  assert_eq!(
    out,
    [3760, 3760, 3760],
    "neutral Y'c must round-trip its code"
  );
}

// ---- OETF anchors (the net-new transfer foundation) ----------------------

/// The BT.2020 OETF / inverse-OETF are exact analytic inverses across the
/// domain, for both the 10-bit and 12-bit constant sets — **except** the
/// documented 12-bit divergence region `[oetf(β12), T)`, whose boundary point
/// `β12` is handled separately below. The sample set deliberately omits
/// `0.0181` (= `β12`) from the 12-bit exact-round-trip points: for 12-bit
/// `β12` forward-maps to `oetf(β12) < T`, which decodes to the *toe* value
/// `≈ 0.0180994 ≠ β12` (the standard discontinuity's inclusive lower
/// endpoint), so it is NOT an exact-round-trip point. The `5e-7` tolerance is
/// tight enough that the `β12` divergence (~6.3e-7) could not silently pass as
/// exact were it left in. (`0.0181` IS an exact round-trip for 10-bit, where
/// there is no overlap, so it stays in the 10-bit set.)
// miri's interpreted floating-point diverges from hardware for these
// transcendental OETF paths, overshooting the round-trip tolerance.
#[cfg_attr(miri, ignore)]
#[test]
fn bt2020_oetf_round_trips() {
  // 10-bit: `β10 = 0.018` round-trips exactly (`oetf(β10) > 4.5·β10`, no
  // overlap), so `0.0181` (just above `β10`) is on the clean power branch.
  for &e in &[0.0_f32, 0.005, 0.018, 0.0181, 0.25, 0.5, 0.9, 1.0] {
    let back = bt2020_oetf::oetf_inverse(bt2020_oetf::oetf(e, false), false);
    assert!(
      (back - e).abs() <= 5e-7,
      "10-bit oetf round-trip e={e}: got {back} (|Δ|={})",
      (back - e).abs()
    );
  }
  // 12-bit: same points EXCEPT `0.0181` (= β12, the inclusive lower endpoint of
  // the divergence region — its divergence, and the full four-interval
  // partition, are pinned by `bt2020_inverse_oetf_12bit_four_interval_partition`).
  for &e in &[0.0_f32, 0.005, 0.018, 0.25, 0.5, 0.9, 1.0] {
    let back = bt2020_oetf::oetf_inverse(bt2020_oetf::oetf(e, true), true);
    assert!(
      (back - e).abs() <= 5e-7,
      "12-bit oetf round-trip e={e}: got {back} (|Δ|={})",
      (back - e).abs()
    );
  }
}

/// **The complete 12-bit encoded-domain partition** — one representative point
/// pinned in each of the four intervals from [`bt2020_oetf::oetf_inverse`]'s
/// table, asserting the colour-matching behaviour and the correct
/// round-trip-or-divergence per interval. This is the authoritative band test
/// (it folds in the prior per-endpoint guards); every value is
/// `colour.oetf_inverse_BT2020(Ep, is_12_bits_system=True)`.
///
/// Boundaries: `oetf(β12) = 0.0814472 < 4.5·β12 = 0.0814500 < T = 0.0816979`.
// miri's interpreted floating-point diverges from hardware for these
// transcendental OETF paths, overshooting the round-trip tolerance.
#[cfg_attr(miri, ignore)]
#[test]
fn bt2020_inverse_oetf_12bit_four_interval_partition() {
  let inv = |ep: f32| bt2020_oetf::oetf_inverse(ep, true);
  let toe = |ep: f32| ep / 4.5;
  let power = |ep: f32| ((ep + (1.0993_f32 - 1.0)) / 1.0993_f32).powf(1.0 / 0.45);

  // ---- I1: [0, oetf(β12)) — toe branch, EXACT round-trip --------------------
  // E = 0.01 (< β12) toe-encodes to 0.045, well below oetf(β12); inverse toe
  // recovers it exactly. colour.oetf_inverse_BT2020(0.045) = 0.01.
  let e1 = 0.045_f32;
  assert!(
    (inv(e1) - 0.01).abs() <= 2e-7,
    "I1 toe-exact: {} ≠ 0.01",
    inv(e1)
  );
  assert!(
    (inv(e1) - toe(e1)).abs() <= 2e-7,
    "I1 must be the toe branch"
  );
  assert!(
    (bt2020_oetf::oetf_inverse(bt2020_oetf::oetf(0.01, true), true) - 0.01).abs() <= 2e-7,
    "I1 round-trips: oetf_inverse(oetf(0.01)) = 0.01"
  );

  // ---- I2: [oetf(β12), 4.5·β12) — STANDARD overlap, non-invertible ----------
  // The LOWER endpoint oetf(β12) is INCLUSIVE: it is exactly β12's forward
  // image, yet decodes to the toe (≠ β12). Both forward branches reach this
  // band, so no threshold recovers the original E (a BT.2020 spec property).
  // colour returns the toe `oetf(β12)/4.5 ≈ 0.0180994`.
  let e2 = bt2020_oetf::oetf(0.0181, true); // = oetf(β12), the β12 image
  assert!(
    (e2 - 0.081_447_18).abs() <= 1e-6,
    "oetf(β12) ≈ 0.08144718, got {e2}"
  );
  assert!(
    (inv(e2) - 0.018_099_38).abs() <= 2e-7,
    "I2: colour toe ≈ 0.01809938, got {}",
    inv(e2)
  );
  assert!(
    (inv(e2) - toe(e2)).abs() <= 2e-7,
    "I2 must be the toe branch"
  );
  assert!(
    (inv(e2) - 0.0181).abs() > 5e-7,
    "I2 lower endpoint β12 must NOT round-trip — it is the inclusive divergence start"
  );

  // ---- I3: [4.5·β12, T) — colour-QUIRK band, intentional divergence ---------
  // A valid POWER preimage exists here (the standard round-trip), but because T
  // uses the 10-bit α, E' < T holds and the inverse deliberately returns the
  // TOE value to match colour. The LOWER endpoint 4.5·β12 is INCLUSIVE (it is
  // power-reachable only — not in the toe image — and 4.5·β12 < T, so it takes
  // the toe). Pinned at the lower endpoint AND a mid point.
  let e3_lo = 4.5 * 0.0181_f32; // = 4.5·β12, the inclusive lower endpoint
  assert!(
    e3_lo > e2,
    "4.5·β12 must be above oetf(β12) (the overlap→quirk boundary)"
  );
  assert!(
    (inv(e3_lo) - 0.0181).abs() <= 2e-7,
    "I3 lower (4.5·β12): colour toe = 0.0181, got {}",
    inv(e3_lo)
  );
  assert!(
    (inv(e3_lo) - toe(e3_lo)).abs() <= 2e-7,
    "I3 lower must be the toe branch"
  );
  assert!(
    (inv(e3_lo) - power(e3_lo)).abs() > 5e-7,
    "I3 lower must NOT be the power preimage {} (the standard round-trip is intentionally not taken)",
    power(e3_lo)
  );
  let e3_mid = 0.081_573_95_f32; // mid quirk band
  assert!(
    e3_mid > e3_lo && e3_mid < 0.081_697_9,
    "mid point must be inside the quirk band"
  );
  assert!(
    (inv(e3_mid) - 0.018_127_54).abs() <= 3e-7,
    "I3 mid: colour toe ≈ 0.01812754, got {}",
    inv(e3_mid)
  );
  assert!(
    (inv(e3_mid) - power(e3_mid)).abs() > 5e-7,
    "I3 mid must NOT be the power preimage — the divergence is the deliberate colour-compat choice"
  );

  // ---- I4: [T, ∞) — power branch, EXACT round-trip --------------------------
  // The LOWER endpoint T is INCLUSIVE: `E' < T` is strict, so a value AT T takes
  // the POWER branch. colour at T returns the power value ≈ 0.01815584 (≠ the
  // toe T/4.5 ≈ 0.01815509). Above T the round-trip is exact.
  let t = 0.081_697_9_f32; // ≈ T
  assert!(
    (inv(t) - 0.018_155_84).abs() <= 1e-6,
    "I4 at T: colour power ≈ 0.01815584, got {}",
    inv(t)
  );
  assert!(
    (inv(t) - power(t)).abs() < (inv(t) - toe(t)).abs(),
    "I4 at T must take the power branch, not the toe"
  );
  let e4 = 0.091_697_89_f32; // T + 0.01, deep in the power region
  assert!(
    (inv(e4) - 0.020_460_51).abs() <= 2e-7,
    "I4 power-exact ≈ 0.02046051, got {}",
    inv(e4)
  );
  let rt = bt2020_oetf::oetf(inv(e4), true);
  assert!(
    (rt - e4).abs() <= 2e-6,
    "I4 round-trips: oetf(inv(E')) ≈ E', got {rt}"
  );
}

/// The **10-bit** encoded domain has **no** overlap or quirk band: there
/// `oetf(β10) = 0.081248 > 4.5·β10 = 0.081`, the curve is monotonic across
/// `β10`, and `T = oetf(β10)` (the threshold `α` and curve `α` coincide). So
/// the partition is the simple two intervals `[0, oetf(β10))` (toe, exact) and
/// `[oetf(β10), ∞)` (power, exact), and `β10` round-trips. The
/// `[4.5·β10, oetf(β10)) = [0.081, 0.081248)` toe gap (a forward-unreachable
/// band) still decodes via the toe — the 10-bit breakpoint is `oetf(β10)`, NOT
/// `4.5·β10` (the bug an earlier `4.5·β` threshold introduced).
// miri's interpreted floating-point diverges from hardware for these
// transcendental OETF paths, overshooting the round-trip tolerance.
#[cfg_attr(miri, ignore)]
#[test]
fn bt2020_inverse_oetf_10bit_two_interval_partition() {
  let inv = |ep: f32| bt2020_oetf::oetf_inverse(ep, false);
  // β10 round-trips exactly (no overlap).
  let back = bt2020_oetf::oetf_inverse(bt2020_oetf::oetf(0.018, false), false);
  assert!(
    (back - 0.018).abs() <= 2e-7,
    "10-bit β10 must round-trip, got {back}"
  );
  // Toe interval [0, oetf(β10)): a deep-toe value round-trips, and the
  // forward-unreachable gap [4.5·β10, oetf(β10)) decodes via the toe.
  assert!((inv(0.045) - 0.01).abs() <= 2e-7, "10-bit toe-exact");
  for &ep in &[0.0810_f32, 0.0811, 0.081_2, 0.081_24] {
    // strictly inside [4.5·β10=0.081, oetf(β10)=0.081248)
    assert!(
      (inv(ep) - ep / 4.5).abs() <= 1e-7,
      "10-bit gap E'={ep}: must take the toe inverse E'/4.5 (breakpoint is oetf(β10), not 4.5·β10)"
    );
  }
  // Power interval [oetf(β10), ∞): a clean power value round-trips.
  let e = 0.3_f32;
  let rt = bt2020_oetf::oetf_inverse(bt2020_oetf::oetf(e, false), false);
  assert!(
    (rt - e).abs() <= 2e-7,
    "10-bit power-exact round-trip, got {rt}"
  );
}

/// BT.2020 OETF pinned against `colour-science`'s `oetf_BT2020`: the toe slope
/// `4.5·E` below `β`, the `α·E^0.45 − (α − 1)` power segment above, and the
/// `1.0 → 1.0` / `0.0 → 0.0` endpoints, for both bit-depth constant sets.
#[test]
fn bt2020_oetf_matches_colour_science_anchors() {
  // 10-bit (α = 1.099, β = 0.018): colour.oetf_BT2020(E).
  assert!((bt2020_oetf::oetf(0.0, false) - 0.0).abs() <= 1e-7);
  assert!((bt2020_oetf::oetf(0.001, false) - 0.004_5).abs() <= 1e-6); // toe: 4.5·0.001
  assert!((bt2020_oetf::oetf(0.018, false) - 0.081_247_94).abs() <= 1e-6);
  assert!((bt2020_oetf::oetf(0.5, false) - 0.705_515_1).abs() <= 1e-5);
  assert!((bt2020_oetf::oetf(1.0, false) - 1.0).abs() <= 1e-6);
  // 12-bit (α = 1.0993, β = 0.0181): colour.oetf_BT2020(E, is_12_bits=True).
  assert!((bt2020_oetf::oetf(0.0181, true) - 0.081_447_2).abs() <= 1e-6);
  assert!((bt2020_oetf::oetf(0.5, true) - 0.705_434_7).abs() <= 1e-5);
  assert!((bt2020_oetf::oetf(1.0, true) - 1.0).abs() <= 1e-6);
}

/// The negative side of both transfers is odd-extended through the origin, so
/// a super-black excursion linearises symmetrically (rather than NaN-ing on a
/// fractional power of a negative base).
// miri's interpreted floating-point diverges from hardware for these
// transcendental OETF paths, overshooting the odd-symmetry tolerance.
#[cfg_attr(miri, ignore)]
#[test]
fn bt2020_oetf_is_odd_extended() {
  for &is12 in &[false, true] {
    for &e in &[0.005_f32, 0.1, 0.7, 1.2] {
      assert!((bt2020_oetf::oetf(-e, is12) + bt2020_oetf::oetf(e, is12)).abs() <= 1e-6);
      assert!(
        (bt2020_oetf::oetf_inverse(-e, is12) + bt2020_oetf::oetf_inverse(e, is12)).abs() <= 1e-6
      );
    }
  }
}

// ---- Kr/Kg/Kb consistency with the chromaticity derivation ---------------

/// The published BT.2020 CL luma weights this module hard-codes
/// ([`KR`] / [`KG`] / [`KB`]) match the chromaticity-derived weights the
/// **non**-constant-luminance sibling computes from the BT.2020 primaries
/// ([`chroma_derived_luma_weights`](crate::row::scalar::chroma_derived_luma_weights)) —
/// the shared `(Kr, Kg, Kb)` derivation reused across ChromaDerivedNcl/Cl. The
/// CL decode uses the published literals (so the per-pixel green solve is
/// exact and `libm`-free), but they are the same numbers.
#[test]
fn published_weights_match_chromaticity_derivation() {
  let (kr, kg, kb) = crate::row::scalar::chroma_derived_luma_weights(&Primaries::Bt2020)
    .expect("Bt2020 carries chromaticities");
  assert!((kr as f32 - KR).abs() <= 5e-4, "Kr {kr} vs {KR}");
  assert!((kg as f32 - KG).abs() <= 5e-4, "Kg {kg} vs {KG}");
  assert!((kb as f32 - KB).abs() <= 5e-4, "Kb {kb} vs {KB}");
  assert!(
    ((kr + kg + kb) - 1.0).abs() <= 1e-9,
    "weights must sum to 1"
  );
}

/// The four BT.2020 chroma normalisers this module hard-codes are the BT.2020
/// OETF evaluated at the gamut boundary (the published derivation
/// `−2Nb = 2·oetf(1 − Kb)`, `2Pb = 2·(1 − oetf(Kb))`, likewise red), matching
/// `colour-science`'s `1.9404 / 1.5816 / 1.7184 / 0.9936`. This pins the
/// constants to the OETF rather than to bare literals — proving they track the
/// transfer.
#[test]
fn chroma_normalisers_derive_from_the_oetf() {
  // 10-bit OETF constants (the BT.2020-2 default the colour-science factors
  // are tabulated against).
  let pb = 1.0 - bt2020_oetf::oetf(KB, false);
  let nb = -bt2020_oetf::oetf(1.0 - KB, false);
  let pr = 1.0 - bt2020_oetf::oetf(KR, false);
  let nr = -bt2020_oetf::oetf(1.0 - KR, false);
  assert!(
    (-2.0 * nb - NEG_2NB).abs() <= 1e-3,
    "-2Nb {} vs {NEG_2NB}",
    -2.0 * nb
  );
  assert!(
    (2.0 * pb - POS_2PB).abs() <= 1e-3,
    "2Pb {} vs {POS_2PB}",
    2.0 * pb
  );
  assert!(
    (-2.0 * nr - NEG_2NR).abs() <= 1e-3,
    "-2Nr {} vs {NEG_2NR}",
    -2.0 * nr
  );
  assert!(
    (2.0 * pr - POS_2PR).abs() <= 1e-3,
    "2Pr {} vs {POS_2PR}",
    2.0 * pr
  );
}

// ---- ClSystem resolution -------------------------------------------------

/// CL resolves **only** for BT.2020 primaries; any other gamut returns `None`
/// (→ the affine fallback). The transfer selects the OETF bit-depth.
#[test]
fn cl_system_resolves_bt2020_only() {
  assert_eq!(
    ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_10Bit).map(|s| s.is_12_bit()),
    Some(false)
  );
  assert_eq!(
    ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).map(|s| s.is_12_bit()),
    Some(true)
  );
  // Unspecified transfer with BT.2020 primaries → NOT CL: the transfer must
  // name a BT.2020 OETF for the camera-gamma decode to be defined. Resolves to
  // None so the caller takes the affine fallback (mirrors ICtCp's explicit
  // transfer allow-list).
  assert!(ClSystem::resolve(&Primaries::Bt2020, &Transfer::Unspecified).is_none());
  // PQ/HLG with BT.2020 primaries → NOT CL: HDR transfers are not the CL camera
  // gamma; decoding them through the BT.2020 inverse-OETF would emit wrong RGB,
  // so they must fall back to the affine path, never silently route as CL.
  assert!(ClSystem::resolve(&Primaries::Bt2020, &Transfer::SmpteSt2084Pq).is_none());
  assert!(ClSystem::resolve(&Primaries::Bt2020, &Transfer::AribStdB67Hlg).is_none());
  // Non-BT.2020 primaries → no CL decode.
  assert!(ClSystem::resolve(&Primaries::Bt709, &Transfer::Bt2020_10Bit).is_none());
  assert!(ClSystem::resolve(&Primaries::Unspecified, &Transfer::Bt2020_12Bit).is_none());
  // as_str accessor.
  let s10 = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_10Bit).unwrap();
  let s12 = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  assert_eq!(s10.as_str(), "bt2020-cl-10");
  assert_eq!(s12.as_str(), "bt2020-cl-12");
}

// ---- Integer-output kernel narrow + alpha + RGB/RGBA consistency ---------

/// The RGB and RGBA kernels agree on the colour channels; RGBA appends opaque
/// alpha (`0xFF` for u8, `(1 << BITS) - 1` for u16). Pinned against the
/// colour-science-derived `R'G'B'` narrow for the 12-bit studio mid-code.
#[test]
fn kernels_narrow_and_alpha_are_consistent() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  let (y, u, v) = (
    [le_wire_u16(2048)],
    [le_wire_u16(2148)],
    [le_wire_u16(1948)],
  );

  let mut rgb_u8 = [0u8; 3];
  let mut rgba_u8 = [0u8; 4];
  cl_444p_n_to_rgb_row::<12, false>(&y, &u, &v, &mut rgb_u8, 1, false, system);
  cl_444p_n_to_rgba_row::<12, false>(&y, &u, &v, &mut rgba_u8, 1, false, system);
  assert_eq!(&rgba_u8[..3], &rgb_u8[..], "u8 RGB vs RGBA colour channels");
  assert_eq!(rgba_u8[3], 0xFF, "u8 opaque alpha");
  assert_eq!(
    rgb_u8,
    [118, 134, 142],
    "u8 R'G'B' narrow (colour-science pinned)"
  );

  let mut rgb_u16 = [0u16; 3];
  let mut rgba_u16 = [0u16; 4];
  cl_444p_n_to_rgb_u16_row::<12, false>(&y, &u, &v, &mut rgb_u16, 1, false, system);
  cl_444p_n_to_rgba_u16_row::<12, false>(&y, &u, &v, &mut rgba_u16, 1, false, system);
  assert_eq!(
    &rgba_u16[..3],
    &rgb_u16[..],
    "u16 RGB vs RGBA colour channels"
  );
  assert_eq!(rgba_u16[3], 4095, "u16 native-depth opaque alpha");
  assert_eq!(
    rgb_u16,
    [1898, 2149, 2275],
    "u16 native R'G'B' narrow (colour-science pinned)"
  );
}

/// **Toe-region regression** for the inverse-OETF breakpoint:
/// a dark 10-bit CL sample whose `Y'c` lands in the encoded mis-branch gap
/// `[4.5·β, oetf(β))` decoded through the kernel must match `colour-science`.
/// At `Y'c = 135, Cbc = 500, Crc = 520` (10-bit studio) the green channel —
/// solved from the inverse-OETF of `Y'c` — narrows to native code `82`
/// (`colour.YcCbcCrc_to_RGB` linear `[0.019982, 0.017753, 0.012236]`,
/// re-encoded + narrowed to 10-bit). The prior `4.5·β` breakpoint produced
/// `81` (it inverted `Y'c` through the power branch instead of the toe). The
/// kernels are const-generic over `BITS`, so this drives the same decode at
/// the 10-bit depth where the gap is widest.
#[test]
fn toe_region_10bit_matches_colour_science_reference() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_10Bit).unwrap();
  assert!(!system.is_12_bit());
  let mut rgb_u16 = [0u16; 3];
  cl_444p_n_to_rgb_u16_row::<10, false>(
    &[le_wire_u16(135)],
    &[le_wire_u16(500)],
    &[le_wire_u16(520)],
    &mut rgb_u16,
    1,
    false,
    system,
  );
  assert_eq!(
    rgb_u16,
    [92, 82, 56],
    "10-bit toe-region decode (colour-science pinned; pre-fix green was 81)"
  );
}

/// Big-endian wire input decodes identically to little-endian once the bytes
/// are swapped — the `BE` const generic only changes the load.
#[test]
fn big_endian_matches_swapped_little_endian() {
  let system = ClSystem::resolve(&Primaries::Bt2020, &Transfer::Bt2020_12Bit).unwrap();
  let (y, u, v) = (2048u16, 2148u16, 1948u16);
  let mut le = [0u16; 3];
  let mut be = [0u16; 3];
  cl_444p_n_to_rgb_u16_row::<12, false>(&[y], &[u], &[v], &mut le, 1, false, system);
  cl_444p_n_to_rgb_u16_row::<12, true>(
    &[y.swap_bytes()],
    &[u.swap_bytes()],
    &[v.swap_bytes()],
    &mut be,
    1,
    false,
    system,
  );
  assert_eq!(le, be, "BE load must match swapped LE");
}