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
// Copyright (C) 2016-2017 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use caps_features::*;
use miniobject::*;
use std::fmt;
use std::marker::PhantomData;
use std::ptr;
use std::str;
use structure::*;

use CapsIntersectMode;

use glib;
use glib::translate::{from_glib, from_glib_full, FromGlibPtrFull, ToGlib, ToGlibPtr};
use glib::value::ToSendValue;
use gst_sys;

gst_define_mini_object_wrapper!(
    Caps,
    CapsRef,
    gst_sys::GstCaps,
    [Debug, PartialEq, Eq,],
    || gst_sys::gst_caps_get_type()
);

impl Caps {
    pub fn builder(name: &str) -> Builder {
        assert_initialized_main_thread!();
        Builder::new(name)
    }

    pub fn builder_full() -> BuilderFull<SomeFeatures> {
        assert_initialized_main_thread!();
        BuilderFull::new()
    }

    pub fn builder_full_with_features(features: CapsFeatures) -> BuilderFull<SomeFeatures> {
        assert_initialized_main_thread!();
        BuilderFull::new_with_features(features)
    }

    pub fn builder_full_with_any_features() -> BuilderFull<AnyFeatures> {
        assert_initialized_main_thread!();
        BuilderFull::new_with_any_features()
    }

    /// Creates a new `Caps` that is empty. That is, the returned
    /// `Caps` contains no media formats.
    /// The `Caps` is guaranteed to be writable.
    /// Caller is responsible for unreffing the returned caps.
    ///
    /// # Returns
    ///
    /// the new `Caps`
    pub fn new_empty() -> Self {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(gst_sys::gst_caps_new_empty()) }
    }

    /// Creates a new `Caps` that indicates that it is compatible with
    /// any media format.
    ///
    /// # Returns
    ///
    /// the new `Caps`
    pub fn new_any() -> Self {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(gst_sys::gst_caps_new_any()) }
    }

    /// Creates a new `Caps` that contains one `Structure`. The
    /// structure is defined by the arguments, which have the same format
    /// as `Structure::new`.
    /// Caller is responsible for unreffing the returned caps.
    /// ## `media_type`
    /// the media type of the structure
    /// ## `fieldname`
    /// first field to set
    ///
    /// # Returns
    ///
    /// the new `Caps`
    pub fn new_simple(name: &str, values: &[(&str, &dyn ToSendValue)]) -> Self {
        assert_initialized_main_thread!();
        let mut caps = Caps::new_empty();

        let structure = Structure::new(name, values);
        caps.get_mut().unwrap().append_structure(structure);

        caps
    }

    /// Modifies the given `self` into a representation with only fixed
    /// values. First the caps will be truncated and then the first structure will be
    /// fixated with `Structure::fixate`.
    ///
    /// This function takes ownership of `self` and will call `gst_caps_make_writable`
    /// on it so you must not use `self` afterwards unless you keep an additional
    /// reference to it with `gst_caps_ref`.
    ///
    /// # Returns
    ///
    /// the fixated caps
    pub fn fixate(caps: Self) -> Self {
        skip_assert_initialized!();
        unsafe {
            // See https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/388
            assert!(!caps.is_any());
            let ptr = if caps.is_empty() {
                gst_sys::gst_caps_new_empty()
            } else {
                gst_sys::gst_caps_fixate(caps.into_ptr())
            };
            from_glib_full(ptr)
        }
    }

    /// Appends the structures contained in `caps2` to `self` if they are not yet
    /// expressed by `self`. The structures in `caps2` are not copied -- they are
    /// transferred to a writable copy of `self`, and then `caps2` is freed.
    /// If either caps is ANY, the resulting caps will be ANY.
    /// ## `caps2`
    /// the `Caps` to merge in
    ///
    /// # Returns
    ///
    /// the merged caps.
    pub fn merge(caps: Self, other: Self) -> Self {
        skip_assert_initialized!();
        unsafe { from_glib_full(gst_sys::gst_caps_merge(caps.into_ptr(), other.into_ptr())) }
    }

    /// Appends `structure` to `self` if its not already expressed by `self`.
    /// ## `structure`
    /// the `Structure` to merge
    ///
    /// # Returns
    ///
    /// the merged caps.
    pub fn merge_structure(caps: Self, structure: Structure) -> Self {
        skip_assert_initialized!();
        unsafe {
            from_glib_full(gst_sys::gst_caps_merge_structure(
                caps.into_ptr(),
                structure.into_ptr(),
            ))
        }
    }

    /// Appends `structure` with `features` to `self` if its not already expressed by `self`.
    /// ## `structure`
    /// the `Structure` to merge
    /// ## `features`
    /// the `CapsFeatures` to merge
    ///
    /// # Returns
    ///
    /// the merged caps.
    pub fn merge_structure_full(
        caps: Self,
        structure: Structure,
        features: Option<CapsFeatures>,
    ) -> Self {
        skip_assert_initialized!();
        unsafe {
            from_glib_full(gst_sys::gst_caps_merge_structure_full(
                caps.into_ptr(),
                structure.into_ptr(),
                features.map(|f| f.into_ptr()).unwrap_or(ptr::null_mut()),
            ))
        }
    }

    /// Returns a `Caps` that represents the same set of formats as
    /// `self`, but contains no lists. Each list is expanded into separate
    /// `GstStructures`.
    ///
    /// This function takes ownership of `self` and will call `gst_caps_make_writable`
    /// on it so you must not use `self` afterwards unless you keep an additional
    /// reference to it with `gst_caps_ref`.
    ///
    /// # Returns
    ///
    /// the normalized `Caps`
    pub fn normalize(caps: Self) -> Self {
        skip_assert_initialized!();
        unsafe { from_glib_full(gst_sys::gst_caps_normalize(caps.into_ptr())) }
    }

    /// Converts the given `self` into a representation that represents the
    /// same set of formats, but in a simpler form. Component structures that are
    /// identical are merged. Component structures that have values that can be
    /// merged are also merged.
    ///
    /// This function takes ownership of `self` and will call `gst_caps_make_writable`
    /// on it if necessary, so you must not use `self` afterwards unless you keep an
    /// additional reference to it with `gst_caps_ref`.
    ///
    /// This method does not preserve the original order of `self`.
    ///
    /// # Returns
    ///
    /// The simplified caps.
    pub fn simplify(caps: Self) -> Self {
        skip_assert_initialized!();
        unsafe { from_glib_full(gst_sys::gst_caps_simplify(caps.into_ptr())) }
    }

    /// Discard all but the first structure from `self`. Useful when
    /// fixating.
    ///
    /// This function takes ownership of `self` and will call `gst_caps_make_writable`
    /// on it if necessary, so you must not use `self` afterwards unless you keep an
    /// additional reference to it with `gst_caps_ref`.
    ///
    /// # Returns
    ///
    /// truncated caps
    pub fn truncate(caps: Self) -> Self {
        skip_assert_initialized!();
        unsafe { from_glib_full(gst_sys::gst_caps_truncate(caps.into_ptr())) }
    }
}

impl str::FromStr for Caps {
    type Err = glib::BoolError;

    fn from_str(s: &str) -> Result<Self, glib::BoolError> {
        assert_initialized_main_thread!();
        unsafe {
            Option::<_>::from_glib_full(gst_sys::gst_caps_from_string(s.to_glib_none().0))
                .ok_or_else(|| glib_bool_error!("Failed to parse caps from string"))
        }
    }
}

impl fmt::Display for Caps {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl CapsRef {
    pub fn set_simple(&mut self, values: &[(&str, &dyn ToSendValue)]) {
        for &(name, value) in values {
            let value = value.to_value();

            unsafe {
                gst_sys::gst_caps_set_value(
                    self.as_mut_ptr(),
                    name.to_glib_none().0,
                    value.to_glib_none().0,
                );
            }
        }
    }

    pub fn get_structure(&self, idx: u32) -> Option<&StructureRef> {
        if idx >= self.get_size() {
            return None;
        }

        unsafe {
            let structure = gst_sys::gst_caps_get_structure(self.as_ptr(), idx);
            if structure.is_null() {
                return None;
            }

            Some(StructureRef::from_glib_borrow(structure))
        }
    }

    pub fn get_mut_structure(&mut self, idx: u32) -> Option<&mut StructureRef> {
        if idx >= self.get_size() {
            return None;
        }

        unsafe {
            let structure = gst_sys::gst_caps_get_structure(self.as_ptr(), idx);
            if structure.is_null() {
                return None;
            }

            Some(StructureRef::from_glib_borrow_mut(structure))
        }
    }

    pub fn get_features(&self, idx: u32) -> Option<&CapsFeaturesRef> {
        if idx >= self.get_size() {
            return None;
        }

        unsafe {
            let features = gst_sys::gst_caps_get_features(self.as_ptr(), idx);
            Some(CapsFeaturesRef::from_glib_borrow(features))
        }
    }

    pub fn get_mut_features(&mut self, idx: u32) -> Option<&mut CapsFeaturesRef> {
        if idx >= self.get_size() {
            return None;
        }

        unsafe {
            let features = gst_sys::gst_caps_get_features(self.as_ptr(), idx);
            Some(CapsFeaturesRef::from_glib_borrow_mut(features))
        }
    }

    pub fn set_features(&mut self, idx: u32, features: Option<CapsFeatures>) {
        assert!(idx < self.get_size());

        unsafe {
            gst_sys::gst_caps_set_features(
                self.as_mut_ptr(),
                idx,
                features.map(|f| f.into_ptr()).unwrap_or(ptr::null_mut()),
            )
        }
    }

    #[cfg(any(feature = "v1_16", feature = "dox"))]
    pub fn set_features_simple(&mut self, features: Option<CapsFeatures>) {
        unsafe {
            gst_sys::gst_caps_set_features_simple(
                self.as_mut_ptr(),
                features.map(|f| f.into_ptr()).unwrap_or(ptr::null_mut()),
            )
        }
    }

    pub fn get_size(&self) -> u32 {
        unsafe { gst_sys::gst_caps_get_size(self.as_ptr()) }
    }

    pub fn iter(&self) -> Iter {
        Iter::new(self)
    }

    pub fn iter_mut(&mut self) -> IterMut {
        IterMut::new(self)
    }

    pub fn iter_with_features(&self) -> IterFeatures {
        IterFeatures::new(self)
    }

    pub fn iter_with_features_mut(&mut self) -> IterFeaturesMut {
        IterFeaturesMut::new(self)
    }

    pub fn append_structure(&mut self, structure: Structure) {
        unsafe { gst_sys::gst_caps_append_structure(self.as_mut_ptr(), structure.into_ptr()) }
    }

    pub fn append_structure_full(&mut self, structure: Structure, features: Option<CapsFeatures>) {
        unsafe {
            gst_sys::gst_caps_append_structure_full(
                self.as_mut_ptr(),
                structure.into_ptr(),
                features.map(|f| f.into_ptr()).unwrap_or(ptr::null_mut()),
            )
        }
    }

    pub fn remove_structure(&mut self, idx: u32) {
        unsafe { gst_sys::gst_caps_remove_structure(self.as_mut_ptr(), idx) }
    }

    pub fn append(&mut self, other: Caps) {
        unsafe { gst_sys::gst_caps_append(self.as_mut_ptr(), other.into_ptr()) }
    }

    pub fn can_intersect(&self, other: &Self) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_can_intersect(
                self.as_ptr(),
                other.as_ptr(),
            ))
        }
    }

    pub fn intersect(&self, other: &Self) -> Caps {
        unsafe {
            from_glib_full(gst_sys::gst_caps_intersect(
                self.as_mut_ptr(),
                other.as_mut_ptr(),
            ))
        }
    }

    pub fn intersect_with_mode(&self, other: &Self, mode: CapsIntersectMode) -> Caps {
        unsafe {
            from_glib_full(gst_sys::gst_caps_intersect_full(
                self.as_mut_ptr(),
                other.as_mut_ptr(),
                mode.to_glib(),
            ))
        }
    }

    pub fn is_always_compatible(&self, other: &Self) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_always_compatible(
                self.as_ptr(),
                other.as_ptr(),
            ))
        }
    }

    pub fn is_any(&self) -> bool {
        unsafe { from_glib(gst_sys::gst_caps_is_any(self.as_ptr())) }
    }

    pub fn is_empty(&self) -> bool {
        unsafe { from_glib(gst_sys::gst_caps_is_empty(self.as_ptr())) }
    }

    pub fn is_fixed(&self) -> bool {
        unsafe { from_glib(gst_sys::gst_caps_is_fixed(self.as_ptr())) }
    }

    pub fn is_equal_fixed(&self, other: &Self) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_equal_fixed(
                self.as_ptr(),
                other.as_ptr(),
            ))
        }
    }

    pub fn is_strictly_equal(&self, other: &Self) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_strictly_equal(
                self.as_ptr(),
                other.as_ptr(),
            ))
        }
    }

    pub fn is_subset(&self, superset: &Self) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_subset(
                self.as_ptr(),
                superset.as_ptr(),
            ))
        }
    }

    pub fn is_subset_structure(&self, structure: &StructureRef) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_subset_structure(
                self.as_ptr(),
                structure.as_ptr(),
            ))
        }
    }

    pub fn is_subset_structure_full(
        &self,
        structure: &StructureRef,
        features: Option<&CapsFeaturesRef>,
    ) -> bool {
        unsafe {
            from_glib(gst_sys::gst_caps_is_subset_structure_full(
                self.as_ptr(),
                structure.as_ptr(),
                features.map(|f| f.as_ptr()).unwrap_or(ptr::null()),
            ))
        }
    }

    pub fn subtract(&self, other: &Self) -> Caps {
        skip_assert_initialized!();
        unsafe {
            from_glib_full(gst_sys::gst_caps_subtract(
                self.as_mut_ptr(),
                other.as_mut_ptr(),
            ))
        }
    }
}

macro_rules! define_iter(
    ($name:ident, $typ:ty, $styp:ty, $get_item:expr) => {
    #[derive(Debug)]
    pub struct $name<'a> {
        caps: $typ,
        idx: u32,
        n_structures: u32,
    }

    impl<'a> $name<'a> {
        fn new(caps: $typ) -> $name<'a> {
            skip_assert_initialized!();
            let n_structures = caps.get_size();

            $name {
                caps: caps,
                idx: 0,
                n_structures: n_structures,
            }
        }
    }

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

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

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

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

            let remaining = (self.n_structures - 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.n_structures {
                return None;
            }

            self.n_structures -= 1;

            unsafe {
                $get_item(self.caps, self.n_structures)
            }
        }
    }

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

define_iter!(
    Iter,
    &'a CapsRef,
    &'a StructureRef,
    |caps: &CapsRef, idx| {
        let ptr = gst_sys::gst_caps_get_structure(caps.as_ptr(), idx);
        if ptr.is_null() {
            None
        } else {
            Some(StructureRef::from_glib_borrow(
                ptr as *const gst_sys::GstStructure,
            ))
        }
    }
);
define_iter!(
    IterMut,
    &'a mut CapsRef,
    &'a mut StructureRef,
    |caps: &CapsRef, idx| {
        let ptr = gst_sys::gst_caps_get_structure(caps.as_ptr(), idx);
        if ptr.is_null() {
            None
        } else {
            Some(StructureRef::from_glib_borrow_mut(
                ptr as *mut gst_sys::GstStructure,
            ))
        }
    }
);
define_iter!(
    IterFeatures,
    &'a CapsRef,
    (&'a StructureRef, &'a CapsFeaturesRef),
    |caps: &CapsRef, idx| {
        let ptr1 = gst_sys::gst_caps_get_structure(caps.as_ptr(), idx);
        let ptr2 = gst_sys::gst_caps_get_features(caps.as_ptr(), idx);
        if ptr1.is_null() || ptr2.is_null() {
            None
        } else {
            Some((
                StructureRef::from_glib_borrow(ptr1 as *const gst_sys::GstStructure),
                CapsFeaturesRef::from_glib_borrow(ptr2 as *const gst_sys::GstCapsFeatures),
            ))
        }
    }
);
define_iter!(
    IterFeaturesMut,
    &'a mut CapsRef,
    (&'a mut StructureRef, &'a mut CapsFeaturesRef),
    |caps: &CapsRef, idx| {
        let ptr1 = gst_sys::gst_caps_get_structure(caps.as_ptr(), idx);
        let ptr2 = gst_sys::gst_caps_get_features(caps.as_ptr(), idx);
        if ptr1.is_null() || ptr2.is_null() {
            None
        } else {
            Some((
                StructureRef::from_glib_borrow_mut(ptr1 as *mut gst_sys::GstStructure),
                CapsFeaturesRef::from_glib_borrow_mut(ptr2 as *mut gst_sys::GstCapsFeatures),
            ))
        }
    }
);

impl fmt::Debug for CapsRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Caps").field(&self.to_string()).finish()
    }
}

impl fmt::Display for CapsRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s =
            unsafe { glib::GString::from_glib_full(gst_sys::gst_caps_to_string(self.as_ptr())) };
        f.write_str(&s)
    }
}

impl PartialEq for CapsRef {
    fn eq(&self, other: &CapsRef) -> bool {
        unsafe { from_glib(gst_sys::gst_caps_is_equal(self.as_ptr(), other.as_ptr())) }
    }
}

impl Eq for CapsRef {}

#[derive(Debug)]
pub struct Builder<'a> {
    s: ::Structure,
    features: Option<&'a [&'a str]>,
    any_features: bool,
}

impl<'a> Builder<'a> {
    fn new<'b>(name: &'b str) -> Builder<'a> {
        Builder {
            s: ::Structure::new_empty(name),
            features: None,
            any_features: false,
        }
    }

    pub fn field<'b, V: ToSendValue>(mut self, name: &'b str, value: &'b V) -> Self {
        self.s.set(name, value);
        self
    }

    pub fn features(mut self, features: &'a [&'a str]) -> Self {
        self.features = Some(features);
        self
    }

    pub fn any_features(mut self) -> Self {
        self.any_features = true;
        self
    }

    pub fn build(self) -> Caps {
        let mut caps = Caps::new_empty();
        let features = if self.any_features {
            Some(CapsFeatures::new_any())
        } else {
            self.features.map(|f| CapsFeatures::new(f))
        };

        caps.get_mut()
            .unwrap()
            .append_structure_full(self.s, features);
        caps
    }
}

pub enum AnyFeatures {}
pub enum SomeFeatures {}

pub struct BuilderFull<T> {
    caps: ::Caps,
    features: Option<CapsFeatures>,
    phantom: PhantomData<T>,
}

impl<T> fmt::Debug for BuilderFull<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Builder")
            .field("caps", &self.caps)
            .field("features", &self.features)
            .field("phantom", &self.phantom)
            .finish()
    }
}

impl BuilderFull<SomeFeatures> {
    fn new() -> Self {
        BuilderFull {
            caps: Caps::new_empty(),
            features: None,
            phantom: PhantomData,
        }
    }

    fn new_with_features(features: CapsFeatures) -> Self {
        BuilderFull {
            caps: Caps::new_empty(),
            features: Some(features),
            phantom: PhantomData,
        }
    }

    pub fn structure_with_features(self, structure: Structure, features: CapsFeatures) -> Self {
        self.append_structure(structure, Some(features))
    }

    pub fn structure_with_any_features(self, structure: Structure) -> Self {
        self.append_structure(structure, Some(CapsFeatures::new_any()))
    }
}

impl BuilderFull<AnyFeatures> {
    fn new_with_any_features() -> Self {
        BuilderFull {
            caps: Caps::new_empty(),
            features: Some(CapsFeatures::new_any()),
            phantom: PhantomData,
        }
    }
}

impl<T> BuilderFull<T> {
    fn append_structure(mut self, structure: Structure, features: Option<CapsFeatures>) -> Self {
        let features = {
            match self.features {
                None => features,
                Some(ref result) => {
                    let mut result = result.clone();
                    match features {
                        None => Some(result),
                        Some(features) => {
                            features.iter().for_each(|feat| result.add(feat));
                            Some(result)
                        }
                    }
                }
            }
        };

        self.caps
            .get_mut()
            .unwrap()
            .append_structure_full(structure, features);
        self
    }

    pub fn structure(self, structure: Structure) -> Self {
        self.append_structure(structure, None)
    }

    pub fn build(self) -> Caps {
        self.caps
    }
}

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

    #[test]
    fn test_simple() {
        ::init().unwrap();

        let mut caps = Caps::new_simple(
            "foo/bar",
            &[
                ("int", &12),
                ("bool", &true),
                ("string", &"bla"),
                ("fraction", &Fraction::new(1, 2)),
                ("array", &Array::new(&[&1, &2])),
            ],
        );
        assert_eq!(
            caps.to_string(),
            "foo/bar, int=(int)12, bool=(boolean)true, string=(string)bla, fraction=(fraction)1/2, array=(int)< 1, 2 >"
        );

        {
            let s = caps.get_structure(0).unwrap();
            assert_eq!(
                s,
                Structure::new(
                    "foo/bar",
                    &[
                        ("int", &12),
                        ("bool", &true),
                        ("string", &"bla"),
                        ("fraction", &Fraction::new(1, 2)),
                        ("array", &Array::new(&[&1, &2])),
                    ],
                )
                .as_ref()
            );
        }
        assert!(caps
            .get_features(0)
            .unwrap()
            .is_equal(::CAPS_FEATURES_MEMORY_SYSTEM_MEMORY.as_ref()));

        {
            let caps = caps.get_mut().unwrap();
            caps.set_features(0, Some(CapsFeatures::new(&["foo:bla"])));
        }
        assert!(caps
            .get_features(0)
            .unwrap()
            .is_equal(CapsFeatures::new(&["foo:bla"]).as_ref()));
    }

    #[test]
    fn test_builder() {
        ::init().unwrap();

        let caps = Caps::builder("foo/bar")
            .field("int", &12)
            .field("bool", &true)
            .field("string", &"bla")
            .field("fraction", &Fraction::new(1, 2))
            .field("array", &Array::new(&[&1, &2]))
            .build();
        assert_eq!(
            caps.to_string(),
            "foo/bar, int=(int)12, bool=(boolean)true, string=(string)bla, fraction=(fraction)1/2, array=(int)< 1, 2 >"
        );

        let caps = Caps::builder("foo/bar")
            .field("int", &12)
            .any_features()
            .build();
        assert_eq!(caps.to_string(), "foo/bar(ANY), int=(int)12");

        let caps = Caps::builder("foo/bar")
            .field("int", &12)
            .features(&["foo:bla", "foo:baz"])
            .build();
        assert_eq!(caps.to_string(), "foo/bar(foo:bla, foo:baz), int=(int)12");
    }

    #[test]
    fn test_display() {
        ::init().unwrap();

        let caps = Caps::new_simple("foo/bar", &[]);
        format!("{}", caps);
    }

    #[test]
    fn test_builder_full() {
        ::init().unwrap();

        let caps = Caps::builder_full()
            .structure(Structure::builder("audio/x-raw").build())
            .structure(Structure::builder("video/x-raw").build())
            .build();
        assert_eq!(caps.to_string(), "audio/x-raw; video/x-raw");

        let caps = Caps::builder_full()
            .structure(
                Structure::builder("audio/x-raw")
                    .field("format", &"S16LE")
                    .build(),
            )
            .structure(Structure::builder("video/x-raw").build())
            .build();
        assert_eq!(
            caps.to_string(),
            "audio/x-raw, format=(string)S16LE; video/x-raw"
        );

        let caps = Caps::builder_full()
            .structure_with_any_features(Structure::builder("audio/x-raw").build())
            .structure_with_features(
                Structure::builder("video/x-raw").build(),
                CapsFeatures::new(&["foo:bla", "foo:baz"]),
            )
            .build();
        assert_eq!(
            caps.to_string(),
            "audio/x-raw(ANY); video/x-raw(foo:bla, foo:baz)"
        );
    }

    #[test]
    fn test_builder_full_with_features() {
        ::init().unwrap();

        let caps = Caps::builder_full_with_features(CapsFeatures::new(&["foo:bla"]))
            .structure(Structure::builder("audio/x-raw").build())
            .structure_with_features(
                Structure::builder("video/x-raw").build(),
                CapsFeatures::new(&["foo:baz"]),
            )
            .build();
        assert_eq!(
            caps.to_string(),
            "audio/x-raw(foo:bla); video/x-raw(foo:bla, foo:baz)"
        );
    }

    #[test]
    fn test_builder_full_with_any_features() {
        ::init().unwrap();

        let caps = Caps::builder_full_with_any_features()
            .structure(Structure::builder("audio/x-raw").build())
            .structure(Structure::builder("video/x-raw").build())
            .build();
        assert_eq!(caps.to_string(), "audio/x-raw(ANY); video/x-raw(ANY)");

        let caps = Caps::builder_full_with_any_features()
            .structure(Structure::builder("audio/x-raw").build())
            .build();
        assert_eq!(caps.to_string(), "audio/x-raw(ANY)");
    }
}