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
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
use super::super::{
  GeometryOverflow, InsufficientBuffer, MixedSinker, MixedSinkerError, RowIndexOutOfRange,
  RowShapeMismatch, RowSlice, check_dimensions_match, packed_yuv444_triple_filter_resample,
  packed_yuv444_triple_resample, reset_high_bit_yuv_streams, rgb_row_buf_or_scratch,
  rgba_plane_row_slice, rgba_u16_plane_row_slice,
};
use crate::{PixelSink, row::*, source::*};

// `NativeRouteChanged` is raised only by the native fast tier's route-flip
// guard, which exists only when the reused planar join is compiled in.
#[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
use super::super::{
  FrozenOutputs, HsvFrameMut, NativePlanarYuvU16, NativeRouteChanged,
  native_planar_hb_preflight_check_only, yuv_planar16_process_native,
};
#[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
use crate::{
  KernelMatrix,
  resample::{
    AveragingDomain, InsertionContext, InsertionPoint, PlanGeometry, ResampleError, ResamplePlan,
    select_insertion_point,
  },
};

// The native fast tier de-interleaves + DE-PACKS each wire plane into
// wrapper-owned host-native LOGICAL u16 scratch BEFORE handing it to the
// planar delegate, so the delegate's own `from_le` / `from_be` decode must be
// a no-op load on every host: pass `BE = HOST_NATIVE_BE` (= `from_ne`).
// Passing the source wire `BE` here would byte-swap the already-native scratch
// on a big-endian target. Mirrors the 4:2:0 high-bit semi-planar `p0xx`.
#[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
const HOST_NATIVE_BE: bool = cfg!(target_endian = "big");

// Test-only allocation failpoint for the wrapper-owned Y / U / V de-pack
// scratch grow in `p4xx_process_native`. Armed, the FIRST (Y) scratch grow of
// an output-bearing row returns the crate's recoverable `AllocationFailed`
// WITHOUT growing — so the atomicity regressions can prove the join's pre-feed
// preflight runs BEFORE this fallible grow. Mirrors the 4:2:0 high-bit
// semi-planar `FORCE_P0XX_ALLOC_FAILURE`. Strictly test-only.
#[cfg(all(
  test,
  feature = "std",
  feature = "yuv-semi-planar",
  feature = "yuv-planar"
))]
std::thread_local! {
  static FORCE_P4XX_ALLOC_FAILURE: core::cell::Cell<bool> =
    const { core::cell::Cell::new(false) };
}

/// Arms the wrapper de-pack scratch allocation failpoint for the **next**
/// output-bearing high-bit semi-planar 4:4:4 native row on the current thread.
/// The flag is consumed (take-on-read) by the first fallible scratch grow that
/// row reaches, so it fires exactly once and cannot leak into a later test.
/// Test-only.
#[cfg(all(
  test,
  feature = "std",
  feature = "yuv-semi-planar",
  feature = "yuv-planar"
))]
pub(crate) fn arm_p4xx_alloc_failure() {
  FORCE_P4XX_ALLOC_FAILURE.with(|f| f.set(true));
}

/// Grows a wrapper-owned de-pack scratch to `len` `u16` under the planner's
/// recoverable-allocation contract, optionally firing the test-only failpoint
/// (`fail = true` only on the FIRST grow of an output-bearing row). Runs after
/// the join's preflight clears, so a rejected row never reaches it.
#[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
#[cfg_attr(not(tarpaulin), inline(always))]
fn grow_depack_scratch(
  scratch: &mut std::vec::Vec<u16>,
  len: usize,
  fail: bool,
  w: usize,
  h: usize,
  plan: &ResamplePlan,
) -> Result<(), MixedSinkerError> {
  // `fail` is consumed by the caller; on the non-test build it is `false` and
  // the whole branch compiles away.
  let _ = fail;
  if scratch.len() < len {
    #[cfg(all(
      test,
      feature = "std",
      feature = "yuv-semi-planar",
      feature = "yuv-planar"
    ))]
    if fail && FORCE_P4XX_ALLOC_FAILURE.with(|f| f.take()) {
      return Err(MixedSinkerError::Resample(ResampleError::AllocationFailed(
        PlanGeometry::new(w, h, plan.out_w(), plan.out_h()),
      )));
    }
    scratch
      .try_reserve_exact(len - scratch.len())
      .map_err(|_| {
        MixedSinkerError::Resample(ResampleError::AllocationFailed(PlanGeometry::new(
          w,
          h,
          plan.out_w(),
          plan.out_h(),
        )))
      })?;
    scratch.resize(len, 0);
  }
  Ok(())
}

/// Native fast-tier decimator for the **high-bit semi-planar 4:4:4** P-format
/// family ([`P410`](crate::source::P410) / [`P412`](crate::source::P412) /
/// [`P416`](crate::source::P416)): bins the native Y / U / V planes straight to
/// the output grid and converts once per output row at output resolution. The
/// 4:4:4 sibling of the 4:2:0 high-bit semi-planar `p0xx_process_native` and
/// the `u16` twin of the 8-bit semi-planar non-4:2:0
/// `semi_planar_process_native_non420`, reusing the high-bit non-4:2:0 PLANAR
/// join verbatim ([`yuv_planar16_process_native`]) after de-interleaving +
/// DE-PACKING the wire row into wrapper-owned host-native LOGICAL u16 scratch.
///
/// THE SEAM: [`yuv_planar16_process_native`] wire-decodes its `y_row` / `u_row`
/// / `v_row` input (`from_le` / `from_be`) but applies **no** high-bit shift —
/// it treats them as **low-packed LOGICAL** u16. P-format Y is HIGH-BIT-PACKED
/// (`logical << (16 - BITS)`) and the UV plane is INTERLEAVED + high-packed. So
/// this wrapper must, per row, decode the wire AND de-pack (`>> (16 - BITS)`)
/// the Y, and de-interleave (`U,V` order — every P-format is UV-order, no VU
/// variant) + de-pack EACH of U and V, into host-native logical scratch — then
/// delegate with `BE = HOST_NATIVE_BE` so the delegate's internal decode is a
/// no-op load on every host. The de-pack hits Y AND U AND V; at `BITS = 16` the
/// shift is `>> 0` (a harmless no-op — the 10/12 tests guard the live shift).
///
/// 4:4:4 layout: the chroma plane is full-resolution (`chroma_w = w`, vertical
/// cadence `chroma_vsub = 1`), so a chroma row feeds EVERY colour Y row and the
/// chroma de-pack runs at full width. The packed UV row is `2 * w` u16 (`w`
/// interleaved pairs). The delegate builds its chroma grid against the same
/// output geometry via the `build_chroma_plan` closure.
///
/// Atomicity + lazy chroma mirror the 4:2:2 `p2xx_process_native`: the join's
/// COMPLETE pre-feed preflight runs FIRST (deterministic typed rejection, never
/// `AllocationFailed`); a luma-only sink skips the chroma de-interleave/scratch.
#[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
#[allow(clippy::too_many_arguments)]
fn p4xx_process_native<const BITS: u32, const BE: bool>(
  plan: &ResamplePlan,
  native_planar_u16: &mut Option<std::boxed::Box<NativePlanarYuvU16>>,
  y_scratch: &mut std::vec::Vec<u16>,
  u_scratch: &mut std::vec::Vec<u16>,
  v_scratch: &mut std::vec::Vec<u16>,
  resample_outputs: &mut Option<FrozenOutputs>,
  rgb: &mut Option<&mut [u8]>,
  rgba: &mut Option<&mut [u8]>,
  rgb_u16: &mut Option<&mut [u16]>,
  rgba_u16: &mut Option<&mut [u16]>,
  luma: &mut Option<&mut [u8]>,
  hsv: &mut Option<HsvFrameMut<'_>>,
  rgb_scratch: &mut std::vec::Vec<u8>,
  rgb_scratch_u16: &mut std::vec::Vec<u16>,
  y_row: &[u16],
  uv_full: &[u16],
  matrix: KernelMatrix,
  full_range: bool,
  idx: usize,
  w: usize,
  h: usize,
  use_simd: bool,
) -> Result<(), MixedSinkerError> {
  const {
    assert!(
      BITS > 8 && BITS <= 16,
      "BITS must be in (8, 16] for high-bit semi-planar 4:4:4 P-format"
    )
  };
  let need_luma = luma.is_some();
  let need_color =
    rgb.is_some() || rgba.is_some() || hsv.is_some() || rgb_u16.is_some() || rgba_u16.is_some();
  // 4:4:4 chroma is full-resolution: `chroma_w = w`, a chroma row per Y row.
  let cw = w;

  // Run the planar join's COMPLETE compare-only pre-feed rejection preflight
  // FIRST — BEFORE any fallible scratch grow below — so every rejection returns
  // its deterministic typed error and leaves the wrapper scratch untouched.
  // Compare-only (no output-set freeze): the de-pack grows below AND the
  // delegate's own colour / source scratch grows all stay pre-commit, and the
  // delegate performs the SINGLE freeze once every pre-feed allocation has
  // succeeded — so a LATER grow (here or in the delegate) failing leaves
  // `resample_outputs` untouched and the row retryable.
  if !native_planar_hb_preflight_check_only(
    native_planar_u16,
    resample_outputs,
    rgb,
    rgba,
    rgb_u16,
    rgba_u16,
    luma,
    // The high-bit semi-planar 4:4:4 P-format exposes no `luma_u16` output.
    &None,
    hsv,
    idx,
    need_luma,
    need_color,
  )? {
    return Ok(());
  }

  // Grow the wrapper de-pack scratch under the planner's recoverable contract —
  // Y always, U / V only on a colour row (4:4:4: every Y row is a chroma row
  // when colour is wanted). All grows precede the infallible de-pack and the
  // delegate call. The failpoint fires on the FIRST (Y) grow only.
  grow_depack_scratch(y_scratch, w, true, w, h, plan)?;
  if need_color {
    grow_depack_scratch(u_scratch, cw, false, w, h, plan)?;
    grow_depack_scratch(v_scratch, cw, false, w, h, plan)?;
  }

  // De-pack the wire planes into host-native LOGICAL scratch. Decode the wire
  // endianness, then shift the active high `BITS` down to the low `BITS`
  // (`>> (16 - BITS)`; `>> 0` at BITS = 16). Everything past here is infallible.
  for (d, &s) in y_scratch[..w].iter_mut().zip(y_row.iter()) {
    let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
    *d = logical >> (16 - BITS);
  }
  if need_color {
    // P-format chroma is interleaved `U,V,U,V…` (U at even element); each of U
    // and V is independently high-bit-packed and must be de-packed. 4:4:4 is
    // full-width: `w` interleaved pairs (`2 * w` u16).
    for (i, pair) in uv_full.as_chunks::<2>().0.iter().enumerate() {
      let u = if BE {
        u16::from_be(pair[0])
      } else {
        u16::from_le(pair[0])
      };
      let v = if BE {
        u16::from_be(pair[1])
      } else {
        u16::from_le(pair[1])
      };
      u_scratch[i] = u >> (16 - BITS);
      v_scratch[i] = v >> (16 - BITS);
    }
  }

  // Delegate to the planar high-bit non-4:2:0 join with `BE = HOST_NATIVE_BE`
  // at the 4:4:4 chroma geometry (`chroma_vsub = 1`, `chroma_w = w`). Empty
  // U / V on luma-only rows (the join reads chroma only under colour).
  let (u_plane, v_plane): (&[u16], &[u16]) = if need_color {
    (&u_scratch[..cw], &v_scratch[..cw])
  } else {
    (&[], &[])
  };
  yuv_planar16_process_native::<BITS, HOST_NATIVE_BE>(
    plan,
    native_planar_u16,
    resample_outputs,
    rgb,
    rgba,
    rgb_u16,
    rgba_u16,
    luma,
    // The high-bit semi-planar 4:4:4 P-format exposes no `luma_u16` output.
    &mut None,
    hsv,
    rgb_scratch,
    rgb_scratch_u16,
    &y_scratch[..w],
    u_plane,
    v_plane,
    matrix,
    full_range,
    idx,
    w,
    h,
    1,
    cw,
    || ResamplePlan::area(cw, h, plan.out_w(), plan.out_h()),
    use_simd,
  )
}

// ---- P410 impl ----------------------------------------------------------
//
// 4:4:4 high-bit-packed semi-planar (10-bit). Full-width interleaved
// UV (`2 * width` u16 elements per row). Uses the new
// `p410_to_rgb_*` row primitives (which dispatch to the
// `p_n_444_to_rgb_*<10>` family).

impl<'a, R, const BE: bool> MixedSinker<'a, P410<BE>, R> {
  /// Attaches a packed **`u16`** RGB output buffer. 10-bit low-packed.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgb_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgb_u16(buf)?;
    Ok(self)
  }
  /// In-place variant.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgb_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(3)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgb_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **8-bit** RGBA output buffer. P410 has no alpha
  /// plane, so alpha = `0xFF` (opaque).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba(mut self, buf: &'a mut [u8]) -> Result<Self, MixedSinkerError> {
    self.set_rgba(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba`](Self::with_rgba).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba(&mut self, buf: &'a mut [u8]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaBuffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGBA output buffer. 10-bit low-packed
  /// (`[0, 1023]`); alpha element is `1023`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgba_u16(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba_u16`](Self::with_rgba_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba_u16 = Some(buf);
    Ok(self)
  }
}

impl<R, const BE: bool> P410Sink<BE> for MixedSinker<'_, P410<BE>, R> {}

impl<R, const BE: bool> PixelSink for MixedSinker<'_, P410<BE>, R> {
  type Input<'r> = P410Row<'r>;
  type Error = MixedSinkerError;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn kernel_matrix(&self) -> crate::KernelMatrix {
    self.kernel_matrix
  }
  fn begin_frame(&mut self, width: u32, height: u32) -> Result<(), Self::Error> {
    check_dimensions_match(self.width, self.height, width, height)?;
    reset_high_bit_yuv_streams(self);
    Ok(())
  }

  fn process(&mut self, row: P410Row<'_>) -> Result<(), Self::Error> {
    const BITS: u32 = 10;
    let w = self.width;
    let h = self.height;
    let idx = row.row();
    let use_simd = self.simd;

    if row.y().len() != w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::Y10,
        idx,
        w,
        row.y().len(),
      )));
    }
    // 4:4:4 semi-planar: full-width x 2 elements per pair.
    if row.uv_full().len() != 2 * w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::UvFull10,
        idx,
        2 * w,
        row.uv_full().len(),
      )));
    }
    if idx >= self.height {
      return Err(MixedSinkerError::RowIndexOutOfRange(
        RowIndexOutOfRange::new(idx, self.height),
      ));
    }

    let Self {
      rgb,
      rgb_u16,
      rgba,
      rgba_u16,
      luma,
      hsv,
      rgb_scratch,
      rgb_scratch_u16,
      luma_scratch_u16,
      rgb_stream,
      rgb_stream_u16,
      luma_stream_u16,
      rgb_filter_stream,
      rgb_filter_stream_u16,
      luma_filter_stream_u16,
      resample_outputs,
      plan,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native_planar_u16,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_y_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_u_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_v_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      frozen_native_route,
      ..
    } = self;

    // Non-identity plan: a `Filter` plan routes to the shared high-bit 4:4:4
    // signed-coefficient filter tail (no native fast tier), so it branches
    // FIRST. An `Area` plan routes native-or-row-stage: when the native tier
    // is enabled (and the planar join it reuses is compiled in), bin the
    // native Y / U / V planes at output resolution and convert once per output
    // row, de-interleaving + de-packing the P410 chroma + Y into wrapper-owned
    // logical scratch first; otherwise (or under `with_native(false)`) feed
    // the shared area triple-resample tail. P410 is semi-planar 4:4:4: the
    // full-width interleaved UV plane (`2 * w` u16) is de-interleaved per-pixel
    // (no chroma upsample) by the `p410_to_rgb*` kernels. The Y de-pack shift
    // `>> (16 - BITS)` yields the logical native Y; `luma = binned_Y >>
    // (BITS - 8)`. P410 exposes no `luma_u16`, so it is `&mut None`. The filter
    // tail clamps a signed-kernel overshoot to the native max for this
    // sub-16-bit source (both colour and native-Y luma), matching the in-range
    // area path.
    if let Some(plan) = plan.as_ref() {
      let matrix = row.matrix();
      let full_range = row.full_range();
      let (y, uv_full) = (row.y(), row.uv_full());
      if plan.kind().is_filter() {
        return packed_yuv444_triple_filter_resample::<BITS>(
          rgb_filter_stream,
          rgb_filter_stream_u16,
          luma_filter_stream_u16,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          &mut None,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          luma_scratch_u16,
          w,
          plan,
          idx,
          use_simd,
          matrix,
          full_range,
          |scratch| {
            p410_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            p410_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
              let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
              *dst = logical >> (16 - BITS);
            }
          },
        );
      }
      // Whether this call carries any output — the EXACT set the tier
      // preflight tests. The route freezes only on an output-bearing row a
      // tier ACCEPTS.
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let need_output = luma.is_some()
        || rgb.is_some()
        || rgba.is_some()
        || rgb_u16.is_some()
        || rgba_u16.is_some()
        || hsv.is_some();
      // Reject a mid-frame native/row-stage route flip BEFORE either tier's
      // dispatch (mirrors the 4:2:0 high-bit semi-planar `p0xx`).
      // The RFC #238 splice stage. A filter plan already returned above, so
      // `area_plan` is true and the selector reproduces the former `*native`
      // boolean bit-for-bit (`cfg!` is true wherever this block compiles).
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let take_native = matches!(
        select_insertion_point(
          AveragingDomain::Encoded,
          InsertionContext {
            native_eligible: cfg!(all(feature = "yuv-semi-planar", feature = "yuv-planar")),
            with_native: *native,
            area_plan: true,
          },
        ),
        InsertionPoint::NativeCodes
      );
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if need_output
        && let Some(frozen) = *frozen_native_route
        && frozen != take_native
      {
        return Err(MixedSinkerError::NativeRouteChanged(
          NativeRouteChanged::new(idx),
        ));
      }
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if take_native {
        p4xx_process_native::<BITS, BE>(
          plan,
          native_planar_u16,
          p0xx_y_half,
          p0xx_u_half,
          p0xx_v_half,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          y,
          uv_full,
          matrix,
          full_range,
          idx,
          w,
          h,
          use_simd,
        )?;
        if frozen_native_route.is_none() && need_output {
          *frozen_native_route = Some(true);
        }
        return Ok(());
      }
      packed_yuv444_triple_resample::<BITS>(
        rgb_stream,
        rgb_stream_u16,
        luma_stream_u16,
        resample_outputs,
        rgb,
        rgba,
        rgb_u16,
        rgba_u16,
        luma,
        &mut None,
        hsv,
        rgb_scratch,
        rgb_scratch_u16,
        luma_scratch_u16,
        w,
        plan,
        idx,
        use_simd,
        matrix,
        full_range,
        |scratch| p410_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE),
        |scratch| {
          p410_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
        },
        |scratch| {
          for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
            let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
            *dst = logical >> (16 - BITS);
          }
        },
      )?;
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if frozen_native_route.is_none() && need_output {
        *frozen_native_route = Some(false);
      }
      return Ok(());
    }

    let one_plane_start = idx * w;
    let one_plane_end = one_plane_start + w;

    // Resolve the output set up front so the atomicity preflight below runs
    // before any output row is written.
    let want_rgb = rgb.is_some();
    let want_rgba = rgba.is_some();
    let want_hsv = hsv.is_some();

    // Atomicity preflight (#308, cf. the crate's #180 resample fix and the
    // high-bit 4:2:0 p0xx / yuv420p siblings): reserve the only growable row
    // scratch this identity row can touch — the u8 RGB row buffer — BEFORE any
    // output row is written (the luma plane below, then the u16 RGB / RGBA
    // fan-out), so an allocator refusal returns a typed `AllocationFailed` and
    // leaves the output frame untouched rather than partially mutated. At 4:4:4
    // the chroma is full-resolution (no upsampling), but the output staging
    // matches 4:2:0: the u16 RGB / RGBA outputs write straight into their caller
    // buffers (the rgb_u16 plane itself stages the rgba_u16 expand) and never
    // grow a scratch, and these formats expose no luma_u16. The allocating
    // (rgb=None) arm of `rgb_row_buf_or_scratch` is reached exactly when a colour
    // decode needs an RGB row but no caller RGB buffer is borrowable —
    // `want_hsv && want_rgba && !want_rgb`. The later decode reuses the
    // already-sized buffer, so the default path is byte-identical; only the
    // failure-path ordering changes.
    if want_hsv && want_rgba && !want_rgb {
      rgb_row_buf_or_scratch(
        rgb.as_deref_mut(),
        rgb_scratch,
        one_plane_start,
        one_plane_end,
        w,
        h,
      )?;
    }

    if let Some(luma) = luma.as_deref_mut() {
      let dst = &mut luma[one_plane_start..one_plane_end];
      for (d, &s) in dst.iter_mut().zip(row.y().iter()) {
        // Normalize BE-encoded wire bytes to host-native before the
        // luma downshift — see P010 luma path for rationale.
        let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
        *d = (logical >> 8) as u8;
      }
    }

    // ===== u16 RGB / RGBA path (Strategy A) =====
    let want_rgb_u16 = rgb_u16.is_some();
    let want_rgba_u16 = rgba_u16.is_some();

    if want_rgba_u16 && !want_rgb_u16 {
      let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
      let rgba_u16_row =
        rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
      p410_to_rgba_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgba_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
    } else if want_rgb_u16 {
      let rgb_u16_buf = rgb_u16.as_deref_mut().unwrap();
      let rgb_plane_end =
        one_plane_end
          .checked_mul(3)
          .ok_or(MixedSinkerError::GeometryOverflow(GeometryOverflow::new(
            w, h, 3,
          )))?;
      let rgb_plane_start = one_plane_start * 3;
      let rgb_u16_row = &mut rgb_u16_buf[rgb_plane_start..rgb_plane_end];
      p410_to_rgb_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgb_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      if want_rgba_u16 {
        let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
        let rgba_u16_row =
          rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
        expand_rgb_u16_to_rgba_u16_row::<BITS>(rgb_u16_row, rgba_u16_row, w);
      }
    }

    // ===== u8 RGB / RGBA / HSV path (Strategy A) =====
    // HSV-without-RGB-or-RGBA goes through the direct `p410_to_hsv_row`
    // kernel (no source-width RGB scratch) — the 4:4:4 full-width-UV twin
    // of the P010 path. When RGB or RGBA is also attached the RGB kernel
    // runs anyway, so HSV derives off that buffer for free and
    // `need_rgb_kernel` keeps it alive.
    let want_hsv_direct = want_hsv && !want_rgb && !want_rgba;
    let need_rgb_kernel = want_rgb || (want_hsv && want_rgba);

    if want_hsv_direct {
      let hsv = hsv.as_mut().expect("want_hsv_direct implies hsv attached");
      let (h, s, v) = hsv.hsv();
      p410_to_hsv_row_endian(
        row.y(),
        row.uv_full(),
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if want_rgba && !need_rgb_kernel {
      let rgba_buf = rgba.as_deref_mut().unwrap();
      let rgba_row = rgba_plane_row_slice(rgba_buf, one_plane_start, one_plane_end, w, h)?;
      p410_to_rgba_row_endian(
        row.y(),
        row.uv_full(),
        rgba_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if !need_rgb_kernel {
      return Ok(());
    }

    let rgb_row = rgb_row_buf_or_scratch(
      rgb.as_deref_mut(),
      rgb_scratch,
      one_plane_start,
      one_plane_end,
      w,
      h,
    )?;

    p410_to_rgb_row_endian(
      row.y(),
      row.uv_full(),
      rgb_row,
      w,
      row.matrix(),
      row.full_range(),
      use_simd,
      BE,
    );

    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      rgb_to_hsv_row(
        rgb_row,
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba.as_deref_mut() {
      let rgba_row = rgba_plane_row_slice(buf, one_plane_start, one_plane_end, w, h)?;
      expand_rgb_to_rgba_row(rgb_row, rgba_row, w);
    }

    Ok(())
  }
}

// ---- P412 impl ----------------------------------------------------------

impl<'a, R, const BE: bool> MixedSinker<'a, P412<BE>, R> {
  /// Attaches a packed **`u16`** RGB output buffer. 12-bit low-packed.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgb_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgb_u16(buf)?;
    Ok(self)
  }
  /// In-place variant.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgb_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(3)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgb_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **8-bit** RGBA output buffer. P412 has no alpha
  /// plane, so alpha = `0xFF` (opaque).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba(mut self, buf: &'a mut [u8]) -> Result<Self, MixedSinkerError> {
    self.set_rgba(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba`](Self::with_rgba).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba(&mut self, buf: &'a mut [u8]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaBuffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGBA output buffer. 12-bit low-packed
  /// (`[0, 4095]`); alpha element is `4095`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgba_u16(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba_u16`](Self::with_rgba_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba_u16 = Some(buf);
    Ok(self)
  }
}

impl<R, const BE: bool> P412Sink<BE> for MixedSinker<'_, P412<BE>, R> {}

impl<R, const BE: bool> PixelSink for MixedSinker<'_, P412<BE>, R> {
  type Input<'r> = P412Row<'r>;
  type Error = MixedSinkerError;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn kernel_matrix(&self) -> crate::KernelMatrix {
    self.kernel_matrix
  }
  fn begin_frame(&mut self, width: u32, height: u32) -> Result<(), Self::Error> {
    check_dimensions_match(self.width, self.height, width, height)?;
    reset_high_bit_yuv_streams(self);
    Ok(())
  }

  fn process(&mut self, row: P412Row<'_>) -> Result<(), Self::Error> {
    const BITS: u32 = 12;
    let w = self.width;
    let h = self.height;
    let idx = row.row();
    let use_simd = self.simd;

    if row.y().len() != w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::Y12,
        idx,
        w,
        row.y().len(),
      )));
    }
    if row.uv_full().len() != 2 * w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::UvFull12,
        idx,
        2 * w,
        row.uv_full().len(),
      )));
    }
    if idx >= self.height {
      return Err(MixedSinkerError::RowIndexOutOfRange(
        RowIndexOutOfRange::new(idx, self.height),
      ));
    }

    let Self {
      rgb,
      rgb_u16,
      rgba,
      rgba_u16,
      luma,
      hsv,
      rgb_scratch,
      rgb_scratch_u16,
      luma_scratch_u16,
      rgb_stream,
      rgb_stream_u16,
      luma_stream_u16,
      rgb_filter_stream,
      rgb_filter_stream_u16,
      luma_filter_stream_u16,
      resample_outputs,
      plan,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native_planar_u16,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_y_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_u_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_v_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      frozen_native_route,
      ..
    } = self;

    // Non-identity plan: filter branches first (no native fast tier); an area
    // plan routes native-or-row-stage. See the P410 impl for the full
    // rationale — P412 is identical bar the 12-bit kernel family
    // (`p412_to_rgb*`).
    if let Some(plan) = plan.as_ref() {
      let matrix = row.matrix();
      let full_range = row.full_range();
      let (y, uv_full) = (row.y(), row.uv_full());
      if plan.kind().is_filter() {
        return packed_yuv444_triple_filter_resample::<BITS>(
          rgb_filter_stream,
          rgb_filter_stream_u16,
          luma_filter_stream_u16,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          &mut None,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          luma_scratch_u16,
          w,
          plan,
          idx,
          use_simd,
          matrix,
          full_range,
          |scratch| {
            p412_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            p412_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
              let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
              *dst = logical >> (16 - BITS);
            }
          },
        );
      }
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let need_output = luma.is_some()
        || rgb.is_some()
        || rgba.is_some()
        || rgb_u16.is_some()
        || rgba_u16.is_some()
        || hsv.is_some();
      // The RFC #238 splice stage. A filter plan already returned above, so
      // `area_plan` is true and the selector reproduces the former `*native`
      // boolean bit-for-bit (`cfg!` is true wherever this block compiles).
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let take_native = matches!(
        select_insertion_point(
          AveragingDomain::Encoded,
          InsertionContext {
            native_eligible: cfg!(all(feature = "yuv-semi-planar", feature = "yuv-planar")),
            with_native: *native,
            area_plan: true,
          },
        ),
        InsertionPoint::NativeCodes
      );
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if need_output
        && let Some(frozen) = *frozen_native_route
        && frozen != take_native
      {
        return Err(MixedSinkerError::NativeRouteChanged(
          NativeRouteChanged::new(idx),
        ));
      }
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if take_native {
        p4xx_process_native::<BITS, BE>(
          plan,
          native_planar_u16,
          p0xx_y_half,
          p0xx_u_half,
          p0xx_v_half,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          y,
          uv_full,
          matrix,
          full_range,
          idx,
          w,
          h,
          use_simd,
        )?;
        if frozen_native_route.is_none() && need_output {
          *frozen_native_route = Some(true);
        }
        return Ok(());
      }
      packed_yuv444_triple_resample::<BITS>(
        rgb_stream,
        rgb_stream_u16,
        luma_stream_u16,
        resample_outputs,
        rgb,
        rgba,
        rgb_u16,
        rgba_u16,
        luma,
        &mut None,
        hsv,
        rgb_scratch,
        rgb_scratch_u16,
        luma_scratch_u16,
        w,
        plan,
        idx,
        use_simd,
        matrix,
        full_range,
        |scratch| p412_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE),
        |scratch| {
          p412_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
        },
        |scratch| {
          for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
            let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
            *dst = logical >> (16 - BITS);
          }
        },
      )?;
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if frozen_native_route.is_none() && need_output {
        *frozen_native_route = Some(false);
      }
      return Ok(());
    }

    let one_plane_start = idx * w;
    let one_plane_end = one_plane_start + w;

    // Resolve the output set up front so the atomicity preflight below runs
    // before any output row is written.
    let want_rgb = rgb.is_some();
    let want_rgba = rgba.is_some();
    let want_hsv = hsv.is_some();

    // Atomicity preflight (#308, cf. the crate's #180 resample fix and the
    // high-bit 4:2:0 p0xx / yuv420p siblings): reserve the only growable row
    // scratch this identity row can touch — the u8 RGB row buffer — BEFORE any
    // output row is written (the luma plane below, then the u16 RGB / RGBA
    // fan-out), so an allocator refusal returns a typed `AllocationFailed` and
    // leaves the output frame untouched rather than partially mutated. At 4:4:4
    // the chroma is full-resolution (no upsampling), but the output staging
    // matches 4:2:0: the u16 RGB / RGBA outputs write straight into their caller
    // buffers (the rgb_u16 plane itself stages the rgba_u16 expand) and never
    // grow a scratch, and these formats expose no luma_u16. The allocating
    // (rgb=None) arm of `rgb_row_buf_or_scratch` is reached exactly when a colour
    // decode needs an RGB row but no caller RGB buffer is borrowable —
    // `want_hsv && want_rgba && !want_rgb`. The later decode reuses the
    // already-sized buffer, so the default path is byte-identical; only the
    // failure-path ordering changes.
    if want_hsv && want_rgba && !want_rgb {
      rgb_row_buf_or_scratch(
        rgb.as_deref_mut(),
        rgb_scratch,
        one_plane_start,
        one_plane_end,
        w,
        h,
      )?;
    }

    if let Some(luma) = luma.as_deref_mut() {
      let dst = &mut luma[one_plane_start..one_plane_end];
      for (d, &s) in dst.iter_mut().zip(row.y().iter()) {
        // Normalize BE-encoded wire bytes to host-native before the
        // luma downshift — see P010 luma path for rationale.
        let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
        *d = (logical >> 8) as u8;
      }
    }

    // ===== u16 RGB / RGBA path (Strategy A) =====
    let want_rgb_u16 = rgb_u16.is_some();
    let want_rgba_u16 = rgba_u16.is_some();

    if want_rgba_u16 && !want_rgb_u16 {
      let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
      let rgba_u16_row =
        rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
      p412_to_rgba_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgba_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
    } else if want_rgb_u16 {
      let rgb_u16_buf = rgb_u16.as_deref_mut().unwrap();
      let rgb_plane_end =
        one_plane_end
          .checked_mul(3)
          .ok_or(MixedSinkerError::GeometryOverflow(GeometryOverflow::new(
            w, h, 3,
          )))?;
      let rgb_plane_start = one_plane_start * 3;
      let rgb_u16_row = &mut rgb_u16_buf[rgb_plane_start..rgb_plane_end];
      p412_to_rgb_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgb_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      if want_rgba_u16 {
        let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
        let rgba_u16_row =
          rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
        expand_rgb_u16_to_rgba_u16_row::<BITS>(rgb_u16_row, rgba_u16_row, w);
      }
    }

    // ===== u8 RGB / RGBA / HSV path (Strategy A) =====
    // HSV-without-RGB-or-RGBA goes through the direct `p412_to_hsv_row`
    // kernel (no source-width RGB scratch) — the 4:4:4 full-width-UV twin
    // of the P012 path. When RGB or RGBA is also attached the RGB kernel
    // runs anyway, so HSV derives off that buffer for free and
    // `need_rgb_kernel` keeps it alive.
    let want_hsv_direct = want_hsv && !want_rgb && !want_rgba;
    let need_rgb_kernel = want_rgb || (want_hsv && want_rgba);

    if want_hsv_direct {
      let hsv = hsv.as_mut().expect("want_hsv_direct implies hsv attached");
      let (h, s, v) = hsv.hsv();
      p412_to_hsv_row_endian(
        row.y(),
        row.uv_full(),
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if want_rgba && !need_rgb_kernel {
      let rgba_buf = rgba.as_deref_mut().unwrap();
      let rgba_row = rgba_plane_row_slice(rgba_buf, one_plane_start, one_plane_end, w, h)?;
      p412_to_rgba_row_endian(
        row.y(),
        row.uv_full(),
        rgba_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if !need_rgb_kernel {
      return Ok(());
    }

    let rgb_row = rgb_row_buf_or_scratch(
      rgb.as_deref_mut(),
      rgb_scratch,
      one_plane_start,
      one_plane_end,
      w,
      h,
    )?;

    p412_to_rgb_row_endian(
      row.y(),
      row.uv_full(),
      rgb_row,
      w,
      row.matrix(),
      row.full_range(),
      use_simd,
      BE,
    );

    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      rgb_to_hsv_row(
        rgb_row,
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba.as_deref_mut() {
      let rgba_row = rgba_plane_row_slice(buf, one_plane_start, one_plane_end, w, h)?;
      expand_rgb_to_rgba_row(rgb_row, rgba_row, w);
    }

    Ok(())
  }
}

// ---- P416 impl ----------------------------------------------------------
//
// 4:4:4 16-bit semi-planar. Uses `p416_to_rgb_*` (parallel i64-chroma
// family for u16 output, i32 for u8).

impl<'a, R, const BE: bool> MixedSinker<'a, P416<BE>, R> {
  /// Attaches a packed **`u16`** RGB output buffer. 16-bit output
  /// (full `[0, 65535]` range).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgb_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgb_u16(buf)?;
    Ok(self)
  }
  /// In-place variant.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgb_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(3)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgb_u16 = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **8-bit** RGBA output buffer. P416 has no alpha
  /// plane, so alpha = `0xFF` (opaque).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba(mut self, buf: &'a mut [u8]) -> Result<Self, MixedSinkerError> {
    self.set_rgba(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba`](Self::with_rgba).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba(&mut self, buf: &'a mut [u8]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaBuffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba = Some(buf);
    Ok(self)
  }

  /// Attaches a packed **`u16`** RGBA output buffer. Full-range output
  /// `[0, 65535]`; alpha element is `0xFFFF`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_rgba_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
    self.set_rgba_u16(buf)?;
    Ok(self)
  }
  /// In-place variant of [`with_rgba_u16`](Self::with_rgba_u16).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_rgba_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
    let expected = self.frame_elems(4)?;
    if buf.len() < expected {
      return Err(MixedSinkerError::InsufficientRgbaU16Buffer(
        InsufficientBuffer::new(expected, buf.len()),
      ));
    }
    self.rgba_u16 = Some(buf);
    Ok(self)
  }
}

impl<R, const BE: bool> P416Sink<BE> for MixedSinker<'_, P416<BE>, R> {}

impl<R, const BE: bool> PixelSink for MixedSinker<'_, P416<BE>, R> {
  type Input<'r> = P416Row<'r>;
  type Error = MixedSinkerError;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn kernel_matrix(&self) -> crate::KernelMatrix {
    self.kernel_matrix
  }
  fn begin_frame(&mut self, width: u32, height: u32) -> Result<(), Self::Error> {
    check_dimensions_match(self.width, self.height, width, height)?;
    reset_high_bit_yuv_streams(self);
    Ok(())
  }

  fn process(&mut self, row: P416Row<'_>) -> Result<(), Self::Error> {
    const BITS: u32 = 16;
    let w = self.width;
    let h = self.height;
    let idx = row.row();
    let use_simd = self.simd;

    if row.y().len() != w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::Y16,
        idx,
        w,
        row.y().len(),
      )));
    }
    if row.uv_full().len() != 2 * w {
      return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
        RowSlice::UvFull16,
        idx,
        2 * w,
        row.uv_full().len(),
      )));
    }
    if idx >= self.height {
      return Err(MixedSinkerError::RowIndexOutOfRange(
        RowIndexOutOfRange::new(idx, self.height),
      ));
    }

    let Self {
      rgb,
      rgb_u16,
      rgba,
      rgba_u16,
      luma,
      hsv,
      rgb_scratch,
      rgb_scratch_u16,
      luma_scratch_u16,
      rgb_stream,
      rgb_stream_u16,
      luma_stream_u16,
      rgb_filter_stream,
      rgb_filter_stream_u16,
      luma_filter_stream_u16,
      resample_outputs,
      plan,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      native_planar_u16,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_y_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_u_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      p0xx_v_half,
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      frozen_native_route,
      ..
    } = self;

    // Non-identity plan: filter branches first (no native fast tier); an area
    // plan routes native-or-row-stage. See the P410 impl for the full
    // rationale. At 16 bits the Y de-pack shift `>> (16 - BITS)` is `>> 0`, and
    // the dedicated 16-bit kernel family (`p416_to_rgb*`) is used; the native
    // max is `u16::MAX`, so the native-depth clamp is a value no-op.
    if let Some(plan) = plan.as_ref() {
      let matrix = row.matrix();
      let full_range = row.full_range();
      let (y, uv_full) = (row.y(), row.uv_full());
      if plan.kind().is_filter() {
        return packed_yuv444_triple_filter_resample::<BITS>(
          rgb_filter_stream,
          rgb_filter_stream_u16,
          luma_filter_stream_u16,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          &mut None,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          luma_scratch_u16,
          w,
          plan,
          idx,
          use_simd,
          matrix,
          full_range,
          |scratch| {
            p416_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            p416_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
          },
          |scratch| {
            for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
              let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
              *dst = logical >> (16 - BITS);
            }
          },
        );
      }
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let need_output = luma.is_some()
        || rgb.is_some()
        || rgba.is_some()
        || rgb_u16.is_some()
        || rgba_u16.is_some()
        || hsv.is_some();
      // The RFC #238 splice stage. A filter plan already returned above, so
      // `area_plan` is true and the selector reproduces the former `*native`
      // boolean bit-for-bit (`cfg!` is true wherever this block compiles).
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      let take_native = matches!(
        select_insertion_point(
          AveragingDomain::Encoded,
          InsertionContext {
            native_eligible: cfg!(all(feature = "yuv-semi-planar", feature = "yuv-planar")),
            with_native: *native,
            area_plan: true,
          },
        ),
        InsertionPoint::NativeCodes
      );
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if need_output
        && let Some(frozen) = *frozen_native_route
        && frozen != take_native
      {
        return Err(MixedSinkerError::NativeRouteChanged(
          NativeRouteChanged::new(idx),
        ));
      }
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if take_native {
        p4xx_process_native::<BITS, BE>(
          plan,
          native_planar_u16,
          p0xx_y_half,
          p0xx_u_half,
          p0xx_v_half,
          resample_outputs,
          rgb,
          rgba,
          rgb_u16,
          rgba_u16,
          luma,
          hsv,
          rgb_scratch,
          rgb_scratch_u16,
          y,
          uv_full,
          matrix,
          full_range,
          idx,
          w,
          h,
          use_simd,
        )?;
        if frozen_native_route.is_none() && need_output {
          *frozen_native_route = Some(true);
        }
        return Ok(());
      }
      packed_yuv444_triple_resample::<BITS>(
        rgb_stream,
        rgb_stream_u16,
        luma_stream_u16,
        resample_outputs,
        rgb,
        rgba,
        rgb_u16,
        rgba_u16,
        luma,
        &mut None,
        hsv,
        rgb_scratch,
        rgb_scratch_u16,
        luma_scratch_u16,
        w,
        plan,
        idx,
        use_simd,
        matrix,
        full_range,
        |scratch| p416_to_rgb_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE),
        |scratch| {
          p416_to_rgb_u16_row_endian(y, uv_full, scratch, w, matrix, full_range, use_simd, BE)
        },
        |scratch| {
          for (dst, &s) in scratch[..w].iter_mut().zip(y.iter()) {
            let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
            *dst = logical >> (16 - BITS);
          }
        },
      )?;
      #[cfg(all(feature = "yuv-semi-planar", feature = "yuv-planar"))]
      if frozen_native_route.is_none() && need_output {
        *frozen_native_route = Some(false);
      }
      return Ok(());
    }

    let one_plane_start = idx * w;
    let one_plane_end = one_plane_start + w;

    // Resolve the output set up front so the atomicity preflight below runs
    // before any output row is written.
    let want_rgb = rgb.is_some();
    let want_rgba = rgba.is_some();
    let want_hsv = hsv.is_some();

    // Atomicity preflight (#308, cf. the crate's #180 resample fix and the
    // high-bit 4:2:0 p0xx / yuv420p siblings): reserve the only growable row
    // scratch this identity row can touch — the u8 RGB row buffer — BEFORE any
    // output row is written (the luma plane below, then the u16 RGB / RGBA
    // fan-out), so an allocator refusal returns a typed `AllocationFailed` and
    // leaves the output frame untouched rather than partially mutated. At 4:4:4
    // the chroma is full-resolution (no upsampling), but the output staging
    // matches 4:2:0: the u16 RGB / RGBA outputs write straight into their caller
    // buffers (the rgb_u16 plane itself stages the rgba_u16 expand) and never
    // grow a scratch, and these formats expose no luma_u16. The allocating
    // (rgb=None) arm of `rgb_row_buf_or_scratch` is reached exactly when a colour
    // decode needs an RGB row but no caller RGB buffer is borrowable —
    // `want_hsv && want_rgba && !want_rgb`. The later decode reuses the
    // already-sized buffer, so the default path is byte-identical; only the
    // failure-path ordering changes.
    if want_hsv && want_rgba && !want_rgb {
      rgb_row_buf_or_scratch(
        rgb.as_deref_mut(),
        rgb_scratch,
        one_plane_start,
        one_plane_end,
        w,
        h,
      )?;
    }

    if let Some(luma) = luma.as_deref_mut() {
      let dst = &mut luma[one_plane_start..one_plane_end];
      for (d, &s) in dst.iter_mut().zip(row.y().iter()) {
        // Normalize BE-encoded wire bytes to host-native before the
        // luma downshift — see P010 luma path for rationale.
        let logical = if BE { u16::from_be(s) } else { u16::from_le(s) };
        *d = (logical >> 8) as u8;
      }
    }

    // ===== u16 RGB / RGBA path (Strategy A) =====
    let want_rgb_u16 = rgb_u16.is_some();
    let want_rgba_u16 = rgba_u16.is_some();

    if want_rgba_u16 && !want_rgb_u16 {
      let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
      let rgba_u16_row =
        rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
      p416_to_rgba_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgba_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
    } else if want_rgb_u16 {
      let rgb_u16_buf = rgb_u16.as_deref_mut().unwrap();
      let rgb_plane_end =
        one_plane_end
          .checked_mul(3)
          .ok_or(MixedSinkerError::GeometryOverflow(GeometryOverflow::new(
            w, h, 3,
          )))?;
      let rgb_plane_start = one_plane_start * 3;
      let rgb_u16_row = &mut rgb_u16_buf[rgb_plane_start..rgb_plane_end];
      p416_to_rgb_u16_row_endian(
        row.y(),
        row.uv_full(),
        rgb_u16_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      if want_rgba_u16 {
        let rgba_u16_buf = rgba_u16.as_deref_mut().unwrap();
        let rgba_u16_row =
          rgba_u16_plane_row_slice(rgba_u16_buf, one_plane_start, one_plane_end, w, h)?;
        expand_rgb_u16_to_rgba_u16_row::<BITS>(rgb_u16_row, rgba_u16_row, w);
      }
    }

    // ===== u8 RGB / RGBA / HSV path (Strategy A) =====
    // HSV-without-RGB-or-RGBA goes through the direct `p416_to_hsv_row`
    // kernel (no source-width RGB scratch) — the 4:4:4 full-width-UV twin
    // of the P016 path. When RGB or RGBA is also attached the RGB kernel
    // runs anyway, so HSV derives off that buffer for free and
    // `need_rgb_kernel` keeps it alive.
    let want_hsv_direct = want_hsv && !want_rgb && !want_rgba;
    let need_rgb_kernel = want_rgb || (want_hsv && want_rgba);

    if want_hsv_direct {
      let hsv = hsv.as_mut().expect("want_hsv_direct implies hsv attached");
      let (h, s, v) = hsv.hsv();
      p416_to_hsv_row_endian(
        row.y(),
        row.uv_full(),
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if want_rgba && !need_rgb_kernel {
      let rgba_buf = rgba.as_deref_mut().unwrap();
      let rgba_row = rgba_plane_row_slice(rgba_buf, one_plane_start, one_plane_end, w, h)?;
      p416_to_rgba_row_endian(
        row.y(),
        row.uv_full(),
        rgba_row,
        w,
        row.matrix(),
        row.full_range(),
        use_simd,
        BE,
      );
      return Ok(());
    }

    if !need_rgb_kernel {
      return Ok(());
    }

    let rgb_row = rgb_row_buf_or_scratch(
      rgb.as_deref_mut(),
      rgb_scratch,
      one_plane_start,
      one_plane_end,
      w,
      h,
    )?;

    p416_to_rgb_row_endian(
      row.y(),
      row.uv_full(),
      rgb_row,
      w,
      row.matrix(),
      row.full_range(),
      use_simd,
      BE,
    );

    if let Some(hsv) = hsv.as_mut() {
      let (h, s, v) = hsv.hsv();
      rgb_to_hsv_row(
        rgb_row,
        &mut h[one_plane_start..one_plane_end],
        &mut s[one_plane_start..one_plane_end],
        &mut v[one_plane_start..one_plane_end],
        w,
        use_simd,
      );
    }

    if let Some(buf) = rgba.as_deref_mut() {
      let rgba_row = rgba_plane_row_slice(buf, one_plane_start, one_plane_end, w, h)?;
      expand_rgb_to_rgba_row(rgb_row, rgba_row, w);
    }

    Ok(())
  }
}