media-core 0.9.1

Define media types and provide basic media utilities
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
use std::{
    cmp,
    fmt::{Display, Formatter},
    iter, mem,
    num::NonZeroU32,
};

use bitflags::bitflags;
use num_enum::TryFromPrimitive;
use strum::EnumCount;

use crate::{
    align_to, ceil_rshift,
    error::Error,
    frame::{Frame, PlaneDescriptor, PlaneVec},
    invalid_error, invalid_param_error,
    video::VideoFrame,
    FrameDescriptor, FrameDescriptorSpec, MediaType, Result,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Dimensions {
    pub width: NonZeroU32,
    pub height: NonZeroU32,
}

impl Dimensions {
    const fn new_unchecked(width: u32, height: u32) -> Self {
        Self {
            width: unsafe { NonZeroU32::new_unchecked(width) },
            height: unsafe { NonZeroU32::new_unchecked(height) },
        }
    }

    pub fn new(width: u32, height: u32) -> Result<Self> {
        Ok(Self {
            width: NonZeroU32::new(width).ok_or_else(|| invalid_param_error!(width))?,
            height: NonZeroU32::new(height).ok_or_else(|| invalid_param_error!(height))?,
        })
    }

    pub const SQCIF: Self = Self::new_unchecked(128, 96);
    pub const QCIF: Self = Self::new_unchecked(176, 144);
    pub const CIF: Self = Self::new_unchecked(352, 288);
    pub const QQVGA: Self = Self::new_unchecked(160, 120);
    pub const QVGA: Self = Self::new_unchecked(320, 240);
    pub const VGA: Self = Self::new_unchecked(640, 480);
    pub const SVGA: Self = Self::new_unchecked(800, 600);
    pub const XGA: Self = Self::new_unchecked(1024, 768);
    pub const SXGA: Self = Self::new_unchecked(1280, 1024);
    pub const UXGA: Self = Self::new_unchecked(1600, 1200);
    pub const QXGA: Self = Self::new_unchecked(2048, 1536);
    pub const SD: Self = Self::new_unchecked(720, 480);
    pub const HD: Self = Self::new_unchecked(1280, 720);
    pub const FHD: Self = Self::new_unchecked(1920, 1080);
    pub const QHD: Self = Self::new_unchecked(2560, 1440);
    pub const UHD_4K: Self = Self::new_unchecked(3840, 2160);
    pub const UHD_8K: Self = Self::new_unchecked(7680, 4320);
}

#[derive(Clone, Copy, Debug, Default, EnumCount, Eq, PartialEq)]
#[repr(u8)]
pub enum ColorRange {
    #[default]
    Unspecified,
    Video,
    Full,
}

impl From<ColorRange> for usize {
    fn from(value: ColorRange) -> Self {
        value as usize
    }
}

impl From<usize> for ColorRange {
    fn from(value: usize) -> Self {
        match value {
            0 => ColorRange::Unspecified,
            1 => ColorRange::Video,
            2 => ColorRange::Full,
            _ => ColorRange::Unspecified,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum ColorMatrix {
    #[default]
    Identity = 0, // The identity matrix
    BT709,            // BT.709
    Unspecified,      // Unspecified
    Reserved,         // Reserved
    FCC,              // FCC Title 47 Code of Federal Regulations 73.682(a)(20)
    BT470BG,          // BT.601 PAL & SECAM
    SMPTE170M,        // BT.601 NTSC
    SMPTE240M,        // SMPTE ST 240
    YCgCo,            // YCgCo
    BT2020NCL,        // BT.2020 non-constant luminance system
    BT2020CL,         // BT.2020 constant luminance system
    SMPTE2085,        // SMPTE ST 2085 Y'D'zD'x
    ChromaDerivedNCL, // Chromaticity-derived non-constant luminance system
    ChromaDerivedCL,  // Chromaticity-derived constant luminance system
    ICtCp,            // BT.2100 ICtCp
    SMPTE2128,        // SMPTE ST 2128
}

impl From<ColorMatrix> for usize {
    fn from(value: ColorMatrix) -> Self {
        value as usize
    }
}

impl TryFrom<usize> for ColorMatrix {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        match value {
            0 => Ok(ColorMatrix::Identity),
            1 => Ok(ColorMatrix::BT709),
            2 => Ok(ColorMatrix::Unspecified),
            4 => Ok(ColorMatrix::FCC),
            5 => Ok(ColorMatrix::BT470BG),
            6 => Ok(ColorMatrix::SMPTE170M),
            7 => Ok(ColorMatrix::SMPTE240M),
            8 => Ok(ColorMatrix::YCgCo),
            9 => Ok(ColorMatrix::BT2020NCL),
            10 => Ok(ColorMatrix::BT2020CL),
            11 => Ok(ColorMatrix::SMPTE2085),
            12 => Ok(ColorMatrix::ChromaDerivedNCL),
            13 => Ok(ColorMatrix::ChromaDerivedCL),
            14 => Ok(ColorMatrix::ICtCp),
            15 => Ok(ColorMatrix::SMPTE2128),
            _ => Err(invalid_param_error!(value)),
        }
    }
}

#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum ColorPrimaries {
    #[default]
    Reserved  = 0, // Reserved
    BT709,          // BT.709
    Unspecified,    // Unspecified
    BT470M    = 4,  // FCC Title 47 Code of Federal Regulations 73.682(a)(20)
    BT470BG,        // BT.601 PAL & SECAM
    SMPTE170M,      // BT.601 NTSC
    SMPTE240M,      // SMPTE ST 240 / SMPTE C
    Film,           // Generic film (color filters using illuminant C)
    BT2020,         // BT.2020
    SMPTE428,       // SMPTE ST 428-1 (CIE 1931 XYZ)
    SMPTE431,       // SMPTE ST 431-2 (DCI P3)
    SMPTE432,       // SMPTE ST 432-1 (P3 D65 / Display P3)
    JEDEC_P22 = 22, // JEDEC P22 phosphors
}

impl From<ColorPrimaries> for usize {
    fn from(value: ColorPrimaries) -> Self {
        value as usize
    }
}

impl TryFrom<usize> for ColorPrimaries {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        match value {
            0 => Ok(ColorPrimaries::Reserved),
            1 => Ok(ColorPrimaries::BT709),
            2 => Ok(ColorPrimaries::Unspecified),
            4 => Ok(ColorPrimaries::BT470M),
            5 => Ok(ColorPrimaries::BT470BG),
            6 => Ok(ColorPrimaries::SMPTE170M),
            7 => Ok(ColorPrimaries::SMPTE240M),
            8 => Ok(ColorPrimaries::Film),
            9 => Ok(ColorPrimaries::BT2020),
            10 => Ok(ColorPrimaries::SMPTE428),
            11 => Ok(ColorPrimaries::SMPTE431),
            12 => Ok(ColorPrimaries::SMPTE432),
            22 => Ok(ColorPrimaries::JEDEC_P22),
            _ => Err(invalid_param_error!(value)),
        }
    }
}

#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ColorTransferCharacteristics {
    #[default]
    Reserved = 0, // Reserved
    BT709,        // BT.709
    Unspecified,  // Unspecified
    BT470M   = 4, // gamma = 2.2 / FCC Title 47 Code of Federal Regulations 73.682(a)(20)
    BT470BG,      // gamma = 2.8 / BT.601 PAL & SECAM
    SMPTE170M,    // BT.601 NTSC
    SMPTE240M,    // SMPTE ST 240
    Linear,       // Linear transfer characteristics
    Log,          // Logarithmic transfer characteristic (100 : 1 range)
    LogSqrt,      // Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)
    IEC61966_2_4, // IEC 61966-2-4
    BT1361E,      // ITU-R BT1361 Extended Colour Gamut
    IEC61966_2_1, // IEC 61966-2-1 (sRGB or sYCC)
    BT2020_10,    // BT.2020 10-bit systems
    BT2020_12,    // BT.2020 12-bit systems
    SMPTE2084,    // SMPTE ST 2084 / BT.2100 perceptual quantization (PQ) system
    SMPTE428,     // SMPTE ST 428-1
    ARIB_STD_B67, // ARIB STD-B67 / BT.2100 hybrid log-gamma (HLG) system
}

impl From<ColorTransferCharacteristics> for usize {
    fn from(value: ColorTransferCharacteristics) -> Self {
        value as usize
    }
}

impl TryFrom<usize> for ColorTransferCharacteristics {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        match value {
            0 => Ok(ColorTransferCharacteristics::Reserved),
            1 => Ok(ColorTransferCharacteristics::BT709),
            2 => Ok(ColorTransferCharacteristics::Unspecified),
            4 => Ok(ColorTransferCharacteristics::BT470M),
            5 => Ok(ColorTransferCharacteristics::BT470BG),
            6 => Ok(ColorTransferCharacteristics::SMPTE170M),
            7 => Ok(ColorTransferCharacteristics::SMPTE240M),
            8 => Ok(ColorTransferCharacteristics::Linear),
            9 => Ok(ColorTransferCharacteristics::Log),
            10 => Ok(ColorTransferCharacteristics::LogSqrt),
            11 => Ok(ColorTransferCharacteristics::IEC61966_2_4),
            12 => Ok(ColorTransferCharacteristics::BT1361E),
            13 => Ok(ColorTransferCharacteristics::IEC61966_2_1),
            14 => Ok(ColorTransferCharacteristics::BT2020_10),
            15 => Ok(ColorTransferCharacteristics::BT2020_12),
            16 => Ok(ColorTransferCharacteristics::SMPTE2084),
            17 => Ok(ColorTransferCharacteristics::SMPTE428),
            18 => Ok(ColorTransferCharacteristics::ARIB_STD_B67),
            _ => Err(invalid_param_error!(value)),
        }
    }
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, EnumCount, Eq, PartialEq, TryFromPrimitive)]
pub enum PixelFormat {
    #[default]
    ARGB32 = 0, // packed ARGB, 32 bits
    BGRA32, // packed BGRA, 32 bits
    ABGR32, // packed ABGR, 32 bits
    RGBA32, // packed RGBA, 32 bits
    RGB24,  // packed RGB, 24 bits
    BGR24,  // packed BGR, 24 bits
    I420,   // planar YUV 4:2:0, 12 bits
    I422,   // planar YUV 4:2:2, 16 bits
    I444,   // planar YUV 4:4:4, 24 bits
    I440,   // planar YUV 4:4:0, 16 bits
    NV12,   // biplanar YUV 4:2:0, 12 bits
    NV21,   // biplanar YUV 4:2:0, 12 bits
    NV16,   // biplanar YUV 4:2:2, 16 bits
    NV61,   // biplanar YUV 4:2:2, 16 bits
    NV24,   // biplanar YUV 4:4:4, 24 bits
    NV42,   // biplanar YUV 4:4:4, 24 bits
    YV12,   // planar YVU 4:2:0, 12 bits
    YV16,   // planar YVU 4:2:2, 16 bits
    YV24,   // planar YVU 4:4:4, 24 bits
    YUYV,   // packed YUV 4:2:2, 16 bits, Y0 Cb Y1 Cr
    YVYU,   // packed YUV 4:2:2, 16 bits, Y0 Cr Y1 Cb
    UYVY,   // packed YUV 4:2:2, 16 bits, Cb Y0 Cr Y1
    VYUY,   // packed YUV 4:2:2, 16 bits, Cr Y0 Cb Y1
    AYUV,   // packed AYUV 4:4:4, 32 bits
    Y8,     // greyscale, 8 bits Y
    YA8,    // greyscale, 8 bits Y, 8 bits alpha
    RGB30,  // packed RGB, 30 bits, 10 bits per channel, 2 bits unused(LSB)
    BGR30,  // packed BGR, 30 bits, 10 bits per channel, 2 bits unused(LSB)
    ARGB64, // packed ARGB, 64 bits, 16 bits per channel, 16-bit big-endian
    BGRA64, // packed BGRA, 64 bits, 16 bits per channel, 16-bit big-endian
    ABGR64, // packed ABGR, 64 bits, 16 bits per channel, 16-bit big-endian
    RGBA64, // packed RGBA, 64 bits, 16 bits per channel, 16-bit big-endian
    I010,   // planar YUV 4:2:0, 10 bits per channel
    I210,   // planar YUV 4:2:2, 10 bits per channel
    I410,   // planar YUV 4:4:4, 10 bits per channel
    I44010, // planar YUV 4:4:0, 10 bits per channel
    P010,   // biplanar YUV 4:2:0, 10 bits per channel
    P210,   // biplanar YUV 4:2:2, 10 bits per channel
    P410,   // biplanar YUV 4:4:4, 10 bits per channel
    I012,   // planar YUV 4:2:2, 12 bits per channel
    I212,   // planar YUV 4:2:2, 12 bits per channel
    I412,   // planar YUV 4:4:4, 12 bits per channel
    I44012, // planar YUV 4:4:0, 12 bits per channel
    P012,   // biplanar YUV 4:2:0, 12 bits per channel
    P212,   // biplanar YUV 4:2:2, 12 bits per channel
    P412,   // biplanar YUV 4:4:4, 12 bits per channel
    I016,   // planar YUV 4:2:0, 16 bits per channel
    I216,   // planar YUV 4:2:2, 16 bits per channel
    I416,   // planar YUV 4:4:4, 16 bits per channel
    I44016, // planar YUV 4:4:0, 16 bits per channel
    P016,   // biplanar YUV 4:2:0, 16 bits per channel
    P216,   // biplanar YUV 4:2:2, 16 bits per channel
    P416,   // biplanar YUV 4:4:4, 16 bits per channel
}

impl From<PixelFormat> for usize {
    fn from(value: PixelFormat) -> Self {
        value as usize
    }
}

impl TryFrom<usize> for PixelFormat {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self> {
        if value < PixelFormat::COUNT {
            Ok(unsafe { mem::transmute::<u8, PixelFormat>(value as u8) })
        } else {
            Err(invalid_param_error!(value))
        }
    }
}

bitflags! {
    #[repr(transparent)]
    struct PixelFormatFlags: u32 {
        const Alpha    = 1 << 0;
        const RGB      = 1 << 1;
        const YUV      = 1 << 2;
        const Planar   = 1 << 3;
        const Packed   = 1 << 4;
        const BiPlanar = 1 << 5;
    }
}

struct PixelFormatDescriptor {
    components: u8,
    chroma_shift_x: u8,
    chroma_shift_y: u8,
    depth: u8,
    flags: PixelFormatFlags,
    component_bytes: [u8; 4],
}

macro_rules! pix_fmt_flags {
    ($($flag:ident)|+) => {
        PixelFormatFlags::from_bits_truncate(0 $(| PixelFormatFlags::$flag.bits())+)
    };
    ($flag:ident) => {
        PixelFormatFlags::from_bits_truncate(PixelFormatFlags::$flag.bits())
    };
}

static PIXEL_FORMAT_DESC: [PixelFormatDescriptor; PixelFormat::COUNT] = [
    // ARGB32
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // BGRA32
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // ABGR32
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // RGBA32
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // RGB24
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(RGB | Packed),
        component_bytes: [3, 0, 0, 0],
    },
    // BGR24
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(RGB | Packed),
        component_bytes: [3, 0, 0, 0],
    },
    // I420
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // I422
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // I444
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // I440
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 1,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // NV12
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // NV21
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // NV16
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // NV61
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // NV24
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // NV42
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [1, 2, 0, 0],
    },
    // YV12
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // YV16
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // YV24
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [1, 1, 1, 0],
    },
    // YUYV
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // YVYU
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // UYVY
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // VYUY
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(YUV | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // AYUV
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | YUV | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // Y8
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: PixelFormatFlags::Planar,
        component_bytes: [1, 0, 0, 0],
    },
    // YA8
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 8,
        flags: pix_fmt_flags!(Alpha | Planar),
        component_bytes: [1, 1, 0, 0],
    },
    // RGB30
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // BGR30
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(RGB | Packed),
        component_bytes: [4, 0, 0, 0],
    },
    // ARGB64
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [8, 0, 0, 0],
    },
    // BGRA64
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [8, 0, 0, 0],
    },
    // ABGR64
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [8, 0, 0, 0],
    },
    // RGBA64
    PixelFormatDescriptor {
        components: 1,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(Alpha | RGB | Packed),
        component_bytes: [8, 0, 0, 0],
    },
    // I010
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 10,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I210
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I410
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I44010
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 1,
        depth: 10,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // P010
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 10,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P210
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P410
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 10,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // I012
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 12,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I212
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 12,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I412
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 12,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I44012
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 1,
        depth: 12,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // P012
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 12,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P212
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 12,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P412
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 12,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // I016
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 16,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I216
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I416
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // I44016
    PixelFormatDescriptor {
        components: 3,
        chroma_shift_x: 0,
        chroma_shift_y: 1,
        depth: 16,
        flags: pix_fmt_flags!(YUV | Planar),
        component_bytes: [2, 2, 2, 0],
    },
    // P016
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 1,
        depth: 16,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P216
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 1,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
    // P416
    PixelFormatDescriptor {
        components: 2,
        chroma_shift_x: 0,
        chroma_shift_y: 0,
        depth: 16,
        flags: pix_fmt_flags!(YUV | BiPlanar),
        component_bytes: [2, 4, 0, 0],
    },
];

impl PixelFormat {
    pub fn components(&self) -> u8 {
        PIXEL_FORMAT_DESC[*self as usize].components
    }

    pub fn component_bytes(&self, component: u8) -> u8 {
        PIXEL_FORMAT_DESC[*self as usize].component_bytes[component as usize]
    }

    pub fn chroma_subsampling(&self) -> Option<ChromaSubsampling> {
        if !self.is_yuv() {
            return None;
        }

        let desc = &PIXEL_FORMAT_DESC[*self as usize];

        match (desc.chroma_shift_x, desc.chroma_shift_y) {
            (1, 1) => Some(ChromaSubsampling::YUV420),
            (1, 0) => Some(ChromaSubsampling::YUV422),
            (0, 0) => Some(ChromaSubsampling::YUV444),
            _ => None,
        }
    }

    pub fn depth(&self) -> u8 {
        PIXEL_FORMAT_DESC[*self as usize].depth
    }

    pub fn is_rgb(&self) -> bool {
        PIXEL_FORMAT_DESC[*self as usize].flags.contains(PixelFormatFlags::RGB)
    }

    pub fn is_yuv(&self) -> bool {
        PIXEL_FORMAT_DESC[*self as usize].flags.contains(PixelFormatFlags::YUV)
    }

    pub fn is_planar(&self) -> bool {
        PIXEL_FORMAT_DESC[*self as usize].flags.contains(PixelFormatFlags::Planar)
    }

    pub fn is_packed(&self) -> bool {
        PIXEL_FORMAT_DESC[*self as usize].flags.contains(PixelFormatFlags::Packed)
    }

    pub fn is_biplanar(&self) -> bool {
        PIXEL_FORMAT_DESC[*self as usize].flags.contains(PixelFormatFlags::BiPlanar)
    }

    pub fn calc_plane_row_bytes(&self, plane_index: usize, width: u32) -> u32 {
        let desc = &PIXEL_FORMAT_DESC[*self as usize];
        let component_bytes = desc.component_bytes[plane_index];

        if plane_index > 0 && (self.is_planar() || self.is_biplanar()) {
            ceil_rshift(width, desc.chroma_shift_x as u32) * component_bytes as u32
        } else {
            width * component_bytes as u32
        }
    }

    pub fn calc_plane_height(&self, plane_index: usize, height: u32) -> u32 {
        if plane_index > 0 && (self.is_planar() || self.is_biplanar()) {
            let desc = &PIXEL_FORMAT_DESC[*self as usize];
            ceil_rshift(height, desc.chroma_shift_y as u32)
        } else {
            height
        }
    }

    pub(crate) fn calc_data_size(&self, width: u32, height: u32, alignment: u32) -> (usize, PlaneVec<PlaneDescriptor>) {
        let desc = &PIXEL_FORMAT_DESC[*self as usize];
        let mut size;
        let mut planes = PlaneVec::with_capacity(desc.components as usize);

        match self {
            PixelFormat::RGB24 | PixelFormat::BGR24 | PixelFormat::Y8 => {
                let stride = align_to(width * desc.component_bytes[0] as u32, cmp::max(alignment, 4)) as usize;
                planes.push(PlaneDescriptor::Video(stride, height));
                size = stride * height as usize;
            }
            PixelFormat::YA8 => {
                let stride = align_to(width * desc.component_bytes[0] as u32, cmp::max(alignment, 4)) as usize;
                planes.extend(iter::repeat_n(PlaneDescriptor::Video(stride, height), 2));
                size = stride * height as usize * 2;
            }
            PixelFormat::YUYV | PixelFormat::YVYU | PixelFormat::UYVY | PixelFormat::VYUY | PixelFormat::AYUV => {
                let stride = align_to(ceil_rshift(width, desc.chroma_shift_x as u32) * 4, alignment) as usize;
                planes.push(PlaneDescriptor::Video(stride, height));
                size = stride * height as usize;
            }
            _ => {
                let stride = align_to(width * desc.component_bytes[0] as u32, alignment) as usize;
                planes.push(PlaneDescriptor::Video(stride, height));
                size = stride * height as usize;
                for i in 1..desc.components as usize {
                    let stride = align_to(ceil_rshift(width, desc.chroma_shift_x as u32) * desc.component_bytes[i] as u32, alignment) as usize;
                    let height = ceil_rshift(height, desc.chroma_shift_y as u32);
                    planes.push(PlaneDescriptor::Video(stride, height));
                    size += stride * height as usize;
                }
            }
        }

        (size, planes)
    }

    pub(crate) fn calc_data_size_with_stride(&self, height: u32, stride: u32) -> (usize, PlaneVec<PlaneDescriptor>) {
        let desc = &PIXEL_FORMAT_DESC[*self as usize];
        let mut size;
        let mut planes = PlaneVec::with_capacity(desc.components as usize);

        planes.push(PlaneDescriptor::Video(stride as usize, height));
        size = stride * height;
        for i in 1..desc.components as usize {
            let plane_stride = ceil_rshift(stride, desc.chroma_shift_x as u32) * desc.component_bytes[i] as u32;
            let plane_height = ceil_rshift(height, desc.chroma_shift_y as u32);
            planes.push(PlaneDescriptor::Video(plane_stride as usize, plane_height));
            size += plane_stride * plane_height;
        }

        (size as usize, planes)
    }

    pub(crate) fn calc_chroma_dimensions(&self, width: u32, height: u32) -> (u32, u32) {
        let desc = &PIXEL_FORMAT_DESC[*self as usize];
        let chroma_width = ceil_rshift(width, desc.chroma_shift_x as u32);
        let chroma_height = ceil_rshift(height, desc.chroma_shift_y as u32);
        (chroma_width, chroma_height)
    }
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, TryFromPrimitive)]
pub enum CompressionFormat {
    #[default]
    MJPEG,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VideoFormat {
    Pixel(PixelFormat),
    Compression(CompressionFormat),
}

impl Display for VideoFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            VideoFormat::Pixel(format) => write!(f, "{:?}", format),
            VideoFormat::Compression(format) => write!(f, "{:?}", format),
        }
    }
}

impl VideoFormat {
    pub fn is_compressed(&self) -> bool {
        matches!(self, VideoFormat::Compression(_))
    }

    pub fn is_yuv(&self) -> bool {
        match self {
            VideoFormat::Pixel(format) => format.is_yuv(),
            VideoFormat::Compression(CompressionFormat::MJPEG) => true,
        }
    }
}

const COMPRESSION_MASK: u32 = 0x8000;

impl From<VideoFormat> for u32 {
    fn from(value: VideoFormat) -> Self {
        match value {
            VideoFormat::Pixel(format) => format as u32,
            VideoFormat::Compression(format) => format as u32 | COMPRESSION_MASK,
        }
    }
}

impl TryFrom<u32> for VideoFormat {
    type Error = Error;

    fn try_from(value: u32) -> Result<Self> {
        if value & COMPRESSION_MASK != 0 {
            let format_value = value & !COMPRESSION_MASK;
            CompressionFormat::try_from(format_value as u8).map(VideoFormat::Compression).map_err(|e| invalid_error!(e.to_string()))
        } else {
            PixelFormat::try_from(value as u8).map(VideoFormat::Pixel).map_err(|e| invalid_error!(e.to_string()))
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ChromaLocation {
    #[default]
    Unspecified,
    Left,
    Center,
    TopLeft,
    Top,
    BottomLeft,
    Bottom,
}

impl From<ChromaLocation> for usize {
    fn from(value: ChromaLocation) -> Self {
        value as usize
    }
}

impl From<usize> for ChromaLocation {
    fn from(value: usize) -> Self {
        match value {
            0 => ChromaLocation::Unspecified,
            1 => ChromaLocation::Left,
            2 => ChromaLocation::Center,
            3 => ChromaLocation::TopLeft,
            4 => ChromaLocation::Top,
            5 => ChromaLocation::BottomLeft,
            6 => ChromaLocation::Bottom,
            _ => ChromaLocation::Unspecified,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChromaSubsampling {
    YUV420,
    YUV422,
    YUV444,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Rotation {
    #[default]
    None,
    Rotation90,
    Rotation180,
    Rotation270,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Origin {
    #[default]
    TopDown,
    BottomUp,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ScaleFilter {
    Nearest,
    #[default]
    Bilinear,
    Bicubic,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VideoFrameDescriptor {
    pub format: PixelFormat,
    pub dimensions: Dimensions,
    pub color_range: ColorRange,
    pub color_matrix: ColorMatrix,
    pub color_primaries: ColorPrimaries,
    pub color_transfer_characteristics: ColorTransferCharacteristics,
    pub chroma_location: ChromaLocation,
    pub rotation: Rotation,
    pub origin: Origin,
    pub transparent: bool,
    pub extra_alpha: bool,
    pub crop_left: u32,
    pub crop_top: u32,
    pub crop_right: u32,
    pub crop_bottom: u32,
}

impl VideoFrameDescriptor {
    pub fn new(format: PixelFormat, width: NonZeroU32, height: NonZeroU32) -> Self {
        Self {
            format,
            dimensions: Dimensions {
                width,
                height,
            },
            color_range: ColorRange::default(),
            color_matrix: ColorMatrix::default(),
            color_primaries: ColorPrimaries::default(),
            color_transfer_characteristics: ColorTransferCharacteristics::default(),
            chroma_location: ChromaLocation::default(),
            rotation: Rotation::default(),
            origin: Origin::default(),
            transparent: false,
            extra_alpha: false,
            crop_left: 0,
            crop_top: 0,
            crop_right: 0,
            crop_bottom: 0,
        }
    }

    pub fn try_new(format: PixelFormat, width: u32, height: u32) -> Result<Self> {
        let width = NonZeroU32::new(width).ok_or_else(|| invalid_param_error!(width))?;
        let height = NonZeroU32::new(height).ok_or_else(|| invalid_param_error!(height))?;

        Ok(Self::new(format, width, height))
    }

    #[inline]
    pub fn width(&self) -> NonZeroU32 {
        self.dimensions.width
    }

    #[inline]
    pub fn height(&self) -> NonZeroU32 {
        self.dimensions.height
    }
}

impl From<VideoFrameDescriptor> for FrameDescriptor {
    fn from(desc: VideoFrameDescriptor) -> Self {
        FrameDescriptor::Video(desc)
    }
}

impl TryFrom<FrameDescriptor> for VideoFrameDescriptor {
    type Error = Error;

    fn try_from(value: FrameDescriptor) -> Result<Self> {
        match value {
            FrameDescriptor::Video(desc) => Ok(desc),
            _ => Err(invalid_param_error!(value)),
        }
    }
}

impl FrameDescriptorSpec for VideoFrameDescriptor {
    fn media_type(&self) -> MediaType {
        MediaType::Video
    }

    fn create_frame(&self) -> Result<Frame<'static, Self>> {
        VideoFrame::new_with_descriptor(self.clone())
    }

    fn as_video(&self) -> Option<&VideoFrameDescriptor> {
        Some(self)
    }
}