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
//! Sinker impls for high-bit-depth planar GBR source formats (Tier 10b).
//!
//! Covers all nine high-bit formats:
//! - `Gbrp9` / `Gbrp10` / `Gbrp12` / `Gbrp14` / `Gbrp16` — three planes
//!   (G, B, R), no alpha. `AV_PIX_FMT_GBRP{9,10,12,14,16}LE`.
//! - `Gbrap10` / `Gbrap12` / `Gbrap14` / `Gbrap16` — four planes
//!   (G, B, R, A), real per-pixel α. `AV_PIX_FMT_GBRAP{10,12,14,16}LE`.
//!   (FFmpeg has no 9-bit Gbrap variant.)
//!
//! # Output paths
//!
//! - `with_rgb` — interleave G/B/R → packed `R, G, B` bytes (downshift by
//!   `BITS - 8`).
//! - `with_rgb_u16` — interleave G/B/R → packed `R, G, B` u16 elements at
//!   native depth (no shift; values in `[0, (1 << BITS) - 1]`).
//! - `with_rgba` — for `GbrpN`: standalone `gbr_to_rgba_opaque_high_bit_row`
//!   (α = `0xFF`); combo with `with_rgb` uses Strategy A (expand). For
//!   `GbrapN`: standalone `gbra_to_rgba_high_bit_row` (real α downshifted by
//!   `BITS - 8`); combo with `with_rgb` uses Strategy A+ (expand + α-overwrite
//!   from source plane).
//! - `with_rgba_u16` — same as above but u16 output; opaque α =
//!   `(1 << BITS) - 1` for `GbrpN`; real α at native depth for `GbrapN`.
//! - `with_luma` — derived from staged RGB (u8) via `rgb_to_luma_row`.
//! - `with_luma_u16` — derived directly from native-precision G/B/R planes via
//!   `gbr_to_luma_u16_high_bit_row`. Uses Q15 coefficients and i64 intermediates
//!   (required for BITS=16). Produces full native-precision output — no 256-level
//!   banding from the old u8-intermediate approach.
//! - `with_hsv` — derived from staged RGB via `rgb_to_hsv_row`.
//!
//! # Strategy A+ (Gbrap combo path)
//!
//! When both `with_rgb` and `with_rgba` are attached to a `GbrapN` sinker:
//! 1. Stage G/B/R → RGB row.
//! 2. Expand RGB → RGBA (α = `0xFF` stub).
//! 3. Overwrite α bytes from the source A plane via
//!    `alpha_extract::copy_alpha_plane_u16_to_u8::<BITS>`.
//!
//! This avoids two calls to the full 4-channel kernel and matches the shape
//! of the 8-bit `Gbrap` sinker.
//!
//! # Fused area-resample (`with_resampler`)
//!
//! The `GbrpN` sinkers are generic over `R: Resampler`. On a non-identity
//! plan each scatters its native-depth G/B/R planes into a source-width
//! packed `u16` RGB row (`gbr_to_rgb_u16_high_bit_row`) and feeds the shared
//! high-bit packed-RGB resample tail
//! ([`packed_rgb_u16_resample_emit`](super::packed_rgb_u16_resample_emit) and
//! siblings) — the `u16` analog of the 8-bit `Gbrp` routing and the same tail
//! the `Rgb48` / `Bgr48` sources take, parameterized by the source depth
//! `BITS` so the u8 narrowing (`>> (BITS - 8)`) and the opaque `rgba_u16`
//! alpha (`(1 << BITS) - 1`) track the native depth rather than a hard-coded
//! 16. Binning runs at native depth: `rgb_u16` / `rgba_u16` copy the binned
//! row, while `rgb` / `rgba` / `luma` / `hsv` derive from a single narrowing
//! of it.
//!
//! `luma_u16` is computed at full native precision from the binned native
//! RGB — via `rgb_to_luma_u16_native_row`, the packed / runtime-`bits` twin
//! of the direct path's `gbr_to_luma_u16_high_bit_row` — so a resampled
//! `GbrpN` `luma_u16` is byte-identical to the direct path: full parity on
//! every output. (`Rgb48` / `Bgr48` keep the tail's narrowed `luma_u16`,
//! which matches their own narrowed direct path.)
//!
//! The `GbrapN` sinkers are likewise generic over `R: Resampler`. On a
//! non-identity plan each de-interleaves its native-depth G/B/R/A planes
//! into a canonical host-native `R, G, B, A` u16 row
//! (`gbra_to_rgba_u16_high_bit_row`) and feeds the **alpha-aware**
//! 4-channel high-bit packed RGBA tail
//! ([`packed_rgba_u16_resample`](super::packed_rgba_u16_resample)) at
//! `BITS` — the `u16` analog of the 8-bit `Gbrap` routing and the same
//! tail `Rgba64` / `Bgra64` take. Resampled alpha is a real native area
//! mean (not expand-stubbed), and under
//! [`AlphaMode::Premultiplied`](super::AlphaMode::Premultiplied) the color
//! is binned premultiplied and un-premultiplied per output row. The
//! per-format default is straight alpha. A straight rgb-only sink (alpha
//! dropped) keeps the 3-channel u16 RGB path with no regression.

use super::{
  GeometryOverflow, InsufficientBuffer, MixedSinker, MixedSinkerError, RowIndexOutOfRange,
  RowShapeMismatch, RowSlice, check_dimensions_match, check_frozen_alpha_mode,
  packed_rgb_u16_resample, packed_rgb_u16_resample_filter, packed_rgba_u16_filter_resample,
  packed_rgba_u16_resample, rgb_row_buf_or_scratch, rgba_plane_row_slice, rgba_u16_plane_row_slice,
};
use crate::{
  PixelSink,
  row::{
    alpha_extract, expand_rgb_to_rgba_row, expand_rgb_u16_to_rgba_u16_row,
    gbr_to_luma_u16_high_bit_row, gbr_to_rgb_high_bit_row, gbr_to_rgb_u16_high_bit_row,
    gbr_to_rgba_opaque_high_bit_row, gbr_to_rgba_opaque_u16_high_bit_row,
    gbra_to_rgba_high_bit_row, gbra_to_rgba_u16_high_bit_row, rgb_to_hsv_row, rgb_to_luma_row,
  },
};

// ---- Gbrp accessors (via format-specific impl blocks) -------------------
//
// Each format gets its own impl block. The pattern is identical for all 5
// depths — only the const BITS value and the concrete Row/Sink types differ.
// We use a local macro to avoid 400 lines of repetition.
//
// The macro generates:
//   impl<'a> MixedSinker<'a, $marker> { with_rgb_u16 / set_rgb_u16 /
//                                        with_rgba / set_rgba /
//                                        with_rgba_u16 / set_rgba_u16 /
//                                        with_luma_u16 / set_luma_u16 }
//   impl $sink for MixedSinker<'_, $marker> {}
//   impl PixelSink for MixedSinker<'_, $marker> { ... }

macro_rules! impl_gbrp_high_bit {
  ($marker:ident, $sink:ident, $row:ident, $bits:literal) => {
    impl<'a, R, const BE: bool> MixedSinker<'a, crate::source::$marker<BE>, R> {
      /// Attaches a packed **`u16`** RGB output buffer. Samples are in
      /// `[0, (1 << BITS) - 1]` (native depth, no depth conversion).
      /// Length is measured in `u16` **elements** (`width x height x 3`).
      #[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 of [`with_rgb_u16`](Self::with_rgb_u16).
      #[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. Alpha is opaque
      /// (`0xFF`) — the GBR format has no alpha plane. Length in bytes
      /// (`width x height x 4`).
      #[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. Alpha is opaque
      /// (`(1 << BITS) - 1`). Length in `u16` elements (`width x height x 4`).
      #[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)
      }

      /// Attaches a `u16` luma output buffer. Luma is computed directly from
      /// the native-precision G/B/R planes via Q15 coefficients, avoiding the
      /// 256-level banding that the old u8-intermediate path produced. Values
      /// are in `[0, (1 << BITS) - 1]` (full-range) or
      /// `[16 << (BITS - 8), 235 << (BITS - 8)]` (limited-range). Length in
      /// `u16` elements (`width x height`).
      #[cfg_attr(not(tarpaulin), inline(always))]
      pub fn with_luma_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
        self.set_luma_u16(buf)?;
        Ok(self)
      }
      /// In-place variant of [`with_luma_u16`](Self::with_luma_u16).
      #[cfg_attr(not(tarpaulin), inline(always))]
      pub fn set_luma_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
        let expected = self.frame_pixels()?;
        if buf.len() < expected {
          return Err(MixedSinkerError::InsufficientLumaU16Buffer(
            InsufficientBuffer::new(expected, buf.len()),
          ));
        }
        self.luma_u16 = Some(buf);
        Ok(self)
      }
    }

    impl<R, const BE: bool> crate::source::$sink<BE>
      for MixedSinker<'_, crate::source::$marker<BE>, R>
    {
    }

    impl<R, const BE: bool> PixelSink for MixedSinker<'_, crate::source::$marker<BE>, R> {
      type Input<'r> = crate::source::$row<'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)?;
        if let Some(stream) = self.rgb_stream_u16.as_mut() {
          stream.reset();
        }
        if let Some(stream) = self.rgb_filter_stream_u16.as_mut() {
          stream.reset();
        }
        self.resample_outputs = None;
        Ok(())
      }

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

        if row.g().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::GPlane,
            idx,
            w,
            row.g().len(),
          )));
        }
        if row.b().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::BPlane,
            idx,
            w,
            row.b().len(),
          )));
        }
        if row.r().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::RPlane,
            idx,
            w,
            row.r().len(),
          )));
        }
        if idx >= h {
          return Err(MixedSinkerError::RowIndexOutOfRange(
            RowIndexOutOfRange::new(idx, h),
          ));
        }

        // Non-identity plan: scatter the native-depth G/B/R planes into a
        // source-width packed u16 RGB row and feed the shared high-bit
        // packed-RGB resample tail (parameterized by BITS) — the u16 analog
        // of the `Rgb48` routing. Binning runs at native depth; rgb_u16
        // / rgba_u16 copy the binned row, u8 / hsv derive from its
        // `>> (BITS - 8)` narrowing, and luma_u16 is computed at native
        // precision from the binned RGB (the packed twin of the direct
        // path's `gbr_to_luma_u16_high_bit_row`). The plan's span kind picks
        // the engine — the integer area stream or the signed-coefficient
        // filter stream — both binning the same staged native-u16 row.
        // Freeze the output set and sequence-check before staging so a
        // no-output sink stays a no-op and an out-of-sequence row is rejected
        // without the allocation.
        if let Some(plan) = self.plan.as_ref() {
          let Self {
            rgb,
            rgb_u16,
            rgba,
            rgba_u16,
            luma,
            luma_u16,
            hsv,
            rgb_scratch,
            rgb_scratch_u16,
            rgb_stream_u16,
            rgb_filter_stream_u16,
            resample_outputs,
            ..
          } = self;
          // Transactional resample (RFC #238 tail-collapse): scatter the native-depth
          // G/B/R planes into the source-width packed-u16 RGB scratch and feed the
          // shared 3-channel u16 helper (`SRC_BITS = BITS`, `NATIVE_LUMA16 = true`
          // for native-precision `luma_u16` parity); the span kind picks the engine.
          return match plan.kind() {
            crate::resample::SpanKind::Area => packed_rgb_u16_resample::<BITS, true>(
              rgb_stream_u16,
              resample_outputs,
              rgb,
              rgba,
              luma,
              rgb_u16,
              rgba_u16,
              luma_u16,
              hsv,
              rgb_scratch_u16,
              rgb_scratch,
              w,
              plan,
              idx,
              use_simd,
              row.matrix(),
              row.full_range(),
              |src_u16| {
                gbr_to_rgb_u16_high_bit_row::<BITS, BE>(
                  row.g(),
                  row.b(),
                  row.r(),
                  src_u16,
                  w,
                  use_simd,
                )
              },
            ),
            crate::resample::SpanKind::Filter => packed_rgb_u16_resample_filter::<BITS, true>(
              rgb_filter_stream_u16,
              resample_outputs,
              rgb,
              rgba,
              luma,
              rgb_u16,
              rgba_u16,
              luma_u16,
              hsv,
              rgb_scratch_u16,
              rgb_scratch,
              w,
              plan,
              idx,
              use_simd,
              row.matrix(),
              row.full_range(),
              |src_u16| {
                gbr_to_rgb_u16_high_bit_row::<BITS, BE>(
                  row.g(),
                  row.b(),
                  row.r(),
                  src_u16,
                  w,
                  use_simd,
                )
              },
            ),
          };
        }

        let Self {
          rgb,
          rgb_u16,
          rgba,
          rgba_u16,
          luma,
          luma_u16,
          hsv,
          rgb_scratch,
          ..
        } = self;
        let one_plane_start = idx * w;
        let one_plane_end = one_plane_start + w;
        let g_in = row.g();
        let b_in = row.b();
        let r_in = row.r();

        // ---- u16 RGB / RGBA output (Strategy A) -------------------------
        //
        // Native-depth path: no u8 staging needed. When both rgb_u16 and
        // rgba_u16 are requested, stage into rgb_u16 then expand; when only
        // rgba_u16 is requested, use the opaque direct kernel.
        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)?;
          gbr_to_rgba_opaque_u16_high_bit_row::<BITS, BE>(
            g_in,
            b_in,
            r_in,
            rgba_u16_row,
            w,
            use_simd,
          );
        } 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];
          gbr_to_rgb_u16_high_bit_row::<BITS, BE>(g_in, b_in, r_in, rgb_u16_row, w, use_simd);
          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);
          }
        }

        // ---- native-depth luma output (no RGB staging needed) -----------
        // Compute luma_u16 first — it reads G/B/R planes directly without
        // going through the u8 staging path, so it is independent of whether
        // RGB staging happens below.
        if let Some(luma_u16_buf) = luma_u16.as_deref_mut() {
          gbr_to_luma_u16_high_bit_row::<BITS, BE>(
            g_in,
            b_in,
            r_in,
            &mut luma_u16_buf[one_plane_start..one_plane_end],
            w,
            row.matrix(),
            row.full_range(),
            use_simd,
          );
        }

        // ---- u8 RGB / RGBA / luma / HSV output (Strategy A) -----------
        let want_rgb = rgb.is_some();
        let want_rgba = rgba.is_some();
        let want_luma = luma.is_some();
        let want_hsv = hsv.is_some();
        let need_rgb_staging = want_rgb || want_luma || want_hsv;

        // RGBA-only fast path: use the 4-channel opaque kernel directly.
        if want_rgba && !need_rgb_staging {
          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)?;
          gbr_to_rgba_opaque_high_bit_row::<BITS, BE>(g_in, b_in, r_in, rgba_row, w, use_simd);
          return Ok(());
        }

        if !need_rgb_staging && !want_rgba {
          return Ok(());
        }

        // Stage RGB once (into user buffer or scratch).
        let rgb_row = rgb_row_buf_or_scratch(
          rgb.as_deref_mut(),
          rgb_scratch,
          one_plane_start,
          one_plane_end,
          w,
          h,
        )?;
        gbr_to_rgb_high_bit_row::<BITS, BE>(g_in, b_in, r_in, rgb_row, w, use_simd);

        if let Some(luma) = luma.as_deref_mut() {
          rgb_to_luma_row(
            rgb_row,
            &mut luma[one_plane_start..one_plane_end],
            w,
            row.matrix(),
            row.full_range(),
            use_simd,
          );
        }

        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() {
          // Strategy A: expand already-computed rgb_row → rgba (opaque).
          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(())
      }
    }
  };
}

macro_rules! impl_gbrap_high_bit {
  ($marker:ident, $sink:ident, $row:ident, $bits:literal) => {
    impl<'a, R, const BE: bool> MixedSinker<'a, crate::source::$marker<BE>, R> {
      /// Attaches a packed **`u16`** RGB output buffer. Samples are in
      /// `[0, (1 << BITS) - 1]` (native depth, no depth conversion).
      /// Length is measured in `u16` **elements** (`width x height x 3`).
      #[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 of [`with_rgb_u16`](Self::with_rgb_u16).
      #[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. Alpha is sourced
      /// from the source A plane, downshifted by `BITS - 8`.
      /// Length in bytes (`width x height x 4`).
      #[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. Alpha is sourced
      /// from the source A plane at native depth (no depth conversion).
      /// Length in `u16` elements (`width x height x 4`).
      #[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)
      }

      /// Attaches a `u16` luma output buffer. Same derivation as `GbrpN` —
      /// computed directly from native-precision G/B/R planes via Q15
      /// coefficients (native-depth, no banding). Length in `u16` elements
      /// (`width x height`).
      #[cfg_attr(not(tarpaulin), inline(always))]
      pub fn with_luma_u16(mut self, buf: &'a mut [u16]) -> Result<Self, MixedSinkerError> {
        self.set_luma_u16(buf)?;
        Ok(self)
      }
      /// In-place variant of [`with_luma_u16`](Self::with_luma_u16).
      #[cfg_attr(not(tarpaulin), inline(always))]
      pub fn set_luma_u16(&mut self, buf: &'a mut [u16]) -> Result<&mut Self, MixedSinkerError> {
        let expected = self.frame_pixels()?;
        if buf.len() < expected {
          return Err(MixedSinkerError::InsufficientLumaU16Buffer(
            InsufficientBuffer::new(expected, buf.len()),
          ));
        }
        self.luma_u16 = Some(buf);
        Ok(self)
      }
    }

    impl<R, const BE: bool> crate::source::$sink<BE>
      for MixedSinker<'_, crate::source::$marker<BE>, R>
    {
    }

    impl<R, const BE: bool> PixelSink for MixedSinker<'_, crate::source::$marker<BE>, R> {
      type Input<'r> = crate::source::$row<'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)?;
        if let Some(stream) = self.rgb_stream_u16.as_mut() {
          stream.reset();
        }
        if let Some(stream) = self.rgba_stream_u16.as_mut() {
          stream.reset();
        }
        if let Some(stream) = self.rgb_filter_stream_u16.as_mut() {
          stream.reset();
        }
        if let Some(stream) = self.rgba_filter_stream_u16.as_mut() {
          stream.reset();
        }
        self.resample_outputs = None;
        self.frozen_alpha_mode = Some(self.alpha_mode);
        Ok(())
      }

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

        if row.g().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::GPlane,
            idx,
            w,
            row.g().len(),
          )));
        }
        if row.b().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::BPlane,
            idx,
            w,
            row.b().len(),
          )));
        }
        if row.r().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::RPlane,
            idx,
            w,
            row.r().len(),
          )));
        }
        if row.a().len() != w {
          return Err(MixedSinkerError::RowShapeMismatch(RowShapeMismatch::new(
            RowSlice::AFull,
            idx,
            w,
            row.a().len(),
          )));
        }
        if idx >= h {
          return Err(MixedSinkerError::RowIndexOutOfRange(
            RowIndexOutOfRange::new(idx, h),
          ));
        }

        // Non-identity plan. Route the alpha-aware 4-channel u16 tail when
        // resampled alpha would be dropped (rgba / rgba_u16 attached) or the
        // color must be alpha-weighted (premultiplied); otherwise the
        // rgb-only straight outputs keep the 3-channel u16 RGB path.
        // `GbrapN` de-interleaves its native-depth G/B/R/A planes into the
        // canonical host-native RGBA row (`gbra_to_rgba_u16_high_bit_row`)
        // the high-bit packed RGBA tail bins at `BITS`, so resampled alpha
        // is a real native area mean and luma derives from the binned RGB.
        // The span kind picks the engine: the integer area stream or the
        // signed-coefficient filter stream (PIL parity, straight alpha only).
        if self.plan.is_some() {
          let alpha_mode = self.alpha_mode;
          let matrix = row.matrix();
          let full_range = row.full_range();
          let g_in = row.g();
          let b_in = row.b();
          let r_in = row.r();
          let a_in = row.a();
          let Self {
            rgb,
            rgb_u16,
            rgba,
            rgba_u16,
            luma,
            luma_u16,
            hsv,
            rgb_scratch,
            rgb_scratch_u16,
            rgba_scratch_u16,
            rgba_color_scratch_u16,
            rgb_stream_u16,
            rgba_stream_u16,
            rgb_filter_stream_u16,
            rgba_filter_stream_u16,
            resample_outputs,
            frozen_alpha_mode,
            plan,
            ..
          } = self;
          let plan = plan.as_ref().expect("plan.is_some() checked above");
          // The alpha mode is snapshotted at begin_frame; reject a mid-frame
          // change here, before route selection (it picks the 4-channel vs
          // 3-channel route), so a flip can neither reroute nor mix modes.
          check_frozen_alpha_mode(*frozen_alpha_mode, alpha_mode, idx)?;
          match plan.kind() {
            crate::resample::SpanKind::Area => {
              if rgba.is_some() || rgba_u16.is_some() || alpha_mode.is_premultiplied() {
                return packed_rgba_u16_resample::<BITS, true, false>(
                  rgba_stream_u16,
                  // No native-Y luma stream: `GbrapN` luma_u16 is native-precision
                  // color-derived (`NATIVE_LUMA16 = true`, `NATIVE_Y_LUMA = false`),
                  // so the Y stream / scratch / de-interleave are inert.
                  &mut None,
                  resample_outputs,
                  rgb,
                  rgba,
                  rgb_u16,
                  rgba_u16,
                  luma,
                  luma_u16,
                  hsv,
                  rgba_scratch_u16,
                  rgba_color_scratch_u16,
                  rgb_scratch,
                  rgb_scratch_u16,
                  &mut std::vec::Vec::new(),
                  w,
                  plan,
                  idx,
                  use_simd,
                  alpha_mode,
                  matrix,
                  full_range,
                  |dst| {
                    gbra_to_rgba_u16_high_bit_row::<BITS, BE>(
                      g_in, b_in, r_in, a_in, dst, w, use_simd,
                    )
                  },
                  |_| {},
                );
              }
              // Straight rgb-only (alpha dropped): scatter the native-depth
              // G/B/R planes into the source-width packed u16 RGB row and feed
              // the 3-channel high-bit tail (luma_u16 at native precision —
              // `NATIVE_LUMA16 = true` — for parity with the direct path).
              // Transactional 3-channel u16 area resample (RFC #238 tail-collapse).
              return packed_rgb_u16_resample::<BITS, true>(
                rgb_stream_u16,
                resample_outputs,
                rgb,
                rgba,
                luma,
                rgb_u16,
                rgba_u16,
                luma_u16,
                hsv,
                rgb_scratch_u16,
                rgb_scratch,
                w,
                plan,
                idx,
                use_simd,
                matrix,
                full_range,
                |src_u16| {
                  gbr_to_rgb_u16_high_bit_row::<BITS, BE>(g_in, b_in, r_in, src_u16, w, use_simd)
                },
              );
            }
            crate::resample::SpanKind::Filter => {
              // Premultiplied alpha has no filter analogue (the filter engine
              // cannot un-premultiply); surface the typed `UnsupportedFilter`
              // via the area tail's reject rather than emit straight-filtered
              // premultiplied color. Straight alpha: filter all four native u16
              // channels independently (PIL RGBA semantics) when alpha survives,
              // else the 3-channel u16 filter for rgb-only outputs.
              if alpha_mode.is_premultiplied() {
                return packed_rgba_u16_resample::<BITS, true, false>(
                  rgba_stream_u16,
                  &mut None,
                  resample_outputs,
                  rgb,
                  rgba,
                  rgb_u16,
                  rgba_u16,
                  luma,
                  luma_u16,
                  hsv,
                  rgba_scratch_u16,
                  rgba_color_scratch_u16,
                  rgb_scratch,
                  rgb_scratch_u16,
                  &mut std::vec::Vec::new(),
                  w,
                  plan,
                  idx,
                  use_simd,
                  alpha_mode,
                  matrix,
                  full_range,
                  |dst| {
                    gbra_to_rgba_u16_high_bit_row::<BITS, BE>(
                      g_in, b_in, r_in, a_in, dst, w, use_simd,
                    )
                  },
                  |_| {},
                );
              }
              if rgba.is_some() || rgba_u16.is_some() {
                return packed_rgba_u16_filter_resample::<BITS, true>(
                  rgba_filter_stream_u16,
                  resample_outputs,
                  rgb,
                  rgba,
                  rgb_u16,
                  rgba_u16,
                  luma,
                  luma_u16,
                  hsv,
                  rgba_scratch_u16,
                  rgba_color_scratch_u16,
                  rgb_scratch,
                  w,
                  plan,
                  idx,
                  use_simd,
                  matrix,
                  full_range,
                  |dst| {
                    gbra_to_rgba_u16_high_bit_row::<BITS, BE>(
                      g_in, b_in, r_in, a_in, dst, w, use_simd,
                    )
                  },
                );
              }
              // Straight rgb-only (alpha dropped): scatter the native-depth
              // G/B/R planes into the source-width packed u16 RGB row and feed
              // the 3-channel high-bit filter tail (luma_u16 at native
              // precision — `NATIVE_LUMA16 = true` — for parity).
              // Transactional 3-channel u16 filter resample (RFC #238 tail-collapse).
              return packed_rgb_u16_resample_filter::<BITS, true>(
                rgb_filter_stream_u16,
                resample_outputs,
                rgb,
                rgba,
                luma,
                rgb_u16,
                rgba_u16,
                luma_u16,
                hsv,
                rgb_scratch_u16,
                rgb_scratch,
                w,
                plan,
                idx,
                use_simd,
                matrix,
                full_range,
                |src_u16| {
                  gbr_to_rgb_u16_high_bit_row::<BITS, BE>(g_in, b_in, r_in, src_u16, w, use_simd)
                },
              );
            }
          }
        }

        let Self {
          rgb,
          rgb_u16,
          rgba,
          rgba_u16,
          luma,
          luma_u16,
          hsv,
          rgb_scratch,
          ..
        } = self;
        let one_plane_start = idx * w;
        let one_plane_end = one_plane_start + w;
        let g_in = row.g();
        let b_in = row.b();
        let r_in = row.r();
        let a_in = row.a();

        // ---- u16 RGB / RGBA output (Strategy A+) -------------------------
        //
        // For GbrapN: rgba_u16 = stage rgb_u16 → expand → α-overwrite from
        // source plane (no depth conv needed — both at native BITS depth).
        let want_rgb_u16 = rgb_u16.is_some();
        let want_rgba_u16 = rgba_u16.is_some();

        if want_rgba_u16 && !want_rgb_u16 {
          // Standalone u16 RGBA — direct 4-channel kernel with real α.
          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)?;
          gbra_to_rgba_u16_high_bit_row::<BITS, BE>(
            g_in,
            b_in,
            r_in,
            a_in,
            rgba_u16_row,
            w,
            use_simd,
          );
        } 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];
          gbr_to_rgb_u16_high_bit_row::<BITS, BE>(g_in, b_in, r_in, rgb_u16_row, w, use_simd);
          if want_rgba_u16 {
            // Strategy A+: expand RGB → RGBA, then overwrite α from source plane.
            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);
            // Overwrite α slot from source plane (native depth, no shift).
            // BE propagated from the parent `GbrapHighBitFrame<'_, BITS, BE>`
            // via the sinker's `MixedSinker<GbrapN<BE>>` monomorphization.
            alpha_extract::copy_alpha_plane_u16::<BITS, BE>(a_in, rgba_u16_row, w, use_simd);
          }
        }

        // ---- native-depth luma output (no RGB staging needed) -----------
        // Compute luma_u16 first — it reads G/B/R planes directly without
        // going through the u8 staging path, so it is independent of whether
        // RGB staging happens below.
        if let Some(luma_u16_buf) = luma_u16.as_deref_mut() {
          gbr_to_luma_u16_high_bit_row::<BITS, BE>(
            g_in,
            b_in,
            r_in,
            &mut luma_u16_buf[one_plane_start..one_plane_end],
            w,
            row.matrix(),
            row.full_range(),
            use_simd,
          );
        }

        // ---- u8 RGB / RGBA / luma / HSV output --------------------------
        let want_rgb = rgb.is_some();
        let want_rgba = rgba.is_some();
        let want_luma = luma.is_some();
        let want_hsv = hsv.is_some();
        let need_rgb_staging = want_rgb || want_luma || want_hsv;

        // RGBA-only fast path — direct 4-channel kernel with real α.
        if want_rgba && !need_rgb_staging {
          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)?;
          gbra_to_rgba_high_bit_row::<BITS, BE>(g_in, b_in, r_in, a_in, rgba_row, w, use_simd);
          return Ok(());
        }

        if !need_rgb_staging && !want_rgba {
          return Ok(());
        }

        // Stage RGB once.
        let rgb_row = rgb_row_buf_or_scratch(
          rgb.as_deref_mut(),
          rgb_scratch,
          one_plane_start,
          one_plane_end,
          w,
          h,
        )?;
        gbr_to_rgb_high_bit_row::<BITS, BE>(g_in, b_in, r_in, rgb_row, w, use_simd);

        if let Some(luma) = luma.as_deref_mut() {
          rgb_to_luma_row(
            rgb_row,
            &mut luma[one_plane_start..one_plane_end],
            w,
            row.matrix(),
            row.full_range(),
            use_simd,
          );
        }

        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() {
          // Strategy A+: expand rgb_row → RGBA (opaque stub), then
          // overwrite α bytes from the source A plane.
          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);
          // BE propagated from the parent frame.
          alpha_extract::copy_alpha_plane_u16_to_u8::<BITS, BE>(a_in, rgba_row, w, use_simd);
        }

        Ok(())
      }
    }
  };
}

// ---- Gbrp formats (no alpha) -------------------------------------------

impl_gbrp_high_bit!(Gbrp9, Gbrp9Sink, Gbrp9Row, 9);
impl_gbrp_high_bit!(Gbrp10, Gbrp10Sink, Gbrp10Row, 10);
impl_gbrp_high_bit!(Gbrp12, Gbrp12Sink, Gbrp12Row, 12);
impl_gbrp_high_bit!(Gbrp14, Gbrp14Sink, Gbrp14Row, 14);
impl_gbrp_high_bit!(Gbrp16, Gbrp16Sink, Gbrp16Row, 16);

// ---- Gbrap formats (with real α plane) ---------------------------------

impl_gbrap_high_bit!(Gbrap10, Gbrap10Sink, Gbrap10Row, 10);
impl_gbrap_high_bit!(Gbrap12, Gbrap12Sink, Gbrap12Row, 12);
impl_gbrap_high_bit!(Gbrap14, Gbrap14Sink, Gbrap14Row, 14);
impl_gbrap_high_bit!(Gbrap16, Gbrap16Sink, Gbrap16Row, 16);