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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::borrow::{Borrow, BorrowMut, ToOwned};
use std::ffi::CStr;
use std::fmt;
use std::mem;
use std::ops;
use std::ptr;

use glib::translate::*;
use glib::StaticType;

use crate::sdp_attribute::SDPAttribute;
use crate::sdp_bandwidth::SDPBandwidth;
use crate::sdp_connection::SDPConnection;
use crate::sdp_key::SDPKey;
use crate::sdp_media::SDPMedia;
use crate::sdp_media::SDPMediaRef;
use crate::sdp_origin::SDPOrigin;
use crate::sdp_time::SDPTime;
use crate::sdp_zone::SDPZone;

glib::wrapper! {
    #[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct SDPMessage(Boxed<ffi::GstSDPMessage>);

    match fn {
        copy => |ptr| {
            let mut copy = std::ptr::null_mut();
            assert_eq!(ffi::gst_sdp_message_copy(ptr, &mut copy), ffi::GST_SDP_OK);
            copy
        },
        free => |ptr| assert_eq!(ffi::gst_sdp_message_free(ptr), ffi::GST_SDP_OK),
        type_ => || ffi::gst_sdp_message_get_type(),
    }
}

unsafe impl Send for SDPMessage {}
unsafe impl Sync for SDPMessage {}

impl Default for SDPMessage {
    fn default() -> Self {
        Self::new()
    }
}

impl ops::Deref for SDPMessage {
    type Target = SDPMessageRef;

    fn deref(&self) -> &SDPMessageRef {
        unsafe { &*(self.to_glib_none().0 as *const SDPMessageRef) }
    }
}

impl ops::DerefMut for SDPMessage {
    fn deref_mut(&mut self) -> &mut SDPMessageRef {
        unsafe { &mut *(self.to_glib_none_mut().0 as *mut SDPMessageRef) }
    }
}

impl fmt::Debug for SDPMessage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <SDPMessageRef as fmt::Debug>::fmt(&*self, f)
    }
}

impl fmt::Display for SDPMessage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <SDPMessageRef as fmt::Display>::fmt(&*self, f)
    }
}

impl SDPMessage {
    pub fn new() -> SDPMessage {
        assert_initialized_main_thread!();
        unsafe {
            let mut msg = ptr::null_mut();
            ffi::gst_sdp_message_new(&mut msg);
            from_glib_full(msg)
        }
    }

    pub fn parse_buffer(data: &[u8]) -> Result<Self, glib::BoolError> {
        assert_initialized_main_thread!();
        unsafe {
            let size = data.len() as u32;
            let mut msg = ptr::null_mut();
            ffi::gst_sdp_message_new(&mut msg);
            let result = ffi::gst_sdp_message_parse_buffer(data.to_glib_none().0, size, msg);
            match result {
                ffi::GST_SDP_OK => Ok(from_glib_full(msg)),
                _ => {
                    ffi::gst_sdp_message_uninit(msg);
                    Err(glib::bool_error!("Failed to parse buffer"))
                }
            }
        }
    }

    pub fn parse_uri(uri: &str) -> Result<Self, glib::BoolError> {
        assert_initialized_main_thread!();
        unsafe {
            let mut msg = ptr::null_mut();
            ffi::gst_sdp_message_new(&mut msg);
            let result = ffi::gst_sdp_message_parse_uri(uri.to_glib_none().0, msg);
            match result {
                ffi::GST_SDP_OK => Ok(from_glib_full(msg)),
                _ => {
                    ffi::gst_sdp_message_uninit(msg);
                    Err(glib::bool_error!("Failed to parse URI"))
                }
            }
        }
    }
}

#[repr(transparent)]
pub struct SDPMessageRef(ffi::GstSDPMessage);

impl fmt::Debug for SDPMessageRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use std::cell::RefCell;

        struct DebugIter<I>(RefCell<I>);
        impl<I: Iterator> fmt::Debug for DebugIter<I>
        where
            I::Item: fmt::Debug,
        {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_list().entries(&mut *self.0.borrow_mut()).finish()
            }
        }

        f.debug_struct("SDPMessage")
            .field("connection", &self.connection())
            .field("information", &self.information())
            .field("key", &self.key())
            .field("origin", &self.origin())
            .field("session-name", &self.session_name())
            .field("uri", &self.uri())
            .field("version", &self.version())
            .field("attributes", &DebugIter(RefCell::new(self.attributes())))
            .field("bandwidths", &DebugIter(RefCell::new(self.bandwidths())))
            .field("emails", &DebugIter(RefCell::new(self.emails())))
            .field("medias", &DebugIter(RefCell::new(self.medias())))
            .field("phones", &DebugIter(RefCell::new(self.phones())))
            .field("times", &DebugIter(RefCell::new(self.times())))
            .field("zones", &DebugIter(RefCell::new(self.zones())))
            .finish()
    }
}

impl fmt::Display for SDPMessageRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.as_text() {
            Ok(text) => f.write_str(text.as_str()),
            Err(_) => Err(fmt::Error),
        }
    }
}

unsafe impl Send for SDPMessageRef {}
unsafe impl Sync for SDPMessageRef {}

impl SDPMessageRef {
    pub fn add_attribute(&mut self, key: &str, value: Option<&str>) {
        unsafe {
            ffi::gst_sdp_message_add_attribute(
                &mut self.0,
                key.to_glib_none().0,
                value.to_glib_none().0,
            );
        }
    }

    pub fn add_email(&mut self, email: &str) {
        unsafe { ffi::gst_sdp_message_add_email(&mut self.0, email.to_glib_none().0) };
    }

    pub fn add_media(&mut self, media: SDPMedia) {
        unsafe {
            ffi::gst_sdp_message_add_media(
                &mut self.0,
                media.to_glib_none().0 as *mut ffi::GstSDPMedia,
            );
        }
    }

    pub fn add_phone(&mut self, phone: &str) {
        unsafe { ffi::gst_sdp_message_add_phone(&mut self.0, phone.to_glib_none().0) };
    }

    pub fn add_time(&mut self, start: &str, stop: &str, repeat: &[&str]) {
        unsafe {
            ffi::gst_sdp_message_add_time(
                &mut self.0,
                start.to_glib_none().0,
                stop.to_glib_none().0,
                repeat.to_glib_none().0,
            )
        };
    }

    pub fn add_zone(&mut self, adj_time: &str, typed_time: &str) {
        unsafe {
            ffi::gst_sdp_message_add_zone(
                &mut self.0,
                adj_time.to_glib_none().0,
                typed_time.to_glib_none().0,
            )
        };
    }

    pub fn as_text(&self) -> Result<String, glib::error::BoolError> {
        unsafe {
            match from_glib_full(ffi::gst_sdp_message_as_text(&self.0)) {
                Some(s) => Ok(s),
                None => Err(glib::bool_error!(
                    "Failed to convert the contents of message to a text string"
                )),
            }
        }
    }

    pub fn attributes_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_attributes_len(&self.0) }
    }

    pub fn attributes_to_caps(&self, caps: &mut gst::CapsRef) -> Result<(), glib::BoolError> {
        let result = unsafe { ffi::gst_sdp_message_attributes_to_caps(&self.0, caps.as_mut_ptr()) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to store attributes in caps")),
        }
    }

    pub fn bandwidths_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_bandwidths_len(&self.0) }
    }

    pub fn dump(&self) {
        unsafe { ffi::gst_sdp_message_dump(&self.0) };
    }

    pub fn emails_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_emails_len(&self.0) }
    }

    #[doc(alias = "get_attribute")]
    pub fn attribute(&self, idx: u32) -> Option<&SDPAttribute> {
        if idx >= self.attributes_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_attribute(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPAttribute))
            }
        }
    }

    #[doc(alias = "get_attribute_val")]
    pub fn attribute_val(&self, key: &str) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_attribute_val(&self.0, key.to_glib_none().0);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_attribute_val_n")]
    pub fn attribute_val_n(&self, key: &str, nth: u32) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_attribute_val_n(&self.0, key.to_glib_none().0, nth);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_bandwidth")]
    pub fn bandwidth(&self, idx: u32) -> Option<&SDPBandwidth> {
        if idx >= self.bandwidths_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_bandwidth(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPBandwidth))
            }
        }
    }

    #[doc(alias = "get_connection")]
    pub fn connection(&self) -> Option<&SDPConnection> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_connection(&self.0);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPConnection))
            }
        }
    }

    #[doc(alias = "get_email")]
    pub fn email(&self, idx: u32) -> Option<&str> {
        if idx >= self.emails_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_email(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_information")]
    pub fn information(&self) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_information(&self.0);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_key")]
    pub fn key(&self) -> Option<&SDPKey> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_key(&self.0);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPKey))
            }
        }
    }

    #[doc(alias = "get_media")]
    pub fn media(&self, idx: u32) -> Option<&SDPMediaRef> {
        if idx >= self.medias_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_media(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *const SDPMediaRef))
            }
        }
    }

    #[doc(alias = "get_media_mut")]
    pub fn media_mut(&mut self, idx: u32) -> Option<&mut SDPMediaRef> {
        if idx >= self.medias_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_media(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&mut *(ptr as *mut SDPMediaRef))
            }
        }
    }

    #[doc(alias = "get_origin")]
    pub fn origin(&self) -> Option<&SDPOrigin> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_origin(&self.0);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPOrigin))
            }
        }
    }

    #[doc(alias = "get_phone")]
    pub fn phone(&self, idx: u32) -> Option<&str> {
        if idx >= self.phones_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_phone(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_session_name")]
    pub fn session_name(&self) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_session_name(&self.0);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_time")]
    pub fn time(&self, idx: u32) -> Option<&SDPTime> {
        if idx >= self.times_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_time(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPTime))
            }
        }
    }

    #[doc(alias = "get_uri")]
    pub fn uri(&self) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_uri(&self.0);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_version")]
    pub fn version(&self) -> Option<&str> {
        unsafe {
            let ptr = ffi::gst_sdp_message_get_version(&self.0);
            if ptr.is_null() {
                None
            } else {
                CStr::from_ptr(ptr).to_str().ok()
            }
        }
    }

    #[doc(alias = "get_zone")]
    pub fn zone(&self, idx: u32) -> Option<&SDPZone> {
        if idx >= self.zones_len() {
            return None;
        }

        unsafe {
            let ptr = ffi::gst_sdp_message_get_zone(&self.0, idx);
            if ptr.is_null() {
                None
            } else {
                Some(&*(ptr as *mut SDPZone))
            }
        }
    }

    pub fn insert_attribute(
        &mut self,
        idx: Option<u32>,
        attr: SDPAttribute,
    ) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.attributes_len() {
                return Err(glib::bool_error!("Failed to insert attribute"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let mut attr = mem::ManuallyDrop::new(attr);
        let result =
            unsafe { ffi::gst_sdp_message_insert_attribute(&mut self.0, idx, &mut attr.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert attribute")),
        }
    }

    pub fn insert_bandwidth(
        &mut self,
        idx: Option<u32>,
        bw: SDPBandwidth,
    ) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.bandwidths_len() {
                return Err(glib::bool_error!("Failed to insert bandwidth"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let mut bw = mem::ManuallyDrop::new(bw);
        let result = unsafe { ffi::gst_sdp_message_insert_bandwidth(&mut self.0, idx, &mut bw.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert bandwidth")),
        }
    }

    pub fn insert_email(&mut self, idx: Option<u32>, email: &str) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.emails_len() {
                return Err(glib::bool_error!("Failed to insert email"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let result =
            unsafe { ffi::gst_sdp_message_insert_email(&mut self.0, idx, email.to_glib_none().0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert email")),
        }
    }

    pub fn insert_phone(&mut self, idx: Option<u32>, phone: &str) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.phones_len() {
                return Err(glib::bool_error!("Failed to insert phone"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let result =
            unsafe { ffi::gst_sdp_message_insert_phone(&mut self.0, idx, phone.to_glib_none().0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert phone")),
        }
    }

    pub fn insert_time(&mut self, idx: Option<u32>, time: SDPTime) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.times_len() {
                return Err(glib::bool_error!("Failed to insert time"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let mut time = mem::ManuallyDrop::new(time);
        let result = unsafe { ffi::gst_sdp_message_insert_time(&mut self.0, idx, &mut time.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert time")),
        }
    }

    pub fn insert_zone(&mut self, idx: Option<u32>, zone: SDPZone) -> Result<(), glib::BoolError> {
        if let Some(idx) = idx {
            if idx >= self.zones_len() {
                return Err(glib::bool_error!("Failed to insert zone"));
            }
        }

        let idx = idx.map(|idx| idx as i32).unwrap_or(-1);
        let mut zone = mem::ManuallyDrop::new(zone);
        let result = unsafe { ffi::gst_sdp_message_insert_zone(&mut self.0, idx, &mut zone.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to insert zone")),
        }
    }

    pub fn medias_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_medias_len(&self.0) }
    }

    pub fn phones_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_phones_len(&self.0) }
    }

    pub fn remove_attribute(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.attributes_len() {
            return Err(glib::bool_error!("Failed to remove attribute"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_attribute(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove attribute")),
        }
    }

    pub fn remove_bandwidth(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.bandwidths_len() {
            return Err(glib::bool_error!("Failed to remove bandwidth"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_bandwidth(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove bandwidth")),
        }
    }

    pub fn remove_email(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.emails_len() {
            return Err(glib::bool_error!("Failed to remove email"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_email(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove email")),
        }
    }

    pub fn remove_phone(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.phones_len() {
            return Err(glib::bool_error!("Failed to remove phone"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_phone(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove phone")),
        }
    }

    pub fn remove_time(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.times_len() {
            return Err(glib::bool_error!("Failed to remove time"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_time(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove time")),
        }
    }

    pub fn remove_zone(&mut self, idx: u32) -> Result<(), glib::BoolError> {
        if idx >= self.zones_len() {
            return Err(glib::bool_error!("Failed to remove zone"));
        }

        let result = unsafe { ffi::gst_sdp_message_remove_zone(&mut self.0, idx) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to remove zone")),
        }
    }

    pub fn replace_attribute(
        &mut self,
        idx: u32,
        attr: SDPAttribute,
    ) -> Result<(), glib::BoolError> {
        if idx >= self.attributes_len() {
            return Err(glib::bool_error!("Failed to replace attribute"));
        }

        let mut attr = mem::ManuallyDrop::new(attr);
        let result =
            unsafe { ffi::gst_sdp_message_replace_attribute(&mut self.0, idx, &mut attr.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace attribute")),
        }
    }

    pub fn replace_bandwidth(&mut self, idx: u32, bw: SDPBandwidth) -> Result<(), glib::BoolError> {
        if idx >= self.bandwidths_len() {
            return Err(glib::bool_error!("Failed to replace bandwidth"));
        }

        let mut bw = mem::ManuallyDrop::new(bw);
        let result = unsafe { ffi::gst_sdp_message_replace_bandwidth(&mut self.0, idx, &mut bw.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace bandwidth")),
        }
    }

    pub fn replace_email(&mut self, idx: u32, email: &str) -> Result<(), glib::BoolError> {
        if idx >= self.emails_len() {
            return Err(glib::bool_error!("Failed to replace email"));
        }

        let result =
            unsafe { ffi::gst_sdp_message_replace_email(&mut self.0, idx, email.to_glib_none().0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace email")),
        }
    }

    pub fn replace_phone(&mut self, idx: u32, phone: &str) -> Result<(), glib::BoolError> {
        if idx >= self.phones_len() {
            return Err(glib::bool_error!("Failed to replace phone"));
        }

        let result =
            unsafe { ffi::gst_sdp_message_replace_phone(&mut self.0, idx, phone.to_glib_none().0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace phone")),
        }
    }

    pub fn replace_time(&mut self, idx: u32, time: SDPTime) -> Result<(), glib::BoolError> {
        if idx >= self.times_len() {
            return Err(glib::bool_error!("Failed to replace time"));
        }

        let mut time = mem::ManuallyDrop::new(time);
        let result = unsafe { ffi::gst_sdp_message_replace_time(&mut self.0, idx, &mut time.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace time")),
        }
    }

    pub fn replace_zone(&mut self, idx: u32, zone: SDPZone) -> Result<(), glib::BoolError> {
        if idx >= self.zones_len() {
            return Err(glib::bool_error!("Failed to replace zone"));
        }

        let mut zone = mem::ManuallyDrop::new(zone);
        let result = unsafe { ffi::gst_sdp_message_replace_zone(&mut self.0, idx, &mut zone.0) };
        match result {
            ffi::GST_SDP_OK => Ok(()),
            _ => Err(glib::bool_error!("Failed to replace zone")),
        }
    }

    pub fn set_connection(
        &mut self,
        nettype: &str,
        addrtype: &str,
        address: &str,
        ttl: u32,
        addr_number: u32,
    ) {
        unsafe {
            ffi::gst_sdp_message_set_connection(
                &mut self.0,
                nettype.to_glib_none().0,
                addrtype.to_glib_none().0,
                address.to_glib_none().0,
                ttl,
                addr_number,
            )
        };
    }

    pub fn set_information(&mut self, information: &str) {
        unsafe { ffi::gst_sdp_message_set_information(&mut self.0, information.to_glib_none().0) };
    }

    pub fn set_key(&mut self, type_: &str, data: &str) {
        unsafe {
            ffi::gst_sdp_message_set_key(&mut self.0, type_.to_glib_none().0, data.to_glib_none().0)
        };
    }

    pub fn set_origin(
        &mut self,
        username: &str,
        sess_id: &str,
        sess_version: &str,
        nettype: &str,
        addrtype: &str,
        addr: &str,
    ) {
        unsafe {
            ffi::gst_sdp_message_set_origin(
                &mut self.0,
                username.to_glib_none().0,
                sess_id.to_glib_none().0,
                sess_version.to_glib_none().0,
                nettype.to_glib_none().0,
                addrtype.to_glib_none().0,
                addr.to_glib_none().0,
            )
        };
    }

    pub fn set_session_name(&mut self, session_name: &str) {
        unsafe {
            ffi::gst_sdp_message_set_session_name(&mut self.0, session_name.to_glib_none().0)
        };
    }

    pub fn set_uri(&mut self, uri: &str) {
        unsafe { ffi::gst_sdp_message_set_uri(&mut self.0, uri.to_glib_none().0) };
    }

    pub fn set_version(&mut self, version: &str) {
        unsafe { ffi::gst_sdp_message_set_version(&mut self.0, version.to_glib_none().0) };
    }

    pub fn times_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_times_len(&self.0) }
    }

    pub fn zones_len(&self) -> u32 {
        unsafe { ffi::gst_sdp_message_zones_len(&self.0) }
    }

    pub fn as_uri(&self, scheme: &str) -> Result<String, glib::error::BoolError> {
        assert_initialized_main_thread!();
        unsafe {
            match from_glib_full(ffi::gst_sdp_message_as_uri(
                scheme.to_glib_none().0,
                &self.0,
            )) {
                Some(s) => Ok(s),
                None => Err(glib::bool_error!("Failed to create an URI from message")),
            }
        }
    }

    pub fn attributes(&self) -> AttributesIter {
        AttributesIter::new(self)
    }

    pub fn bandwidths(&self) -> BandwidthsIter {
        BandwidthsIter::new(self)
    }

    pub fn emails(&self) -> EmailsIter {
        EmailsIter::new(self)
    }

    pub fn medias(&self) -> MediasIter {
        MediasIter::new(self)
    }

    pub fn medias_mut(&mut self) -> MediasIterMut {
        MediasIterMut::new(self)
    }

    pub fn phones(&self) -> PhonesIter {
        PhonesIter::new(self)
    }

    pub fn times(&self) -> TimesIter {
        TimesIter::new(self)
    }

    pub fn zones(&self) -> ZonesIter {
        ZonesIter::new(self)
    }
}

impl Borrow<SDPMessageRef> for SDPMessage {
    fn borrow(&self) -> &SDPMessageRef {
        &*self
    }
}

impl BorrowMut<SDPMessageRef> for SDPMessage {
    fn borrow_mut(&mut self) -> &mut SDPMessageRef {
        &mut *self
    }
}

impl ToOwned for SDPMessageRef {
    type Owned = SDPMessage;

    fn to_owned(&self) -> SDPMessage {
        unsafe {
            let mut ptr = ptr::null_mut();
            ffi::gst_sdp_message_copy(&self.0, &mut ptr);
            from_glib_full(ptr)
        }
    }
}

impl glib::types::StaticType for SDPMessageRef {
    fn static_type() -> glib::types::Type {
        unsafe { from_glib(ffi::gst_sdp_message_get_type()) }
    }
}

unsafe impl<'a> glib::value::FromValue<'a> for &'a SDPMessageRef {
    type Checker = glib::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a glib::Value) -> Self {
        skip_assert_initialized!();
        &*(glib::gobject_ffi::g_value_get_boxed(value.to_glib_none().0) as *mut SDPMessageRef)
    }
}

impl glib::value::ToValue for SDPMessageRef {
    fn to_value(&self) -> glib::Value {
        let mut value = glib::Value::for_value_type::<SDPMessage>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                &self.0 as *const ffi::GstSDPMessage as *mut _,
            )
        }
        value
    }

    fn value_type(&self) -> glib::Type {
        Self::static_type()
    }
}

impl glib::value::ToValueOptional for SDPMessageRef {
    fn to_value_optional(s: Option<&Self>) -> glib::Value {
        skip_assert_initialized!();
        let mut value = glib::Value::for_value_type::<SDPMessage>();
        unsafe {
            glib::gobject_ffi::g_value_set_boxed(
                value.to_glib_none_mut().0,
                s.map(|s| &s.0 as *const ffi::GstSDPMessage)
                    .unwrap_or(ptr::null()) as *mut _,
            )
        }
        value
    }
}

macro_rules! define_iter(
    ($name:ident, $typ:ty, $get_item:expr, $get_len:expr) => {
    #[derive(Debug)]
    pub struct $name<'a> {
        message: &'a SDPMessageRef,
        idx: u32,
        len: u32,
    }

    impl<'a> $name<'a> {
        fn new(message: &'a SDPMessageRef) -> $name<'a> {
            skip_assert_initialized!();
            let len = $get_len(message);

            $name {
                message,
                idx: 0,
                len,
            }
        }
    }

    impl<'a> Iterator for $name<'a> {
        type Item = $typ;

        fn next(&mut self) -> Option<Self::Item> {
            if self.idx >= self.len {
                return None;
            }

            let item = $get_item(self.message, self.idx)?;
            self.idx += 1;
            Some(item)
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            if self.idx == self.len {
                return (0, Some(0))
            }

            let remaining = (self.len - self.idx) as usize;

            (remaining, Some(remaining))
        }
    }

    impl<'a> DoubleEndedIterator for $name<'a> {
        fn next_back(&mut self) -> Option<Self::Item> {
            if self.idx == self.len {
                return None;
            }

            self.len -= 1;

            $get_item(self.message, self.len)
        }
    }

    impl<'a> ExactSizeIterator for $name<'a> {}
    }
);

macro_rules! define_iter_mut(
    ($name:ident, $typ:ty, $get_item:expr, $get_len:expr) => {
    #[derive(Debug)]
    pub struct $name<'a> {
        message: &'a mut SDPMessageRef,
        idx: u32,
        len: u32,
    }

    impl<'a> $name<'a> {
        fn new(message: &'a mut SDPMessageRef) -> $name<'a> {
            skip_assert_initialized!();
            let len = $get_len(message);

            $name {
                message,
                idx: 0,
                len,
            }
        }
    }

    impl<'a> Iterator for $name<'a> {
        type Item = $typ;

        fn next(&mut self) -> Option<Self::Item> {
            // The lifetime of the passed self is not 'a but we need to return a message reference
            // with that lifetime here. The reason here is that the compiler does not and can't
            // know that it's statically impossible to mutate the message between different calls
            // to next(), so it has to assume that every call to next() will invalidate any
            // returned references.
            //
            // In theory we could have a function on the iterator that mutates the message and for
            // example removes the message that was returned here at an earlier time. The compiler
            // would be correct to complain in that case, but we don't provide such a function.
            let message = unsafe {
                &mut *(self.message as *mut SDPMessageRef)
            };
            if self.idx >= self.len {
                return None;
            }

            let item = $get_item(message, self.idx)?;
            self.idx += 1;
            Some(item)
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            if self.idx == self.len {
                return (0, Some(0))
            }

            let remaining = (self.len - self.idx) as usize;

            (remaining, Some(remaining))
        }
    }

    impl<'a> DoubleEndedIterator for $name<'a> {
        fn next_back(&mut self) -> Option<Self::Item> {
            let message = unsafe {
                &mut *(self.message as *mut SDPMessageRef)
            };
            if self.idx == self.len {
                return None;
            }

            self.len -= 1;

            $get_item(message, self.len)
        }
    }

    impl<'a> ExactSizeIterator for $name<'a> {}
    }
);

define_iter!(
    AttributesIter,
    &'a SDPAttribute,
    |message: &'a SDPMessageRef, idx| message.attribute(idx),
    |message: &SDPMessageRef| message.attributes_len()
);
define_iter!(
    BandwidthsIter,
    &'a SDPBandwidth,
    |message: &'a SDPMessageRef, idx| message.bandwidth(idx),
    |message: &SDPMessageRef| message.bandwidths_len()
);
define_iter!(
    EmailsIter,
    &'a str,
    |message: &'a SDPMessageRef, idx| message.email(idx),
    |message: &SDPMessageRef| message.emails_len()
);
define_iter!(
    MediasIter,
    &'a SDPMediaRef,
    |message: &'a SDPMessageRef, idx| message.media(idx),
    |message: &SDPMessageRef| message.medias_len()
);
define_iter_mut!(
    MediasIterMut,
    &'a mut SDPMediaRef,
    |message: &'a mut SDPMessageRef, idx| message.media_mut(idx),
    |message: &SDPMessageRef| message.medias_len()
);
define_iter!(
    PhonesIter,
    &'a str,
    |message: &'a SDPMessageRef, idx| message.phone(idx),
    |message: &SDPMessageRef| message.phones_len()
);
define_iter!(
    TimesIter,
    &'a SDPTime,
    |message: &'a SDPMessageRef, idx| message.time(idx),
    |message: &SDPMessageRef| message.times_len()
);
define_iter!(
    ZonesIter,
    &'a SDPZone,
    |message: &'a SDPMessageRef, idx| message.zone(idx),
    |message: &SDPMessageRef| message.zones_len()
);

#[cfg(test)]
mod tests {
    use crate::SDPMessage;

    fn init() {
        gst::init().unwrap();
    }

    #[test]
    fn media_from_message() {
        init();

        let sdp = "v=0\r\no=- 1938737043334325940 0 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=ice-options:trickle\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\nc=IN IP4 0.0.0.0\r\na=setup:actpass\r\na=ice-ufrag:YZxU9JlWHzHcF6O2U09/q3PvBhbTPdZW\r\na=ice-pwd:fyrt730GWo5mFGc9m2z/vbUu3z1lewla\r\na=sendrecv\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:96 VP8/90000\r\na=rtcp-fb:96 nack\r\na=rtcp-fb:96 nack pli\r\na=framerate:30\r\na=mid:video0\r\na=fingerprint:sha-256 DB:48:8F:18:13:F3:AA:13:31:B3:75:3D:1A:D3:BA:88:4A:ED:1B:56:14:C3:09:CD:BC:4D:18:42:B9:6A:5F:98\r\nm=audio 9 UDP/TLS/RTP/SAVPF 97\r\nc=IN IP4 0.0.0.0\r\na=setup:actpass\r\na=ice-ufrag:04KZM9qE2S4r06AN6A9CeXOM6mzO0LZY\r\na=ice-pwd:cJTSfHF6hHDAcsTJXZVJeuYCC6rKqBvW\r\na=sendrecv\r\na=rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:97 OPUS/48000/2\r\na=rtcp-fb:97 nack\r\na=rtcp-fb:97 nack pli\r\na=mid:audio1\r\na=fingerprint:sha-256 DB:48:8F:18:13:F3:AA:13:31:B3:75:3D:1A:D3:BA:88:4A:ED:1B:56:14:C3:09:CD:BC:4D:18:42:B9:6A:5F:98\r\n";
        let sdp = SDPMessage::parse_buffer(sdp.as_bytes()).unwrap();
        let media = sdp.media(0).unwrap();
        assert_eq!(media.formats_len(), 1);
    }

    #[test]
    fn debug_impl() {
        init();

        let sdp = SDPMessage::new();
        assert!(!format!("{:?}", sdp).is_empty());
    }
}