Skip to main content

gstreamer/
caps.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{fmt, marker::PhantomData, ptr, str};
4
5use cfg_if::cfg_if;
6use glib::{
7    GStr,
8    prelude::*,
9    translate::*,
10    value::{SendValue, ToSendValue},
11};
12
13use crate::{CapsIntersectMode, IdStr, caps_features::*, ffi, structure::*};
14
15mini_object_wrapper!(Caps, CapsRef, ffi::GstCaps, || { ffi::gst_caps_get_type() });
16
17impl Caps {
18    #[doc(alias = "gst_caps_new_simple")]
19    pub fn builder(name: impl IntoGStr) -> Builder<NoFeature> {
20        assert_initialized_main_thread!();
21        Builder::new(name)
22    }
23
24    #[doc(alias = "gst_caps_new_static_str_simple")]
25    pub fn builder_from_static(name: impl AsRef<GStr> + 'static) -> Builder<NoFeature> {
26        assert_initialized_main_thread!();
27        Builder::from_static(name)
28    }
29
30    #[doc(alias = "gst_caps_new_id_str_simple")]
31    pub fn builder_from_id(name: impl AsRef<IdStr>) -> Builder<NoFeature> {
32        assert_initialized_main_thread!();
33        Builder::from_id(name)
34    }
35
36    #[doc(alias = "gst_caps_new_full")]
37    pub fn builder_full() -> BuilderFull<SomeFeatures> {
38        assert_initialized_main_thread!();
39        BuilderFull::new()
40    }
41
42    #[doc(alias = "gst_caps_new_full")]
43    pub fn builder_full_with_features(features: CapsFeatures) -> BuilderFull<SomeFeatures> {
44        assert_initialized_main_thread!();
45        BuilderFull::with_features(features)
46    }
47
48    #[doc(alias = "gst_caps_new_full")]
49    pub fn builder_full_with_any_features() -> BuilderFull<AnyFeatures> {
50        assert_initialized_main_thread!();
51        BuilderFull::with_any_features()
52    }
53
54    /// Creates a new [`Caps`][crate::Caps] that is empty. That is, the returned
55    /// [`Caps`][crate::Caps] contains no media formats.
56    /// The [`Caps`][crate::Caps] is guaranteed to be writable.
57    ///
58    /// # Returns
59    ///
60    /// the new [`Caps`][crate::Caps]
61    #[doc(alias = "gst_caps_new_empty")]
62    pub fn new_empty() -> Self {
63        assert_initialized_main_thread!();
64        unsafe { from_glib_full(ffi::gst_caps_new_empty()) }
65    }
66
67    /// Creates a new [`Caps`][crate::Caps] that indicates that it is compatible with
68    /// any media format.
69    ///
70    /// # Returns
71    ///
72    /// the new [`Caps`][crate::Caps]
73    #[doc(alias = "gst_caps_new_any")]
74    pub fn new_any() -> Self {
75        assert_initialized_main_thread!();
76        unsafe { from_glib_full(ffi::gst_caps_new_any()) }
77    }
78
79    /// Creates a new [`Caps`][crate::Caps] that contains one [`Structure`][crate::Structure] with name
80    /// `media_type`.
81    /// ## `media_type`
82    /// the media type of the structure
83    ///
84    /// # Returns
85    ///
86    /// the new [`Caps`][crate::Caps]
87    #[doc(alias = "gst_caps_new_empty_simple")]
88    pub fn new_empty_simple(name: impl IntoGStr) -> Self {
89        assert_initialized_main_thread!();
90        unsafe {
91            let ptr = name.run_with_gstr(|name| ffi::gst_caps_new_empty_simple(name.as_ptr()));
92            from_glib_full(ptr)
93        }
94    }
95
96    #[doc(alias = "gst_caps_new_static_str_empty_simple")]
97    pub fn new_empty_simple_from_static(name: impl AsRef<GStr> + 'static) -> Self {
98        skip_assert_initialized!();
99        let mut caps = Caps::new_empty();
100
101        let structure = Structure::new_empty_from_static(name);
102        caps.get_mut().unwrap().append_structure(structure);
103
104        caps
105    }
106
107    #[doc(alias = "gst_caps_new_id_str_empty_simple")]
108    pub fn new_empty_simple_from_id(name: impl AsRef<IdStr>) -> Self {
109        skip_assert_initialized!();
110        let mut caps = Caps::new_empty();
111
112        let structure = Structure::new_empty_from_id(name);
113        caps.get_mut().unwrap().append_structure(structure);
114
115        caps
116    }
117
118    /// Modifies the given `self` into a representation with only fixed
119    /// values. First the caps will be truncated and then the first structure will be
120    /// fixated with `gst_structure_fixate()`.
121    ///
122    /// This function takes ownership of `self` and will call [`make_writable()`][Self::make_writable()]
123    /// on it so you must not use `self` afterwards unless you keep an additional
124    /// reference to it with `gst_caps_ref()`.
125    ///
126    /// Note that it is not guaranteed that the returned caps have exactly one
127    /// structure. If `self` are empty caps then the returned caps will be
128    /// the empty too and contain no structure at all.
129    ///
130    /// Calling this function with ANY caps is not allowed.
131    ///
132    /// # Returns
133    ///
134    /// the fixated caps
135    #[doc(alias = "gst_caps_fixate")]
136    pub fn fixate(&mut self) {
137        unsafe {
138            // See https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/388
139            assert!(!self.is_any());
140            let ptr = if self.is_empty() {
141                ffi::gst_caps_new_empty()
142            } else {
143                ffi::gst_caps_fixate(self.as_mut_ptr())
144            };
145            self.replace_ptr(ptr);
146        }
147    }
148
149    /// Appends the structures contained in `caps2` to `self` if they are not yet
150    /// expressed by `self`. The structures in `caps2` are not copied -- they are
151    /// transferred to a writable copy of `self`, and then `caps2` is freed.
152    /// If either caps is ANY, the resulting caps will be ANY.
153    /// ## `caps2`
154    /// the [`Caps`][crate::Caps] to merge in
155    ///
156    /// # Returns
157    ///
158    /// the merged caps.
159    #[doc(alias = "gst_caps_merge")]
160    pub fn merge(&mut self, other: Self) {
161        unsafe {
162            let ptr = ffi::gst_caps_merge(self.as_mut_ptr(), other.into_glib_ptr());
163            self.replace_ptr(ptr);
164        }
165    }
166
167    /// Appends `structure` to `self` if it is not already expressed by `self`.
168    /// ## `structure`
169    /// the [`Structure`][crate::Structure] to merge
170    ///
171    /// # Returns
172    ///
173    /// the merged caps.
174    #[doc(alias = "gst_caps_merge_structure")]
175    pub fn merge_structure(&mut self, structure: Structure) {
176        unsafe {
177            let ptr = ffi::gst_caps_merge_structure(self.as_mut_ptr(), structure.into_glib_ptr());
178            self.replace_ptr(ptr);
179        }
180    }
181
182    /// Appends `structure` with `features` to `self` if its not already expressed by `self`.
183    /// ## `structure`
184    /// the [`Structure`][crate::Structure] to merge
185    /// ## `features`
186    /// the [`CapsFeatures`][crate::CapsFeatures] to merge
187    ///
188    /// # Returns
189    ///
190    /// the merged caps.
191    #[doc(alias = "gst_caps_merge_structure_full")]
192    pub fn merge_structure_full(&mut self, structure: Structure, features: Option<CapsFeatures>) {
193        unsafe {
194            let ptr = ffi::gst_caps_merge_structure_full(
195                self.as_mut_ptr(),
196                structure.into_glib_ptr(),
197                features
198                    .map(|f| f.into_glib_ptr())
199                    .unwrap_or(ptr::null_mut()),
200            );
201            self.replace_ptr(ptr);
202        }
203    }
204
205    /// Returns a [`Caps`][crate::Caps] that represents the same set of formats as
206    /// `self`, but contains no lists. Each list is expanded into separate
207    /// [`Structure`][crate::Structure].
208    ///
209    /// This function takes ownership of `self` and will call [`make_writable()`][Self::make_writable()]
210    /// on it so you must not use `self` afterwards unless you keep an additional
211    /// reference to it with `gst_caps_ref()`.
212    ///
213    /// # Returns
214    ///
215    /// the normalized [`Caps`][crate::Caps]
216    #[doc(alias = "gst_caps_normalize")]
217    pub fn normalize(&mut self) {
218        unsafe {
219            let ptr = ffi::gst_caps_normalize(self.as_mut_ptr());
220            self.replace_ptr(ptr);
221        }
222    }
223
224    /// Converts the given `self` into a representation that represents the
225    /// same set of formats, but in a simpler form. Component structures that are
226    /// identical are merged. Component structures that have values that can be
227    /// merged are also merged.
228    ///
229    /// This function takes ownership of `self` and will call [`make_writable()`][Self::make_writable()]
230    /// on it if necessary, so you must not use `self` afterwards unless you keep an
231    /// additional reference to it with `gst_caps_ref()`.
232    ///
233    /// This method does not preserve the original order of `self`.
234    ///
235    /// # Returns
236    ///
237    /// The simplified caps.
238    #[doc(alias = "gst_caps_simplify")]
239    pub fn simplify(&mut self) {
240        unsafe {
241            let ptr = ffi::gst_caps_simplify(self.as_mut_ptr());
242            self.replace_ptr(ptr);
243        }
244    }
245
246    /// Discards all but the first structure from `self`. Useful when
247    /// fixating.
248    ///
249    /// This function takes ownership of `self` and will call [`make_writable()`][Self::make_writable()]
250    /// on it if necessary, so you must not use `self` afterwards unless you keep an
251    /// additional reference to it with `gst_caps_ref()`.
252    ///
253    /// Note that it is not guaranteed that the returned caps have exactly one
254    /// structure. If `self` is any or empty caps then the returned caps will be
255    /// the same and contain no structure at all.
256    ///
257    /// # Returns
258    ///
259    /// truncated caps
260    #[doc(alias = "gst_caps_truncate")]
261    pub fn truncate(&mut self) {
262        unsafe {
263            let ptr = ffi::gst_caps_truncate(self.as_mut_ptr());
264            self.replace_ptr(ptr);
265        }
266    }
267}
268
269impl str::FromStr for Caps {
270    type Err = glib::BoolError;
271
272    #[doc(alias = "gst_caps_from_string")]
273    fn from_str(s: &str) -> Result<Self, Self::Err> {
274        assert_initialized_main_thread!();
275        unsafe {
276            s.run_with_gstr(|s| {
277                Option::<_>::from_glib_full(ffi::gst_caps_from_string(s.as_ptr()))
278                    .ok_or_else(|| glib::bool_error!("Failed to parse caps from string"))
279            })
280        }
281    }
282}
283
284impl From<Structure> for Caps {
285    fn from(v: Structure) -> Caps {
286        skip_assert_initialized!();
287        let mut caps = Caps::new_empty();
288
289        {
290            let caps = caps.get_mut().unwrap();
291            caps.append_structure(v);
292        }
293
294        caps
295    }
296}
297
298impl<const N: usize> From<[Structure; N]> for Caps {
299    fn from(v: [Structure; N]) -> Caps {
300        skip_assert_initialized!();
301        let mut caps = Caps::new_empty();
302
303        {
304            let caps = caps.get_mut().unwrap();
305            v.into_iter().for_each(|s| caps.append_structure(s));
306        }
307
308        caps
309    }
310}
311
312impl From<(Structure, CapsFeatures)> for Caps {
313    fn from(v: (Structure, CapsFeatures)) -> Caps {
314        skip_assert_initialized!();
315        let mut caps = Caps::new_empty();
316
317        {
318            let caps = caps.get_mut().unwrap();
319            caps.append_structure_full(v.0, Some(v.1));
320        }
321
322        caps
323    }
324}
325
326impl<const N: usize> From<[(Structure, CapsFeatures); N]> for Caps {
327    fn from(v: [(Structure, CapsFeatures); N]) -> Caps {
328        skip_assert_initialized!();
329        let mut caps = Caps::new_empty();
330
331        {
332            let caps = caps.get_mut().unwrap();
333            v.into_iter()
334                .for_each(|s| caps.append_structure_full(s.0, Some(s.1)));
335        }
336
337        caps
338    }
339}
340
341impl<const N: usize> From<[(Structure, Option<CapsFeatures>); N]> for Caps {
342    fn from(v: [(Structure, Option<CapsFeatures>); N]) -> Caps {
343        skip_assert_initialized!();
344        let mut caps = Caps::new_empty();
345
346        {
347            let caps = caps.get_mut().unwrap();
348            v.into_iter()
349                .for_each(|s| caps.append_structure_full(s.0, s.1));
350        }
351
352        caps
353    }
354}
355
356impl std::iter::FromIterator<Structure> for Caps {
357    fn from_iter<T: IntoIterator<Item = Structure>>(iter: T) -> Self {
358        skip_assert_initialized!();
359        let mut caps = Caps::new_empty();
360
361        {
362            let caps = caps.get_mut().unwrap();
363            iter.into_iter().for_each(|s| caps.append_structure(s));
364        }
365
366        caps
367    }
368}
369
370impl std::iter::FromIterator<(Structure, CapsFeatures)> for Caps {
371    fn from_iter<T: IntoIterator<Item = (Structure, CapsFeatures)>>(iter: T) -> Self {
372        skip_assert_initialized!();
373        let mut caps = Caps::new_empty();
374
375        {
376            let caps = caps.get_mut().unwrap();
377            iter.into_iter()
378                .for_each(|(s, f)| caps.append_structure_full(s, Some(f)));
379        }
380
381        caps
382    }
383}
384
385impl std::iter::FromIterator<(Structure, Option<CapsFeatures>)> for Caps {
386    fn from_iter<T: IntoIterator<Item = (Structure, Option<CapsFeatures>)>>(iter: T) -> Self {
387        skip_assert_initialized!();
388        let mut caps = Caps::new_empty();
389
390        {
391            let caps = caps.get_mut().unwrap();
392            iter.into_iter()
393                .for_each(|(s, f)| caps.append_structure_full(s, f));
394        }
395
396        caps
397    }
398}
399
400impl std::iter::FromIterator<Caps> for Caps {
401    fn from_iter<T: IntoIterator<Item = Caps>>(iter: T) -> Self {
402        skip_assert_initialized!();
403        let mut caps = Caps::new_empty();
404
405        {
406            let caps = caps.get_mut().unwrap();
407            iter.into_iter()
408                .for_each(|other_caps| caps.append(other_caps));
409        }
410
411        caps
412    }
413}
414
415impl std::iter::Extend<Structure> for CapsRef {
416    fn extend<T: IntoIterator<Item = Structure>>(&mut self, iter: T) {
417        iter.into_iter().for_each(|s| self.append_structure(s));
418    }
419}
420
421impl std::iter::Extend<(Structure, CapsFeatures)> for CapsRef {
422    fn extend<T: IntoIterator<Item = (Structure, CapsFeatures)>>(&mut self, iter: T) {
423        iter.into_iter()
424            .for_each(|(s, f)| self.append_structure_full(s, Some(f)));
425    }
426}
427
428impl std::iter::Extend<(Structure, Option<CapsFeatures>)> for CapsRef {
429    fn extend<T: IntoIterator<Item = (Structure, Option<CapsFeatures>)>>(&mut self, iter: T) {
430        iter.into_iter()
431            .for_each(|(s, f)| self.append_structure_full(s, f));
432    }
433}
434
435impl std::iter::Extend<Caps> for CapsRef {
436    fn extend<T: IntoIterator<Item = Caps>>(&mut self, iter: T) {
437        iter.into_iter().for_each(|caps| self.append(caps));
438    }
439}
440
441impl CapsRef {
442    // rustdoc-stripper-ignore-next
443    /// Sets field `name` to the given value `value`.
444    ///
445    /// Overrides any default or previously defined value for `name`.
446    #[doc(alias = "gst_caps_set_value")]
447    #[doc(alias = "gst_caps_set_simple")]
448    pub fn set(&mut self, name: impl IntoGStr, value: impl ToSendValue + Sync) {
449        let value = value.to_send_value();
450        self.set_value(name, value);
451    }
452
453    // rustdoc-stripper-ignore-next
454    /// Sets field `name` to the given value `value`.
455    ///
456    /// Overrides any default or previously defined value for `name`.
457    #[doc(alias = "gst_caps_set_value_static_str")]
458    #[doc(alias = "gst_caps_set_simple_static_str")]
459    pub fn set_with_static(
460        &mut self,
461        name: impl AsRef<GStr> + 'static,
462        value: impl ToSendValue + Sync,
463    ) {
464        let value = value.to_send_value();
465        self.set_value_with_static(name, value);
466    }
467
468    // rustdoc-stripper-ignore-next
469    /// Sets field `name` to the given value `value`.
470    ///
471    /// Overrides any default or previously defined value for `name`.
472    #[doc(alias = "gst_caps_id_str_set_value")]
473    #[doc(alias = "gst_caps_id_str_set_simple")]
474    pub fn set_with_id(&mut self, name: impl AsRef<IdStr>, value: impl ToSendValue + Sync) {
475        let value = value.to_send_value();
476        self.set_value_with_id(name, value);
477    }
478
479    // rustdoc-stripper-ignore-next
480    /// Sets field `name` to the given value if the `predicate` evaluates to `true`.
481    ///
482    /// This has no effect if the `predicate` evaluates to `false`,
483    /// i.e. default or previous value for `name` is kept.
484    #[doc(alias = "gst_caps_set_value")]
485    #[doc(alias = "gst_caps_set_simple")]
486    pub fn set_if(&mut self, name: impl IntoGStr, value: impl ToSendValue + Sync, predicate: bool) {
487        if predicate {
488            self.set(name, value);
489        }
490    }
491
492    // rustdoc-stripper-ignore-next
493    /// Sets field `name` to the given value if the `predicate` evaluates to `true`.
494    ///
495    /// This has no effect if the `predicate` evaluates to `false`,
496    /// i.e. default or previous value for `name` is kept.
497    #[doc(alias = "gst_caps_set_value_static_str")]
498    #[doc(alias = "gst_caps_set_simple_static_str")]
499    pub fn set_with_static_if(
500        &mut self,
501        name: impl AsRef<GStr> + 'static,
502        value: impl ToSendValue + Sync,
503        predicate: bool,
504    ) {
505        if predicate {
506            self.set_with_static(name, value);
507        }
508    }
509
510    // rustdoc-stripper-ignore-next
511    /// Sets field `name` to the given value if the `predicate` evaluates to `true`.
512    ///
513    /// This has no effect if the `predicate` evaluates to `false`,
514    /// i.e. default or previous value for `name` is kept.
515    #[doc(alias = "gst_caps_id_str_set_value")]
516    #[doc(alias = "gst_caps_id_str_set_simple")]
517    pub fn set_with_id_if(
518        &mut self,
519        name: impl AsRef<IdStr>,
520        value: impl ToSendValue + Sync,
521        predicate: bool,
522    ) {
523        if predicate {
524            self.set_with_id(name, value);
525        }
526    }
527
528    // rustdoc-stripper-ignore-next
529    /// Sets field `name` to the given inner value if `value` is `Some`.
530    ///
531    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
532    #[doc(alias = "gst_caps_set_value")]
533    #[doc(alias = "gst_caps_set_simple")]
534    pub fn set_if_some(&mut self, name: impl IntoGStr, value: Option<impl ToSendValue + Sync>) {
535        if let Some(value) = value {
536            self.set(name, value);
537        }
538    }
539
540    // rustdoc-stripper-ignore-next
541    /// Sets field `name` to the given inner value if `value` is `Some`.
542    ///
543    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
544    #[doc(alias = "gst_caps_set_value_static_str")]
545    #[doc(alias = "gst_caps_set_simple_static_str")]
546    pub fn set_with_static_if_some(
547        &mut self,
548        name: impl AsRef<GStr> + 'static,
549        value: Option<impl ToSendValue + Sync>,
550    ) {
551        if let Some(value) = value {
552            self.set_with_static(name, value);
553        }
554    }
555
556    // rustdoc-stripper-ignore-next
557    /// Sets field `name` to the given inner value if `value` is `Some`.
558    ///
559    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
560    #[doc(alias = "gst_caps_id_str_set_value")]
561    #[doc(alias = "gst_caps_id_str_set_simple")]
562    pub fn set_with_id_if_some(
563        &mut self,
564        name: impl AsRef<IdStr>,
565        value: Option<impl ToSendValue + Sync>,
566    ) {
567        if let Some(value) = value {
568            self.set_with_id(name, value);
569        }
570    }
571
572    // rustdoc-stripper-ignore-next
573    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s the `Item`s.
574    ///
575    /// Overrides any default or previously defined value for `name`.
576    #[inline]
577    pub fn set_from_iter<
578        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
579        I: ToSendValue,
580    >(
581        &mut self,
582        name: impl IntoGStr,
583        iter: impl IntoIterator<Item = I>,
584    ) {
585        let iter = iter.into_iter().map(|item| item.to_send_value());
586        self.set(name, V::from_iter(iter));
587    }
588
589    // rustdoc-stripper-ignore-next
590    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s the `Item`s.
591    ///
592    /// Overrides any default or previously defined value for `name`.
593    #[inline]
594    pub fn set_with_static_from_iter<
595        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
596        I: ToSendValue,
597    >(
598        &mut self,
599        name: impl AsRef<GStr> + 'static,
600        iter: impl IntoIterator<Item = I>,
601    ) {
602        let iter = iter.into_iter().map(|item| item.to_send_value());
603        self.set_with_static(name, V::from_iter(iter));
604    }
605
606    // rustdoc-stripper-ignore-next
607    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s the `Item`s.
608    ///
609    /// Overrides any default or previously defined value for `name`.
610    #[inline]
611    pub fn set_with_id_from_iter<
612        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
613        I: ToSendValue,
614    >(
615        &mut self,
616        name: impl AsRef<IdStr>,
617        iter: impl IntoIterator<Item = I>,
618    ) {
619        let iter = iter.into_iter().map(|item| item.to_send_value());
620        self.set_with_id(name, V::from_iter(iter));
621    }
622
623    // rustdoc-stripper-ignore-next
624    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s Item`s,
625    /// if `iter` is not empty.
626    ///
627    /// This has no effect if `iter` is empty, i.e. previous value for `name` is unchanged.
628    #[inline]
629    pub fn set_if_not_empty<
630        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
631        I: ToSendValue,
632    >(
633        &mut self,
634        name: impl IntoGStr,
635        iter: impl IntoIterator<Item = I>,
636    ) {
637        let mut iter = iter.into_iter().peekable();
638        if iter.peek().is_some() {
639            let iter = iter.map(|item| item.to_send_value());
640            self.set(name, V::from_iter(iter));
641        }
642    }
643
644    // rustdoc-stripper-ignore-next
645    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s Item`s,
646    /// if `iter` is not empty.
647    ///
648    /// This has no effect if `iter` is empty, i.e. previous value for `name` is unchanged.
649    #[inline]
650    pub fn set_with_static_if_not_empty<
651        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
652        I: ToSendValue,
653    >(
654        &mut self,
655        name: impl AsRef<GStr> + 'static,
656        iter: impl IntoIterator<Item = I>,
657    ) {
658        let mut iter = iter.into_iter().peekable();
659        if iter.peek().is_some() {
660            let iter = iter.map(|item| item.to_send_value());
661            self.set_with_static(name, V::from_iter(iter));
662        }
663    }
664
665    // rustdoc-stripper-ignore-next
666    /// Sets field `name` using the given `ValueType` `V` built from `iter`'s Item`s,
667    /// if `iter` is not empty.
668    ///
669    /// This has no effect if `iter` is empty, i.e. previous value for `name` is unchanged.
670    #[inline]
671    pub fn set_with_id_if_not_empty<
672        V: ValueType + ToSendValue + FromIterator<SendValue> + Sync,
673        I: ToSendValue,
674    >(
675        &mut self,
676        name: impl AsRef<IdStr>,
677        iter: impl IntoIterator<Item = I>,
678    ) {
679        let mut iter = iter.into_iter().peekable();
680        if iter.peek().is_some() {
681            let iter = iter.map(|item| item.to_send_value());
682            self.set_with_id(name, V::from_iter(iter));
683        }
684    }
685
686    // rustdoc-stripper-ignore-next
687    /// Sets field `name` to the given value `value`.
688    ///
689    /// Overrides any default or previously defined value for `name`.
690    #[doc(alias = "gst_caps_set_value")]
691    pub fn set_value(&mut self, name: impl IntoGStr, value: glib::SendValue) {
692        unsafe {
693            name.run_with_gstr(|name| {
694                ffi::gst_caps_set_value(self.as_mut_ptr(), name.as_ptr(), value.to_glib_none().0)
695            });
696        }
697    }
698
699    // rustdoc-stripper-ignore-next
700    /// Sets field `name` to the given value `value`.
701    ///
702    /// Overrides any default or previously defined value for `name`.
703    #[doc(alias = "gst_caps_set_value_static_str")]
704    pub fn set_value_with_static(
705        &mut self,
706        name: impl AsRef<GStr> + 'static,
707        value: glib::SendValue,
708    ) {
709        unsafe {
710            cfg_if! {
711                if #[cfg(feature = "v1_26")] {
712                    ffi::gst_caps_set_value_static_str(
713                        self.as_mut_ptr(),
714                        name.as_ref().as_ptr(),
715                        value.to_glib_none().0,
716                    )
717                } else {
718                    ffi::gst_caps_set_value(self.as_mut_ptr(), name.as_ref().as_ptr(), value.to_glib_none().0)
719                }
720            }
721        }
722    }
723
724    // rustdoc-stripper-ignore-next
725    /// Sets field `name` to the given value `value`.
726    ///
727    /// Overrides any default or previously defined value for `name`.
728    #[doc(alias = "gst_caps_id_str_set_value")]
729    pub fn set_value_with_id(&mut self, name: impl AsRef<IdStr>, value: glib::SendValue) {
730        unsafe {
731            cfg_if! {
732                if #[cfg(feature = "v1_26")] {
733                    ffi::gst_caps_id_str_set_value(
734                        self.as_mut_ptr(),
735                        name.as_ref().as_ptr(),
736                        value.to_glib_none().0,
737                    )
738                } else {
739                    ffi::gst_caps_set_value(self.as_mut_ptr(), name.as_ref().as_gstr().as_ptr(), value.to_glib_none().0)
740                }
741            }
742        }
743    }
744
745    // rustdoc-stripper-ignore-next
746    /// Sets field `name` to the given `value` if the `predicate` evaluates to `true`.
747    ///
748    /// This has no effect if the `predicate` evaluates to `false`,
749    /// i.e. default or previous value for `name` is kept.
750    #[doc(alias = "gst_caps_set_value")]
751    pub fn set_value_if(&mut self, name: impl IntoGStr, value: SendValue, predicate: bool) {
752        if predicate {
753            self.set_value(name, value);
754        }
755    }
756
757    // rustdoc-stripper-ignore-next
758    /// Sets field `name` to the given `value` if the `predicate` evaluates to `true`.
759    ///
760    /// This has no effect if the `predicate` evaluates to `false`,
761    /// i.e. default or previous value for `name` is kept.
762    #[doc(alias = "gst_caps_set_value_static_str")]
763    pub fn set_value_with_static_if(
764        &mut self,
765        name: impl AsRef<GStr> + 'static,
766        value: SendValue,
767        predicate: bool,
768    ) {
769        if predicate {
770            self.set_value_with_static(name, value);
771        }
772    }
773
774    // rustdoc-stripper-ignore-next
775    /// Sets field `name` to the given `value` if the `predicate` evaluates to `true`.
776    ///
777    /// This has no effect if the `predicate` evaluates to `false`,
778    /// i.e. default or previous value for `name` is kept.
779    #[doc(alias = "gst_caps_id_str_set_value")]
780    pub fn set_value_with_id_if(
781        &mut self,
782        name: impl AsRef<IdStr>,
783        value: SendValue,
784        predicate: bool,
785    ) {
786        if predicate {
787            self.set_value_with_id(name, value);
788        }
789    }
790
791    // rustdoc-stripper-ignore-next
792    /// Sets field `name` to the given inner value if `value` is `Some`.
793    ///
794    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
795    #[doc(alias = "gst_caps_set_value")]
796    pub fn set_value_if_some(&mut self, name: impl IntoGStr, value: Option<SendValue>) {
797        if let Some(value) = value {
798            self.set_value(name, value);
799        }
800    }
801
802    // rustdoc-stripper-ignore-next
803    /// Sets field `name` to the given inner value if `value` is `Some`.
804    ///
805    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
806    #[doc(alias = "gst_caps_set_value_static_str")]
807    pub fn set_value_with_static_if_some(
808        &mut self,
809        name: impl AsRef<GStr> + 'static,
810        value: Option<SendValue>,
811    ) {
812        if let Some(value) = value {
813            self.set_value_with_static(name, value);
814        }
815    }
816
817    // rustdoc-stripper-ignore-next
818    /// Sets field `name` to the given inner value if `value` is `Some`.
819    ///
820    /// This has no effect if the value is `None`, i.e. default or previous value for `name` is kept.
821    #[doc(alias = "gst_caps_id_str_set_value")]
822    pub fn set_value_with_id_if_some(&mut self, name: impl AsRef<IdStr>, value: Option<SendValue>) {
823        if let Some(value) = value {
824            self.set_value_with_id(name, value);
825        }
826    }
827
828    #[doc(alias = "get_structure")]
829    #[doc(alias = "gst_caps_get_structure")]
830    pub fn structure(&self, idx: usize) -> Option<&StructureRef> {
831        if idx >= self.size() {
832            return None;
833        }
834
835        unsafe {
836            let structure = ffi::gst_caps_get_structure(self.as_ptr(), idx as u32);
837            if structure.is_null() {
838                return None;
839            }
840
841            Some(StructureRef::from_glib_borrow(structure))
842        }
843    }
844
845    #[doc(alias = "get_mut_structure")]
846    #[doc(alias = "gst_caps_get_structure")]
847    pub fn structure_mut(&mut self, idx: usize) -> Option<&mut StructureRef> {
848        if idx >= self.size() {
849            return None;
850        }
851
852        unsafe {
853            let structure = ffi::gst_caps_get_structure(self.as_ptr(), idx as u32);
854            if structure.is_null() {
855                return None;
856            }
857
858            Some(StructureRef::from_glib_borrow_mut(structure))
859        }
860    }
861
862    #[doc(alias = "get_features")]
863    #[doc(alias = "gst_caps_get_features")]
864    pub fn features(&self, idx: usize) -> Option<&CapsFeaturesRef> {
865        if idx >= self.size() {
866            return None;
867        }
868
869        unsafe {
870            let features = ffi::gst_caps_get_features(self.as_ptr(), idx as u32);
871            Some(CapsFeaturesRef::from_glib_borrow(features))
872        }
873    }
874
875    #[doc(alias = "get_mut_features")]
876    #[doc(alias = "gst_caps_get_features")]
877    pub fn features_mut(&mut self, idx: usize) -> Option<&mut CapsFeaturesRef> {
878        if idx >= self.size() {
879            return None;
880        }
881
882        unsafe {
883            let features = ffi::gst_caps_get_features(self.as_ptr(), idx as u32);
884            Some(CapsFeaturesRef::from_glib_borrow_mut(features))
885        }
886    }
887
888    #[doc(alias = "gst_caps_set_features")]
889    pub fn set_features(&mut self, idx: usize, features: Option<CapsFeatures>) {
890        assert!(idx < self.size());
891
892        unsafe {
893            ffi::gst_caps_set_features(
894                self.as_mut_ptr(),
895                idx as u32,
896                features
897                    .map(|f| f.into_glib_ptr())
898                    .unwrap_or(ptr::null_mut()),
899            )
900        }
901    }
902
903    #[cfg(feature = "v1_16")]
904    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
905    #[doc(alias = "gst_caps_set_features_simple")]
906    pub fn set_features_simple(&mut self, features: Option<CapsFeatures>) {
907        unsafe {
908            ffi::gst_caps_set_features_simple(
909                self.as_mut_ptr(),
910                features
911                    .map(|f| f.into_glib_ptr())
912                    .unwrap_or(ptr::null_mut()),
913            )
914        }
915    }
916
917    #[doc(alias = "get_size")]
918    #[doc(alias = "gst_caps_get_size")]
919    pub fn size(&self) -> usize {
920        unsafe { ffi::gst_caps_get_size(self.as_ptr()) as usize }
921    }
922
923    pub fn len(&self) -> usize {
924        self.size()
925    }
926
927    pub fn iter(&self) -> Iter<'_> {
928        Iter::new(self)
929    }
930
931    pub fn iter_mut(&mut self) -> IterMut<'_> {
932        IterMut::new(self)
933    }
934
935    pub fn iter_with_features(&self) -> IterFeatures<'_> {
936        IterFeatures::new(self)
937    }
938
939    pub fn iter_with_features_mut(&mut self) -> IterFeaturesMut<'_> {
940        IterFeaturesMut::new(self)
941    }
942
943    #[doc(alias = "gst_caps_append_structure")]
944    pub fn append_structure(&mut self, structure: Structure) {
945        unsafe { ffi::gst_caps_append_structure(self.as_mut_ptr(), structure.into_glib_ptr()) }
946    }
947
948    #[doc(alias = "gst_caps_append_structure_full")]
949    pub fn append_structure_full(&mut self, structure: Structure, features: Option<CapsFeatures>) {
950        unsafe {
951            ffi::gst_caps_append_structure_full(
952                self.as_mut_ptr(),
953                structure.into_glib_ptr(),
954                features
955                    .map(|f| f.into_glib_ptr())
956                    .unwrap_or(ptr::null_mut()),
957            )
958        }
959    }
960
961    #[doc(alias = "gst_caps_remove_structure")]
962    pub fn remove_structure(&mut self, idx: usize) {
963        assert!(idx < self.size());
964
965        unsafe { ffi::gst_caps_remove_structure(self.as_mut_ptr(), idx as u32) }
966    }
967
968    #[doc(alias = "gst_caps_append")]
969    pub fn append(&mut self, other: Caps) {
970        unsafe { ffi::gst_caps_append(self.as_mut_ptr(), other.into_glib_ptr()) }
971    }
972
973    #[doc(alias = "gst_caps_can_intersect")]
974    pub fn can_intersect(&self, other: &Self) -> bool {
975        unsafe { from_glib(ffi::gst_caps_can_intersect(self.as_ptr(), other.as_ptr())) }
976    }
977
978    #[doc(alias = "gst_caps_intersect")]
979    pub fn intersect(&self, other: &Self) -> Caps {
980        unsafe {
981            from_glib_full(ffi::gst_caps_intersect(
982                self.as_mut_ptr(),
983                other.as_mut_ptr(),
984            ))
985        }
986    }
987
988    #[doc(alias = "gst_caps_intersect_full")]
989    pub fn intersect_with_mode(&self, other: &Self, mode: CapsIntersectMode) -> Caps {
990        unsafe {
991            from_glib_full(ffi::gst_caps_intersect_full(
992                self.as_mut_ptr(),
993                other.as_mut_ptr(),
994                mode.into_glib(),
995            ))
996        }
997    }
998
999    #[doc(alias = "gst_caps_is_always_compatible")]
1000    pub fn is_always_compatible(&self, other: &Self) -> bool {
1001        unsafe {
1002            from_glib(ffi::gst_caps_is_always_compatible(
1003                self.as_ptr(),
1004                other.as_ptr(),
1005            ))
1006        }
1007    }
1008
1009    #[doc(alias = "gst_caps_is_any")]
1010    pub fn is_any(&self) -> bool {
1011        unsafe { from_glib(ffi::gst_caps_is_any(self.as_ptr())) }
1012    }
1013
1014    #[doc(alias = "gst_caps_is_empty")]
1015    pub fn is_empty(&self) -> bool {
1016        unsafe { from_glib(ffi::gst_caps_is_empty(self.as_ptr())) }
1017    }
1018
1019    #[doc(alias = "gst_caps_is_fixed")]
1020    pub fn is_fixed(&self) -> bool {
1021        unsafe { from_glib(ffi::gst_caps_is_fixed(self.as_ptr())) }
1022    }
1023
1024    #[doc(alias = "gst_caps_is_equal_fixed")]
1025    pub fn is_equal_fixed(&self, other: &Self) -> bool {
1026        unsafe { from_glib(ffi::gst_caps_is_equal_fixed(self.as_ptr(), other.as_ptr())) }
1027    }
1028
1029    #[doc(alias = "gst_caps_is_strictly_equal")]
1030    pub fn is_strictly_equal(&self, other: &Self) -> bool {
1031        unsafe {
1032            from_glib(ffi::gst_caps_is_strictly_equal(
1033                self.as_ptr(),
1034                other.as_ptr(),
1035            ))
1036        }
1037    }
1038
1039    #[doc(alias = "gst_caps_is_subset")]
1040    pub fn is_subset(&self, superset: &Self) -> bool {
1041        unsafe { from_glib(ffi::gst_caps_is_subset(self.as_ptr(), superset.as_ptr())) }
1042    }
1043
1044    #[doc(alias = "gst_caps_is_subset_structure")]
1045    pub fn is_subset_structure(&self, structure: &StructureRef) -> bool {
1046        unsafe {
1047            from_glib(ffi::gst_caps_is_subset_structure(
1048                self.as_ptr(),
1049                structure.as_ptr(),
1050            ))
1051        }
1052    }
1053
1054    #[doc(alias = "gst_caps_is_subset_structure_full")]
1055    pub fn is_subset_structure_full(
1056        &self,
1057        structure: &StructureRef,
1058        features: Option<&CapsFeaturesRef>,
1059    ) -> bool {
1060        unsafe {
1061            from_glib(ffi::gst_caps_is_subset_structure_full(
1062                self.as_ptr(),
1063                structure.as_ptr(),
1064                features.map(|f| f.as_ptr()).unwrap_or(ptr::null()),
1065            ))
1066        }
1067    }
1068
1069    #[doc(alias = "gst_caps_subtract")]
1070    pub fn subtract(&self, other: &Self) -> Caps {
1071        unsafe {
1072            from_glib_full(ffi::gst_caps_subtract(
1073                self.as_mut_ptr(),
1074                other.as_mut_ptr(),
1075            ))
1076        }
1077    }
1078
1079    #[cfg(feature = "v1_20")]
1080    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
1081    #[doc(alias = "gst_caps_serialize")]
1082    pub fn serialize(&self, flags: crate::SerializeFlags) -> glib::GString {
1083        unsafe { from_glib_full(ffi::gst_caps_serialize(&self.0, flags.into_glib())) }
1084    }
1085
1086    #[doc(alias = "gst_caps_foreach")]
1087    pub fn foreach<F: FnMut(&CapsFeaturesRef, &StructureRef) -> std::ops::ControlFlow<()>>(
1088        &self,
1089        mut func: F,
1090    ) -> bool {
1091        unsafe {
1092            unsafe extern "C" fn trampoline<
1093                F: FnMut(&CapsFeaturesRef, &StructureRef) -> std::ops::ControlFlow<()>,
1094            >(
1095                features: *mut ffi::GstCapsFeatures,
1096                s: *mut ffi::GstStructure,
1097                user_data: glib::ffi::gpointer,
1098            ) -> glib::ffi::gboolean {
1099                unsafe {
1100                    let func = &mut *(user_data as *mut F);
1101                    let res = func(
1102                        CapsFeaturesRef::from_glib_borrow(features),
1103                        StructureRef::from_glib_borrow(s),
1104                    );
1105
1106                    matches!(res, std::ops::ControlFlow::Continue(_)).into_glib()
1107                }
1108            }
1109            let func = &mut func as *mut F;
1110            from_glib(ffi::gst_caps_foreach(
1111                self.as_ptr(),
1112                Some(trampoline::<F>),
1113                func as glib::ffi::gpointer,
1114            ))
1115        }
1116    }
1117
1118    #[doc(alias = "gst_caps_map_in_place")]
1119    pub fn map_in_place<
1120        F: FnMut(&mut CapsFeaturesRef, &mut StructureRef) -> std::ops::ControlFlow<()>,
1121    >(
1122        &mut self,
1123        mut func: F,
1124    ) {
1125        unsafe {
1126            unsafe extern "C" fn trampoline<
1127                F: FnMut(&mut CapsFeaturesRef, &mut StructureRef) -> std::ops::ControlFlow<()>,
1128            >(
1129                features: *mut ffi::GstCapsFeatures,
1130                s: *mut ffi::GstStructure,
1131                user_data: glib::ffi::gpointer,
1132            ) -> glib::ffi::gboolean {
1133                unsafe {
1134                    let func = &mut *(user_data as *mut F);
1135                    let res = func(
1136                        CapsFeaturesRef::from_glib_borrow_mut(features),
1137                        StructureRef::from_glib_borrow_mut(s),
1138                    );
1139
1140                    matches!(res, std::ops::ControlFlow::Continue(_)).into_glib()
1141                }
1142            }
1143            let func = &mut func as *mut F;
1144            let _ = ffi::gst_caps_map_in_place(
1145                self.as_mut_ptr(),
1146                Some(trampoline::<F>),
1147                func as glib::ffi::gpointer,
1148            );
1149        }
1150    }
1151
1152    #[doc(alias = "gst_caps_filter_and_map_in_place")]
1153    pub fn filter_map_in_place<
1154        F: FnMut(&mut CapsFeaturesRef, &mut StructureRef) -> CapsFilterMapAction,
1155    >(
1156        &mut self,
1157        mut func: F,
1158    ) {
1159        unsafe {
1160            unsafe extern "C" fn trampoline<
1161                F: FnMut(&mut CapsFeaturesRef, &mut StructureRef) -> CapsFilterMapAction,
1162            >(
1163                features: *mut ffi::GstCapsFeatures,
1164                s: *mut ffi::GstStructure,
1165                user_data: glib::ffi::gpointer,
1166            ) -> glib::ffi::gboolean {
1167                unsafe {
1168                    let func = &mut *(user_data as *mut F);
1169
1170                    let res = func(
1171                        CapsFeaturesRef::from_glib_borrow_mut(features),
1172                        StructureRef::from_glib_borrow_mut(s),
1173                    );
1174
1175                    match res {
1176                        CapsFilterMapAction::Keep => glib::ffi::GTRUE,
1177                        CapsFilterMapAction::Remove => glib::ffi::GFALSE,
1178                    }
1179                }
1180            }
1181
1182            let func = &mut func as *mut F;
1183            ffi::gst_caps_filter_and_map_in_place(
1184                self.as_mut_ptr(),
1185                Some(trampoline::<F>),
1186                func as glib::ffi::gpointer,
1187            );
1188        }
1189    }
1190}
1191
1192#[derive(Debug)]
1193pub enum CapsFilterMapAction {
1194    Keep,
1195    Remove,
1196}
1197
1198macro_rules! define_iter(
1199    ($name:ident, $typ:ty, $styp:ty, $get_item:expr) => {
1200        crate::utils::define_fixed_size_iter!(
1201            $name, $typ, $styp,
1202            |collection: &CapsRef| collection.size(),
1203            $get_item
1204        );
1205    }
1206);
1207
1208define_iter!(
1209    Iter,
1210    &'a CapsRef,
1211    &'a StructureRef,
1212    |caps: &CapsRef, idx| unsafe {
1213        let ptr = ffi::gst_caps_get_structure(caps.as_ptr(), idx as u32);
1214        StructureRef::from_glib_borrow(ptr as *const ffi::GstStructure)
1215    }
1216);
1217define_iter!(
1218    IterMut,
1219    &'a mut CapsRef,
1220    &'a mut StructureRef,
1221    |caps: &mut CapsRef, idx| unsafe {
1222        let ptr = ffi::gst_caps_get_structure(caps.as_ptr(), idx as u32);
1223        StructureRef::from_glib_borrow_mut(ptr)
1224    }
1225);
1226define_iter!(
1227    IterFeatures,
1228    &'a CapsRef,
1229    (&'a StructureRef, &'a CapsFeaturesRef),
1230    |caps: &CapsRef, idx| unsafe {
1231        let ptr1 = ffi::gst_caps_get_structure(caps.as_ptr(), idx as u32);
1232        let ptr2 = ffi::gst_caps_get_features(caps.as_ptr(), idx as u32);
1233        (
1234            StructureRef::from_glib_borrow(ptr1),
1235            CapsFeaturesRef::from_glib_borrow(ptr2),
1236        )
1237    }
1238);
1239define_iter!(
1240    IterFeaturesMut,
1241    &'a mut CapsRef,
1242    (&'a mut StructureRef, &'a mut CapsFeaturesRef),
1243    |caps: &mut CapsRef, idx| unsafe {
1244        let ptr1 = ffi::gst_caps_get_structure(caps.as_ptr(), idx as u32);
1245        let ptr2 = ffi::gst_caps_get_features(caps.as_ptr(), idx as u32);
1246        (
1247            StructureRef::from_glib_borrow_mut(ptr1),
1248            CapsFeaturesRef::from_glib_borrow_mut(ptr2),
1249        )
1250    }
1251);
1252
1253impl<'a> IntoIterator for &'a CapsRef {
1254    type IntoIter = IterFeatures<'a>;
1255    type Item = (&'a StructureRef, &'a CapsFeaturesRef);
1256
1257    fn into_iter(self) -> Self::IntoIter {
1258        self.iter_with_features()
1259    }
1260}
1261
1262impl<'a> IntoIterator for &'a mut CapsRef {
1263    type IntoIter = IterFeaturesMut<'a>;
1264    type Item = (&'a mut StructureRef, &'a mut CapsFeaturesRef);
1265
1266    fn into_iter(self) -> Self::IntoIter {
1267        self.iter_with_features_mut()
1268    }
1269}
1270
1271impl fmt::Debug for Caps {
1272    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1273        <CapsRef as fmt::Debug>::fmt(self, f)
1274    }
1275}
1276
1277impl fmt::Display for Caps {
1278    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1279        <CapsRef as fmt::Display>::fmt(self, f)
1280    }
1281}
1282
1283impl PartialEq for Caps {
1284    fn eq(&self, other: &Caps) -> bool {
1285        CapsRef::eq(self, other)
1286    }
1287}
1288
1289impl Eq for Caps {}
1290
1291impl PartialEq<CapsRef> for Caps {
1292    fn eq(&self, other: &CapsRef) -> bool {
1293        CapsRef::eq(self, other)
1294    }
1295}
1296
1297impl PartialEq<Caps> for CapsRef {
1298    fn eq(&self, other: &Caps) -> bool {
1299        CapsRef::eq(other, self)
1300    }
1301}
1302
1303impl fmt::Debug for CapsRef {
1304    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1305        if self.is_any() {
1306            f.debug_tuple("Caps(\"ANY\")").finish()
1307        } else if self.is_empty() {
1308            f.debug_tuple("Caps(\"EMPTY\")").finish()
1309        } else {
1310            let mut debug = f.debug_tuple("Caps");
1311
1312            for (structure, features) in self.iter_with_features() {
1313                struct WithFeatures<'a> {
1314                    features: &'a CapsFeaturesRef,
1315                    structure: &'a StructureRef,
1316                }
1317
1318                impl fmt::Debug for WithFeatures<'_> {
1319                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320                        let name = format!("{}({})", self.structure.name(), self.features);
1321                        let mut debug = f.debug_struct(&name);
1322
1323                        for (id, field) in self.structure.iter() {
1324                            if field.type_() == Structure::static_type() {
1325                                let s = field.get::<Structure>().unwrap();
1326                                debug.field(id, &s);
1327                            } else if field.type_() == crate::Array::static_type() {
1328                                let arr = field.get::<crate::Array>().unwrap();
1329                                debug.field(id, &arr);
1330                            } else if field.type_() == crate::List::static_type() {
1331                                let list = field.get::<crate::List>().unwrap();
1332                                debug.field(id, &list);
1333                            } else {
1334                                debug.field(id, &field);
1335                            }
1336                        }
1337
1338                        debug.finish()
1339                    }
1340                }
1341
1342                debug.field(&WithFeatures {
1343                    structure,
1344                    features,
1345                });
1346            }
1347
1348            debug.finish()
1349        }
1350    }
1351}
1352
1353impl fmt::Display for CapsRef {
1354    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1355        let s = unsafe { glib::GString::from_glib_full(ffi::gst_caps_to_string(self.as_ptr())) };
1356        f.write_str(&s)
1357    }
1358}
1359
1360impl PartialEq for CapsRef {
1361    #[doc(alias = "gst_caps_is_equal")]
1362    fn eq(&self, other: &CapsRef) -> bool {
1363        unsafe { from_glib(ffi::gst_caps_is_equal(self.as_ptr(), other.as_ptr())) }
1364    }
1365}
1366
1367impl Eq for CapsRef {}
1368
1369#[cfg(feature = "v1_28")]
1370impl std::hash::Hash for CapsRef {
1371    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1372        if self.is_any() {
1373            "ANY".hash(state);
1374        } else if self.is_empty() {
1375            "EMPTY".hash(state);
1376        } else {
1377            // do no sort as structure order matters
1378            for (s, feature) in self.iter_with_features() {
1379                s.hash(state);
1380                feature.hash(state);
1381            }
1382        }
1383    }
1384}
1385
1386#[cfg(feature = "v1_28")]
1387impl std::hash::Hash for Caps {
1388    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1389        self.as_ref().hash(state);
1390    }
1391}
1392
1393pub enum NoFeature {}
1394pub enum HasFeatures {}
1395
1396#[must_use = "The builder must be built to be used"]
1397pub struct Builder<T> {
1398    s: crate::Structure,
1399    features: Option<CapsFeatures>,
1400    phantom: PhantomData<T>,
1401}
1402
1403impl<T> fmt::Debug for Builder<T> {
1404    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1405        f.debug_struct("Builder")
1406            .field("s", &self.s)
1407            .field("features", &self.features)
1408            .field("phantom", &self.phantom)
1409            .finish()
1410    }
1411}
1412
1413impl Builder<NoFeature> {
1414    fn new(name: impl IntoGStr) -> Builder<NoFeature> {
1415        skip_assert_initialized!();
1416        Builder {
1417            s: crate::Structure::new_empty(name),
1418            features: None,
1419            phantom: PhantomData,
1420        }
1421    }
1422
1423    fn from_static(name: impl AsRef<GStr> + 'static) -> Builder<NoFeature> {
1424        skip_assert_initialized!();
1425        Builder {
1426            s: crate::Structure::new_empty_from_static(name),
1427            features: None,
1428            phantom: PhantomData,
1429        }
1430    }
1431
1432    fn from_id(name: impl AsRef<IdStr>) -> Builder<NoFeature> {
1433        skip_assert_initialized!();
1434        Builder {
1435            s: crate::Structure::new_empty_from_id(name),
1436            features: None,
1437            phantom: PhantomData,
1438        }
1439    }
1440
1441    pub fn features<S: IntoGStr>(
1442        self,
1443        features: impl IntoIterator<Item = S>,
1444    ) -> Builder<HasFeatures> {
1445        Builder {
1446            s: self.s,
1447            features: Some(CapsFeatures::new(features)),
1448            phantom: PhantomData,
1449        }
1450    }
1451
1452    pub fn features_from_statics<S: AsRef<GStr> + 'static>(
1453        self,
1454        features: impl IntoIterator<Item = S>,
1455    ) -> Builder<HasFeatures> {
1456        Builder {
1457            s: self.s,
1458            features: Some(CapsFeatures::new_from_static(features)),
1459            phantom: PhantomData,
1460        }
1461    }
1462
1463    pub fn features_from_ids<S: AsRef<IdStr>>(
1464        self,
1465        features: impl IntoIterator<Item = S>,
1466    ) -> Builder<HasFeatures> {
1467        Builder {
1468            s: self.s,
1469            features: Some(CapsFeatures::new_from_id(features)),
1470            phantom: PhantomData,
1471        }
1472    }
1473
1474    pub fn any_features(self) -> Builder<HasFeatures> {
1475        Builder {
1476            s: self.s,
1477            features: Some(CapsFeatures::new_any()),
1478            phantom: PhantomData,
1479        }
1480    }
1481}
1482
1483impl<T> Builder<T> {
1484    // rustdoc-stripper-ignore-next
1485    /// Sets field `name` to the given value `value`.
1486    ///
1487    /// Overrides any default or previously defined value for `name`.
1488    #[inline]
1489    pub fn field(mut self, name: impl IntoGStr, value: impl Into<glib::Value> + Send) -> Self {
1490        self.s.set(name, value);
1491        self
1492    }
1493
1494    // rustdoc-stripper-ignore-next
1495    /// Sets field `name` to the given value `value`.
1496    ///
1497    /// Overrides any default or previously defined value for `name`.
1498    #[inline]
1499    pub fn field_with_static(
1500        mut self,
1501        name: impl AsRef<glib::GStr> + 'static,
1502        value: impl Into<glib::Value> + Send,
1503    ) -> Self {
1504        self.s.set_with_static(name, value);
1505        self
1506    }
1507
1508    // rustdoc-stripper-ignore-next
1509    /// Sets field `name` to the given value `value`.
1510    ///
1511    /// Overrides any default or previously defined value for `name`.
1512    #[inline]
1513    pub fn field_with_id(
1514        mut self,
1515        name: impl AsRef<IdStr>,
1516        value: impl Into<glib::Value> + Send,
1517    ) -> Self {
1518        self.s.set_with_id(name, value);
1519        self
1520    }
1521
1522    impl_builder_gvalue_extra_setters!(field);
1523
1524    #[must_use = "Building the caps without using them has no effect"]
1525    pub fn build(self) -> Caps {
1526        let mut caps = Caps::new_empty();
1527
1528        caps.get_mut()
1529            .unwrap()
1530            .append_structure_full(self.s, self.features);
1531        caps
1532    }
1533
1534    pub fn structure(&self) -> &crate::Structure {
1535        &self.s
1536    }
1537}
1538
1539pub enum AnyFeatures {}
1540pub enum SomeFeatures {}
1541
1542#[must_use = "The builder must be built to be used"]
1543pub struct BuilderFull<T> {
1544    caps: crate::Caps,
1545    features: Option<CapsFeatures>,
1546    phantom: PhantomData<T>,
1547}
1548
1549impl<T> fmt::Debug for BuilderFull<T> {
1550    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1551        f.debug_struct("Builder")
1552            .field("caps", &self.caps)
1553            .field("features", &self.features)
1554            .field("phantom", &self.phantom)
1555            .finish()
1556    }
1557}
1558
1559impl BuilderFull<SomeFeatures> {
1560    fn new() -> Self {
1561        BuilderFull {
1562            caps: Caps::new_empty(),
1563            features: None,
1564            phantom: PhantomData,
1565        }
1566    }
1567
1568    fn with_features(features: CapsFeatures) -> Self {
1569        skip_assert_initialized!();
1570        BuilderFull {
1571            caps: Caps::new_empty(),
1572            features: Some(features),
1573            phantom: PhantomData,
1574        }
1575    }
1576
1577    pub fn structure_with_features(self, structure: Structure, features: CapsFeatures) -> Self {
1578        self.append_structure(structure, Some(features))
1579    }
1580
1581    pub fn structure_with_features_if_some(
1582        self,
1583        structure: Option<Structure>,
1584        features: CapsFeatures,
1585    ) -> Self {
1586        if let Some(structure) = structure {
1587            self.structure_with_features(structure, features)
1588        } else {
1589            self
1590        }
1591    }
1592
1593    pub fn structure_with_any_features(self, structure: Structure) -> Self {
1594        self.append_structure(structure, Some(CapsFeatures::new_any()))
1595    }
1596
1597    pub fn structure_with_any_features_if_some(self, structure: Option<Structure>) -> Self {
1598        if let Some(structure) = structure {
1599            self.structure_with_any_features(structure)
1600        } else {
1601            self
1602        }
1603    }
1604}
1605
1606impl BuilderFull<AnyFeatures> {
1607    fn with_any_features() -> Self {
1608        BuilderFull {
1609            caps: Caps::new_empty(),
1610            features: Some(CapsFeatures::new_any()),
1611            phantom: PhantomData,
1612        }
1613    }
1614}
1615
1616impl<T> BuilderFull<T> {
1617    fn append_structure(mut self, structure: Structure, features: Option<CapsFeatures>) -> Self {
1618        let features = {
1619            match self.features {
1620                None => features,
1621                Some(ref result) => {
1622                    let mut result = result.clone();
1623                    match features {
1624                        None => Some(result),
1625                        Some(features) => {
1626                            features.iter().for_each(|feat| result.add(feat));
1627                            Some(result)
1628                        }
1629                    }
1630                }
1631            }
1632        };
1633
1634        self.caps
1635            .get_mut()
1636            .unwrap()
1637            .append_structure_full(structure, features);
1638        self
1639    }
1640
1641    pub fn structure(self, structure: Structure) -> Self {
1642        self.append_structure(structure, None)
1643    }
1644
1645    pub fn structure_if_some(self, structure: Option<Structure>) -> Self {
1646        if let Some(structure) = structure {
1647            self.structure(structure)
1648        } else {
1649            self
1650        }
1651    }
1652
1653    #[must_use = "Building the caps without using them has no effect"]
1654    pub fn build(self) -> Caps {
1655        self.caps
1656    }
1657}
1658
1659#[cfg(test)]
1660mod tests {
1661    use super::*;
1662    use crate::{Array, Fraction};
1663    use glib::gstr;
1664
1665    #[test]
1666    fn test_builder() {
1667        crate::init().unwrap();
1668
1669        let mut caps = Caps::builder("foo/bar")
1670            .field("int", 12)
1671            .field_with_static(gstr!("bool"), true)
1672            .field_with_id(idstr!("string"), "bla")
1673            .field("fraction", Fraction::new(1, 2))
1674            .field_with_id(idstr!("array"), Array::new([1, 2]))
1675            .build();
1676        assert_eq!(
1677            caps.to_string(),
1678            "foo/bar, int=(int)12, bool=(boolean)true, string=(string)bla, fraction=(fraction)1/2, array=(int)< 1, 2 >"
1679        );
1680
1681        assert!(
1682            caps.features(0)
1683                .unwrap()
1684                .is_equal(crate::CAPS_FEATURES_MEMORY_SYSTEM_MEMORY.as_ref())
1685        );
1686
1687        {
1688            let caps = caps.get_mut().unwrap();
1689            caps.set_features(0, Some(CapsFeatures::new(["foo:bla"])));
1690        }
1691        assert!(
1692            caps.features(0)
1693                .unwrap()
1694                .is_equal(CapsFeatures::new(["foo:bla"]).as_ref())
1695        );
1696
1697        let caps = Caps::builder("foo/bar")
1698            .field("int", 12)
1699            .any_features()
1700            .build();
1701        assert_eq!(caps.to_string(), "foo/bar(ANY), int=(int)12");
1702
1703        let caps = Caps::builder("foo/bar")
1704            .field("int", 12)
1705            .features(["foo:bla", "foo:baz"])
1706            .build();
1707        assert_eq!(caps.to_string(), "foo/bar(foo:bla, foo:baz), int=(int)12");
1708
1709        let caps = Caps::builder("foo/bar")
1710            .field_if_some("int0", Option::<i32>::None)
1711            .field_if_some("int1", Some(12))
1712            .field_with_static_if_some(gstr!("string0"), Option::<String>::None)
1713            .field_with_id_if_some(idstr!("string1"), Some("bla"))
1714            .build();
1715        assert_eq!(
1716            caps.to_string(),
1717            "foo/bar, int1=(int)12, string1=(string)bla"
1718        );
1719    }
1720
1721    #[test]
1722    fn test_display() {
1723        crate::init().unwrap();
1724
1725        let caps = Caps::builder("foo/bar").build();
1726        let _ = format!("{caps}");
1727    }
1728
1729    #[test]
1730    fn test_builder_full() {
1731        crate::init().unwrap();
1732
1733        let caps = Caps::builder_full()
1734            .structure(Structure::builder("audio/x-raw").build())
1735            .structure(Structure::builder("video/x-raw").build())
1736            .build();
1737        assert_eq!(caps.to_string(), "audio/x-raw; video/x-raw");
1738
1739        let caps = Caps::builder_full()
1740            .structure(
1741                Structure::builder("audio/x-raw")
1742                    .field("format", "S16LE")
1743                    .build(),
1744            )
1745            .structure(Structure::builder("video/x-raw").build())
1746            .build();
1747        assert_eq!(
1748            caps.to_string(),
1749            "audio/x-raw, format=(string)S16LE; video/x-raw"
1750        );
1751
1752        let caps = Caps::builder_full()
1753            .structure_with_any_features(Structure::builder("audio/x-raw").build())
1754            .structure_with_features(
1755                Structure::builder("video/x-raw").build(),
1756                CapsFeatures::new(["foo:bla", "foo:baz"]),
1757            )
1758            .build();
1759        assert_eq!(
1760            caps.to_string(),
1761            "audio/x-raw(ANY); video/x-raw(foo:bla, foo:baz)"
1762        );
1763
1764        let caps = Caps::builder_full()
1765            .structure_if_some(Option::<Structure>::None)
1766            .build();
1767        assert!(caps.is_empty());
1768
1769        let caps = Caps::builder_full()
1770            .structure_if_some(Some(Structure::builder("audio/x-raw").build()))
1771            .build();
1772        assert_eq!(caps.to_string(), "audio/x-raw");
1773
1774        let caps = Caps::builder_full()
1775            .structure_with_any_features_if_some(Some(Structure::builder("audio/x-raw").build()))
1776            .structure_with_features_if_some(
1777                Some(Structure::builder("video/x-raw").build()),
1778                CapsFeatures::new_from_id([idstr!("foo:bla"), idstr!("foo:baz")]),
1779            )
1780            .build();
1781        assert_eq!(
1782            caps.to_string(),
1783            "audio/x-raw(ANY); video/x-raw(foo:bla, foo:baz)"
1784        );
1785
1786        let caps = Caps::builder_full()
1787            .structure_with_any_features_if_some(Option::<Structure>::None)
1788            .structure_with_features_if_some(
1789                Option::<Structure>::None,
1790                CapsFeatures::new(["foo:bla", "foo:baz"]),
1791            )
1792            .build();
1793        assert!(caps.is_empty());
1794    }
1795
1796    #[test]
1797    fn test_builder_full_with_features() {
1798        crate::init().unwrap();
1799
1800        let caps = Caps::builder_full_with_features(CapsFeatures::new(["foo:bla"]))
1801            .structure(Structure::builder("audio/x-raw").build())
1802            .structure_with_features(
1803                Structure::builder("video/x-raw").build(),
1804                CapsFeatures::new(["foo:baz"]),
1805            )
1806            .build();
1807        assert_eq!(
1808            caps.to_string(),
1809            "audio/x-raw(foo:bla); video/x-raw(foo:bla, foo:baz)"
1810        );
1811    }
1812
1813    #[test]
1814    fn test_builder_full_with_any_features() {
1815        crate::init().unwrap();
1816
1817        let caps = Caps::builder_full_with_any_features()
1818            .structure(Structure::builder("audio/x-raw").build())
1819            .structure(Structure::builder("video/x-raw").build())
1820            .build();
1821        assert_eq!(caps.to_string(), "audio/x-raw(ANY); video/x-raw(ANY)");
1822
1823        let caps = Caps::builder_full_with_any_features()
1824            .structure(Structure::builder("audio/x-raw").build())
1825            .build();
1826        assert_eq!(caps.to_string(), "audio/x-raw(ANY)");
1827    }
1828
1829    #[test]
1830    fn test_new_from_iter() {
1831        crate::init().unwrap();
1832
1833        let caps = Caps::builder_full_with_any_features()
1834            .structure(Structure::builder("audio/x-raw").build())
1835            .structure(Structure::builder("video/x-raw").build())
1836            .build();
1837
1838        let audio = caps
1839            .iter()
1840            .filter(|s| s.name() == "audio/x-raw")
1841            .map(|s| s.to_owned())
1842            .collect::<Caps>();
1843        assert_eq!(audio.to_string(), "audio/x-raw");
1844
1845        let audio = caps
1846            .iter_with_features()
1847            .filter(|(s, _)| s.name() == "audio/x-raw")
1848            .map(|(s, c)| (s.to_owned(), c.to_owned()))
1849            .collect::<Caps>();
1850        assert_eq!(audio.to_string(), "audio/x-raw(ANY)");
1851    }
1852
1853    #[test]
1854    fn test_debug() {
1855        crate::init().unwrap();
1856
1857        let caps = Caps::new_any();
1858        assert_eq!(format!("{caps:?}"), "Caps(\"ANY\")");
1859
1860        let caps = Caps::new_empty();
1861        assert_eq!(format!("{caps:?}"), "Caps(\"EMPTY\")");
1862
1863        let caps = Caps::builder_full_with_any_features()
1864            .structure(Structure::builder("audio/x-raw").build())
1865            .build();
1866        assert_eq!(format!("{caps:?}"), "Caps(audio/x-raw(ANY))");
1867
1868        let caps = Caps::builder_full_with_features(CapsFeatures::new(["foo:bla"]))
1869            .structure(
1870                Structure::builder("audio/x-raw")
1871                    .field(
1872                        "struct",
1873                        Structure::builder("nested").field("badger", true).build(),
1874                    )
1875                    .build(),
1876            )
1877            .structure(
1878                Structure::builder("video/x-raw")
1879                    .field("width", 800u32)
1880                    .build(),
1881            )
1882            .build();
1883
1884        assert_eq!(
1885            format!("{caps:?}"),
1886            "Caps(audio/x-raw(foo:bla) { struct: Structure(nested { badger: (gboolean) TRUE }) }, video/x-raw(foo:bla) { width: (guint) 800 })"
1887        );
1888
1889        let caps = Caps::builder_full()
1890            .structure(
1891                Structure::builder("video/x-raw")
1892                    .field("array", crate::Array::new(["a", "b", "c"]))
1893                    .field("list", crate::List::new(["d", "e", "f"]))
1894                    .build(),
1895            )
1896            .build();
1897
1898        assert_eq!(
1899            format!("{caps:?}"),
1900            "Caps(video/x-raw(memory:SystemMemory) { array: Array([(gchararray) \"a\", (gchararray) \"b\", (gchararray) \"c\"]), list: List([(gchararray) \"d\", (gchararray) \"e\", (gchararray) \"f\"]) })"
1901        );
1902    }
1903
1904    #[cfg(feature = "v1_28")]
1905    #[test]
1906    fn test_hash() {
1907        crate::init().unwrap();
1908
1909        use std::hash::BuildHasher;
1910        let bh = std::hash::RandomState::new();
1911
1912        let caps = Caps::builder("video/x-raw").build();
1913        assert_eq!(bh.hash_one(&caps), bh.hash_one(&caps));
1914
1915        let caps_any = Caps::new_any();
1916        let caps_empty = Caps::new_empty();
1917        assert_eq!(bh.hash_one(&caps_any), bh.hash_one(&caps_any));
1918        assert_eq!(bh.hash_one(&caps_empty), bh.hash_one(&caps_empty));
1919        assert_ne!(bh.hash_one(&caps_any), bh.hash_one(&caps_empty));
1920
1921        // Same caps but fields in a different order
1922        let caps_a = Caps::builder("video/x-raw")
1923            .field("width", 1920u32)
1924            .field("height", 1080u32)
1925            .build();
1926        let caps_b = Caps::builder("video/x-raw")
1927            .field("height", 1080u32)
1928            .field("width", 1920u32)
1929            .build();
1930        assert_eq!(bh.hash_one(&caps_a), bh.hash_one(&caps_a));
1931        assert_eq!(bh.hash_one(&caps_b), bh.hash_one(&caps_b));
1932        assert_eq!(bh.hash_one(&caps_a), bh.hash_one(&caps_b));
1933
1934        // Same fields but different feature
1935        let caps_a = Caps::builder("video/x-raw")
1936            .features(["memory:DMABuf"])
1937            .field("width", 1920u32)
1938            .field("height", 1080u32)
1939            .build();
1940        let caps_b = Caps::builder("video/x-raw")
1941            .features(["memory:GLMemory"])
1942            .field("height", 1080u32)
1943            .field("width", 1920u32)
1944            .build();
1945        assert_eq!(bh.hash_one(&caps_a), bh.hash_one(&caps_a));
1946        assert_eq!(bh.hash_one(&caps_b), bh.hash_one(&caps_b));
1947        assert_ne!(bh.hash_one(&caps_a), bh.hash_one(&caps_b));
1948
1949        // Caps have the same structures but in different order, so they are actually different
1950        let caps_a = Caps::builder_full()
1951            .structure(Structure::builder("audio/x-raw").build())
1952            .structure(Structure::builder("video/x-raw").build())
1953            .build();
1954        let caps_b = Caps::builder_full()
1955            .structure(Structure::builder("video/x-raw").build())
1956            .structure(Structure::builder("audio/x-raw").build())
1957            .build();
1958        assert_eq!(bh.hash_one(&caps_a), bh.hash_one(&caps_a));
1959        assert_eq!(bh.hash_one(&caps_b), bh.hash_one(&caps_b));
1960        assert_ne!(bh.hash_one(&caps_a), bh.hash_one(&caps_b));
1961    }
1962}