oxideav-core 0.1.7

Core types and registries for oxideav — timestamps, packets, frames, codec/container/source/filter registries (pure Rust, no C deps)
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
//! Media-type and sample/pixel format enumerations.
//!
//! Audio channel ordering follows SMPTE 2036-2 / ITU-R BS.775 conventions
//! for surround layouts; per-channel positions are named with the
//! WAVEFORMATEXTENSIBLE / FFmpeg "front-left, front-right, …" vocabulary.

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MediaType {
    Audio,
    Video,
    Subtitle,
    Data,
    Unknown,
}

/// A single speaker position within a multi-channel audio layout.
///
/// Names follow the WAVEFORMATEXTENSIBLE / FFmpeg / SMPTE convention.
/// `Side*` and `Back*` are kept distinct (mirroring 7.1's
/// L/R + Ls/Rs + Lb/Rb separation) so codecs that surface the
/// distinction don't collapse it. `Lr`/`Rr` (rear / back-rear) are aliases
/// for `BackLeft`/`BackRight` in this taxonomy — the rear pair sits behind
/// the listener on the room's centreline-extension, the side pair is at
/// roughly ±90° from front. The enum is `#[non_exhaustive]` so additional
/// positions (height channels for Atmos / Auro-3D, etc.) can be added
/// without breaking downstream match arms.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChannelPosition {
    /// Front-left (L). 30° left of centre in BS.775 listening geometry.
    FrontLeft,
    /// Front-right (R). 30° right of centre.
    FrontRight,
    /// Front-centre (C). Direct centre, 0°.
    FrontCenter,
    /// Low-frequency effects (LFE). Sub-bass, no positional meaning.
    LowFrequency,
    /// Back-left (Lb / Lr). Behind the listener, ±150° in 7.1.
    BackLeft,
    /// Back-right (Rb / Rr). Behind the listener, mirror of `BackLeft`.
    BackRight,
    /// Front left-of-centre (Lc). Used in cinema 7.1 SDDS layouts.
    FrontLeftOfCenter,
    /// Front right-of-centre (Rc). Mirror of `FrontLeftOfCenter`.
    FrontRightOfCenter,
    /// Back-centre (Cs). Single rear channel for 6.1 / BS.775 4.0.
    BackCenter,
    /// Side-left (Ls). ±90° on the listener's left in 5.1 / 7.1.
    SideLeft,
    /// Side-right (Rs). Mirror of `SideLeft`.
    SideRight,
    /// Top front-left. Atmos / Auro-3D height layer (placeholder).
    TopFrontLeft,
    /// Top front-right. Atmos / Auro-3D height layer (placeholder).
    TopFrontRight,
    /// Top back-left. Atmos / Auro-3D ceiling layer (placeholder).
    TopBackLeft,
    /// Top back-right. Atmos / Auro-3D ceiling layer (placeholder).
    TopBackRight,
}

/// Audio channel layout — names a fixed ordered tuple of speaker
/// positions, OR carries a discrete fallback count when the layout is
/// unknown / non-standard.
///
/// Channel orderings are taken from ITU-R BS.775 (5.1 / 7.1 surround
/// reference) and SMPTE ST 2036-2 (audio channel ordering for UHDTV).
/// For 5.1 the canonical order this crate adopts is
/// `L, R, C, LFE, Ls, Rs` (the WAVEFORMATEXTENSIBLE / Vorbis / Opus
/// convention). 7.1 extends that with `Lb, Rb` (back-rear pair).
///
/// The `Stereo` variant covers both regular two-channel stereo and the
/// AC-3 / AC-4 matrix-encoded downmix carriers `Lo/Ro` ("two of",
/// downmix-compatible) and `Lt/Rt` ("matrix-encoded for Pro Logic
/// extraction"); the dedicated [`LoRo`] / [`LtRt`] variants surface the
/// distinction explicitly when a downstream filter or muxer needs it.
///
/// `DiscreteN(n)` is the catch-all for "we know there are `n` channels
/// but no recognised layout" — used when a codec produces an unusual
/// channel count (>8) or when the container failed to surface a layout
/// flag. It is the only variant whose `position()` returns `None`.
///
/// Marked `#[non_exhaustive]` so additional standard layouts (Atmos
/// 7.1.4, Auro-3D 9.1, …) can be added without breaking match-exhaustive
/// downstream consumers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChannelLayout {
    /// Mono (1ch): C.
    Mono,
    /// Stereo (2ch): L, R.
    Stereo,
    /// 2.1 (3ch): L, R, LFE.
    Stereo21,
    /// 3.0 surround (3ch): L, R, C.
    Surround30,
    /// Quadraphonic (4ch): L, R, Ls, Rs — no centre, side surrounds.
    Quad,
    /// 4.0 surround per BS.775 (4ch): L, R, C, Cs — centre + back surround.
    Surround40,
    /// 4.1 surround (5ch): L, R, C, Cs, LFE.
    Surround41,
    /// 5.0 surround (5ch): L, R, C, Ls, Rs.
    Surround50,
    /// 5.1 surround (6ch): L, R, C, LFE, Ls, Rs.
    Surround51,
    /// 6.0 surround (6ch): L, R, C, Cs, Ls, Rs.
    Surround60,
    /// 6.1 surround (7ch): L, R, C, LFE, Cs, Ls, Rs.
    Surround61,
    /// 7.0 surround (7ch): L, R, C, Ls, Rs, Lb, Rb.
    Surround70,
    /// 7.1 surround (8ch): L, R, C, LFE, Ls, Rs, Lb, Rb.
    Surround71,
    /// AC-3 / AC-4 Lo/Ro stereo downmix (2ch). Two-channel mix preserving
    /// downmix-compatibility coefficients; not matrix-encoded.
    LoRo,
    /// AC-3 / AC-4 Lt/Rt stereo downmix (2ch). Two-channel matrix-encoded
    /// downmix carrying surround information for Dolby Pro Logic decoding.
    LtRt,
    /// Discrete fallback: `n` channels with no recognised layout. Used for
    /// unusual / >8ch / unknown layouts surfaced by exotic codecs or
    /// containers that drop layout flags.
    DiscreteN(u16),
}

impl ChannelLayout {
    /// Number of channels in this layout.
    pub fn channel_count(&self) -> u16 {
        match self {
            Self::Mono => 1,
            Self::Stereo | Self::LoRo | Self::LtRt => 2,
            Self::Stereo21 | Self::Surround30 => 3,
            Self::Quad | Self::Surround40 => 4,
            Self::Surround41 | Self::Surround50 => 5,
            Self::Surround51 | Self::Surround60 => 6,
            Self::Surround61 | Self::Surround70 => 7,
            Self::Surround71 => 8,
            Self::DiscreteN(n) => *n,
        }
    }

    /// Speaker positions in canonical order. Returns an empty slice for
    /// `DiscreteN` since the layout is unknown — call [`positions_owned`]
    /// to get a `Vec` if you need to enumerate slots regardless of
    /// known/unknown status.
    ///
    /// [`positions_owned`]: Self::positions_owned
    pub fn positions(&self) -> &'static [ChannelPosition] {
        use ChannelPosition::*;
        match self {
            Self::Mono => &[FrontCenter],
            Self::Stereo | Self::LoRo | Self::LtRt => &[FrontLeft, FrontRight],
            Self::Stereo21 => &[FrontLeft, FrontRight, LowFrequency],
            Self::Surround30 => &[FrontLeft, FrontRight, FrontCenter],
            Self::Quad => &[FrontLeft, FrontRight, SideLeft, SideRight],
            Self::Surround40 => &[FrontLeft, FrontRight, FrontCenter, BackCenter],
            Self::Surround41 => &[FrontLeft, FrontRight, FrontCenter, BackCenter, LowFrequency],
            Self::Surround50 => &[FrontLeft, FrontRight, FrontCenter, SideLeft, SideRight],
            Self::Surround51 => &[
                FrontLeft,
                FrontRight,
                FrontCenter,
                LowFrequency,
                SideLeft,
                SideRight,
            ],
            Self::Surround60 => &[
                FrontLeft,
                FrontRight,
                FrontCenter,
                BackCenter,
                SideLeft,
                SideRight,
            ],
            Self::Surround61 => &[
                FrontLeft,
                FrontRight,
                FrontCenter,
                LowFrequency,
                BackCenter,
                SideLeft,
                SideRight,
            ],
            Self::Surround70 => &[
                FrontLeft,
                FrontRight,
                FrontCenter,
                SideLeft,
                SideRight,
                BackLeft,
                BackRight,
            ],
            Self::Surround71 => &[
                FrontLeft,
                FrontRight,
                FrontCenter,
                LowFrequency,
                SideLeft,
                SideRight,
                BackLeft,
                BackRight,
            ],
            Self::DiscreteN(_) => &[],
        }
    }

    /// Owned position list. For known layouts this clones [`positions`];
    /// for `DiscreteN(n)` it returns an empty `Vec` (positions remain
    /// unknown). Provided so callers that just want "give me positions
    /// for any layout" don't have to special-case the discrete arm.
    ///
    /// [`positions`]: Self::positions
    pub fn positions_owned(&self) -> Vec<ChannelPosition> {
        self.positions().to_vec()
    }

    /// Speaker position at slot `idx` in canonical order, or `None` for
    /// out-of-range slots and for `DiscreteN` (where the layout is
    /// unknown).
    pub fn position(&self, idx: usize) -> Option<ChannelPosition> {
        self.positions().get(idx).copied()
    }

    /// True when this layout carries a low-frequency-effects (LFE) channel.
    pub fn has_lfe(&self) -> bool {
        self.positions()
            .iter()
            .any(|p| matches!(p, ChannelPosition::LowFrequency))
    }

    /// True when this layout carries surround information (more than two
    /// channels OR an LFE). `Stereo` / `Mono` return false; `LoRo` /
    /// `LtRt` are 2-channel downmixes and also return false even though
    /// they encode surround content (that's the whole point of a
    /// downmix).
    pub fn is_surround(&self) -> bool {
        self.channel_count() > 2 || self.has_lfe()
    }

    /// Back-compat bridge: infer a layout from a bare channel count.
    ///
    /// This mapping is what lets codecs that haven't been updated to set
    /// a layout explicitly continue to work: they keep producing a count
    /// and we infer the most-common layout for that count. The choices
    /// follow industry defaults — 5.1 wins for 6ch (more common than
    /// 6.0), 7.1 wins for 8ch, and so on.
    ///
    /// | count | layout       |
    /// |-------|--------------|
    /// | 1     | `Mono`       |
    /// | 2     | `Stereo`     |
    /// | 3     | `Surround30` |
    /// | 4     | `Quad`       |
    /// | 5     | `Surround50` |
    /// | 6     | `Surround51` |
    /// | 7     | `Surround61` |
    /// | 8     | `Surround71` |
    /// | other | `DiscreteN`  |
    pub fn from_count(n: u16) -> ChannelLayout {
        match n {
            1 => Self::Mono,
            2 => Self::Stereo,
            3 => Self::Surround30,
            4 => Self::Quad,
            5 => Self::Surround50,
            6 => Self::Surround51,
            7 => Self::Surround61,
            8 => Self::Surround71,
            other => Self::DiscreteN(other),
        }
    }
}

impl std::fmt::Display for ChannelLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Mono => "mono",
            Self::Stereo => "stereo",
            Self::Stereo21 => "2.1",
            Self::Surround30 => "3.0",
            Self::Quad => "quad",
            Self::Surround40 => "4.0",
            Self::Surround41 => "4.1",
            Self::Surround50 => "5.0",
            Self::Surround51 => "5.1",
            Self::Surround60 => "6.0",
            Self::Surround61 => "6.1",
            Self::Surround70 => "7.0",
            Self::Surround71 => "7.1",
            Self::LoRo => "loro",
            Self::LtRt => "ltrt",
            Self::DiscreteN(n) => return write!(f, "discrete{n}"),
        };
        f.write_str(s)
    }
}

/// Error returned by the [`ChannelLayout`] `FromStr` impl when the input
/// doesn't match any recognised layout name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseChannelLayoutError(pub String);

impl std::fmt::Display for ParseChannelLayoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unrecognised channel layout: {:?}", self.0)
    }
}

impl std::error::Error for ParseChannelLayoutError {}

impl std::str::FromStr for ChannelLayout {
    type Err = ParseChannelLayoutError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lower = s.trim().to_ascii_lowercase();
        let layout = match lower.as_str() {
            "mono" | "1.0" => Self::Mono,
            "stereo" | "2.0" => Self::Stereo,
            "2.1" => Self::Stereo21,
            "3.0" | "surround3" | "surround30" => Self::Surround30,
            "quad" => Self::Quad,
            "4.0" | "surround4" | "surround40" => Self::Surround40,
            "4.1" | "surround41" => Self::Surround41,
            "5.0" | "surround5" | "surround50" => Self::Surround50,
            "5.1" | "surround51" => Self::Surround51,
            "6.0" | "surround6" | "surround60" => Self::Surround60,
            "6.1" | "surround61" => Self::Surround61,
            "7.0" | "surround7" | "surround70" => Self::Surround70,
            "7.1" | "surround71" => Self::Surround71,
            "loro" | "lo/ro" => Self::LoRo,
            "ltrt" | "lt/rt" => Self::LtRt,
            other => {
                if let Some(rest) = other.strip_prefix("discrete") {
                    if let Ok(n) = rest.parse::<u16>() {
                        return Ok(Self::DiscreteN(n));
                    }
                }
                return Err(ParseChannelLayoutError(s.to_owned()));
            }
        };
        Ok(layout)
    }
}

/// Audio sample format.
///
/// Variants carry **stable explicit discriminants** — the integer value
/// of `SampleFormat::S16 as u8` is part of the public ABI. Add new
/// variants only at the end with a fresh number; never reorder, renumber,
/// or remove. `#[non_exhaustive]` lets the enum grow without breaking
/// downstream `match` statements; pinned discriminants additionally let
/// the format round-trip through any byte-stable serialization
/// (config files, capability blobs, IPC) without losing meaning across
/// crate versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum SampleFormat {
    /// Unsigned 8-bit, interleaved.
    U8 = 0,
    /// Signed 8-bit, interleaved. Native format of Amiga 8SVX and MOD samples.
    S8 = 1,
    /// Signed 16-bit little-endian, interleaved.
    S16 = 2,
    /// Signed 24-bit packed (3 bytes/sample) little-endian, interleaved.
    S24 = 3,
    /// Signed 32-bit little-endian, interleaved.
    S32 = 4,
    /// 32-bit IEEE float, interleaved.
    F32 = 5,
    /// 64-bit IEEE float, interleaved.
    F64 = 6,
    /// Planar variants — one plane per channel.
    U8P = 7,
    S16P = 8,
    S32P = 9,
    F32P = 10,
    F64P = 11,
}

impl SampleFormat {
    pub fn is_planar(&self) -> bool {
        matches!(
            self,
            Self::U8P | Self::S16P | Self::S32P | Self::F32P | Self::F64P
        )
    }

    /// Bytes per sample *per channel*.
    pub fn bytes_per_sample(&self) -> usize {
        match self {
            Self::U8 | Self::U8P | Self::S8 => 1,
            Self::S16 | Self::S16P => 2,
            Self::S24 => 3,
            Self::S32 | Self::S32P | Self::F32 | Self::F32P => 4,
            Self::F64 | Self::F64P => 8,
        }
    }

    pub fn is_float(&self) -> bool {
        matches!(self, Self::F32 | Self::F64 | Self::F32P | Self::F64P)
    }

    /// Number of `Vec<u8>` planes an [`AudioFrame`](crate::AudioFrame)
    /// of this format carries for `channels` channels: planar formats
    /// use one plane per channel, interleaved formats use one plane
    /// total.
    pub fn plane_count(&self, channels: u16) -> usize {
        if self.is_planar() {
            channels as usize
        } else {
            1
        }
    }
}

/// Video pixel format.
///
/// Variants carry **stable explicit discriminants** — the integer value
/// of `PixelFormat::Yuv420P as u16` is part of the public ABI. Add new
/// variants only at the end with a fresh number; never reorder, renumber,
/// or remove. `#[non_exhaustive]` lets the enum grow without breaking
/// downstream `match` statements; pinned discriminants additionally let
/// the format round-trip through any byte-stable serialization
/// (config files, capability blobs, IPC, on-disk caches) without losing
/// meaning across crate versions, and prevent inserts in the middle of
/// the enum from shifting every later variant's number (which
/// cargo-semver-checks rightly flags as a breaking change).
///
/// The first six variants (`Yuv420P` through `Gray8`) are the original
/// formats produced by the early codec crates. Everything beyond that
/// is additional surface handled by `oxideav-pixfmt` and the still-image
/// codecs (PNG, GIF, still-JPEG).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u16)]
pub enum PixelFormat {
    /// 8-bit YUV 4:2:0, planar (Y, U, V).
    Yuv420P = 0,
    /// 8-bit YUV 4:2:2, planar.
    Yuv422P = 1,
    /// 8-bit YUV 4:4:4, planar.
    Yuv444P = 2,
    /// Packed 8-bit RGB, 3 bytes/pixel.
    Rgb24 = 3,
    /// Packed 8-bit RGBA, 4 bytes/pixel.
    Rgba = 4,
    /// Packed 8-bit grayscale.
    Gray8 = 5,

    // --- Palette ---
    /// 8-bit palette indices — companion palette carried out of band.
    Pal8 = 6,

    // --- Packed RGB/BGR swizzles ---
    /// Packed 8-bit BGR, 3 bytes/pixel.
    Bgr24 = 7,
    /// Packed 8-bit BGRA, 4 bytes/pixel.
    Bgra = 8,
    /// Packed 8-bit ARGB, 4 bytes/pixel (alpha first).
    Argb = 9,
    /// Packed 8-bit ABGR, 4 bytes/pixel.
    Abgr = 10,

    // --- Deeper packed RGB ---
    /// Packed 16-bit-per-channel RGB, little-endian, 6 bytes/pixel.
    Rgb48Le = 11,
    /// Packed 16-bit-per-channel RGBA, little-endian, 8 bytes/pixel.
    Rgba64Le = 12,

    // --- Grayscale deeper / partial bit depths ---
    /// 16-bit little-endian grayscale.
    Gray16Le = 13,
    /// 10-bit grayscale in a 16-bit little-endian word.
    Gray10Le = 14,
    /// 12-bit grayscale in a 16-bit little-endian word.
    Gray12Le = 15,

    // --- Higher-precision YUV ---
    /// 10-bit YUV 4:2:0 planar, little-endian 16-bit storage.
    Yuv420P10Le = 16,
    /// 10-bit YUV 4:2:2 planar, little-endian 16-bit storage.
    Yuv422P10Le = 17,
    /// 10-bit YUV 4:4:4 planar, little-endian 16-bit storage.
    Yuv444P10Le = 18,
    /// 12-bit YUV 4:2:0 planar, little-endian 16-bit storage.
    Yuv420P12Le = 19,
    /// 12-bit YUV 4:2:2 planar, little-endian 16-bit storage.
    Yuv422P12Le = 20,
    /// 12-bit YUV 4:4:4 planar, little-endian 16-bit storage.
    Yuv444P12Le = 21,

    // --- Full-range ("J") YUV ---
    /// JPEG/full-range YUV 4:2:0 planar.
    YuvJ420P = 22,
    /// JPEG/full-range YUV 4:2:2 planar.
    YuvJ422P = 23,
    /// JPEG/full-range YUV 4:4:4 planar.
    YuvJ444P = 24,

    // --- Semi-planar YUV ---
    /// YUV 4:2:0, planar Y + interleaved UV (NV12).
    Nv12 = 25,
    /// YUV 4:2:0, planar Y + interleaved VU (NV21).
    Nv21 = 26,

    // --- Gray + alpha / YUV + alpha ---
    /// Packed grayscale + alpha, 2 bytes/pixel (Y, A).
    Ya8 = 27,
    /// Yuv420P with an additional full-resolution alpha plane.
    Yuva420P = 28,

    // --- Mono (1 bit per pixel) ---
    /// 1 bit per pixel, packed MSB-first, 0 = black.
    MonoBlack = 29,
    /// 1 bit per pixel, packed MSB-first, 0 = white.
    MonoWhite = 30,

    // --- Interleaved YUV 4:2:2 ---
    /// Packed 4:2:2, byte order Y0 U0 Y1 V0.
    Yuyv422 = 31,
    /// Packed 4:2:2, byte order U0 Y0 V0 Y1.
    Uyvy422 = 32,

    // --- Print / prepress ---
    /// Packed 8-bit CMYK, 4 bytes/pixel in byte order C, M, Y, K.
    /// "Regular" convention: C=0 means no cyan ink (white), C=255 means
    /// full cyan. Used by JPEG 4-component scans from non-Adobe encoders
    /// and by many print-side image toolchains. Adobe Photoshop's
    /// inverted CMYK (where 0 = full ink) is a separate variant reserved
    /// for a future `CmykInverted`.
    Cmyk = 33,
}

impl PixelFormat {
    /// True if this format stores its components in separate planes.
    pub fn is_planar(&self) -> bool {
        matches!(
            self,
            Self::Yuv420P
                | Self::Yuv422P
                | Self::Yuv444P
                | Self::Yuv420P10Le
                | Self::Yuv422P10Le
                | Self::Yuv444P10Le
                | Self::Yuv420P12Le
                | Self::Yuv422P12Le
                | Self::Yuv444P12Le
                | Self::YuvJ420P
                | Self::YuvJ422P
                | Self::YuvJ444P
                | Self::Nv12
                | Self::Nv21
                | Self::Yuva420P
        )
    }

    /// True if the format is a palette index format (`Pal8`).
    pub fn is_palette(&self) -> bool {
        matches!(self, Self::Pal8)
    }

    /// True if this format carries an alpha channel.
    pub fn has_alpha(&self) -> bool {
        matches!(
            self,
            Self::Rgba
                | Self::Bgra
                | Self::Argb
                | Self::Abgr
                | Self::Rgba64Le
                | Self::Ya8
                | Self::Yuva420P
        )
    }

    /// Number of planes in the stored layout. Packed and palette formats
    /// return 1; NV12/NV21 return 2; planar YUV without alpha returns 3;
    /// YuvA variants return 4.
    pub fn plane_count(&self) -> usize {
        match self {
            Self::Nv12 | Self::Nv21 => 2,
            Self::Yuv420P
            | Self::Yuv422P
            | Self::Yuv444P
            | Self::Yuv420P10Le
            | Self::Yuv422P10Le
            | Self::Yuv444P10Le
            | Self::Yuv420P12Le
            | Self::Yuv422P12Le
            | Self::Yuv444P12Le
            | Self::YuvJ420P
            | Self::YuvJ422P
            | Self::YuvJ444P => 3,
            Self::Yuva420P => 4,
            _ => 1,
        }
    }

    /// Rough bits-per-pixel estimate, useful for buffer sizing. Not exact
    /// for chroma-subsampled YUV — intended for worst-case preallocation
    /// rather than wire-accurate accounting.
    pub fn bits_per_pixel_approx(&self) -> u32 {
        match self {
            Self::MonoBlack | Self::MonoWhite => 1,
            Self::Gray8 | Self::Pal8 => 8,
            Self::Ya8 => 16,
            Self::Gray16Le | Self::Gray10Le | Self::Gray12Le => 16,
            Self::Rgb24 | Self::Bgr24 => 24,
            Self::Rgba | Self::Bgra | Self::Argb | Self::Abgr => 32,
            Self::Rgb48Le => 48,
            Self::Rgba64Le => 64,
            Self::Yuyv422 | Self::Uyvy422 => 16,
            Self::Cmyk => 32,
            // Planar YUV: 4:2:0 ≈ 12, 4:2:2 ≈ 16, 4:4:4 ≈ 24
            // 10/12-bit variants double the byte count but we report the
            // packed-bits-per-pixel estimate for a uniform heuristic.
            Self::Yuv420P | Self::YuvJ420P | Self::Nv12 | Self::Nv21 => 12,
            Self::Yuv422P | Self::YuvJ422P => 16,
            Self::Yuv444P | Self::YuvJ444P => 24,
            Self::Yuv420P10Le | Self::Yuv420P12Le => 24,
            Self::Yuv422P10Le | Self::Yuv422P12Le => 32,
            Self::Yuv444P10Le | Self::Yuv444P12Le => 48,
            Self::Yuva420P => 20,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Pin every `PixelFormat` and `SampleFormat` discriminant. This is the
    /// stability commitment — the integer value of each variant is part of
    /// the public ABI. Any reorder, renumber, or removal will fail this test
    /// and the change MUST be a major version bump (or a fresh variant
    /// appended at a new number, leaving the existing ones untouched).
    #[test]
    fn pixel_format_discriminants_pinned() {
        assert_eq!(PixelFormat::Yuv420P as u16, 0);
        assert_eq!(PixelFormat::Yuv422P as u16, 1);
        assert_eq!(PixelFormat::Yuv444P as u16, 2);
        assert_eq!(PixelFormat::Rgb24 as u16, 3);
        assert_eq!(PixelFormat::Rgba as u16, 4);
        assert_eq!(PixelFormat::Gray8 as u16, 5);
        assert_eq!(PixelFormat::Pal8 as u16, 6);
        assert_eq!(PixelFormat::Bgr24 as u16, 7);
        assert_eq!(PixelFormat::Bgra as u16, 8);
        assert_eq!(PixelFormat::Argb as u16, 9);
        assert_eq!(PixelFormat::Abgr as u16, 10);
        assert_eq!(PixelFormat::Rgb48Le as u16, 11);
        assert_eq!(PixelFormat::Rgba64Le as u16, 12);
        assert_eq!(PixelFormat::Gray16Le as u16, 13);
        assert_eq!(PixelFormat::Gray10Le as u16, 14);
        assert_eq!(PixelFormat::Gray12Le as u16, 15);
        assert_eq!(PixelFormat::Yuv420P10Le as u16, 16);
        assert_eq!(PixelFormat::Yuv422P10Le as u16, 17);
        assert_eq!(PixelFormat::Yuv444P10Le as u16, 18);
        assert_eq!(PixelFormat::Yuv420P12Le as u16, 19);
        assert_eq!(PixelFormat::Yuv422P12Le as u16, 20);
        assert_eq!(PixelFormat::Yuv444P12Le as u16, 21);
        assert_eq!(PixelFormat::YuvJ420P as u16, 22);
        assert_eq!(PixelFormat::YuvJ422P as u16, 23);
        assert_eq!(PixelFormat::YuvJ444P as u16, 24);
        assert_eq!(PixelFormat::Nv12 as u16, 25);
        assert_eq!(PixelFormat::Nv21 as u16, 26);
        assert_eq!(PixelFormat::Ya8 as u16, 27);
        assert_eq!(PixelFormat::Yuva420P as u16, 28);
        assert_eq!(PixelFormat::MonoBlack as u16, 29);
        assert_eq!(PixelFormat::MonoWhite as u16, 30);
        assert_eq!(PixelFormat::Yuyv422 as u16, 31);
        assert_eq!(PixelFormat::Uyvy422 as u16, 32);
        assert_eq!(PixelFormat::Cmyk as u16, 33);
    }

    #[test]
    fn sample_format_discriminants_pinned() {
        assert_eq!(SampleFormat::U8 as u8, 0);
        assert_eq!(SampleFormat::S8 as u8, 1);
        assert_eq!(SampleFormat::S16 as u8, 2);
        assert_eq!(SampleFormat::S24 as u8, 3);
        assert_eq!(SampleFormat::S32 as u8, 4);
        assert_eq!(SampleFormat::F32 as u8, 5);
        assert_eq!(SampleFormat::F64 as u8, 6);
        assert_eq!(SampleFormat::U8P as u8, 7);
        assert_eq!(SampleFormat::S16P as u8, 8);
        assert_eq!(SampleFormat::S32P as u8, 9);
        assert_eq!(SampleFormat::F32P as u8, 10);
        assert_eq!(SampleFormat::F64P as u8, 11);
    }

    #[test]
    fn high_bit_yuv_planar_metadata() {
        // 10-bit reference variants are planar with three planes.
        assert!(PixelFormat::Yuv420P10Le.is_planar());
        assert!(PixelFormat::Yuv422P10Le.is_planar());
        assert!(PixelFormat::Yuv444P10Le.is_planar());

        // 12-bit variants must follow the same shape.
        assert!(PixelFormat::Yuv420P12Le.is_planar());
        assert!(PixelFormat::Yuv422P12Le.is_planar());
        assert!(PixelFormat::Yuv444P12Le.is_planar());

        assert_eq!(PixelFormat::Yuv420P12Le.plane_count(), 3);
        assert_eq!(PixelFormat::Yuv422P12Le.plane_count(), 3);
        assert_eq!(PixelFormat::Yuv444P12Le.plane_count(), 3);

        // None of the high-bit YUV variants carry alpha or palette.
        assert!(!PixelFormat::Yuv422P12Le.has_alpha());
        assert!(!PixelFormat::Yuv444P12Le.has_alpha());
        assert!(!PixelFormat::Yuv422P12Le.is_palette());
        assert!(!PixelFormat::Yuv444P12Le.is_palette());
    }

    #[test]
    fn channel_layout_round_trip_count_for_known_layouts() {
        // For every `n` that `from_count` maps to a named layout, the
        // resulting layout's `channel_count()` must equal `n` again.
        for n in 1..=8u16 {
            let layout = ChannelLayout::from_count(n);
            assert_eq!(layout.channel_count(), n, "round-trip failed for n={n}");
            // None of these defaults should fall through to DiscreteN.
            assert!(
                !matches!(layout, ChannelLayout::DiscreteN(_)),
                "from_count({n}) unexpectedly produced DiscreteN"
            );
        }
    }

    #[test]
    fn channel_layout_from_count_default_table() {
        // The exact mapping documented on `from_count` — pin it so
        // future refactors don't silently change the inferred layout.
        assert_eq!(ChannelLayout::from_count(1), ChannelLayout::Mono);
        assert_eq!(ChannelLayout::from_count(2), ChannelLayout::Stereo);
        assert_eq!(ChannelLayout::from_count(3), ChannelLayout::Surround30);
        assert_eq!(ChannelLayout::from_count(4), ChannelLayout::Quad);
        assert_eq!(ChannelLayout::from_count(5), ChannelLayout::Surround50);
        assert_eq!(ChannelLayout::from_count(6), ChannelLayout::Surround51);
        assert_eq!(ChannelLayout::from_count(7), ChannelLayout::Surround61);
        assert_eq!(ChannelLayout::from_count(8), ChannelLayout::Surround71);
    }

    #[test]
    fn channel_layout_unknown_count_falls_through_to_discrete() {
        assert_eq!(ChannelLayout::from_count(0), ChannelLayout::DiscreteN(0));
        assert_eq!(ChannelLayout::from_count(13), ChannelLayout::DiscreteN(13));
        assert_eq!(
            ChannelLayout::from_count(64).channel_count(),
            64,
            "DiscreteN must report the count it was constructed with"
        );
    }

    #[test]
    fn channel_layout_position_lookup() {
        assert_eq!(
            ChannelLayout::Stereo.position(0),
            Some(ChannelPosition::FrontLeft)
        );
        assert_eq!(
            ChannelLayout::Stereo.position(1),
            Some(ChannelPosition::FrontRight)
        );
        assert_eq!(ChannelLayout::Stereo.position(2), None);

        // 5.1 canonical: L, R, C, LFE, Ls, Rs.
        let s51 = ChannelLayout::Surround51;
        assert_eq!(s51.position(0), Some(ChannelPosition::FrontLeft));
        assert_eq!(s51.position(1), Some(ChannelPosition::FrontRight));
        assert_eq!(s51.position(2), Some(ChannelPosition::FrontCenter));
        assert_eq!(s51.position(3), Some(ChannelPosition::LowFrequency));
        assert_eq!(s51.position(4), Some(ChannelPosition::SideLeft));
        assert_eq!(s51.position(5), Some(ChannelPosition::SideRight));
        assert_eq!(s51.position(6), None);

        // DiscreteN never reveals a position.
        assert_eq!(ChannelLayout::DiscreteN(13).position(0), None);
    }

    #[test]
    fn channel_layout_lfe_and_surround_predicates() {
        assert!(ChannelLayout::Surround51.has_lfe());
        assert!(ChannelLayout::Surround71.has_lfe());
        assert!(ChannelLayout::Stereo21.has_lfe());
        assert!(!ChannelLayout::Quad.has_lfe());
        assert!(!ChannelLayout::Surround50.has_lfe());
        assert!(!ChannelLayout::Stereo.has_lfe());

        assert!(!ChannelLayout::Mono.is_surround());
        assert!(!ChannelLayout::Stereo.is_surround());
        // Downmix carriers are still 2ch / no-LFE → not "surround" by
        // the layout-shape definition; the surround info lives in the
        // sample matrix itself.
        assert!(!ChannelLayout::LoRo.is_surround());
        assert!(!ChannelLayout::LtRt.is_surround());
        assert!(ChannelLayout::Stereo21.is_surround());
        assert!(ChannelLayout::Surround51.is_surround());
        assert!(ChannelLayout::Surround71.is_surround());
    }

    #[test]
    fn channel_layout_display_and_fromstr_round_trip() {
        use std::str::FromStr;
        let cases = [
            ChannelLayout::Mono,
            ChannelLayout::Stereo,
            ChannelLayout::Stereo21,
            ChannelLayout::Surround30,
            ChannelLayout::Quad,
            ChannelLayout::Surround40,
            ChannelLayout::Surround41,
            ChannelLayout::Surround50,
            ChannelLayout::Surround51,
            ChannelLayout::Surround60,
            ChannelLayout::Surround61,
            ChannelLayout::Surround70,
            ChannelLayout::Surround71,
            ChannelLayout::LoRo,
            ChannelLayout::LtRt,
            ChannelLayout::DiscreteN(13),
        ];
        for layout in cases {
            let s = layout.to_string();
            let parsed = ChannelLayout::from_str(&s).expect("display output must parse back");
            assert_eq!(parsed, layout, "round-trip failed via {s:?}");
        }
    }

    #[test]
    fn channel_layout_fromstr_accepts_aliases_and_case() {
        use std::str::FromStr;
        assert_eq!(
            ChannelLayout::from_str("STEREO").unwrap(),
            ChannelLayout::Stereo
        );
        assert_eq!(
            ChannelLayout::from_str("2.0").unwrap(),
            ChannelLayout::Stereo
        );
        assert_eq!(
            ChannelLayout::from_str("5.1").unwrap(),
            ChannelLayout::Surround51
        );
        assert_eq!(
            ChannelLayout::from_str("Lo/Ro").unwrap(),
            ChannelLayout::LoRo
        );
        assert_eq!(
            ChannelLayout::from_str("lt/rt").unwrap(),
            ChannelLayout::LtRt
        );
        assert!(ChannelLayout::from_str("absurd_layout").is_err());
    }

    #[test]
    fn channel_layout_positions_owned_matches_static_slice() {
        for layout in [
            ChannelLayout::Mono,
            ChannelLayout::Surround51,
            ChannelLayout::Surround71,
        ] {
            assert_eq!(layout.positions_owned(), layout.positions());
        }
        // DiscreteN returns an empty owned vec — positions are unknown.
        assert!(ChannelLayout::DiscreteN(7).positions_owned().is_empty());
    }

    #[test]
    fn sample_format_plane_count_interleaved_is_one() {
        // Interleaved formats always pack into a single plane, regardless
        // of channel count.
        for ch in [1u16, 2, 6, 8, 64, 0] {
            assert_eq!(SampleFormat::S16.plane_count(ch), 1);
            assert_eq!(SampleFormat::F32.plane_count(ch), 1);
            assert_eq!(SampleFormat::U8.plane_count(ch), 1);
            assert_eq!(SampleFormat::S24.plane_count(ch), 1);
        }
    }

    #[test]
    fn sample_format_plane_count_planar_matches_channels() {
        // Planar formats use one plane per channel.
        assert_eq!(SampleFormat::S16P.plane_count(1), 1);
        assert_eq!(SampleFormat::S16P.plane_count(2), 2);
        assert_eq!(SampleFormat::F32P.plane_count(6), 6);
        assert_eq!(SampleFormat::F64P.plane_count(8), 8);

        // Edge case: zero channels in a planar format yields zero planes.
        assert_eq!(SampleFormat::S32P.plane_count(0), 0);
    }

    #[test]
    fn high_bit_yuv_bits_per_pixel_approx() {
        // 4:2:2 and 4:4:4 12-bit match their 10-bit siblings on the
        // packed-bits estimator (the approximation reports samples-per-pixel
        // density, not the 16-bit storage width).
        assert_eq!(PixelFormat::Yuv422P10Le.bits_per_pixel_approx(), 32);
        assert_eq!(PixelFormat::Yuv422P12Le.bits_per_pixel_approx(), 32);
        assert_eq!(PixelFormat::Yuv444P10Le.bits_per_pixel_approx(), 48);
        assert_eq!(PixelFormat::Yuv444P12Le.bits_per_pixel_approx(), 48);
        assert_eq!(PixelFormat::Yuv420P12Le.bits_per_pixel_approx(), 24);
    }
}