gpu-handle-types 0.1.0

Typed, owned native GPU resource handles (Vulkan, D3D11/12, Metal, OpenGL, CUDA, OpenCL, DMA-BUF, IOSurface, AHardwareBuffer, WebGPU, ...), cross-API sync points and video pixel formats, for passing GPU resources between libraries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
// SPDX-License-Identifier: MIT OR Apache-2.0

//! `PixelFormat` is the authoritative enumeration of the pixel layouts
//! the handle-types layer (this crate) knows how to reason about. Every backend references the
//! single [`PixelFormat::plane_layout`] table — there is no parallel
//! table to drift out of step with it.

use video_types::{ColorFamily, ResolvedRange};

/// All pixel layouts currently understood.
///
/// `#[non_exhaustive]` — future versions can add new variants (e.g. YCBCR 4:2:0 /
/// 4:2:2 mixed, additional HDR packings) without breaking callers.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PixelFormat {
    // 4:2:0 biplanar — HW-decode default
    NV12,
    NV21,
    P010LE,
    P016LE,
    // 4:2:2 / 4:4:4 biplanar
    /// Biplanar 8-bit 4:2:2 (FFmpeg `AV_PIX_FMT_NV16`): full-resolution
    /// `R8` luma plane + half-width **full-height** `RG8` interleaved
    /// U/V chroma plane. The 4:2:2 sibling of [`Self::NV12`] and the
    /// 8-bit sibling of [`Self::P210LE`] — NVDEC's SDK-13 `NV16`
    /// output surface for 4:2:2 8-bit H.264/HEVC decode (Blackwell+).
    NV16,
    P210LE,
    P216LE,
    P410LE,
    P416LE,
    /// Biplanar 8-bit 4:4:4 (FFmpeg `AV_PIX_FMT_NV24`): full-resolution
    /// `R8` luma plane + **full-resolution** `RG8` interleaved U/V chroma
    /// plane. The 4:4:4 sibling of [`Self::NV16`] and the 8-bit sibling
    /// of [`Self::P410LE`] — VideoToolbox's `'444v'` /`'444f'`
    /// (`kCVPixelFormatType_444YpCbCr8BiPlanar{Video,Full}Range`) native
    /// decode surface for 8-bit 4:4:4 HEVC RExt.
    NV24,
    /// Tri-planar 4:2:0 NV12 **plus a full-resolution 8-bit alpha plane**
    /// (Apple `kCVPixelFormatType_420YpCbCr8VideoRange_8A_TriPlanar` =
    /// `'v0a8'`). Three planes: plane 0 full-resolution `R8` luma (Y'),
    /// plane 1 half-resolution interleaved `RG8` chroma (Cb, Cr) exactly
    /// like [`Self::NV12`], plane 2 **full-resolution** `R8` alpha. The
    /// colour planes are video-range Y'CbCr (BT.601/709/2020 matrix, the
    /// `VideoRange` fourcc suffix); the alpha plane is **full-range by
    /// definition** (code `0..255` maps linearly to `0..1` straight
    /// opacity — no limited-range video quantisation, no colour matrix),
    /// exactly like the alpha plane of the [`Self::YUVA444P10LE`] family
    /// and the `A` lane of [`Self::AYUV64LE`]. VideoToolbox's
    /// decoder-native output surface for HEVC-with-alpha (`muxa`); the
    /// 8-bit member of the tri-planar YCbCr+alpha family (the only >8-bit
    /// carrier Apple publishes is the 16-bit
    /// `444YpCbCr16VideoRange_16A_TriPlanar` `'s4as'` — there is no 10-bit
    /// planar alpha format). Imports zero-copy as three Metal textures
    /// (`R8` + `Rg8` + `R8` `Split(3)`); all three plane primitives are
    /// core wgpu formats, so it is outside the `TEXTURE_FORMAT_16BIT_NORM`
    /// gate.
    NV12A,
    // triplanar
    YUV420P,
    YUV422P,
    YUV444P,
    YUV420P10LE,
    YUV420P12LE,
    YUV420P14LE,
    YUV420P16LE,
    YUV422P10LE,
    YUV422P12LE,
    YUV422P14LE,
    YUV422P16LE,
    YUV444P10LE,
    YUV444P12LE,
    YUV444P14LE,
    YUV444P16LE,
    /// Planar YUV 4:4:4 + alpha (FFmpeg `AV_PIX_FMT_YUVA444P10LE`):
    /// four full-resolution `R16` planes — Y, U, V, A — each carrying a
    /// 10-bit code LSB-aligned in a 16-bit little-endian word
    /// (`AVPixFmtDescriptor.shift == 0`, exactly like the alpha-less
    /// triplanar `YUV*P10LE` family). The alpha plane is **full-range by
    /// definition** (code `0..1023` maps linearly to `0..1` opacity — no
    /// limited-range video quantisation, no colour matrix); every
    /// conversion dequantises / requantises it through the full-range
    /// luma ladder regardless of the frame's `ColorRange`. The
    /// alpha-carrying ProRes 4444 / 4444XQ interchange format (the
    /// `prores_ks` ENCODER input).
    YUVA444P10LE,
    /// 12-bit sibling of [`Self::YUVA444P10LE`] — the same four-plane
    /// LSB-aligned layout at 12 bits per code (alpha full-range,
    /// `0..4095` mapping `0..1` opacity). FFmpeg's ProRes DECODER emits
    /// `yuva444p12le` for alpha-carrying 4444 / 4444XQ streams (the
    /// bitstream codes 12-bit), so this is the decode-side twin of the
    /// 10-bit encoder input.
    YUVA444P12LE,
    // packed
    UYVY422,
    YUYV422,
    AYUV64LE,
    /// Packed 4:2:2, 16 bits per component (Apple
    /// `kCVPixelFormatType_422YpCbCr16` = `'v216'`). Single plane: for each
    /// horizontal pair of pixels, four 16-bit **little-endian** components in
    /// the order **Cb, Y'0, Cr, Y'1** — the 16-bit sibling of the 8-bit
    /// `'2vuy'` / [`Self::UYVY422`] layout (Apple *Ice Floe* #19). Stored under
    /// an `Rgba16Unorm` texture at half horizontal resolution
    /// (`size_scale (2, 1)`): one texel carries both luma samples plus the
    /// shared chroma pair, and the shader reinterprets the RGBA lanes as
    /// `.r=Cb, .g=Y'0, .b=Cr, .a=Y'1`. This is VideoToolbox's
    /// **decoder-native** output surface for ProRes 422 (WWDC20) — pinning it
    /// eliminates the internal `v216 → x422` pixel transfer VideoToolbox would
    /// otherwise insert on every frame. Video-range Y'CbCr.
    V216,
    /// Packed 4:2:2, 10 bits per component carried MSB-aligned in a 16-bit
    /// **little-endian** word (Microsoft/DXGI `Y210`, VAAPI
    /// `VA_FOURCC_Y210 = 0x30313259`). Single plane, **4 bytes/px**: for each
    /// horizontal pair of pixels, four 16-bit words in the order
    /// **Y'0, Cb, Y'1, Cr** — each holding a 10-bit code in bits `[15..6]`
    /// with the low 6 bits zero (the same MSB-aligned convention as
    /// [`Self::P010LE`]). Stored under an `Rgba16Unorm` texture at half
    /// horizontal resolution (`size_scale (2, 1)`): one texel carries both
    /// luma samples plus the shared chroma pair, and the shader reinterprets
    /// the RGBA lanes as `.r=Y'0, .g=Cb, .b=Y'1, .a=Cr` — the 10-bit sibling
    /// of the 8-bit [`Self::YUYV422`] lane order (whereas [`Self::V216`]
    /// carries the 16-bit UYVY lane order). This is the VAAPI **decoder-native**
    /// output surface for HEVC Main 4:2:2 10 (`VA_RT_FORMAT_YUV422_10`) on
    /// Intel Gen11+; VAAPI defines no `P210` fourcc, so Y210 is the 4:2:2-10
    /// carrier. Video-range Y'CbCr.
    Y210LE,
    // RGB
    RgbaU8,
    BgraU8,
    /// Packed 8-bit **R, G, B, X** — 4 B/px, byte-identical to
    /// [`Self::RgbaU8`] except that the fourth lane is **padding, not
    /// alpha** (FFmpeg `AV_PIX_FMT_RGB0`, DRM `XBGR8888`, AHardwareBuffer
    /// `R8G8B8X8_UNORM`).
    ///
    /// **The X contract, stated at the type:** [`Self::alpha_channel`]
    /// answers [`AlphaChannel::Padding`], so [`Self::has_alpha`] is
    /// `false`. The stored bits of lane 3 carry NO information — a producer
    /// may leave them at anything (a decoded FFV1 `bgr0` frame was measured
    /// to write `0x00` into all of them, i.e. "fully transparent" if they
    /// were ever read as alpha), and every reader MUST substitute full
    /// opacity instead of sampling them.
    ///
    /// The storage is unchanged, so this costs **nothing**: the same
    /// `RGBA8` plane, the same texture, the same zero-copy import. What
    /// changes is only what consumers are allowed to conclude from lane 3 —
    /// which is why this is a distinct `PixelFormat` and not a comment on
    /// [`Self::RgbaU8`]. Aliasing an X format onto its A twin is the one
    /// mistake this variant exists to make impossible.
    RgbxU8,
    /// Packed 8-bit **B, G, R, X** — the BGRA-ordered twin of
    /// [`Self::RgbxU8`], carrying the same opaque-X contract (FFmpeg
    /// `AV_PIX_FMT_BGR0`, DXGI `B8G8R8X8_UNORM`, DRM `XRGB8888`). The
    /// dominant desktop screen-capture layout: Windows desktop duplication,
    /// `gdigrab` / `ddagrab`, and X11 capture all hand over BGRX.
    BgrxU8,
    RgbaU16,
    BgraU16,
    RgbaF16,
    BgraF16,
    RgbaF32,
    BgraF32,
    /// Packed 10:10:10:2 unsigned-normalized RGBA, 4 B/px — R in bits
    /// 0..10, G 10..20, B 20..30, A 30..32 (little-endian; wgpu
    /// `Rgb10a2Unorm`, DXGI `R10G10B10A2_UNORM`, Vulkan
    /// `A2B10G10R10_UNORM_PACK32`). The HDR10 swapchain / foreign
    /// render-target format: lets a host describe a 10-bit PQ render
    /// target through the interop import/export path.
    Rgb10A2,
    /// 3-channel 16-bit unsigned RGB, interleaved, host-order.
    /// 6 bytes per pixel. Produced by R3D CUDA / OpenCL debayer output.
    ///
    /// **Packed buffer shape** — there is no native wgpu texture format
    /// (no GPU samples 3-channel 16-bit natively). Consumers MUST check
    /// [`PixelFormat::is_packed_buffer_shape`] and route through a
    /// buffer-shape import path plus an RGB16 → RGBA16 expand pass before
    /// sampling.
    RgbU16,

    // ── Single-channel scalar fields ──────────────────────────────────
    /// Single-channel 16-bit **unsigned-integer** scalar field: one plane
    /// of [`PlaneFormat::R16Uint`], 2 B/px, `size_scale (1, 1)`. The
    /// single-channel analogue of [`Self::RgbaU16`] for non-colour host
    /// workloads (a raw-sensor CFA mosaic, an index map, a 16-bit depth
    /// buffer). Read via `textureLoad` (`texture_2d<u32>`) on the GPU — not
    /// sampler-filterable. This is the `PixelFormat` a single-plane CPU
    /// surface keyed on `R16Uint` (or a CPU intermediate typed only by
    /// that storage primitive) materialises as, so a single-plane CPU
    /// image view covers it exactly like any other single-plane format.
    R16U,

    /// Single-channel 32-bit **float** scalar field: one plane of
    /// [`PlaneFormat::R32Float`], 4 B/px, `size_scale (1, 1)`. The
    /// single-channel analogue of [`Self::RgbaF32`] for non-colour host
    /// workloads (a normalized-linear CFA, a scalar coefficient field, a
    /// floating depth buffer). The `PixelFormat` a single-plane CPU surface
    /// keyed on `R32Float` (or a CPU intermediate typed only by that
    /// storage primitive) materialises as.
    R32F,

    /// Four-channel 16-bit **unsigned-integer** RGBA: one plane of
    /// [`PlaneFormat::RGBA16Uint`], 8 B/px, `size_scale (1, 1)`. The
    /// 4-channel integer analogue of [`Self::R16U`] for non-colour host
    /// workloads that carry several already-separated 16-bit channels per
    /// pixel (an already-colour multi-plane raw frame packed interleaved —
    /// Foveon's 3 stacked layers, a pixel-shift RGBG quad, a linear-RGB DNG).
    /// Read via `textureLoad` (`texture_2d<u32>`) on the GPU — not
    /// sampler-filterable (the integer channels carry raw sensor counts that
    /// must not be normalised). The `PixelFormat` a single-plane CPU surface
    /// keyed on `RGBA16Uint` materialises as, so a single-plane CPU image
    /// view covers it exactly like any other single-plane format.
    Rgba16U,
}

/// Per-plane storage primitive. A plane's `PlaneFormat` names the
/// smallest texture format a GPU upload would use for it; the shader
/// reinterprets the channels when needed (e.g. AYUV64LE uses `RGBA16`
/// storage with AYUV channel semantics).
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PlaneFormat {
    R8,
    R16,
    RG8,
    RG16,
    RGBA8,
    BGRA8,
    RGBA16,
    RGBA16F,
    RGBA32F,
    R16Uint,
    R32Float,
    /// Four-channel 16-bit unsigned-integer RGBA (`Rgba16Uint`), 8 B/px. The
    /// integer 4-channel storage primitive an already-colour multi-plane raw
    /// frame uploads as (read via `textureLoad` — never sampler-normalised).
    RGBA16Uint,
    /// Packed 10:10:10:2 unsigned-normalized RGBA (`Rgb10a2Unorm`), 4 B/px —
    /// R in bits 0..10, G 10..20, B 20..30, A 30..32 (little-endian; DXGI
    /// `R10G10B10A2_UNORM` / Vulkan `A2B10G10R10_UNORM_PACK32`). The HDR10
    /// swapchain / render-target primitive ([`PixelFormat::Rgb10A2`]).
    RGB10A2,
}

impl PlaneFormat {
    /// Size in bytes of one stored texel of this plane format (all
    /// channels). `width_in_texels * bytes_per_sample()` is the tight
    /// row stride; every backend's stride / buffer-length math derives
    /// from this single table. `RGBA16F` is two bytes per channel (IEEE
    /// half), matching `RGBA16`.
    pub const fn bytes_per_sample(self) -> u32 {
        match self {
            PlaneFormat::R8 => 1,
            PlaneFormat::R16 => 2,
            PlaneFormat::RG8 => 2,
            PlaneFormat::RG16 => 4,
            PlaneFormat::RGBA8 | PlaneFormat::BGRA8 => 4,
            PlaneFormat::RGBA16 => 8,
            PlaneFormat::RGBA16F => 8,
            PlaneFormat::RGBA32F => 16,
            PlaneFormat::R16Uint => 2,
            PlaneFormat::R32Float => 4,
            PlaneFormat::RGBA16Uint => 8,
            PlaneFormat::RGB10A2 => 4,
        }
    }

    /// True when a texture of this plane format needs the
    /// [`wgpu::Features::TEXTURE_FORMAT_16BIT_NORM`] adapter feature — the
    /// three 16-bit **normalized** storage primitives (`R16` → `R16Unorm`,
    /// `RG16` → `Rg16Unorm`, `RGBA16` → `Rgba16Unorm`). The 16-bit **integer**
    /// primitives (`R16Uint`, `RGBA16Uint`), the 16-bit **float** primitive
    /// (`RGBA16F` → `Rgba16Float`), and every 8-/10-/32-bit primitive are core
    /// wgpu formats and return `false`.
    ///
    /// This is the single source of truth an interop import gate keys on: a
    /// `PixelFormat` whose plane layout contains any such plane cannot be
    /// zero-copy imported on a device without the feature (see
    /// [`PixelFormat::requires_16bit_norm`]).
    pub const fn requires_16bit_norm(self) -> bool {
        matches!(self, PlaneFormat::R16 | PlaneFormat::RG16 | PlaneFormat::RGBA16)
    }

    /// Canonical wgpu equivalent of this per-plane storage primitive.
    /// Used at the wgpu-backend boundary where the type system needs the
    /// real `wgpu::TextureFormat` (transient texture creation, pipeline
    /// layout). Backend-agnostic code carries `PlaneFormat` instead.
    #[cfg(feature = "wgpu")]
    pub const fn to_wgpu_texture_format(self) -> wgpu::TextureFormat {
        match self {
            PlaneFormat::R8 => wgpu::TextureFormat::R8Unorm,
            PlaneFormat::R16 => wgpu::TextureFormat::R16Unorm,
            PlaneFormat::RG8 => wgpu::TextureFormat::Rg8Unorm,
            PlaneFormat::RG16 => wgpu::TextureFormat::Rg16Unorm,
            PlaneFormat::RGBA8 => wgpu::TextureFormat::Rgba8Unorm,
            PlaneFormat::BGRA8 => wgpu::TextureFormat::Bgra8Unorm,
            PlaneFormat::RGBA16 => wgpu::TextureFormat::Rgba16Unorm,
            PlaneFormat::RGBA16F => wgpu::TextureFormat::Rgba16Float,
            PlaneFormat::RGBA32F => wgpu::TextureFormat::Rgba32Float,
            PlaneFormat::R16Uint => wgpu::TextureFormat::R16Uint,
            PlaneFormat::R32Float => wgpu::TextureFormat::R32Float,
            PlaneFormat::RGBA16Uint => wgpu::TextureFormat::Rgba16Uint,
            PlaneFormat::RGB10A2 => wgpu::TextureFormat::Rgb10a2Unorm,
        }
    }
}

/// Storage description of a single plane in a [`PlaneLayout`].
///
/// `size_scale = (x_denom, y_denom)` describes the **storage texel
/// count** of this plane relative to the frame's nominal `(W, H)`: a
/// UV plane in NV12 has `size_scale = (2, 2)` because there are
/// `W/2 × H/2` UV-pair texels (each `RG8`), even though the row stride
/// in *bytes* equals the Y plane's `W`. Use [`PixelFormat::plane_size`]
/// to materialise dimensions — that is the only contract every backend
/// agrees on.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PlaneInfo {
    pub format: PlaneFormat,
    pub size_scale: (u8, u8),
}

/// How a pixel format lays out its planes in memory.
///
/// Plane 0 is stored as a non-`Option` [`PlaneInfo`] because every
/// `PixelFormat` has at least one plane — the type encodes that
/// invariant so callers (stride math, CPU upload, etc.) can name plane
/// 0 without a runtime `expect(...)`. Planes 1..=3 are `Option` because
/// only multi-plane formats populate them.
///
/// `extra[i]` is `Some` iff `i + 1 < count()`. Use [`Self::plane`] for
/// index-based access; [`Self::count`] for the populated plane count.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PlaneLayout {
    pub plane0: PlaneInfo,
    pub extra: [Option<PlaneInfo>; 3],
}

impl PlaneLayout {
    /// Total populated plane count (`1..=4`). Plane 0 always counts.
    pub const fn count(&self) -> u8 {
        let mut c: u8 = 1;
        if self.extra[0].is_some() {
            c += 1;
        }
        if self.extra[1].is_some() {
            c += 1;
        }
        if self.extra[2].is_some() {
            c += 1;
        }
        c
    }

    /// Storage description of plane `i`. `Some` iff `i < self.count()`.
    pub const fn plane(&self, i: u8) -> Option<PlaneInfo> {
        match i {
            0 => Some(self.plane0),
            1 => self.extra[0],
            2 => self.extra[1],
            3 => self.extra[2],
            _ => None,
        }
    }
}

/// What a [`PixelFormat`]'s fourth component *means* — the contract a
/// consumer must honour before it reads lane 3 of a packed layout (or the
/// fourth plane of a planar one).
///
/// This exists because "4 channels" and "has alpha" are **not the same
/// statement**, and treating them as one is an easy mistake to make.
/// The X-padded desktop layouts (`BGRX` / `RGBX` — FFmpeg `bgr0` / `rgb0`,
/// DXGI `B8G8R8X8_UNORM`, DRM `XRGB8888`, AHardwareBuffer
/// `R8G8B8X8_UNORM`) are byte-for-byte identical to their alpha-carrying
/// twins, so nothing about the *layout* can tell them apart — the
/// distinction is semantic, and therefore has to live in the type. Prose
/// alone does not stop `av_hwframe_transfer_data` handing a compositor a
/// frame of all-zero padding bytes that it reads as "fully transparent".
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum AlphaChannel {
    /// The format has no fourth component at all (`NV12`, `YUV420P`,
    /// `UYVY422`, `RgbU16`, the scalar fields, …). There is nothing to read.
    None,
    /// A real, **straight** (non-premultiplied) alpha: lane 3 / plane 3
    /// carries opacity, full-range by definition (code `0` → transparent,
    /// max code → opaque), and a compositor MUST honour it.
    Straight,
    /// A **padding lane**. The bits exist in memory and carry **no
    /// information**: a producer may write anything into them (a decoded
    /// FFV1 `bgr0` frame writes `0x00`; a D3D `B8G8R8X8` render target
    /// writes whatever the last shader left), and every reader MUST
    /// substitute full opacity rather than sampling them.
    ///
    /// Practically that means: never multiply by lane 3, never use it as a
    /// composite weight, never propagate it into an alpha-carrying
    /// destination. A format that answers `Padding` is **opaque** —
    /// [`PixelFormat::has_alpha`] is `false` for it, which is what a
    /// compositor's alpha gate keys on.
    Padding,
}

impl PixelFormat {
    /// **Every** `PixelFormat`, indexed by its [`shader_id`](Self::shader_id)
    /// — the single canonical roster to enumerate over.
    ///
    /// Hand-written copies of this list drift: a gate that keeps its own
    /// copy silently stops checking the newest variants. One list, in the
    /// crate that owns the enum, is the only arrangement that cannot drift
    /// silently.
    ///
    /// **Adding a variant.** Six exhaustive matches already fail to compile
    /// ([`plane_layout`](Self::plane_layout),
    /// [`bits_per_sample`](Self::bits_per_sample),
    /// [`shader_id`](Self::shader_id),
    /// [`color_family`](Self::color_family),
    /// [`alpha_channel`](Self::alpha_channel) and
    /// [`packed_expand_depth`](Self::packed_expand_depth)). Adding the new
    /// ordinal to `shader_id` then trips [`Self::COUNT`], which is what forces
    /// the entry here — so the roster stays complete without relying on
    /// anyone remembering it.
    ///
    /// Order is `shader_id` order, and `ALL[i].shader_id() == i` is asserted
    /// at compile time below.
    pub const ALL: &'static [PixelFormat] = &[
        PixelFormat::NV12,         // 0
        PixelFormat::NV21,         // 1
        PixelFormat::P010LE,       // 2
        PixelFormat::P016LE,       // 3
        PixelFormat::P210LE,       // 4
        PixelFormat::P216LE,       // 5
        PixelFormat::P410LE,       // 6
        PixelFormat::P416LE,       // 7
        PixelFormat::YUV420P,      // 8
        PixelFormat::YUV422P,      // 9
        PixelFormat::YUV444P,      // 10
        PixelFormat::YUV420P10LE,  // 11
        PixelFormat::YUV420P12LE,  // 12
        PixelFormat::YUV420P14LE,  // 13
        PixelFormat::YUV420P16LE,  // 14
        PixelFormat::YUV422P10LE,  // 15
        PixelFormat::YUV422P12LE,  // 16
        PixelFormat::YUV422P14LE,  // 17
        PixelFormat::YUV422P16LE,  // 18
        PixelFormat::YUV444P10LE,  // 19
        PixelFormat::YUV444P12LE,  // 20
        PixelFormat::YUV444P14LE,  // 21
        PixelFormat::YUV444P16LE,  // 22
        PixelFormat::UYVY422,      // 23
        PixelFormat::YUYV422,      // 24
        PixelFormat::AYUV64LE,     // 25
        PixelFormat::RgbaU8,       // 26
        PixelFormat::BgraU8,       // 27
        PixelFormat::RgbaU16,      // 28
        PixelFormat::BgraU16,      // 29
        PixelFormat::RgbaF16,      // 30
        PixelFormat::BgraF16,      // 31
        PixelFormat::RgbaF32,      // 32
        PixelFormat::BgraF32,      // 33
        PixelFormat::RgbU16,       // 34
        PixelFormat::R16U,         // 35
        PixelFormat::R32F,         // 36
        PixelFormat::Rgba16U,      // 37
        PixelFormat::YUVA444P10LE, // 38
        PixelFormat::YUVA444P12LE, // 39
        PixelFormat::Rgb10A2,      // 40
        PixelFormat::NV16,         // 41
        PixelFormat::NV24,         // 42
        PixelFormat::V216,         // 43
        PixelFormat::NV12A,        // 44
        PixelFormat::Y210LE,       // 45
        PixelFormat::RgbxU8,       // 46
        PixelFormat::BgrxU8,       // 47
    ];

    /// Number of `PixelFormat` variants — `PixelFormat::ALL.len()`, and one
    /// past the highest [`shader_id`](Self::shader_id).
    ///
    /// This constant is the tripwire that keeps [`Self::ALL`] complete: a new
    /// variant gets a new ordinal in the (compile-enforced) `shader_id` match,
    /// and the `const` assertion below then refuses to build until both this
    /// number and the roster entry follow. State it as a literal so the bump
    /// is a deliberate act.
    pub const COUNT: usize = 48;

    /// Immutable plane descriptor. Single source of truth for every
    /// backend's upload / readback / shader.
    pub const fn plane_layout(self) -> PlaneLayout {
        use PixelFormat as P;
        use PlaneFormat as F;
        // Shorthand for "plane absent".
        const NONE: Option<PlaneInfo> = None;
        const S11: (u8, u8) = (1, 1);
        const S22: (u8, u8) = (2, 2); // 4:2:0 YUV per-axis halved
        const S21: (u8, u8) = (2, 1); // 4:2:2 chroma (half horizontal)
        // const-friendly per-plane builder.
        const fn p(format: PlaneFormat, size_scale: (u8, u8)) -> PlaneInfo {
            PlaneInfo { format, size_scale }
        }
        match self {
            // --- 4:2:0 biplanar (NV12 family) ---
            // Y: full-res R8. UV: interleaved in a single RG8 plane —
            // `W/2 × H/2` RG-pair texels, byte stride `W` (matches the Y
            // plane's stride — confusing that byte-stride with the texel
            // count is how one arrives at a wrong "(1, 2)").
            P::NV12 | P::NV21 => PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::RG8, S22)), NONE, NONE] },
            // 10/16-bit biplanar (P010/P016). Both planes are 16-bit storage.
            P::P010LE | P::P016LE => PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::RG16, S22)), NONE, NONE] },

            // --- 4:2:2 / 4:4:4 biplanar ---
            // NV16: 8-bit sibling of P210 — R8 luma + half-width
            // full-height interleaved RG8 chroma.
            P::NV16 => PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::RG8, S21)), NONE, NONE] },
            P::P210LE | P::P216LE => PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::RG16, S21)), NONE, NONE] },
            P::P410LE | P::P416LE => PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::RG16, S11)), NONE, NONE] },
            // NV24: 8-bit sibling of P410 — R8 luma + full-resolution
            // interleaved RG8 chroma (4:4:4).
            P::NV24 => PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::RG8, S11)), NONE, NONE] },
            // NV12A: NV12 (R8 luma + half-res RG8 chroma, 4:2:0) plus a
            // FULL-resolution R8 alpha plane. Three planes; the alpha
            // shares the luma's 8-bit R8 storage but dequantises full-range.
            P::NV12A => PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::RG8, S22)), Some(p(F::R8, S11)), NONE] },

            // --- triplanar 8-bit ---
            P::YUV420P => {
                PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::R8, S22)), Some(p(F::R8, S22)), NONE] }
            }
            P::YUV422P => {
                PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::R8, S21)), Some(p(F::R8, S21)), NONE] }
            }
            P::YUV444P => {
                PlaneLayout { plane0: p(F::R8, S11), extra: [Some(p(F::R8, S11)), Some(p(F::R8, S11)), NONE] }
            }

            // --- triplanar 10/12/14/16-bit ---
            P::YUV420P10LE | P::YUV420P12LE | P::YUV420P14LE | P::YUV420P16LE => {
                PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::R16, S22)), Some(p(F::R16, S22)), NONE] }
            }
            P::YUV422P10LE | P::YUV422P12LE | P::YUV422P14LE | P::YUV422P16LE => {
                PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::R16, S21)), Some(p(F::R16, S21)), NONE] }
            }
            P::YUV444P10LE | P::YUV444P12LE | P::YUV444P14LE | P::YUV444P16LE => {
                PlaneLayout { plane0: p(F::R16, S11), extra: [Some(p(F::R16, S11)), Some(p(F::R16, S11)), NONE] }
            }

            // --- triplanar + alpha ---
            // Four full-resolution R16 planes (Y, U, V, A). The alpha
            // plane shares the 10-bit LSB-aligned storage of the colour
            // planes but is dequantised full-range (see the variant doc).
            P::YUVA444P10LE | P::YUVA444P12LE => PlaneLayout {
                plane0: p(F::R16, S11),
                extra: [Some(p(F::R16, S11)), Some(p(F::R16, S11)), Some(p(F::R16, S11))],
            },

            // --- packed 4:2:2 ---
            // UYVY422 / YUYV422: 2 samples per 4 bytes = BGRA8/RGBA8 texture
            // at half horizontal resolution.
            P::UYVY422 | P::YUYV422 => PlaneLayout { plane0: p(F::RGBA8, S21), extra: [NONE, NONE, NONE] },

            // AYUV64LE: packed 4:4:4, 16 bpc, single plane. Storage is
            // RGBA16; shader reinterprets lanes as A=0, Y=2, U=4, V=6
            // (ffmpeg AV_PIX_FMT_AYUV64LE).
            P::AYUV64LE => PlaneLayout { plane0: p(F::RGBA16, S11), extra: [NONE, NONE, NONE] },

            // V216: packed 4:2:2, 16 bpc, single plane. Storage is RGBA16 at
            // HALF horizontal resolution (`W/2 × H` RGBA-pair texels) — one
            // texel per pixel pair carries (Cb, Y0, Cr, Y1); the shader
            // reinterprets .r=Cb, .g=Y0, .b=Cr, .a=Y1 (Apple v216, the 16-bit
            // sibling of UYVY422). Same (2, 1) shape as UYVY422 at RGBA16.
            P::V216 => PlaneLayout { plane0: p(F::RGBA16, S21), extra: [NONE, NONE, NONE] },

            // Y210LE: packed 4:2:2, 10-in-16-MSB, single plane. SAME storage
            // shape as V216 — RGBA16 at HALF horizontal resolution (`W/2 × H`
            // RGBA-pair texels), one texel per pixel pair carries (Y0, Cb, Y1,
            // Cr); the shader reinterprets .r=Y0, .g=Cb, .b=Y1, .a=Cr (the
            // 10-bit sibling of YUYV422's lane order). The 10-bit code sits
            // MSB-aligned in each 16-bit word, dequantised by `bit_depth = 10`.
            P::Y210LE => PlaneLayout { plane0: p(F::RGBA16, S21), extra: [NONE, NONE, NONE] },

            // --- RGB packed ---
            // Channel order is part of the storage primitive wherever the
            // hardware can express it: 8-bit BGRA has a real swizzled
            // texture format (`BGRA8` → `Bgra8Unorm`), so the BGRA-ordered
            // layouts name it rather than borrowing `RGBA8`. Reporting
            // `RGBA8` here would hand every consumer that derives its
            // texture format from the plane layout (rather than from a
            // backend's own table) a red/blue swap.
            //
            // The X-padded twins share their alpha-carrying twin's layout
            // byte for byte — only `alpha_channel()` distinguishes them.
            P::RgbaU8 | P::RgbxU8 => PlaneLayout { plane0: p(F::RGBA8, S11), extra: [NONE, NONE, NONE] },
            P::BgraU8 | P::BgrxU8 => PlaneLayout { plane0: p(F::BGRA8, S11), extra: [NONE, NONE, NONE] },
            // Above 8 bits there is no BGRA-ordered texture format anywhere
            // in the stack — no `Bgra16Unorm` / `Bgra16Float` /
            // `Bgra32Float` in wgpu, and none in Vulkan, D3D or Metal
            // beneath it. `BgraU16` / `BgraF16` / `BgraF32` therefore
            // describe host memory a producer can hand over, not a texture
            // a GPU can sample in place, and plane 0 can only name the
            // same-width RGBA-ordered primitive. An interop import path
            // refuses them for exactly that reason; a consumer must not
            // build a texture from this plane format without a swizzle.
            P::RgbaU16 | P::BgraU16 => PlaneLayout { plane0: p(F::RGBA16, S11), extra: [NONE, NONE, NONE] },
            P::RgbaF16 | P::BgraF16 => PlaneLayout { plane0: p(F::RGBA16F, S11), extra: [NONE, NONE, NONE] },
            P::RgbaF32 | P::BgraF32 => PlaneLayout { plane0: p(F::RGBA32F, S11), extra: [NONE, NONE, NONE] },
            // Packed 10:10:10:2 — one full-resolution RGB10A2 plane (4 B/px).
            P::Rgb10A2 => PlaneLayout { plane0: p(F::RGB10A2, S11), extra: [NONE, NONE, NONE] },

            // --- packed buffer-shape (no native wgpu texture format) ---
            // RgbU16 is 6 B/px and has no native wgpu format. This arm
            // returns a placeholder `RGBA16` PlaneLayout so the signature
            // stays infallible; callers that could reach this format MUST
            // guard upstream via `is_packed_buffer_shape()` and route
            // through a buffer import + expand pass. Reaching this arm in
            // production code is a contract violation.
            P::RgbU16 => PlaneLayout { plane0: p(F::RGBA16, S11), extra: [NONE, NONE, NONE] },

            // --- single-channel scalar fields ---
            // One full-resolution plane of the matching storage primitive;
            // tight row stride is `W * bytes_per_sample()` (2 / 4 B/px).
            P::R16U => PlaneLayout { plane0: p(F::R16Uint, S11), extra: [NONE, NONE, NONE] },
            P::R32F => PlaneLayout { plane0: p(F::R32Float, S11), extra: [NONE, NONE, NONE] },
            // Four-channel 16-bit unsigned-integer RGBA — one full-resolution
            // plane of `RGBA16Uint` (8 B/px). The already-colour multi-plane
            // raw-frame input format.
            P::Rgba16U => PlaneLayout { plane0: p(F::RGBA16Uint, S11), extra: [NONE, NONE, NONE] },
        }
    }

    /// The canonical **single-plane** `PixelFormat` whose only plane stores
    /// `plane`, or `None` when no single-plane `PixelFormat` represents that
    /// storage primitive (the sub-channel YUV plane primitives `R8` / `R16`
    /// / `RG8` / `RG16`, which only exist as members of a multi-plane
    /// layout). The inverse of `plane_layout().plane0.format` restricted to
    /// the single-plane (`count() == 1`) formats.
    ///
    /// This is the bridge a CPU backend uses to bind an intermediate buffer
    /// typed only by a [`PlaneFormat`] as a strided single-plane CPU image.
    /// `BGRA8` resolves to [`Self::BgraU8`]; every other multi-channel
    /// primitive to its `Rgba*` form. The packed-buffer-shape `RgbU16` is
    /// intentionally NOT produced here (it has no native single-plane
    /// sampling path).
    pub const fn for_single_plane(plane: PlaneFormat) -> Option<PixelFormat> {
        use PixelFormat as P;
        use PlaneFormat as F;
        match plane {
            F::RGBA8 => Some(P::RgbaU8),
            F::BGRA8 => Some(P::BgraU8),
            F::RGBA16 => Some(P::RgbaU16),
            F::RGBA16F => Some(P::RgbaF16),
            F::RGBA32F => Some(P::RgbaF32),
            F::R16Uint => Some(P::R16U),
            F::R32Float => Some(P::R32F),
            F::RGBA16Uint => Some(P::Rgba16U),
            F::RGB10A2 => Some(P::Rgb10A2),
            // Sub-channel YUV plane primitives are never a standalone
            // single-plane PixelFormat.
            F::R8 | F::R16 | F::RG8 | F::RG16 => None,
        }
    }

    /// Tight (unpadded) bytes per pixel of a single-plane format —
    /// `plane0.format.bytes_per_sample()`. For multi-plane formats this is
    /// the bytes-per-texel of plane 0 only; callers handling multi-plane
    /// layouts must use [`Self::plane_size`] + per-plane
    /// [`PlaneFormat::bytes_per_sample`] instead. A single-plane CPU image
    /// view derives its tight row stride as `width * bytes_per_pixel()`.
    pub const fn bytes_per_pixel(self) -> u32 {
        self.plane_layout().plane0.format.bytes_per_sample()
    }

    /// `(width, height)` of `plane` in pixels, given the frame's nominal
    /// `frame_w` × `frame_h`. Panics on an out-of-range plane index.
    ///
    /// A subsampled plane's dimension is the frame dimension divided by the
    /// per-axis `size_scale`, **rounded up** — exactly matching FFmpeg's
    /// `av_image_fill_pointers` / `av_image_fill_plane_sizes`
    /// (`AV_CEIL_RSHIFT(dim, log2_chroma)`, i.e. `(dim + s - 1) / s`). At an
    /// odd frame dimension a 4:2:0 / 4:2:2 chroma plane therefore keeps its
    /// trailing half-covered row/column (e.g. 4:2:0 at 321×241 → chroma
    /// 161×121, not 160×120). This is the row/column count every
    /// FFmpeg-allocated source plane actually carries, so allocation sizing,
    /// stride recovery, and copy bounds must all agree with it. For even
    /// dimensions (the common case) the result is identical to a truncating
    /// divide.
    pub fn plane_size(self, frame_w: u32, frame_h: u32, plane: u8) -> (u32, u32) {
        let info =
            self.plane_layout().plane(plane).unwrap_or_else(|| panic!("plane {plane} out of range for {self:?}"));
        let (sx, sy) = info.size_scale;
        (frame_w.div_ceil(sx as u32), frame_h.div_ceil(sy as u32))
    }

    /// Bits per sample in a single channel. For float formats, returns
    /// the width of the float (16 or 32).
    pub const fn bits_per_sample(self) -> u8 {
        use PixelFormat as P;
        match self {
            // 8-bit
            P::NV12
            | P::NV21
            | P::NV16
            | P::NV24
            | P::NV12A
            | P::YUV420P
            | P::YUV422P
            | P::YUV444P
            | P::UYVY422
            | P::YUYV422
            | P::RgbaU8
            | P::BgraU8
            | P::RgbxU8
            | P::BgrxU8 => 8,
            // 10-bit
            P::P010LE
            | P::P210LE
            | P::P410LE
            | P::YUV420P10LE
            | P::YUV422P10LE
            | P::YUV444P10LE
            | P::YUVA444P10LE
            | P::Y210LE
            | P::Rgb10A2 => 10,
            // 12-bit
            P::YUV420P12LE | P::YUV422P12LE | P::YUV444P12LE | P::YUVA444P12LE => 12,
            // 14-bit
            P::YUV420P14LE | P::YUV422P14LE | P::YUV444P14LE => 14,
            // 16-bit integer
            P::P016LE
            | P::P216LE
            | P::P416LE
            | P::YUV420P16LE
            | P::YUV422P16LE
            | P::YUV444P16LE
            | P::AYUV64LE
            | P::V216
            | P::RgbaU16
            | P::BgraU16
            | P::RgbU16
            | P::R16U
            | P::Rgba16U => 16,
            // Float widths
            P::RgbaF16 | P::BgraF16 => 16,
            P::RgbaF32 | P::BgraF32 | P::R32F => 32,
        }
    }

    /// Stable ordinal for the format as GPU shaders see it.
    ///
    /// **Hard-coded literal match, NOT `self as u32`** — future variant
    /// insertion-order changes must not silently re-order the ordinals
    /// the GPU shaders depend on. Despite `#[non_exhaustive]`, this
    /// match is exhaustive within the defining crate; any future
    /// variant added without a matching arm here will fail to compile.
    pub const fn shader_id(self) -> u32 {
        use PixelFormat as P;
        match self {
            P::NV12 => 0,
            P::NV21 => 1,
            P::P010LE => 2,
            P::P016LE => 3,
            P::P210LE => 4,
            P::P216LE => 5,
            P::P410LE => 6,
            P::P416LE => 7,
            P::YUV420P => 8,
            P::YUV422P => 9,
            P::YUV444P => 10,
            P::YUV420P10LE => 11,
            P::YUV420P12LE => 12,
            P::YUV420P14LE => 13,
            P::YUV420P16LE => 14,
            P::YUV422P10LE => 15,
            P::YUV422P12LE => 16,
            P::YUV422P14LE => 17,
            P::YUV422P16LE => 18,
            P::YUV444P10LE => 19,
            P::YUV444P12LE => 20,
            P::YUV444P14LE => 21,
            P::YUV444P16LE => 22,
            P::UYVY422 => 23,
            P::YUYV422 => 24,
            P::AYUV64LE => 25,
            P::RgbaU8 => 26,
            P::BgraU8 => 27,
            P::RgbaU16 => 28,
            P::BgraU16 => 29,
            P::RgbaF16 => 30,
            P::BgraF16 => 31,
            P::RgbaF32 => 32,
            P::BgraF32 => 33,
            P::RgbU16 => 34,
            P::R16U => 35,
            P::R32F => 36,
            P::Rgba16U => 37,
            P::YUVA444P10LE => 38,
            P::YUVA444P12LE => 39,
            P::Rgb10A2 => 40,
            P::NV16 => 41,
            P::NV24 => 42,
            P::V216 => 43,
            P::NV12A => 44,
            P::Y210LE => 45,
            // Appended — existing ordinals are load-bearing in any shader
            // that switches on them and must never be renumbered.
            P::RgbxU8 => 46,
            P::BgrxU8 => 47,
        }
    }

    /// True for packed multi-channel layouts that do not map to a native
    /// wgpu texture format. The decoded `GpuResource` for these formats
    /// MUST be a buffer-shape variant (`CudaBufferHandle` / `OpenClMem`
    /// of `cl_mem` buffer type / etc.) and consumers MUST run an
    /// expand pass before sampling.
    ///
    /// Currently: `RgbU16` (6 B/px 16-bit RGB from R3D CUDA / OpenCL).
    /// (`Rgb10A2` is NOT one of these — it maps natively to
    /// `wgpu::TextureFormat::Rgb10a2Unorm`.)
    pub const fn is_packed_buffer_shape(self) -> bool {
        use PixelFormat as P;
        matches!(self, P::RgbU16)
    }

    /// True if the format's underlying precision is ≥10 bits and the
    /// layout is plausibly HDR. SDR 8-bit RGB/NV12/YUV420P are excluded.
    pub const fn is_hdr_native(self) -> bool {
        use PixelFormat as P;
        // Excluded: 8-bit families — even with a BT.2020 matrix these
        // clip in practice.
        let is_sdr_8bit = matches!(
            self,
            P::NV12
                | P::NV21
                | P::NV16
                | P::NV24
                | P::NV12A
                | P::YUV420P
                | P::YUV422P
                | P::YUV444P
                | P::UYVY422
                | P::YUYV422
                | P::RgbaU8
                | P::BgraU8
                | P::RgbxU8
                | P::BgrxU8
        );
        !is_sdr_8bit && self.bits_per_sample() >= 10
    }

    /// The [`ColorFamily`] this format encodes its samples in — the coarse
    /// classification a colour-neutral-vs-colour-changing repack decision
    /// keys on (`Yuv` ↔ `Yuv` and `Rgb` ↔ `Rgb` are layout/bit-depth
    /// repacks within one colourspace; a family crossing is a real matrix
    /// transform). Hard-coded literal match — exhaustive within the
    /// defining crate, so a future variant must add an arm here.
    pub const fn color_family(self) -> ColorFamily {
        use ColorFamily as C;
        use PixelFormat as P;
        match self {
            // Luma + chroma carriers (planar, biplanar, packed, alpha-planar).
            P::NV12
            | P::NV21
            | P::NV16
            | P::NV24
            | P::NV12A
            | P::P010LE
            | P::P016LE
            | P::P210LE
            | P::P216LE
            | P::P410LE
            | P::P416LE
            | P::YUV420P
            | P::YUV422P
            | P::YUV444P
            | P::YUV420P10LE
            | P::YUV420P12LE
            | P::YUV420P14LE
            | P::YUV420P16LE
            | P::YUV422P10LE
            | P::YUV422P12LE
            | P::YUV422P14LE
            | P::YUV422P16LE
            | P::YUV444P10LE
            | P::YUV444P12LE
            | P::YUV444P14LE
            | P::YUV444P16LE
            | P::YUVA444P10LE
            | P::YUVA444P12LE
            | P::UYVY422
            | P::YUYV422
            | P::AYUV64LE
            | P::V216
            | P::Y210LE => C::Yuv,
            // Additive RGB (packed + buffer-shape).
            P::RgbaU8
            | P::BgraU8
            | P::RgbxU8
            | P::BgrxU8
            | P::RgbaU16
            | P::BgraU16
            | P::RgbaF16
            | P::BgraF16
            | P::RgbaF32
            | P::BgraF32
            | P::Rgb10A2
            | P::RgbU16 => C::Rgb,
            // Non-colour scalar / raw-channel fields.
            P::R16U | P::R32F | P::Rgba16U => C::Scalar,
        }
    }

    /// The bit depth at which a **packed** source carried on this format must have
    /// its limited swing decoded to full swing, or `0` when nothing is owed.
    ///
    /// **The ONE derivation of that answer** — every route that ingests a
    /// packed RGB source (an encoder's RGB plan, a still-image conversion, a
    /// render chain's RGB input stage) should call it rather than derive its
    /// own. A second derivation is precisely how one route ends up right and
    /// another silently wrong, which is the failure the tri-state exists to
    /// remove.
    ///
    /// It takes the **resolved** swing because that is what it consumes: "this
    /// source is narrow AND its carrier has an integer code space". Callers
    /// holding a wire tag resolve it first — `range.resolve(fmt.color_family())`
    /// — and callers downstream of a resolve
    /// boundary (an encode plan, a render-chain front) already hold the
    /// definite value and must not re-derive it.
    ///
    /// This crate does not call it itself: it exists for the render-chain
    /// fronts and encode plans built on top of it.
    ///
    /// `0` (nothing owed) is returned for four genuinely different reasons,
    /// and all four are correct:
    ///
    /// - the range **resolves full** — an explicit `Full`, or an unsignalled
    ///   RGB source, which `pl_color_levels_guess` reads as full;
    /// - the carrier is **float** (`RgbaF16` / `RgbaF32` / BGRA twins) — a
    ///   narrow *swing* is a property of an integer code space and a float
    ///   edge has none, so there is nothing to decode even if a caller
    ///   insisted on the tag;
    /// - the carrier is a **scalar raw-channel field** (`R16U` / `R32F` /
    ///   `Rgba16U`) — no luma pedestal, and reachable only via an explicit
    ///   `Limited` tag that does not describe a sensor mosaic or an index map;
    /// - the carrier is **YUV** — its swing belongs to the YUV conversion path
    ///   (luma / chroma dequantisation, which has its own chroma pedestal and
    ///   its own MSB-aligned storage convention). Answering a depth here would
    ///   invite a second, wrong decode on top of the right one.
    ///
    /// The `0` sentinel suits a GPU-side config field that takes this depth
    /// directly with the same "0 = no expand" convention, so there is one
    /// convention end to end rather than an `Option` that every caller
    /// unwraps to `0`.
    ///
    /// **Depths are the *natural* normalisation** (`code / (2^d − 1)`), which
    /// is how a sampler reads a packed texture — NOT the MSB-aligned-in-16-bit
    /// convention a YUV dequantiser uses for a ≥10-bit plane. The two agree
    /// at 8 and 16 bits and differ by ~0.1% at 10/12/14, which is why a
    /// packed path needs its own affine rather than reusing the YUV one.
    pub const fn packed_expand_depth(self, range: ResolvedRange) -> u32 {
        use PixelFormat as P;
        match range {
            // The match is **literal and exhaustive**, matching
            // `plane_layout` / `shader_id` / `color_family`: a new
            // `#[non_exhaustive]` `PixelFormat` variant must fail to compile
            // here rather than fall into a catch-all that silently answers
            // "nothing owed" for a carrier that owes a levels decode.
            ResolvedRange::Limited => match self {
                // Integer packed RGB — the only carriers that owe a decode.
                // Depths are the *natural* normalisation `code / (2^d − 1)`.
                P::RgbaU8 | P::BgraU8 | P::RgbxU8 | P::BgrxU8 => 8,
                P::Rgb10A2 => 10,
                P::RgbaU16 | P::BgraU16 | P::RgbU16 => 16,
                // Float RGB carriers: a narrow *swing* is a property of an
                // integer code space and a float edge has none, so nothing
                // is owed even when a caller insisted on the tag.
                P::RgbaF16 | P::BgraF16 | P::RgbaF32 | P::BgraF32 => 0,
                // Non-colour scalar / raw-channel fields. `ColorRange::resolve`
                // guesses these FULL, so they only land here on an explicit
                // `Limited` tag — which does not describe a raw sensor
                // mosaic or an index map, and owes no decode either way.
                P::R16U | P::R32F | P::Rgba16U => 0,
                // Every YUV carrier: its swing belongs to the YUV conversion
                // path (luma / chroma dequantisation, with its own chroma
                // pedestal and MSB-aligned storage convention). Answering a
                // depth here would invite a second, wrong decode.
                P::NV12
                | P::NV21
                | P::NV16
                | P::NV24
                | P::NV12A
                | P::P010LE
                | P::P016LE
                | P::P210LE
                | P::P216LE
                | P::P410LE
                | P::P416LE
                | P::YUV420P
                | P::YUV422P
                | P::YUV444P
                | P::YUV420P10LE
                | P::YUV420P12LE
                | P::YUV420P14LE
                | P::YUV420P16LE
                | P::YUV422P10LE
                | P::YUV422P12LE
                | P::YUV422P14LE
                | P::YUV422P16LE
                | P::YUV444P10LE
                | P::YUV444P12LE
                | P::YUV444P14LE
                | P::YUV444P16LE
                | P::YUVA444P10LE
                | P::YUVA444P12LE
                | P::UYVY422
                | P::YUYV422
                | P::AYUV64LE
                | P::V216
                | P::Y210LE => 0,
            },
            // Full swing owes nothing, by definition. There is no third arm
            // to write — which is the point of taking the resolved swing:
            // "what if the guess leaked an unknown through" is not a runtime
            // possibility to defend against, it does not typecheck.
            ResolvedRange::Full => 0,
        }
    }

    /// What this format's fourth component means — the **single source of
    /// truth** for every alpha decision. See
    /// [`AlphaChannel`] for why the answer cannot be derived from the plane
    /// layout: an X-padded layout and its alpha-carrying twin are identical
    /// bytes.
    ///
    /// Hard-coded literal match, exhaustive within the defining crate — a
    /// future variant must state its answer here rather than inherit one.
    pub const fn alpha_channel(self) -> AlphaChannel {
        use AlphaChannel as A;
        use PixelFormat as P;
        match self {
            // Real, straight alpha: the YCbCr+alpha carriers (`NV12A`
            // tri-planar NV12+A, `AYUV64LE` packed 4:4:4:4, the planar
            // `YUVA444P*` family) and every packed `Rgba*`/`Bgra*` layout,
            // including the 2-bit-alpha `Rgb10A2`.
            P::NV12A
            | P::AYUV64LE
            | P::YUVA444P10LE
            | P::YUVA444P12LE
            | P::RgbaU8
            | P::BgraU8
            | P::RgbaU16
            | P::BgraU16
            | P::RgbaF16
            | P::BgraF16
            | P::RgbaF32
            | P::BgraF32
            | P::Rgb10A2 => A::Straight,
            // Four channels, but the fourth is padding — the desktop
            // X-formats. Byte-identical storage to `RgbaU8` / `BgraU8`.
            P::RgbxU8 | P::BgrxU8 => A::Padding,
            // No fourth component at all.
            P::NV12
            | P::NV21
            | P::NV16
            | P::NV24
            | P::P010LE
            | P::P016LE
            | P::P210LE
            | P::P216LE
            | P::P410LE
            | P::P416LE
            | P::YUV420P
            | P::YUV422P
            | P::YUV444P
            | P::YUV420P10LE
            | P::YUV420P12LE
            | P::YUV420P14LE
            | P::YUV420P16LE
            | P::YUV422P10LE
            | P::YUV422P12LE
            | P::YUV422P14LE
            | P::YUV422P16LE
            | P::YUV444P10LE
            | P::YUV444P12LE
            | P::YUV444P14LE
            | P::YUV444P16LE
            | P::UYVY422
            | P::YUYV422
            | P::V216
            | P::Y210LE
            | P::RgbU16
            | P::R16U
            | P::R32F
            | P::Rgba16U => A::None,
        }
    }

    /// True when the format carries a dedicated **alpha** channel/plane —
    /// the single source of truth a compositor keys on to decide whether a
    /// decoded frame needs alpha compositing (opaque formats are blitted
    /// directly). Exactly [`AlphaChannel::Straight`]: an X-padded layout
    /// ([`Self::RgbxU8`] / [`Self::BgrxU8`]) has four channels but **no**
    /// alpha, and answers `false` here, so a compositor gate that reads this
    /// predicate treats it as opaque.
    pub const fn has_alpha(self) -> bool {
        matches!(self.alpha_channel(), AlphaChannel::Straight)
    }

    /// True for biplanar YUV layouts (one luma plane + one interleaved
    /// chroma plane). Covers NV12/NV21 (4:2:0 8-bit), NV16 (4:2:2 8-bit),
    /// NV24 (4:4:4 8-bit), P010/P016 (4:2:0 10/16-bit), P210/P216 (4:2:2
    /// 10/16-bit), P410/P416 (4:4:4 10/16-bit).
    pub const fn is_biplanar(self) -> bool {
        use PixelFormat as P;
        matches!(
            self,
            P::NV12
                | P::NV21
                | P::NV16
                | P::NV24
                | P::P010LE
                | P::P016LE
                | P::P210LE
                | P::P216LE
                | P::P410LE
                | P::P416LE
        )
    }

    /// True when zero-copy importing / sampling this format needs the
    /// [`wgpu::Features::TEXTURE_FORMAT_16BIT_NORM`] adapter feature — i.e. any
    /// plane rides a 16-bit **normalized** storage primitive
    /// ([`PlaneFormat::requires_16bit_norm`]). The 10-/16-bit biplanar YUV
    /// families (`P010`/`P210`/`P410`/`P016`/`P216`/`P416`), the packed 16-bit
    /// `AYUV64LE`, and the 16-bit-unorm RGBA packings return `true`; the 8-bit
    /// families (`NV12`/`NV16`/`NV24`/…), the integer scalar fields (`R16U`,
    /// `Rgba16U` — `R16Uint`/`Rgba16Uint` storage), and the float formats
    /// return `false`. Derived from [`Self::plane_layout`], so a new variant is
    /// classified automatically.
    ///
    /// A decode backend can probe this against the device's feature set to
    /// fail fast at construction (a clear error) instead of surfacing a late,
    /// less-readable HAL validation failure at import time.
    pub const fn requires_16bit_norm(self) -> bool {
        let layout = self.plane_layout();
        let count = layout.count();
        let mut i: u8 = 0;
        while i < count {
            if let Some(p) = layout.plane(i)
                && p.format.requires_16bit_norm()
            {
                return true;
            }
            i += 1;
        }
        false
    }

    /// True for any multi-plane layout whose planes are all bare channel
    /// planes (`R8` / `R16` / `RG8` / `RG16`) — the structural requirement
    /// for packing a frame into one linear per-plane-footprint allocation
    /// (e.g. one CUDA buffer carrying every plane of a frame). Covers every
    /// [`Self::is_biplanar`] format plus the triplanar `YUV*P*` family and
    /// the alpha-planar `YUVA444P*` quad layouts; packed formats
    /// (`UYVY422` / `AYUV64LE` / RGB) are single-plane and excluded.
    /// Derived from [`Self::plane_layout`], so a new planar variant is
    /// covered automatically.
    pub const fn is_planar(self) -> bool {
        let layout = self.plane_layout();
        let count = layout.count();
        if count < 2 {
            return false;
        }
        let mut i: u8 = 0;
        while i < count {
            let format = match layout.plane(i) {
                Some(p) => p.format,
                None => return false,
            };
            if !matches!(format, PlaneFormat::R8 | PlaneFormat::R16 | PlaneFormat::RG8 | PlaneFormat::RG16) {
                return false;
            }
            i += 1;
        }
        true
    }

    /// FFmpeg sub-byte storage convention: for sub-16-bit YUV planar
    /// formats the 10/12/14-bit active code sits in one of two halves of
    /// the 16-bit storage word.
    ///
    /// - **MSB-aligned** (`u16 = code << (16 - bit_depth)`): biplanar
    ///   `P010 / P016 / P210 / P216 / P410 / P416` (FFmpeg
    ///   `AVPixFmtDescriptor.shift = 16 - depth`).
    /// - **LSB-aligned** (`u16 = code`): triplanar
    ///   `YUV{420,422,444}P{10,12,14}LE` plus the alpha-planar
    ///   `YUVA444P{10,12}LE` (FFmpeg `AVPixFmtDescriptor.shift = 0`).
    ///
    /// 8-bit (`R8`) and 16-bit (`R16` w/ depth=16) formats have no
    /// shift ambiguity and return `true`. RGB / packed YUV formats also
    /// return `true` (they have no half-word slack).
    pub const fn is_msb_aligned_storage(self) -> bool {
        use PixelFormat as P;
        !matches!(
            self,
            P::YUV420P10LE
                | P::YUV420P12LE
                | P::YUV420P14LE
                | P::YUV422P10LE
                | P::YUV422P12LE
                | P::YUV422P14LE
                | P::YUV444P10LE
                | P::YUV444P12LE
                | P::YUV444P14LE
                | P::YUVA444P10LE
                | P::YUVA444P12LE
        )
    }

    /// Storage-alignment bridge factor between a normalised storage
    /// sample (`code / 65535`) and an MSB-aligned dequant / quant ladder —
    /// the per-format constant a GPU shader reading such a sample must apply
    /// too, so CPU and GPU paths agree exactly. Returns
    /// `2^(16 - bit_depth)` for FFmpeg's LSB-aligned
    /// triplanar `YUV*P{10,12,14}LE` family + `YUVA444P{10,12}LE`
    /// (`AVPixFmtDescriptor.shift == 0`) and `1.0` for every other
    /// layout (8-bit, true 16-bit P16LE,
    /// MSB-aligned biplanar, packed, RGB) — the bridge collapses to a
    /// no-op there.
    ///
    /// Apply on the **read** side: multiply the storage-normalised sample
    /// to lift an LSB-aligned value into the MSB domain. The **write**
    /// side divides by this (or multiplies by
    /// [`storage_sample_scale_inv`](Self::storage_sample_scale_inv)).
    pub const fn storage_sample_scale(self) -> f32 {
        if self.is_msb_aligned_storage() {
            1.0
        } else {
            // LSB-aligned triplanar only: `is_msb_aligned_storage` has
            // already excluded the 8-bit and true-16-bit (P16LE)
            // variants, so `bits_per_sample` here is 10/12/14.
            (1u32 << (16 - self.bits_per_sample() as u32)) as f32
        }
    }

    /// Write-side reciprocal of
    /// [`storage_sample_scale`](Self::storage_sample_scale): multiply an
    /// MSB-aligned quantised sample by this to land it in this format's
    /// storage convention. For a converter that multiplies on the write
    /// side; dividing by `storage_sample_scale` directly is equivalent (the
    /// factor is a power of two, so both are exact).
    pub const fn storage_sample_scale_inv(self) -> f32 {
        1.0 / self.storage_sample_scale()
    }
}

/// `PixelFormat::ALL` **is** the `shader_id` table: index == ordinal, no gap,
/// no duplicate, and `COUNT` names its length. Checked at compile time, so a
/// roster that drifts out of step with `shader_id` cannot ship.
const _: () = {
    assert!(PixelFormat::ALL.len() == PixelFormat::COUNT);
    let mut i = 0;
    while i < PixelFormat::ALL.len() {
        assert!(PixelFormat::ALL[i].shader_id() as usize == i);
        i += 1;
    }
};