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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
//! This module deals with SPA pods, providing ways to represent pods using idiomatic types
//! and serialize them into their raw representation, and the other way around.
//!
//! Everything concerning serializing raw pods from rust types is in the [`serialize`] submodule.
//! and everything about deserializing rust types from raw pods is in the [`deserialize`] submodule.
//!
//! The entire serialization and deserialization approach is inspired by and similar to the excellent `serde` crate,
//! but is much more specialized to fit the SPA pod format.

pub mod builder;
pub mod deserialize;
pub mod parser;
pub mod serialize;

use std::{
    ffi::c_void,
    io::{Seek, Write},
    mem::MaybeUninit,
    os::fd::RawFd,
    ptr::addr_of,
};

use bitflags::bitflags;
use cookie_factory::{
    bytes::{ne_f32, ne_f64, ne_i32, ne_i64, ne_u32},
    gen_simple,
    sequence::pair,
    GenError,
};
use nix::errno::Errno;
use nom::{
    combinator::map,
    number::{
        complete::{f32, f64, i32, i64, u32},
        Endianness,
    },
    IResult,
};

use deserialize::{BoolVisitor, NoneVisitor, PodDeserialize, PodDeserializer};
use serialize::{PodSerialize, PodSerializer};

use crate::utils::{Choice, Fd, Fraction, Id, Rectangle, SpaTypes};

use self::deserialize::{
    ChoiceBoolVisitor, ChoiceDoubleVisitor, ChoiceFdVisitor, ChoiceFloatVisitor,
    ChoiceFractionVisitor, ChoiceIdVisitor, ChoiceIntVisitor, ChoiceLongVisitor,
    ChoiceRectangleVisitor, DoubleVisitor, FdVisitor, FloatVisitor, FractionVisitor, IdVisitor,
    IntVisitor, LongVisitor, PointerVisitor, RectangleVisitor,
};

/// A transparent wrapper around a `spa_sys::spa_pod`.
#[repr(transparent)]
pub struct Pod(spa_sys::spa_pod);

impl Pod {
    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod.
    ///
    /// The pods allocation must fit the entire size of the pod as indicated
    /// by the pods header, including header size, body size and any padding.
    ///
    /// The provided pod must not be mutated, moved, freed or similar while
    /// the borrow returned from this function is in use.
    /// This also means that other nonmutable borrows may be created to this pod,
    /// but no mutable borrows to this pod may be created until all borrows are dropped.
    ///
    /// The returned type has `'static` lifetime.
    /// It is suggested to shorten the lifetime to whatever is applicable afterwards.
    pub unsafe fn from_raw(pod: *const spa_sys::spa_pod) -> &'static Self {
        pod.cast::<Self>().as_ref().unwrap()
    }

    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod.
    ///
    /// The pods allocation must fit the entire size of the pod as indicated
    /// by the pods header, including header size, body size and any padding.
    ///
    /// The provided pod must not be mutated, moved, freed or similar while
    /// the borrow returned from this function is in use.
    /// This also means that no other borrow to this pod may be created until the borrow is dropped.
    ///
    /// The returned type has `'static` lifetime.
    /// It is suggested to shorten the lifetime to whatever is applicable afterwards.
    pub unsafe fn from_raw_mut(pod: *mut spa_sys::spa_pod) -> &'static mut Self {
        pod.cast::<Self>().as_mut().unwrap()
    }

    pub fn as_raw_ptr(&self) -> *mut spa_sys::spa_pod {
        addr_of!(self.0).cast_mut()
    }

    /// Returns a pointer to the pods body.
    ///
    /// If the pod has an empty body, this can be outside the pods allocation.
    pub fn body(&self) -> *mut c_void {
        unsafe {
            self.as_raw_ptr()
                .byte_add(std::mem::size_of::<spa_sys::spa_pod>())
                .cast()
        }
    }

    /// Construct a pod from raw bytes.
    ///
    /// The provided slice must be big enough to fit the entire pod including padding.
    pub fn from_bytes(bytes: &[u8]) -> Option<&Self> {
        // Ensure bytes contains at least a readable pod header
        // that we can read the pods size from

        const HEADER_SIZE: usize = std::mem::size_of::<spa_sys::spa_pod>();

        if bytes.len() < HEADER_SIZE {
            return None;
        }

        let pod: *const spa_sys::spa_pod = bytes.as_ptr().cast();

        // `pod` now points to a valid pod header that we can read
        let size: usize = unsafe { *pod }.size.try_into().unwrap();

        let padding = (8 - (size % 8)) % 8;

        // Now, ensure that `bytes` is big enough to fit the entire pod
        if HEADER_SIZE + size + padding <= bytes.len() {
            // Bytes is big enough to fit the entire header, body and padding.
            // We can safely convert this to a &Pod
            Some(unsafe { Self::from_raw(pod) })
        } else {
            None
        }
    }

    pub fn as_bytes(&self) -> &[u8] {
        let ptr: *const u8 = self.as_raw_ptr().cast();
        let size: usize = self.size().try_into().unwrap();
        let size = size + std::mem::size_of::<spa_sys::spa_pod>();

        unsafe { std::slice::from_raw_parts(ptr, size) }
    }

    pub fn type_(&self) -> SpaTypes {
        SpaTypes::from_raw(self.0.type_)
    }

    pub fn size(&self) -> u32 {
        self.0.size
    }

    // TODO: Other methods from iter.h that are still missing

    pub fn is_none(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_none(self.as_raw_ptr()) };
        res != 0
    }

    pub fn is_bool(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_bool(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_bool(&self) -> Result<bool, Errno> {
        unsafe {
            let mut b: MaybeUninit<bool> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_bool(self.as_raw_ptr(), b.as_mut_ptr());

            if res >= 0 {
                Ok(b.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_id(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_id(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_id(&self) -> Result<Id, Errno> {
        unsafe {
            let mut id: MaybeUninit<u32> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_id(self.as_raw_ptr(), id.as_mut_ptr());

            if res >= 0 {
                Ok(Id(id.assume_init()))
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_int(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_int(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_int(&self) -> Result<i32, Errno> {
        unsafe {
            let mut int: MaybeUninit<i32> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_int(self.as_raw_ptr(), int.as_mut_ptr());

            if res >= 0 {
                Ok(int.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_long(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_long(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_long(&self) -> Result<i64, Errno> {
        unsafe {
            let mut long: MaybeUninit<i64> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_long(self.as_raw_ptr(), long.as_mut_ptr());

            if res >= 0 {
                Ok(long.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_float(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_float(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_float(&self) -> Result<f32, Errno> {
        unsafe {
            let mut float: MaybeUninit<f32> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_float(self.as_raw_ptr(), float.as_mut_ptr());

            if res >= 0 {
                Ok(float.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_double(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_double(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_double(&self) -> Result<f64, Errno> {
        unsafe {
            let mut double: MaybeUninit<f64> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_double(self.as_raw_ptr(), double.as_mut_ptr());

            if res >= 0 {
                Ok(double.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_string(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_string(self.as_raw_ptr()) };
        res != 0
    }

    // TODO: to_string

    pub fn is_bytes(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_bytes(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_bytes(&self) -> Result<&[u8], Errno> {
        unsafe {
            let mut bytes: MaybeUninit<*const c_void> = MaybeUninit::uninit();
            let mut len: MaybeUninit<u32> = MaybeUninit::uninit();
            let res =
                spa_sys::spa_pod_get_bytes(self.as_raw_ptr(), bytes.as_mut_ptr(), len.as_mut_ptr());

            if res >= 0 {
                let bytes = bytes.assume_init();
                let len = len.assume_init();
                let bytes = std::slice::from_raw_parts(bytes.cast(), len.try_into().unwrap());
                Ok(bytes)
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_pointer(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_pointer(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_pointer(&self) -> Result<(*const c_void, Id), Errno> {
        unsafe {
            let mut _type: MaybeUninit<u32> = MaybeUninit::uninit();
            let mut pointer: MaybeUninit<*const c_void> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_pointer(
                self.as_raw_ptr(),
                _type.as_mut_ptr(),
                pointer.as_mut_ptr(),
            );

            if res >= 0 {
                let _type = Id(_type.assume_init());
                let pointer = pointer.assume_init();
                Ok((pointer, _type))
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_fd(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_fd(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_fd(&self) -> Result<RawFd, Errno> {
        unsafe {
            let mut fd: MaybeUninit<i64> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_fd(self.as_raw_ptr(), fd.as_mut_ptr());

            if res >= 0 {
                let fd = fd.assume_init();
                let fd: RawFd = fd.try_into().unwrap();
                Ok(fd)
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_rectangle(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_rectangle(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_rectangle(&self) -> Result<Rectangle, Errno> {
        unsafe {
            let mut rectangle: MaybeUninit<spa_sys::spa_rectangle> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_rectangle(self.as_raw_ptr(), rectangle.as_mut_ptr());

            if res >= 0 {
                Ok(rectangle.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_fraction(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_fraction(self.as_raw_ptr()) };
        res != 0
    }

    pub fn get_fraction(&self) -> Result<Fraction, Errno> {
        unsafe {
            let mut fraction: MaybeUninit<spa_sys::spa_fraction> = MaybeUninit::uninit();
            let res = spa_sys::spa_pod_get_fraction(self.as_raw_ptr(), fraction.as_mut_ptr());

            if res >= 0 {
                Ok(fraction.assume_init())
            } else {
                Err(Errno::from_i32(-res))
            }
        }
    }

    pub fn is_bitmap(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_bitmap(self.as_raw_ptr()) };
        res != 0
    }

    pub fn is_array(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_array(self.as_raw_ptr()) };
        res != 0
    }

    pub fn is_choice(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_choice(self.as_raw_ptr()) };
        res != 0
    }

    pub fn is_struct(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_struct(self.as_raw_ptr()) };
        res != 0
    }

    pub fn as_struct(&self) -> Result<&PodStruct, Errno> {
        if self.is_struct() {
            // Safety: We already know that the pod is valid, and since it is a struct, we can
            //         safely create a PodStruct from it
            Ok(unsafe { PodStruct::from_raw(self.as_raw_ptr() as *const spa_sys::spa_pod_struct) })
        } else {
            Err(Errno::EINVAL)
        }
    }

    pub fn is_object(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_object(self.as_raw_ptr()) };
        res != 0
    }

    // TODO: spa_pod_is_object_type, spa_pod_is_object_id

    pub fn as_object(&self) -> Result<&PodObject, Errno> {
        if self.is_object() {
            // Safety: We already know that the pod is valid, and since it is an object, we can
            //         safely create a PodObject from it
            Ok(unsafe { PodObject::from_raw(self.as_raw_ptr() as *const spa_sys::spa_pod_object) })
        } else {
            Err(Errno::EINVAL)
        }
    }

    pub fn is_sequence(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_is_sequence(self.as_raw_ptr()) };
        res != 0
    }
}

impl<'p> From<&'p PodStruct> for &'p Pod {
    fn from(value: &'p PodStruct) -> Self {
        value.as_pod()
    }
}

impl<'p> From<&'p PodObject> for &'p Pod {
    fn from(value: &'p PodObject) -> Self {
        value.as_pod()
    }
}

/// A transparent wrapper around a `spa_sys::spa_pod_struct`.
#[repr(transparent)]
pub struct PodStruct(spa_sys::spa_pod_struct);

impl PodStruct {
    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod of type struct.
    ///
    /// All restrictions from [`Pod::from_raw`] also apply here.
    pub unsafe fn from_raw(pod: *const spa_sys::spa_pod_struct) -> &'static Self {
        pod.cast::<Self>().as_ref().unwrap()
    }

    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod of type struct.
    ///
    /// All restrictions from [`Pod::from_raw_mut`] also apply here.
    pub unsafe fn from_raw_mut(pod: *mut spa_sys::spa_pod_struct) -> &'static mut Self {
        pod.cast::<Self>().as_mut().unwrap()
    }

    pub fn as_raw_ptr(&self) -> *mut spa_sys::spa_pod_struct {
        std::ptr::addr_of!(self.0).cast_mut()
    }

    pub fn as_pod(&self) -> &Pod {
        // Safety: Since this is a valid spa_pod_object, it must also be a valid spa_pod
        unsafe { Pod::from_raw(addr_of!(self.0.pod)) }
    }

    pub fn fields(&self) -> PodStructIter<'_> {
        PodStructIter::new(self)
    }
}

impl<'p> TryFrom<&'p Pod> for &'p PodStruct {
    type Error = Errno;

    fn try_from(value: &'p Pod) -> Result<Self, Self::Error> {
        value.as_struct()
    }
}

impl AsRef<Pod> for PodStruct {
    fn as_ref(&self) -> &Pod {
        self.as_pod()
    }
}

pub struct PodStructIter<'s> {
    struct_pod: &'s PodStruct,
    next: *mut c_void,
}

impl<'s> PodStructIter<'s> {
    fn new(struct_pod: &'s PodStruct) -> Self {
        let first_field = struct_pod.as_pod().body();

        Self {
            struct_pod,
            next: first_field,
        }
    }
}

impl<'s> Iterator for PodStructIter<'s> {
    type Item = &'s Pod;

    fn next(&mut self) -> Option<Self::Item> {
        // Check if the iterator has at least one element left that we can return
        let has_next = unsafe {
            spa_sys::spa_pod_is_inside(
                self.struct_pod.as_pod().body(),
                self.struct_pod.0.pod.size,
                self.next,
            )
        };

        if has_next {
            let res = unsafe { Pod::from_raw(self.next as *const spa_sys::spa_pod) };

            // Advance iter to next property
            self.next = unsafe { spa_sys::spa_pod_next(self.next) };

            Some(res)
        } else {
            None
        }
    }
}

/// A transparent wrapper around a `spa_sys::spa_pod_object`.
#[repr(transparent)]
pub struct PodObject(spa_sys::spa_pod_object);

impl PodObject {
    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod of type object.
    ///
    /// All restrictions from [`Pod::from_raw`] also apply here.
    pub unsafe fn from_raw(pod: *const spa_sys::spa_pod_object) -> &'static Self {
        pod.cast::<Self>().as_ref().unwrap()
    }

    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod of type object.
    ///
    /// All restrictions from [`Pod::from_raw_mut`] also apply here.
    pub unsafe fn from_raw_mut(pod: *mut spa_sys::spa_pod_object) -> &'static mut Self {
        pod.cast::<Self>().as_mut().unwrap()
    }

    pub fn as_raw_ptr(&self) -> *mut spa_sys::spa_pod_object {
        std::ptr::addr_of!(self.0).cast_mut()
    }

    pub fn as_pod(&self) -> &Pod {
        // Safety: Since this is a valid spa_pod_object, it must also be a valid spa_pod
        unsafe { Pod::from_raw(addr_of!(self.0.pod)) }
    }

    pub fn type_(&self) -> SpaTypes {
        SpaTypes::from_raw(self.0.body.type_)
    }

    pub fn id(&self) -> Id {
        Id(self.0.body.id)
    }

    pub fn props(&self) -> PodObjectIter<'_> {
        PodObjectIter::new(self)
    }

    pub fn find_prop(&self, /* TODO: start, */ key: Id) -> Option<&PodProp> {
        let prop = unsafe {
            spa_sys::spa_pod_object_find_prop(self.as_raw_ptr(), std::ptr::null(), key.0)
        };

        if !prop.is_null() {
            unsafe { Some(PodProp::from_raw(prop)) }
        } else {
            None
        }
    }

    pub fn fixate(&mut self) {
        let _res = unsafe { spa_sys::spa_pod_object_fixate(self.as_raw_ptr()) };
        // C implementation always returns 0
    }

    #[cfg(feature = "v0_3_40")]
    pub fn is_fixated(&self) -> bool {
        let res = unsafe { spa_sys::spa_pod_object_is_fixated(self.as_raw_ptr()) };
        res != 0
    }
}

impl<'p> TryFrom<&'p Pod> for &'p PodObject {
    type Error = Errno;

    fn try_from(value: &'p Pod) -> Result<Self, Self::Error> {
        value.as_object()
    }
}

impl AsRef<Pod> for PodObject {
    fn as_ref(&self) -> &Pod {
        self.as_pod()
    }
}

pub struct PodObjectIter<'o> {
    object: &'o PodObject,
    next: *mut spa_sys::spa_pod_prop,
}

impl<'o> PodObjectIter<'o> {
    fn new(object: &'o PodObject) -> Self {
        let first_prop = unsafe { spa_sys::spa_pod_prop_first(addr_of!(object.0.body)) };

        Self {
            object,
            next: first_prop,
        }
    }
}

impl<'o> Iterator for PodObjectIter<'o> {
    type Item = &'o PodProp;

    fn next(&mut self) -> Option<Self::Item> {
        // Check if the iterator has at least one element left that we can return
        let has_next = unsafe {
            spa_sys::spa_pod_prop_is_inside(
                addr_of!(self.object.0.body),
                self.object.0.pod.size,
                self.next,
            )
        };

        if has_next {
            let res = unsafe { PodProp::from_raw(self.next.cast_const()) };

            // Advance iter to next property
            self.next = unsafe { spa_sys::spa_pod_prop_next(self.next) };

            Some(res)
        } else {
            None
        }
    }
}

bitflags! {
    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    pub struct PodPropFlags: u32 {
        const READONLY = spa_sys::SPA_POD_PROP_FLAG_READONLY;
        const HARDWARE = spa_sys::SPA_POD_PROP_FLAG_HARDWARE;
        const HINT_DICT = spa_sys::SPA_POD_PROP_FLAG_HINT_DICT;
        const MANDATORY = spa_sys::SPA_POD_PROP_FLAG_MANDATORY;
        const DONT_FIXATE = spa_sys::SPA_POD_PROP_FLAG_DONT_FIXATE;
    }
}

/// A transparent wrapper around a `spa_sys::spa_pod_prop`.
#[repr(transparent)]
pub struct PodProp(spa_sys::spa_pod_prop);

impl PodProp {
    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned [`spa_sys::spa_pod_prop`].
    ///
    /// While this struct doesn't represent a full pod, all restrictions from [`Pod::from_raw`] also apply
    /// to this struct and the contained `value` pod.
    pub unsafe fn from_raw(prop: *const spa_sys::spa_pod_prop) -> &'static Self {
        prop.cast::<Self>().as_ref().unwrap()
    }

    /// # Safety
    ///
    /// The provided pointer must point to a valid, well-aligned pod of type object.
    ///
    /// While this struct doesn't represent a full pod, all restrictions from [`Pod::from_raw`] also apply
    /// to this struct and the contained `value` pod.
    pub unsafe fn from_raw_mut(prop: *mut spa_sys::spa_pod_prop) -> &'static mut Self {
        prop.cast::<Self>().as_mut().unwrap()
    }

    pub fn as_raw_ptr(&self) -> *mut spa_sys::spa_pod_prop {
        std::ptr::addr_of!(self.0).cast_mut()
    }

    pub fn key(&self) -> Id {
        Id(self.0.key)
    }

    pub fn flags(&self) -> PodPropFlags {
        PodPropFlags::from_bits_retain(self.0.flags)
    }

    pub fn value(&self) -> &Pod {
        // Safety: Since PodProp may only be constructed around valid Pods, the contained value must also be valid.
        //         We don't mutate the pod and neither can the returned reference.
        //         The returned lifetime is properly shortened by this methods signature.
        unsafe { Pod::from_raw(addr_of!(self.0.value)) }
    }
}

/// Implementors of this trait are the canonical representation of a specific type of fixed sized SPA pod.
///
/// They can be used as an output type for [`FixedSizedPod`] implementors
/// and take care of the actual serialization/deserialization from/to the type of raw SPA pod they represent.
///
/// The trait is sealed, so it can't be implemented outside of this crate.
/// This is to ensure that no invalid pod can be serialized.
///
/// If you want to have your type convert from and to a fixed sized pod, implement [`FixedSizedPod`] instead and choose
/// a fitting implementor of this trait as the `CanonicalType` instead.
pub trait CanonicalFixedSizedPod: private::CanonicalFixedSizedPodSeal {
    /// The raw type this serializes into.
    #[doc(hidden)]
    const TYPE: u32;
    /// The size of the pods body.
    #[doc(hidden)]
    const SIZE: u32;
    #[doc(hidden)]
    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError>;
    #[doc(hidden)]
    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized;
}

mod private {
    /// This trait makes [`super::CanonicalFixedSizedPod`] a "sealed trait", which makes it impossible to implement
    /// outside of this crate.
    pub trait CanonicalFixedSizedPodSeal {}
    impl CanonicalFixedSizedPodSeal for () {}
    impl CanonicalFixedSizedPodSeal for bool {}
    impl CanonicalFixedSizedPodSeal for i32 {}
    impl CanonicalFixedSizedPodSeal for i64 {}
    impl CanonicalFixedSizedPodSeal for f32 {}
    impl CanonicalFixedSizedPodSeal for f64 {}
    impl CanonicalFixedSizedPodSeal for super::Rectangle {}
    impl CanonicalFixedSizedPodSeal for super::Fraction {}
    impl CanonicalFixedSizedPodSeal for super::Id {}
    impl CanonicalFixedSizedPodSeal for super::Fd {}
}

impl<T: CanonicalFixedSizedPod + Copy> FixedSizedPod for T {
    type CanonicalType = Self;

    fn as_canonical_type(&self) -> Self::CanonicalType {
        *self
    }

    fn from_canonical_type(canonical: &Self::CanonicalType) -> Self {
        *canonical
    }
}

/// Serialize into a `None` type pod.
impl CanonicalFixedSizedPod for () {
    const TYPE: u32 = spa_sys::SPA_TYPE_None;
    const SIZE: u32 = 0;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        Ok(out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        Ok((input, ()))
    }
}

/// Serialize into a `Bool` type pod.
impl CanonicalFixedSizedPod for bool {
    const TYPE: u32 = spa_sys::SPA_TYPE_Bool;
    const SIZE: u32 = 4;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_u32(u32::from(*self)), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        map(u32(Endianness::Native), |b| b != 0)(input)
    }
}

/// Serialize into a `Int` type pod.
impl CanonicalFixedSizedPod for i32 {
    const TYPE: u32 = spa_sys::SPA_TYPE_Int;
    const SIZE: u32 = 4;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_i32(*self), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        i32(Endianness::Native)(input)
    }
}

/// Serialize into a `Long` type pod.
impl CanonicalFixedSizedPod for i64 {
    const TYPE: u32 = spa_sys::SPA_TYPE_Long;
    const SIZE: u32 = 8;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_i64(*self), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        i64(Endianness::Native)(input)
    }
}

/// Serialize into a `Float` type pod.
impl CanonicalFixedSizedPod for f32 {
    const TYPE: u32 = spa_sys::SPA_TYPE_Float;
    const SIZE: u32 = 4;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_f32(*self), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        f32(Endianness::Native)(input)
    }
}

/// Serialize into a `Double` type pod.
impl CanonicalFixedSizedPod for f64 {
    const TYPE: u32 = spa_sys::SPA_TYPE_Double;
    const SIZE: u32 = 8;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_f64(*self), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        f64(Endianness::Native)(input)
    }
}

/// Serialize into a `Rectangle` type pod.
impl CanonicalFixedSizedPod for Rectangle {
    const TYPE: u32 = spa_sys::SPA_TYPE_Rectangle;
    const SIZE: u32 = 8;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(pair(ne_u32(self.width), ne_u32(self.height)), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        map(
            nom::sequence::pair(u32(Endianness::Native), u32(Endianness::Native)),
            |(width, height)| Rectangle { width, height },
        )(input)
    }
}

/// Serialize into a `Fraction` type pod.
impl CanonicalFixedSizedPod for Fraction {
    const TYPE: u32 = spa_sys::SPA_TYPE_Fraction;
    const SIZE: u32 = 8;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(pair(ne_u32(self.num), ne_u32(self.denom)), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        map(
            nom::sequence::pair(u32(Endianness::Native), u32(Endianness::Native)),
            |(num, denom)| Fraction { num, denom },
        )(input)
    }
}

impl CanonicalFixedSizedPod for Id {
    const TYPE: u32 = spa_sys::SPA_TYPE_Id;
    const SIZE: u32 = 4;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_u32(self.0), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        map(u32(Endianness::Native), Id)(input)
    }
}

impl CanonicalFixedSizedPod for Fd {
    const TYPE: u32 = spa_sys::SPA_TYPE_Fd;
    const SIZE: u32 = 8;

    fn serialize_body<O: Write>(&self, out: O) -> Result<O, GenError> {
        gen_simple(ne_i64(self.0), out)
    }

    fn deserialize_body(input: &[u8]) -> IResult<&[u8], Self>
    where
        Self: Sized,
    {
        map(i64(Endianness::Native), Fd)(input)
    }
}

/// Implementors of this trait can be serialized into pods that always have the same size.
/// This lets them be used as elements in `Array` type SPA Pods.
///
/// Implementors of this automatically implement [`PodSerialize`].
///
/// Serialization is accomplished by having the type convert itself into/from the canonical representation of this pod,
/// e.g. `i32` for a `Int` type pod.
///
/// That type then takes care of the actual serialization.
///
/// See the [`CanonicalFixedSizedPod`] trait for a list of possible target types.
///
/// Which type to convert in is specified with the traits [`FixedSizedPod::CanonicalType`] type,
/// while the traits [`as_canonical_type`](`FixedSizedPod::as_canonical_type`)
/// and [`from_canonical_type`](`FixedSizedPod::from_canonical_type`) methods are responsible for the actual conversion.
///
/// # Examples
/// Implementing the trait on a `i32` newtype wrapper:
/// ```rust
/// use libspa::pod::FixedSizedPod;
///
/// struct Newtype(i32);
///
/// impl FixedSizedPod for Newtype {
///     // The pod we want to serialize into is a `Int` type pod, which has `i32` as it's canonical representation.
///     type CanonicalType = i32;
///
///     fn as_canonical_type(&self) -> Self::CanonicalType {
///         // Convert self to the canonical type.
///         self.0
///     }
///
///     fn from_canonical_type(canonical: &Self::CanonicalType) -> Self {
///         // Create a new Self instance from the canonical type.
///         Newtype(*canonical)
///     }
/// }
/// ```
pub trait FixedSizedPod {
    /// The canonical representation of the type of pod that should be serialized to/deserialized from.
    type CanonicalType: CanonicalFixedSizedPod;

    /// Convert `self` to the canonical type.
    fn as_canonical_type(&self) -> Self::CanonicalType;
    /// Convert the canonical type to `Self`.
    fn from_canonical_type(_: &Self::CanonicalType) -> Self;
}

impl<T: FixedSizedPod> PodSerialize for T {
    fn serialize<O: Write + Seek>(
        &self,
        serializer: PodSerializer<O>,
    ) -> Result<serialize::SerializeSuccess<O>, GenError> {
        serializer.serialized_fixed_sized_pod(self)
    }
}

impl<'de> PodDeserialize<'de> for () {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_none(NoneVisitor)
    }
}

impl<'de> PodDeserialize<'de> for bool {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_bool(BoolVisitor)
    }
}

impl<'de> PodDeserialize<'de> for i32 {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_int(IntVisitor)
    }
}

impl<'de> PodDeserialize<'de> for i64 {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_long(LongVisitor)
    }
}

impl<'de> PodDeserialize<'de> for f32 {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_float(FloatVisitor)
    }
}

impl<'de> PodDeserialize<'de> for f64 {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_double(DoubleVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Rectangle {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_rectangle(RectangleVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Fraction {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_fraction(FractionVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Id {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_id(IdVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Fd {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_fd(FdVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<bool> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceBoolVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<i32> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceIntVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<i64> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceLongVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<f32> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceFloatVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<f64> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceDoubleVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<Id> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceIdVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<Rectangle> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceRectangleVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<Fraction> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceFractionVisitor)
    }
}

impl<'de> PodDeserialize<'de> for Choice<Fd> {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_choice(ChoiceFdVisitor)
    }
}

impl<'de, T> PodDeserialize<'de> for (u32, *const T) {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_pointer(PointerVisitor::<T>::default())
    }
}

impl<'de> PodDeserialize<'de> for Value {
    fn deserialize(
        deserializer: PodDeserializer<'de>,
    ) -> Result<
        (Self, deserialize::DeserializeSuccess<'de>),
        deserialize::DeserializeError<&'de [u8]>,
    >
    where
        Self: Sized,
    {
        deserializer.deserialize_any()
    }
}

/// A typed pod value.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// no value or a NULL pointer.
    None,
    /// a boolean value.
    Bool(bool),
    /// an enumerated value.
    Id(Id),
    /// a 32 bits integer.
    Int(i32),
    /// a 64 bits integer.
    Long(i64),
    /// a 32 bits floating.
    Float(f32),
    /// a 64 bits floating.
    Double(f64),
    /// a string.
    String(String),
    /// a byte array.
    Bytes(Vec<u8>),
    /// a rectangle with width and height.
    Rectangle(Rectangle),
    /// a fraction with numerator and denominator.
    Fraction(Fraction),
    /// a file descriptor.
    Fd(Fd),
    /// an array of same type objects.
    ValueArray(ValueArray),
    /// a collection of types and objects.
    Struct(Vec<Value>),
    /// an object.
    Object(Object),
    /// a choice.
    Choice(ChoiceValue),
    /// a pointer.
    Pointer(u32, *const c_void),
}

/// an array of same type objects.
#[derive(Debug, Clone, PartialEq)]
pub enum ValueArray {
    /// an array of none.
    None(Vec<()>),
    /// an array of booleans.
    Bool(Vec<bool>),
    /// an array of Id.
    Id(Vec<Id>),
    /// an array of 32 bits integer.
    Int(Vec<i32>),
    /// an array of 64 bits integer.
    Long(Vec<i64>),
    /// an array of 32 bits floating.
    Float(Vec<f32>),
    /// an array of 64 bits floating.
    Double(Vec<f64>),
    /// an array of Rectangle.
    Rectangle(Vec<Rectangle>),
    /// an array of Fraction.
    Fraction(Vec<Fraction>),
    /// an array of Fd.
    Fd(Vec<Fd>),
}

/// A typed choice.
#[derive(Debug, Clone, PartialEq)]
pub enum ChoiceValue {
    /// Choice on boolean values.
    Bool(Choice<bool>),
    /// Choice on 32 bits integer values.
    Int(Choice<i32>),
    /// Choice on 64 bits integer values.
    Long(Choice<i64>),
    /// Choice on 32 bits floating values.
    Float(Choice<f32>),
    /// Choice on 64 bits floating values.
    Double(Choice<f64>),
    /// Choice on id values.
    Id(Choice<Id>),
    /// Choice on rectangle values.
    Rectangle(Choice<Rectangle>),
    /// Choice on fraction values.
    Fraction(Choice<Fraction>),
    /// Choice on fd values.
    Fd(Choice<Fd>),
}

/// An object from a pod.
#[derive(Debug, Clone, PartialEq)]
pub struct Object {
    /// the object type.
    pub type_: u32,
    /// the object id.
    pub id: u32,
    /// the object properties.
    pub properties: Vec<Property>,
}

/// A macro for creating a new [`Object`] with properties.
///
/// The macro accepts the object type, id and a list of properties, separated by commas.
///
/// # Examples:
/// Create an `Object`.
/// ```rust
/// use libspa::pod::{object, property};
///
/// let pod_object = object!{
///     libspa::utils::SpaTypes::ObjectParamFormat,
///     libspa::param::ParamType::EnumFormat,
///     property!(
///         libspa::param::format::FormatProperties::MediaType,
///         Id,
///         libspa::param::format::MediaType::Video
///     ),
///     property!(
///         libspa::param::format::FormatProperties::MediaSubtype,
///         Id,
///         libspa::param::format::MediaSubtype::Raw
///     ),
/// };
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! __object__ {
    ($type_:expr, $id:expr, $($properties:expr),* $(,)?) => {
        pipewire::spa::pod::Object {
            type_: $type_.as_raw(),
            id: $id.as_raw(),
            properties: [ $( $properties, )* ].to_vec(),
        }
    };
}
#[doc(inline)]
pub use __object__ as object;

/// An object property.
#[derive(Debug, Clone, PartialEq)]
pub struct Property {
    /// key of the property, list of valid keys depends on the object type.
    pub key: u32,
    /// flags for the property.
    pub flags: PropertyFlags,
    /// value of the property.
    pub value: Value,
}

impl Property {
    pub fn new(key: u32, value: Value) -> Self {
        Self {
            key,
            value,
            flags: PropertyFlags::empty(),
        }
    }
}

bitflags! {
    /// Property flags
    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    pub struct PropertyFlags: u32 {
        // These flags are redefinitions from
        // https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/master/spa/include/spa/pod/pod.h
        /// Property is read-only.
        const READONLY = spa_sys::SPA_POD_PROP_FLAG_READONLY;
        /// Property is some sort of hardware parameter.
        const HARDWARE = spa_sys::SPA_POD_PROP_FLAG_HARDWARE;
        /// Property contains a dictionary struct.
        const HINT_DICT = spa_sys::SPA_POD_PROP_FLAG_HINT_DICT;
        /// Property is mandatory.
        const MANDATORY = spa_sys::SPA_POD_PROP_FLAG_MANDATORY;
        /// Property choices need no fixation.
        #[cfg(feature = "v0_3_33")]
        const DONT_FIXATE = spa_sys::SPA_POD_PROP_FLAG_DONT_FIXATE;
    }
}

/// A macro for creating a new Object [`Property`].
///
/// The macro accepts the following:
/// - properties!(libspa::format::FormatProperties::`<key>`, Id, `<value>`)
/// - properties!(libspa::format::FormatProperties::`<key>`, `<type>`, libspa::utils::`<type>`(`<value>`))
/// - properties!(libspa::format::FormatProperties::`<key>`, Choice, Enum, Id, `<default>`, `<value>`, ...)
/// - properties!(libspa::format::FormatProperties::`<key>`, Choice, Enum, `<type>`,
///                 libspa::utils::`<type>`(`<default>`),
///                 libspa::utils::`<type>`(`<value>`), ...)
/// - properties!(libspa::format::FormatProperties::`<key>`, Choice, Flags, `<type>`,
///                 libspa::utils::`<type>`(`<default>`),
///                 libspa::utils::`<type>`(`<value>`), ...)
/// - properties!(libspa::format::FormatProperties::`<key>`, Choice, Step, `<type>`,
///                 libspa::utils::`<type>`(default),
///                 libspa::utils::`<type>`(min),
///                 libspa::utils::`<type>`(max),
///                 libspa::utils::`<type>`(step))
/// - properties!(libspa::format::FormatProperties::`<key>`, Choice, Range, `<type>`,
///                 libspa::utils::`<type>`(default),
///                 libspa::utils::`<type>`(min),
///                 libspa::utils::`<type>`(max))
#[doc(hidden)]
#[macro_export]
macro_rules! __property__ {
    ($key:expr, $value:expr) => {
        pipewire::spa::pod::Property {
            key: $key.as_raw(),
            flags: pipewire::spa::pod::PropertyFlags::empty(),
            value: $value,
        }
    };

    ($key:expr, Id, $value:expr) => {
        pipewire::spa::pod::property!($key, pipewire::spa::pod::Value::Id(pipewire::spa::utils::Id($value.as_raw())))
    };

    ($key:expr, $type_:ident, $value:expr) => {
        pipewire::spa::pod::property!($key, pipewire::spa::pod::Value::$type_($value))
    };

    ($key:expr, Choice, Enum, Id, $default:expr, $($alternative:expr),+ $(,)?) => {
        pipewire::spa::pod::property!(
            $key,
            pipewire::spa::pod::Value::Choice(pipewire::spa::pod::ChoiceValue::Id(
                pipewire::spa::utils::Choice::<pipewire::spa::utils::Id>(
                    pipewire::spa::utils::ChoiceFlags::empty(),
                    pipewire::spa::utils::ChoiceEnum::<pipewire::spa::utils::Id>::Enum {
                        default: pipewire::spa::utils::Id($default.as_raw()),
                        alternatives: [ $( pipewire::spa::utils::Id($alternative.as_raw()), )+ ].to_vec()
                    }
                )
            ))
        )
    };

    ($key:expr, Choice, Enum, $type_:ident, $default:expr, $($alternative:expr),+ $(,)?) => {
        pipewire::spa::pod::property!(
            $key,
            pipewire::spa::pod::Value::Choice(pipewire::spa::pod::ChoiceValue::$type_(
                pipewire::spa::utils::Choice::<pipewire::spa::utils::$type_>(
                    pipewire::spa::utils::ChoiceFlags::empty(),
                    pipewire::spa::utils::ChoiceEnum::<pipewire::spa::utils::$type_>::Enum {
                        default: $default,
                        alternatives: [ $( $alternative, )+ ].to_vec()
                    }
                )
            ))
        )
    };

    ($key:expr, Choice, Flags, $type_:ident, $default:expr, $($alternative:expr),+ $(,)?) => {
        pipewire::spa::pod::property!(
            $key,
            pipewire::spa::pod::Value::Choice(pipewire::spa::pod::ChoiceValue::$type_(
                pipewire::spa::utils::Choice::<pipewire::spa::utils::$type_>(
                    pipewire::spa::utils::ChoiceFlags::empty(),
                    pipewire::spa::utils::ChoiceEnum::<pipewire::spa::utils::$type_>::Flags {
                        default: $default,
                        flags: [ $( $alternative, )+ ].to_vec()
                    }
                )
            ))
        )
    };

    ($key:expr, Choice, Step, $type_:ident, $default:expr, $min:expr, $max:expr, $step:expr) => {
        pipewire::spa::pod::property!(
            $key,
            pipewire::spa::pod::Value::Choice(pipewire::spa::pod::ChoiceValue::$type_(
                pipewire::spa::utils::Choice::<pipewire::spa::utils::$type_>(
                    pipewire::spa::utils::ChoiceFlags::empty(),
                    pipewire::spa::utils::ChoiceEnum::<pipewire::spa::utils::$type_>::Step {
                        default: $default,
                        min: $min,
                        max: $max,
                        step: $step,
                    }
                )
            ))
        )
    };

    ($key:expr, Choice, Range, $type_:ident, $default:expr, $min:expr, $max:expr) => {
        pipewire::spa::pod::property!(
            $key,
            pipewire::spa::pod::Value::Choice(pipewire::spa::pod::ChoiceValue::$type_(
                pipewire::spa::utils::Choice::<pipewire::spa::utils::$type_>(
                    pipewire::spa::utils::ChoiceFlags::empty(),
                    pipewire::spa::utils::ChoiceEnum::<pipewire::spa::utils::$type_>::Range {
                        default: $default,
                        min: $min,
                        max: $max,
                    }
                )
            ))
        )
    };
}
#[doc(inline)]
pub use __property__ as property;