colconv 0.1.0

SIMD-dispatched color-conversion kernels covering the FFmpeg AVPixelFormat space, with a Sink-based API so consumers pick which derived outputs (RGB / Luma / HSV / custom) they want without paying for the ones they don't.
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
//! AVX-512 (F + BW) kernels for 16-bit packed RGB/BGR/RGBA/BGRA sources
//! (Tier 8 finish).
//!
//! ## Format layouts
//!
//! | Format | Elements per pixel | Channel order in memory |
//! |--------|--------------------|------------------------|
//! | Rgb48  | 3 u16              | R, G, B                |
//! | Bgr48  | 3 u16              | B, G, R                |
//! | Rgba64 | 4 u16              | R, G, B, A             |
//! | Bgra64 | 4 u16              | B, G, R, A             |
//!
//! ## Per-format SIMD strategy (32 pixels per outer iteration)
//!
//! ### Rgb48 / Bgr48 (stride-3)
//!
//! 32 pixels = 96 u16 = 192 bytes. Processed as **four** 8-pixel SSE4.1-style
//! half-iterations (each 24 u16, 3 x 128-bit loads) under the AVX-512
//! `target_feature` context. SSE4.1 and SSSE3 are subsets of AVX-512 so
//! `_mm_*` intrinsics are freely available. This avoids complex stride-3
//! cross-lane permutes in 512-bit registers that do not tile cleanly.
//!
//! ### Rgba64 / Bgra64 (stride-4)
//!
//! 32 pixels = 128 u16 = 256 bytes = 4 x `_mm512_loadu_si512`.
//!
//! The deinterleave uses a 3-level `_mm512_unpacklo/hi_epi16` cascade mirroring
//! the AVX2 sibling (xv36.rs pattern), followed by `_mm512_permutexvar_epi64`
//! lane-cross fixup. Produces four `__m512i` channel vectors each holding 32
//! u16 samples in natural order.
//!
//! ## Depth conversion
//!
//! - **u16 → u8:** `_mm512_srli_epi16::<8>` + `_mm512_cvtusepi16_epi8`
//!   (saturating narrow to u8x32). The 256-bit result is stored via a 256-bit
//!   unaligned store.
//! - **u16 → u16:** write 8-pixel chunks via `write_rgb_u16_8` / `write_rgba_u16_8`
//!   (for stride-3 path) or via the `write_rgb_u16_32` / `write_rgba_u16_32`
//!   helpers from the AVX-512 mod (for stride-4 path).
//!
//! ## Scalar tail
//!
//! All kernels handle `width % 32` remaining pixels via the scalar reference.
// Kernels are wired into the dispatcher in the dispatch-wiring step; suppress
// dead_code until then.
#![allow(dead_code)]

use core::arch::x86_64::*;

use super::*;
// Shared deinterleave helper (stride-3, 8-pixel, SSE4.1-level — same masks as
// the AVX2 and SSE4.1 siblings)
/// Deinterleave 8 pixels of stride-3 u16 from three `__m128i` loads into
/// `(ch0, ch1, ch2)` channel vectors, each holding 8 u16 values.
///
/// For Rgb48: `ch0=R`, `ch1=G`, `ch2=B`.
/// For Bgr48: `ch0=B`, `ch1=G`, `ch2=R`; caller swaps on output.
///
/// # Safety
///
/// Caller must hold AVX-512F + AVX-512BW `target_feature` (SSSE3/SSE4.1 are
/// subsets).
#[inline(always)]
unsafe fn deinterleave_rgb48_8px(
  v0: __m128i,
  v1: __m128i,
  v2: __m128i,
) -> (__m128i, __m128i, __m128i) {
  unsafe {
    // ch0 (first channel)
    let ch0_v0 = _mm_setr_epi8(0, 1, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
    let ch0_v1 = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, 2, 3, 8, 9, 14, 15, -1, -1, -1, -1);
    let ch0_v2 = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 5, 10, 11);
    let ch0 = _mm_or_si128(
      _mm_or_si128(_mm_shuffle_epi8(v0, ch0_v0), _mm_shuffle_epi8(v1, ch0_v1)),
      _mm_shuffle_epi8(v2, ch0_v2),
    );

    // ch1 (middle channel — G for both Rgb48 and Bgr48)
    let ch1_v0 = _mm_setr_epi8(2, 3, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
    let ch1_v1 = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, 4, 5, 10, 11, -1, -1, -1, -1, -1, -1);
    let ch1_v2 = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 6, 7, 12, 13);
    let ch1 = _mm_or_si128(
      _mm_or_si128(_mm_shuffle_epi8(v0, ch1_v0), _mm_shuffle_epi8(v1, ch1_v1)),
      _mm_shuffle_epi8(v2, ch1_v2),
    );

    // ch2 (third channel)
    let ch2_v0 = _mm_setr_epi8(4, 5, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
    let ch2_v1 = _mm_setr_epi8(-1, -1, -1, -1, 0, 1, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1);
    let ch2_v2 = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 9, 14, 15);
    let ch2 = _mm_or_si128(
      _mm_or_si128(_mm_shuffle_epi8(v0, ch2_v0), _mm_shuffle_epi8(v1, ch2_v1)),
      _mm_shuffle_epi8(v2, ch2_v2),
    );

    (ch0, ch1, ch2)
  }
}

// Rgba64 / Bgra64 helpers — stride-4, 32-pixel deinterleave (__m512i).
//
// 32 pixels x 4 u16 channels = 128 u16 = 256 bytes.
//
// Layout after 4 contiguous `_mm512_loadu_si512` (each 32 u16 = 8 pixels):
//
//   raw0 = [C0_0..C3_0, C0_1..C3_1, ..., C0_7..C3_7]    (pixels 0-7)
//   raw1 = [C0_8..C3_8, ...,             C0_15..C3_15]   (pixels 8-15)
//   raw2 = [C0_16..C3_16, ...,           C0_23..C3_23]   (pixels 16-23)
//   raw3 = [C0_24..C3_24, ...,           C0_31..C3_31]   (pixels 24-31)
//
// Goal: ch0=[C0_0..C0_31], ch1=[C1_0..C1_31], ... in natural pixel order.
//
// Strategy (mirrors the `xv36.rs` AVX-512 deinterleave):
// 1. Round 1 — two `_mm512_permutex2var_epi16` per channel: gather 16
//    `Cc` values from each consecutive raw pair (raw0,raw1) and
//    (raw2,raw3) into the low 16 lanes of a 512-bit register.
// 2. Round 2 — one `_mm512_permutex2var_epi16` per channel: concatenate
//    the two 16-value half-vectors into the natural 32-lane channel
//    vector.
//
// `_mm512_permutex2var_epi16` (AVX-512BW `vpermt2w`) gives random 5-bit
// gather across two source vectors with no cross-lane restrictions, so
// the channels land directly in pixel-natural order with no fix-up
// permute needed.

// Round-1 index: gather channel 0 from a `(raw_n, raw_{n+1})` pair.
//   Lanes  0..7  pick `raw_n` lanes 0,4,8,12,16,20,24,28 (= channel 0 of
//   the 8 pixels held by `raw_n`).
//   Lanes  8..15 pick `raw_{n+1}` lanes 0,4,...,28 via `idx >= 32` (the
//   permutex2var convention: index `>= 32` selects the second source).
//   Lanes 16..31 are don't-care; `0` is a safe in-range index.
#[rustfmt::skip]
static C0_FROM_PAIR_IDX: [i16; 32] = [
   0,  4,  8, 12, 16, 20, 24, 28,
  32, 36, 40, 44, 48, 52, 56, 60,
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
];

// Round-1 index: gather channel 1 (offset +1 within each pixel quad).
#[rustfmt::skip]
static C1_FROM_PAIR_IDX: [i16; 32] = [
   1,  5,  9, 13, 17, 21, 25, 29,
  33, 37, 41, 45, 49, 53, 57, 61,
   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
];

// Round-1 index: gather channel 2 (offset +2 within each pixel quad).
#[rustfmt::skip]
static C2_FROM_PAIR_IDX: [i16; 32] = [
   2,  6, 10, 14, 18, 22, 26, 30,
  34, 38, 42, 46, 50, 54, 58, 62,
   2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
];

// Round-1 index: gather channel 3 (offset +3 within each pixel quad).
#[rustfmt::skip]
static C3_FROM_PAIR_IDX: [i16; 32] = [
   3,  7, 11, 15, 19, 23, 27, 31,
  35, 39, 43, 47, 51, 55, 59, 63,
   3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
];

// Round-2 index: combine the two 16-pixel half-vectors (low 16 lanes
// each) into a full 32-lane channel vector. Low 16 lanes come from the
// first source (pixels 0-15); high 16 come from the second (pixels
// 16-31, available at lanes 0..16 of that vector → idx 32..47).
#[rustfmt::skip]
static COMBINE_HALVES_IDX: [i16; 32] = [
   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
];

/// Deinterleave 32 pixels of stride-4 u16 (Rgba64 or Bgra64) from four
/// `__m512i` loads into four separate u16x32 channel vectors in natural
/// pixel order.
///
/// Returns `(ch0, ch1, ch2, ch3)` in memory order.
/// For Rgba64: `(R, G, B, A)`. For Bgra64: `(B, G, R, A)`.
///
/// 12 ops total (8 round-1 `vpermt2w` + 4 round-2 `vpermt2w`).
///
/// # Safety
///
/// Caller must hold AVX-512F + AVX-512BW `target_feature` (BW provides
/// `vpermt2w`, the u16 cross-vector permute).
#[inline(always)]
unsafe fn deinterleave_rgba64_32px(
  raw0: __m512i,
  raw1: __m512i,
  raw2: __m512i,
  raw3: __m512i,
) -> (__m512i, __m512i, __m512i, __m512i) {
  unsafe {
    let c0_idx = _mm512_loadu_si512(C0_FROM_PAIR_IDX.as_ptr().cast());
    let c1_idx = _mm512_loadu_si512(C1_FROM_PAIR_IDX.as_ptr().cast());
    let c2_idx = _mm512_loadu_si512(C2_FROM_PAIR_IDX.as_ptr().cast());
    let c3_idx = _mm512_loadu_si512(C3_FROM_PAIR_IDX.as_ptr().cast());
    let comb_idx = _mm512_loadu_si512(COMBINE_HALVES_IDX.as_ptr().cast());

    // Round 1: gather each channel from each consecutive raw pair. 16
    // valid lanes in low half; high half is don't-care (overwritten by
    // round 2).
    let ch0_lo = _mm512_permutex2var_epi16(raw0, c0_idx, raw1);
    let ch0_hi = _mm512_permutex2var_epi16(raw2, c0_idx, raw3);
    let ch1_lo = _mm512_permutex2var_epi16(raw0, c1_idx, raw1);
    let ch1_hi = _mm512_permutex2var_epi16(raw2, c1_idx, raw3);
    let ch2_lo = _mm512_permutex2var_epi16(raw0, c2_idx, raw1);
    let ch2_hi = _mm512_permutex2var_epi16(raw2, c2_idx, raw3);
    let ch3_lo = _mm512_permutex2var_epi16(raw0, c3_idx, raw1);
    let ch3_hi = _mm512_permutex2var_epi16(raw2, c3_idx, raw3);

    // Round 2: concatenate the lo halves into a single 32-lane channel
    // vector in natural pixel order.
    let ch0 = _mm512_permutex2var_epi16(ch0_lo, comb_idx, ch0_hi);
    let ch1 = _mm512_permutex2var_epi16(ch1_lo, comb_idx, ch1_hi);
    let ch2 = _mm512_permutex2var_epi16(ch2_lo, comb_idx, ch2_hi);
    let ch3 = _mm512_permutex2var_epi16(ch3_lo, comb_idx, ch3_hi);

    (ch0, ch1, ch2, ch3)
  }
}

// u16 → u8 narrowing via srli::<8> + cvtusepi16_epi8.
/// Narrow a u16x32 vector to u8x32 (256-bit result) via logical right-shift
/// by 8, then saturating unsigned narrow with `_mm512_cvtusepi16_epi8`.
///
/// Equivalent to scalar `(v >> 8) as u8`.
#[inline(always)]
unsafe fn narrow_u16x32_to_u8x32(v: __m512i) -> __m256i {
  unsafe { _mm512_cvtusepi16_epi8(_mm512_srli_epi16::<8>(v)) }
}

// ---- endian byte-swap helpers -----------------------------------------------

/// Compile-time host endianness. `true` on BE targets, `false` on LE.
///
/// Used by the byte-swap helpers below to gate the swap on
/// `BE != HOST_NATIVE_BE`, covering all four `wire x host` quadrants. Mirrors
/// the gate established in `gray.rs` and the canonical NEON
/// `bswap_u16x8_if_be` helper.
const HOST_NATIVE_BE: bool = cfg!(target_endian = "big");

/// Conditionally byte-swap every u16 lane in a `__m128i` so the returned
/// value is in **host-native** byte order regardless of the host endianness.
///
/// The gate is `BE != HOST_NATIVE_BE` — see [`byteswap512_if_be`] for the
/// full truth table. Uses `_mm_shuffle_epi8` (SSSE3, a subset of AVX-512).
#[inline(always)]
unsafe fn byteswap128_if_be<const BE: bool>(v: __m128i) -> __m128i {
  if BE != HOST_NATIVE_BE {
    const MASK: __m128i =
      unsafe { core::mem::transmute([1u8, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14]) };
    unsafe { _mm_shuffle_epi8(v, MASK) }
  } else {
    v
  }
}

/// Conditionally byte-swap every u16 lane in a `__m512i` so the returned
/// value is in **host-native** byte order regardless of the host endianness.
///
/// The gate is `BE != HOST_NATIVE_BE`:
///
/// | wire `BE` | host | gate    | action            |
/// |-----------|------|---------|-------------------|
/// | `false`   | LE   | `false` | no swap (LE→LE)   |
/// | `false`   | BE   | `true`  | swap (LE→BE)      |
/// | `true`    | LE   | `true`  | swap (BE→LE)      |
/// | `true`    | BE   | `false` | no swap (BE→BE)   |
///
/// Uses `_mm512_shuffle_epi8` (AVX-512BW). The unused branch folds at
/// compile time since both `BE` and `HOST_NATIVE_BE` are constants.
#[inline(always)]
unsafe fn byteswap512_if_be<const BE: bool>(v: __m512i) -> __m512i {
  if BE != HOST_NATIVE_BE {
    // Same u16-lane byte-swap mask, broadcast across all 64 bytes.
    const MASK: __m512i = unsafe {
      core::mem::transmute([
        1u8, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11,
        10, 13, 12, 15, 14, 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, 2, 5, 4,
        7, 6, 9, 8, 11, 10, 13, 12, 15, 14,
      ])
    };
    unsafe { _mm512_shuffle_epi8(v, MASK) }
  } else {
    v
  }
}

// Rgb48 (R, G, B — 3 u16 elements per pixel).
/// AVX-512 Rgb48 → packed u8 RGB. 32 pixels per outer iteration.
///
/// Processes four 8-pixel halves (3 x 128-bit loads each) under the
/// AVX-512 target_feature context (SSE4.1/SSSE3 are subsets). Narrows
/// each channel via `>> 8` and writes 8 pixels (24 bytes) per half.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available (caller obligation).
/// 2. `rgb48.len() >= width * 3`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgb48_to_rgb_row<const BE: bool>(
  rgb48: &[u16],
  rgb_out: &mut [u8],
  width: usize,
) {
  debug_assert!(rgb48.len() >= width * 3, "rgb48 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let zero = _mm_setzero_si128();
    let mut x = 0usize;
    // Process 32 pixels per outer iteration (4 x 8-pixel halves).
    while x + 32 <= width {
      let ptr = rgb48.as_ptr().add(x * 3);
      // Half 0: pixels x..x+7
      let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr.cast()));
      let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr.add(8).cast()));
      let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr.add(16).cast()));
      let (r0, g0, b0) = deinterleave_rgb48_8px(v0, v1, v2);
      let r0u8 = narrow_u16x8_to_u8x8(r0, zero);
      let g0u8 = narrow_u16x8_to_u8x8(g0, zero);
      let b0u8 = narrow_u16x8_to_u8x8(b0, zero);
      let mut tmp0 = [0u8; 48];
      write_rgb_16(r0u8, g0u8, b0u8, tmp0.as_mut_ptr());
      core::ptr::copy_nonoverlapping(tmp0.as_ptr(), rgb_out.as_mut_ptr().add(x * 3), 24);

      // Half 1: pixels x+8..x+15
      let ptr8 = ptr.add(24);
      let v3 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr8.cast()));
      let v4 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr8.add(8).cast()));
      let v5 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr8.add(16).cast()));
      let (r1, g1, b1) = deinterleave_rgb48_8px(v3, v4, v5);
      let r1u8 = narrow_u16x8_to_u8x8(r1, zero);
      let g1u8 = narrow_u16x8_to_u8x8(g1, zero);
      let b1u8 = narrow_u16x8_to_u8x8(b1, zero);
      let mut tmp1 = [0u8; 48];
      write_rgb_16(r1u8, g1u8, b1u8, tmp1.as_mut_ptr());
      core::ptr::copy_nonoverlapping(tmp1.as_ptr(), rgb_out.as_mut_ptr().add((x + 8) * 3), 24);

      // Half 2: pixels x+16..x+23
      let ptr16 = ptr.add(48);
      let v6 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr16.cast()));
      let v7 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr16.add(8).cast()));
      let v8 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr16.add(16).cast()));
      let (r2, g2, b2) = deinterleave_rgb48_8px(v6, v7, v8);
      let r2u8 = narrow_u16x8_to_u8x8(r2, zero);
      let g2u8 = narrow_u16x8_to_u8x8(g2, zero);
      let b2u8 = narrow_u16x8_to_u8x8(b2, zero);
      let mut tmp2 = [0u8; 48];
      write_rgb_16(r2u8, g2u8, b2u8, tmp2.as_mut_ptr());
      core::ptr::copy_nonoverlapping(tmp2.as_ptr(), rgb_out.as_mut_ptr().add((x + 16) * 3), 24);

      // Half 3: pixels x+24..x+31
      let ptr24 = ptr.add(72);
      let v9 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr24.cast()));
      let v10 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr24.add(8).cast()));
      let v11 = byteswap128_if_be::<BE>(_mm_loadu_si128(ptr24.add(16).cast()));
      let (r3, g3, b3) = deinterleave_rgb48_8px(v9, v10, v11);
      let r3u8 = narrow_u16x8_to_u8x8(r3, zero);
      let g3u8 = narrow_u16x8_to_u8x8(g3, zero);
      let b3u8 = narrow_u16x8_to_u8x8(b3, zero);
      let mut tmp3 = [0u8; 48];
      write_rgb_16(r3u8, g3u8, b3u8, tmp3.as_mut_ptr());
      core::ptr::copy_nonoverlapping(tmp3.as_ptr(), rgb_out.as_mut_ptr().add((x + 24) * 3), 24);

      x += 32;
    }
    // Scalar tail: remaining < 32 pixels.
    if x < width {
      scalar::rgb48_to_rgb_row::<BE>(&rgb48[x * 3..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Rgb48 → packed u8 RGBA. 32 pixels per outer iteration. Alpha
/// forced to 0xFF.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgb48.len() >= width * 3`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgb48_to_rgba_row<const BE: bool>(
  rgb48: &[u16],
  rgba_out: &mut [u8],
  width: usize,
) {
  debug_assert!(rgb48.len() >= width * 3, "rgb48 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let zero = _mm_setzero_si128();
    let opaque_u16 = _mm_set1_epi16(0x00FFu16 as i16);
    let opaque_u8 = _mm_packus_epi16(opaque_u16, zero);
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgb48.as_ptr().add(x * 3);

      macro_rules! process_half {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (r, g, b) = deinterleave_rgb48_8px(v0, v1, v2);
          let ru8 = narrow_u16x8_to_u8x8(r, zero);
          let gu8 = narrow_u16x8_to_u8x8(g, zero);
          let bu8 = narrow_u16x8_to_u8x8(b, zero);
          let mut tmp = [0u8; 64];
          write_rgba_16(ru8, gu8, bu8, opaque_u8, tmp.as_mut_ptr());
          core::ptr::copy_nonoverlapping(tmp.as_ptr(), rgba_out.as_mut_ptr().add($out_off), 32);
        }};
      }

      process_half!(ptr, x * 4);
      process_half!(ptr.add(24), (x + 8) * 4);
      process_half!(ptr.add(48), (x + 16) * 4);
      process_half!(ptr.add(72), (x + 24) * 4);

      x += 32;
    }
    if x < width {
      scalar::rgb48_to_rgba_row::<BE>(&rgb48[x * 3..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

/// AVX-512 Rgb48 → native-depth u16 RGB (identity repack). 32 pixels per iter.
///
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgb48.len() >= width * 3`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgb48_to_rgb_u16_row<const BE: bool>(
  rgb48: &[u16],
  rgb_out: &mut [u16],
  width: usize,
) {
  debug_assert!(rgb48.len() >= width * 3, "rgb48 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgb48.as_ptr().add(x * 3);

      macro_rules! process_half_u16 {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (r, g, b) = deinterleave_rgb48_8px(v0, v1, v2);
          write_rgb_u16_8(r, g, b, rgb_out.as_mut_ptr().add($out_off));
        }};
      }

      process_half_u16!(ptr, x * 3);
      process_half_u16!(ptr.add(24), (x + 8) * 3);
      process_half_u16!(ptr.add(48), (x + 16) * 3);
      process_half_u16!(ptr.add(72), (x + 24) * 3);

      x += 32;
    }
    if x < width {
      scalar::rgb48_to_rgb_u16_row::<BE>(&rgb48[x * 3..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Rgb48 → native-depth u16 RGBA. 32 pixels per iter. Alpha forced to
/// 0xFFFF.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgb48.len() >= width * 3`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgb48_to_rgba_u16_row<const BE: bool>(
  rgb48: &[u16],
  rgba_out: &mut [u16],
  width: usize,
) {
  debug_assert!(rgb48.len() >= width * 3, "rgb48 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let opaque = _mm_set1_epi16(0xFFFFu16 as i16);
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgb48.as_ptr().add(x * 3);

      macro_rules! process_half_rgba_u16 {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (r, g, b) = deinterleave_rgb48_8px(v0, v1, v2);
          write_rgba_u16_8(r, g, b, opaque, rgba_out.as_mut_ptr().add($out_off));
        }};
      }

      process_half_rgba_u16!(ptr, x * 4);
      process_half_rgba_u16!(ptr.add(24), (x + 8) * 4);
      process_half_rgba_u16!(ptr.add(48), (x + 16) * 4);
      process_half_rgba_u16!(ptr.add(72), (x + 24) * 4);

      x += 32;
    }
    if x < width {
      scalar::rgb48_to_rgba_u16_row::<BE>(&rgb48[x * 3..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

// Bgr48 (B, G, R — 3 u16 elements per pixel).
/// AVX-512 Bgr48 → packed u8 RGB. 32 pixels per outer iteration.
/// B↔R swap via passing `(ch2, ch1, ch0)` to write helpers.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgr48.len() >= width * 3`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgr48_to_rgb_row<const BE: bool>(
  bgr48: &[u16],
  rgb_out: &mut [u8],
  width: usize,
) {
  debug_assert!(bgr48.len() >= width * 3, "bgr48 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let zero = _mm_setzero_si128();
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgr48.as_ptr().add(x * 3);

      macro_rules! process_half_bgr {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (b, g, r) = deinterleave_rgb48_8px(v0, v1, v2);
          let ru8 = narrow_u16x8_to_u8x8(r, zero);
          let gu8 = narrow_u16x8_to_u8x8(g, zero);
          let bu8 = narrow_u16x8_to_u8x8(b, zero);
          let mut tmp = [0u8; 48];
          write_rgb_16(ru8, gu8, bu8, tmp.as_mut_ptr());
          core::ptr::copy_nonoverlapping(tmp.as_ptr(), rgb_out.as_mut_ptr().add($out_off), 24);
        }};
      }

      process_half_bgr!(ptr, x * 3);
      process_half_bgr!(ptr.add(24), (x + 8) * 3);
      process_half_bgr!(ptr.add(48), (x + 16) * 3);
      process_half_bgr!(ptr.add(72), (x + 24) * 3);

      x += 32;
    }
    if x < width {
      scalar::bgr48_to_rgb_row::<BE>(&bgr48[x * 3..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Bgr48 → packed u8 RGBA. 32 pixels per iter.
/// B↔R swap; alpha forced to 0xFF.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgr48.len() >= width * 3`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgr48_to_rgba_row<const BE: bool>(
  bgr48: &[u16],
  rgba_out: &mut [u8],
  width: usize,
) {
  debug_assert!(bgr48.len() >= width * 3, "bgr48 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let zero = _mm_setzero_si128();
    let opaque_u16 = _mm_set1_epi16(0x00FFu16 as i16);
    let opaque_u8 = _mm_packus_epi16(opaque_u16, zero);
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgr48.as_ptr().add(x * 3);

      macro_rules! process_half_bgr_rgba {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (b, g, r) = deinterleave_rgb48_8px(v0, v1, v2);
          let ru8 = narrow_u16x8_to_u8x8(r, zero);
          let gu8 = narrow_u16x8_to_u8x8(g, zero);
          let bu8 = narrow_u16x8_to_u8x8(b, zero);
          let mut tmp = [0u8; 64];
          write_rgba_16(ru8, gu8, bu8, opaque_u8, tmp.as_mut_ptr());
          core::ptr::copy_nonoverlapping(tmp.as_ptr(), rgba_out.as_mut_ptr().add($out_off), 32);
        }};
      }

      process_half_bgr_rgba!(ptr, x * 4);
      process_half_bgr_rgba!(ptr.add(24), (x + 8) * 4);
      process_half_bgr_rgba!(ptr.add(48), (x + 16) * 4);
      process_half_bgr_rgba!(ptr.add(72), (x + 24) * 4);

      x += 32;
    }
    if x < width {
      scalar::bgr48_to_rgba_row::<BE>(&bgr48[x * 3..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

/// AVX-512 Bgr48 → native-depth u16 RGB. 32 pixels per iter.
/// B↔R swap; values unchanged.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgr48.len() >= width * 3`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgr48_to_rgb_u16_row<const BE: bool>(
  bgr48: &[u16],
  rgb_out: &mut [u16],
  width: usize,
) {
  debug_assert!(bgr48.len() >= width * 3, "bgr48 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgr48.as_ptr().add(x * 3);

      macro_rules! process_half_bgr_u16 {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (b, g, r) = deinterleave_rgb48_8px(v0, v1, v2);
          write_rgb_u16_8(r, g, b, rgb_out.as_mut_ptr().add($out_off));
        }};
      }

      process_half_bgr_u16!(ptr, x * 3);
      process_half_bgr_u16!(ptr.add(24), (x + 8) * 3);
      process_half_bgr_u16!(ptr.add(48), (x + 16) * 3);
      process_half_bgr_u16!(ptr.add(72), (x + 24) * 3);

      x += 32;
    }
    if x < width {
      scalar::bgr48_to_rgb_u16_row::<BE>(&bgr48[x * 3..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Bgr48 → native-depth u16 RGBA. 32 pixels per iter.
/// B↔R swap; alpha forced to 0xFFFF.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgr48.len() >= width * 3`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgr48_to_rgba_u16_row<const BE: bool>(
  bgr48: &[u16],
  rgba_out: &mut [u16],
  width: usize,
) {
  debug_assert!(bgr48.len() >= width * 3, "bgr48 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let opaque = _mm_set1_epi16(0xFFFFu16 as i16);
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgr48.as_ptr().add(x * 3);

      macro_rules! process_half_bgr_rgba_u16 {
        ($ptr:expr, $out_off:expr) => {{
          let v0 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.cast()));
          let v1 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(8).cast()));
          let v2 = byteswap128_if_be::<BE>(_mm_loadu_si128($ptr.add(16).cast()));
          let (b, g, r) = deinterleave_rgb48_8px(v0, v1, v2);
          write_rgba_u16_8(r, g, b, opaque, rgba_out.as_mut_ptr().add($out_off));
        }};
      }

      process_half_bgr_rgba_u16!(ptr, x * 4);
      process_half_bgr_rgba_u16!(ptr.add(24), (x + 8) * 4);
      process_half_bgr_rgba_u16!(ptr.add(48), (x + 16) * 4);
      process_half_bgr_rgba_u16!(ptr.add(72), (x + 24) * 4);

      x += 32;
    }
    if x < width {
      scalar::bgr48_to_rgba_u16_row::<BE>(&bgr48[x * 3..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

// Rgba64 (R, G, B, A — 4 u16 elements per pixel).
/// AVX-512 Rgba64 → packed u8 RGB. 32 pixels per SIMD iteration.
/// Loads 4 x `__m512i` (128 u16 = 32 pixels), deinterleaves via the
/// AVX-512 cascade helper, narrows via `>> 8` + `cvtusepi16_epi8`, writes
/// 32 pixels (96 bytes) via `write_rgb_16` on 128-bit quarters.
///
/// Alpha discarded.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgba64.len() >= width * 4`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgba64_to_rgb_row<const BE: bool>(
  rgba64: &[u16],
  rgb_out: &mut [u8],
  width: usize,
) {
  debug_assert!(rgba64.len() >= width * 4, "rgba64 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgba64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      let (r_u16, g_u16, b_u16, _a) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let r_u8 = narrow_u16x32_to_u8x32(r_u16);
      let g_u8 = narrow_u16x32_to_u8x32(g_u16);
      let b_u8 = narrow_u16x32_to_u8x32(b_u16);
      // write_rgb_16 takes __m128i; split the 256-bit result into two 128-bit halves.
      let out_ptr = rgb_out.as_mut_ptr().add(x * 3);
      write_rgb_16(
        _mm256_castsi256_si128(r_u8),
        _mm256_castsi256_si128(g_u8),
        _mm256_castsi256_si128(b_u8),
        out_ptr,
      );
      write_rgb_16(
        _mm256_extracti128_si256::<1>(r_u8),
        _mm256_extracti128_si256::<1>(g_u8),
        _mm256_extracti128_si256::<1>(b_u8),
        out_ptr.add(48),
      );
      x += 32;
    }
    if x < width {
      scalar::rgba64_to_rgb_row::<BE>(&rgba64[x * 4..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Rgba64 → packed u8 RGBA. 32 pixels per SIMD iteration.
/// Source alpha passes through (narrowed via `>> 8`).
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgba64.len() >= width * 4`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgba64_to_rgba_row<const BE: bool>(
  rgba64: &[u16],
  rgba_out: &mut [u8],
  width: usize,
) {
  debug_assert!(rgba64.len() >= width * 4, "rgba64 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgba64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      let (r_u16, g_u16, b_u16, a_u16) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let r_u8 = narrow_u16x32_to_u8x32(r_u16);
      let g_u8 = narrow_u16x32_to_u8x32(g_u16);
      let b_u8 = narrow_u16x32_to_u8x32(b_u16);
      let a_u8 = narrow_u16x32_to_u8x32(a_u16);
      let out_ptr = rgba_out.as_mut_ptr().add(x * 4);
      write_rgba_16(
        _mm256_castsi256_si128(r_u8),
        _mm256_castsi256_si128(g_u8),
        _mm256_castsi256_si128(b_u8),
        _mm256_castsi256_si128(a_u8),
        out_ptr,
      );
      write_rgba_16(
        _mm256_extracti128_si256::<1>(r_u8),
        _mm256_extracti128_si256::<1>(g_u8),
        _mm256_extracti128_si256::<1>(b_u8),
        _mm256_extracti128_si256::<1>(a_u8),
        out_ptr.add(64),
      );
      x += 32;
    }
    if x < width {
      scalar::rgba64_to_rgba_row::<BE>(&rgba64[x * 4..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

/// AVX-512 Rgba64 → native-depth u16 RGB. 32 pixels per SIMD iteration.
/// Alpha discarded.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgba64.len() >= width * 4`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgba64_to_rgb_u16_row<const BE: bool>(
  rgba64: &[u16],
  rgb_out: &mut [u16],
  width: usize,
) {
  debug_assert!(rgba64.len() >= width * 4, "rgba64 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgba64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      let (r_u16, g_u16, b_u16, _a) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      // Use the shared write_rgb_u16_32 helper (writes 32 px = 4 x 8-px chunks).
      write_rgb_u16_32(r_u16, g_u16, b_u16, rgb_out.as_mut_ptr().add(x * 3));
      x += 32;
    }
    if x < width {
      scalar::rgba64_to_rgb_u16_row::<BE>(&rgba64[x * 4..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Rgba64 → native-depth u16 RGBA (identity copy). 32 pixels per iter.
/// Source alpha preserved.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `rgba64.len() >= width * 4`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_rgba64_to_rgba_u16_row<const BE: bool>(
  rgba64: &[u16],
  rgba_out: &mut [u16],
  width: usize,
) {
  debug_assert!(rgba64.len() >= width * 4, "rgba64 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = rgba64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      let (r_u16, g_u16, b_u16, a_u16) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let opaque = _mm_set1_epi16(-1i16); // 0xFFFF placeholder — not used; a_u16 has real alpha
      let out_ptr = rgba_out.as_mut_ptr().add(x * 4);
      // write_rgba_u16_32 passes a constant alpha __m128i, but we have a per-pixel alpha.
      // Instead split into four 8-pixel chunks using write_rgba_u16_8.
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<0>(r_u16),
        _mm512_extracti32x4_epi32::<0>(g_u16),
        _mm512_extracti32x4_epi32::<0>(b_u16),
        _mm512_extracti32x4_epi32::<0>(a_u16),
        out_ptr,
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<1>(r_u16),
        _mm512_extracti32x4_epi32::<1>(g_u16),
        _mm512_extracti32x4_epi32::<1>(b_u16),
        _mm512_extracti32x4_epi32::<1>(a_u16),
        out_ptr.add(32),
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<2>(r_u16),
        _mm512_extracti32x4_epi32::<2>(g_u16),
        _mm512_extracti32x4_epi32::<2>(b_u16),
        _mm512_extracti32x4_epi32::<2>(a_u16),
        out_ptr.add(64),
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<3>(r_u16),
        _mm512_extracti32x4_epi32::<3>(g_u16),
        _mm512_extracti32x4_epi32::<3>(b_u16),
        _mm512_extracti32x4_epi32::<3>(a_u16),
        out_ptr.add(96),
      );
      let _ = opaque; // suppress unused-variable warning
      x += 32;
    }
    if x < width {
      scalar::rgba64_to_rgba_u16_row::<BE>(&rgba64[x * 4..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

// Bgra64 (B, G, R, A — 4 u16 elements per pixel).
/// AVX-512 Bgra64 → packed u8 RGB. 32 pixels per SIMD iteration.
/// B↔R swap; alpha discarded.
///
/// `deinterleave_rgba64_32px` yields `(B, G, R, A)` in source memory order.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgra64.len() >= width * 4`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgra64_to_rgb_row<const BE: bool>(
  bgra64: &[u16],
  rgb_out: &mut [u8],
  width: usize,
) {
  debug_assert!(bgra64.len() >= width * 4, "bgra64 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgra64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      // ch0=B, ch1=G, ch2=R, ch3=A (source BGRA order)
      let (b_u16, g_u16, r_u16, _a) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let r_u8 = narrow_u16x32_to_u8x32(r_u16);
      let g_u8 = narrow_u16x32_to_u8x32(g_u16);
      let b_u8 = narrow_u16x32_to_u8x32(b_u16);
      let out_ptr = rgb_out.as_mut_ptr().add(x * 3);
      write_rgb_16(
        _mm256_castsi256_si128(r_u8),
        _mm256_castsi256_si128(g_u8),
        _mm256_castsi256_si128(b_u8),
        out_ptr,
      );
      write_rgb_16(
        _mm256_extracti128_si256::<1>(r_u8),
        _mm256_extracti128_si256::<1>(g_u8),
        _mm256_extracti128_si256::<1>(b_u8),
        out_ptr.add(48),
      );
      x += 32;
    }
    if x < width {
      scalar::bgra64_to_rgb_row::<BE>(&bgra64[x * 4..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Bgra64 → packed u8 RGBA. 32 pixels per SIMD iteration.
/// B↔R swap; source alpha passes through (narrowed via `>> 8`).
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgra64.len() >= width * 4`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgra64_to_rgba_row<const BE: bool>(
  bgra64: &[u16],
  rgba_out: &mut [u8],
  width: usize,
) {
  debug_assert!(bgra64.len() >= width * 4, "bgra64 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgra64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      let (b_u16, g_u16, r_u16, a_u16) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let r_u8 = narrow_u16x32_to_u8x32(r_u16);
      let g_u8 = narrow_u16x32_to_u8x32(g_u16);
      let b_u8 = narrow_u16x32_to_u8x32(b_u16);
      let a_u8 = narrow_u16x32_to_u8x32(a_u16);
      let out_ptr = rgba_out.as_mut_ptr().add(x * 4);
      write_rgba_16(
        _mm256_castsi256_si128(r_u8),
        _mm256_castsi256_si128(g_u8),
        _mm256_castsi256_si128(b_u8),
        _mm256_castsi256_si128(a_u8),
        out_ptr,
      );
      write_rgba_16(
        _mm256_extracti128_si256::<1>(r_u8),
        _mm256_extracti128_si256::<1>(g_u8),
        _mm256_extracti128_si256::<1>(b_u8),
        _mm256_extracti128_si256::<1>(a_u8),
        out_ptr.add(64),
      );
      x += 32;
    }
    if x < width {
      scalar::bgra64_to_rgba_row::<BE>(&bgra64[x * 4..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

/// AVX-512 Bgra64 → native-depth u16 RGB. 32 pixels per SIMD iteration.
/// B↔R swap; alpha discarded.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgra64.len() >= width * 4`.
/// 3. `rgb_out.len() >= width * 3`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgra64_to_rgb_u16_row<const BE: bool>(
  bgra64: &[u16],
  rgb_out: &mut [u16],
  width: usize,
) {
  debug_assert!(bgra64.len() >= width * 4, "bgra64 row too short");
  debug_assert!(rgb_out.len() >= width * 3, "rgb_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgra64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      // Swap B↔R: store (R=ch2, G=ch1, B=ch0)
      let (b_u16, g_u16, r_u16, _a) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      write_rgb_u16_32(r_u16, g_u16, b_u16, rgb_out.as_mut_ptr().add(x * 3));
      x += 32;
    }
    if x < width {
      scalar::bgra64_to_rgb_u16_row::<BE>(&bgra64[x * 4..], &mut rgb_out[x * 3..], width - x);
    }
  }
}

/// AVX-512 Bgra64 → native-depth u16 RGBA. 32 pixels per SIMD iteration.
/// B↔R swap; source alpha preserved at position 3.
/// When `BE = true` each loaded register is byte-swapped before deinterleaving.
///
/// # Safety
///
/// 1. AVX-512F + AVX-512BW must be available.
/// 2. `bgra64.len() >= width * 4`.
/// 3. `rgba_out.len() >= width * 4`.
#[inline]
#[target_feature(enable = "avx512f,avx512bw")]
pub(crate) unsafe fn avx512_bgra64_to_rgba_u16_row<const BE: bool>(
  bgra64: &[u16],
  rgba_out: &mut [u16],
  width: usize,
) {
  debug_assert!(bgra64.len() >= width * 4, "bgra64 row too short");
  debug_assert!(rgba_out.len() >= width * 4, "rgba_out row too short");

  unsafe {
    let mut x = 0usize;
    while x + 32 <= width {
      let ptr = bgra64.as_ptr().add(x * 4);
      let raw0 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.cast()));
      let raw1 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(32).cast()));
      let raw2 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(64).cast()));
      let raw3 = byteswap512_if_be::<BE>(_mm512_loadu_si512(ptr.add(96).cast()));
      // Swap B↔R: (R=ch2, G=ch1, B=ch0, A=ch3)
      let (b_u16, g_u16, r_u16, a_u16) = deinterleave_rgba64_32px(raw0, raw1, raw2, raw3);
      let out_ptr = rgba_out.as_mut_ptr().add(x * 4);
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<0>(r_u16),
        _mm512_extracti32x4_epi32::<0>(g_u16),
        _mm512_extracti32x4_epi32::<0>(b_u16),
        _mm512_extracti32x4_epi32::<0>(a_u16),
        out_ptr,
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<1>(r_u16),
        _mm512_extracti32x4_epi32::<1>(g_u16),
        _mm512_extracti32x4_epi32::<1>(b_u16),
        _mm512_extracti32x4_epi32::<1>(a_u16),
        out_ptr.add(32),
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<2>(r_u16),
        _mm512_extracti32x4_epi32::<2>(g_u16),
        _mm512_extracti32x4_epi32::<2>(b_u16),
        _mm512_extracti32x4_epi32::<2>(a_u16),
        out_ptr.add(64),
      );
      write_rgba_u16_8(
        _mm512_extracti32x4_epi32::<3>(r_u16),
        _mm512_extracti32x4_epi32::<3>(g_u16),
        _mm512_extracti32x4_epi32::<3>(b_u16),
        _mm512_extracti32x4_epi32::<3>(a_u16),
        out_ptr.add(96),
      );
      x += 32;
    }
    if x < width {
      scalar::bgra64_to_rgba_u16_row::<BE>(&bgra64[x * 4..], &mut rgba_out[x * 4..], width - x);
    }
  }
}

// Helper: narrow u16x8 (128-bit) to u8x8 (used by stride-3 paths).
/// Narrow a u16x8 vector to u8x8 (in the low half) via logical right-shift by 8.
///
/// Equivalent to scalar `(v >> 8) as u8`. Zero-packs the high half.
#[inline(always)]
unsafe fn narrow_u16x8_to_u8x8(v: __m128i, zero: __m128i) -> __m128i {
  unsafe { _mm_packus_epi16(_mm_srli_epi16::<8>(v), zero) }
}