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

#[cfg(feature = "v1_16")]
#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
use std::boxed::Box as Box_;
#[cfg(feature = "v1_16")]
#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
use std::mem::transmute;
use std::{mem, ptr};

#[cfg(feature = "v1_16")]
#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
use glib::signal::{connect_raw, SignalHandlerId};
use glib::{prelude::*, translate::*};
use gst::{format::FormattedValue, prelude::*};

use crate::Aggregator;
use crate::AggregatorPad;

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::Aggregator>> Sealed for T {}
}

pub trait AggregatorExtManual: sealed::Sealed + IsA<Aggregator> + 'static {
    /// Lets [`Aggregator`][crate::Aggregator] sub-classes get the memory `allocator`
    /// acquired by the base class and its `params`.
    ///
    /// Unref the `allocator` after use it.
    ///
    /// # Returns
    ///
    ///
    /// ## `allocator`
    /// the [`gst::Allocator`][crate::gst::Allocator]
    /// used
    ///
    /// ## `params`
    /// the
    /// [`gst::AllocationParams`][crate::gst::AllocationParams] of `allocator`
    #[doc(alias = "get_allocator")]
    #[doc(alias = "gst_aggregator_get_allocator")]
    fn allocator(&self) -> (Option<gst::Allocator>, gst::AllocationParams) {
        unsafe {
            let mut allocator = ptr::null_mut();
            let mut params = mem::MaybeUninit::uninit();
            ffi::gst_aggregator_get_allocator(
                self.as_ref().to_glib_none().0,
                &mut allocator,
                params.as_mut_ptr(),
            );
            (from_glib_full(allocator), params.assume_init().into())
        }
    }

    #[cfg(feature = "v1_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    #[doc(alias = "min-upstream-latency")]
    fn min_upstream_latency(&self) -> gst::ClockTime {
        self.as_ref().property("min-upstream-latency")
    }

    #[cfg(feature = "v1_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    #[doc(alias = "min-upstream-latency")]
    fn set_min_upstream_latency(&self, min_upstream_latency: gst::ClockTime) {
        self.as_ref()
            .set_property("min-upstream-latency", min_upstream_latency);
    }

    #[cfg(feature = "v1_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    #[doc(alias = "min-upstream-latency")]
    fn connect_min_upstream_latency_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::min-upstream-latency\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_min_upstream_latency_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    /// Subclasses should use this to update the segment on their
    /// source pad, instead of directly pushing new segment events
    /// downstream.
    ///
    /// Subclasses MUST call this before [`selected_samples()`][Self::selected_samples()],
    /// if it is used at all.
    #[cfg(feature = "v1_18")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_18")))]
    #[doc(alias = "gst_aggregator_update_segment")]
    fn update_segment<F: gst::format::FormattedValueIntrinsic>(
        &self,
        segment: &gst::FormattedSegment<F>,
    ) {
        unsafe {
            ffi::gst_aggregator_update_segment(
                self.as_ref().to_glib_none().0,
                mut_override(segment.to_glib_none().0),
            )
        }
    }

    fn set_position(&self, position: impl FormattedValue) {
        unsafe {
            let ptr: *mut ffi::GstAggregator = self.as_ref().to_glib_none().0;
            let ptr = &mut *ptr;
            let _guard = self.as_ref().object_lock();

            // gstaggregator.c asserts that the src pad is always of type GST_TYPE_AGGREGATOR_PAD,
            // so the pointer cast here should be safe.
            let srcpad = &mut *(ptr.srcpad as *mut ffi::GstAggregatorPad);

            assert_eq!(srcpad.segment.format, position.format().into_glib());
            srcpad.segment.position = position.into_raw_value() as u64;
        }
    }

    /// Subclasses should call this when they have prepared the
    /// buffers they will aggregate for each of their sink pads, but
    /// before using any of the properties of the pads that govern
    /// *how* aggregation should be performed, for example z-index
    /// for video aggregators.
    ///
    /// If [`update_segment()`][Self::update_segment()] is used by the subclass,
    /// it MUST be called before [`selected_samples()`][Self::selected_samples()].
    ///
    /// This function MUST only be called from the `GstAggregatorClass::aggregate()`
    /// function.
    /// ## `pts`
    /// The presentation timestamp of the next output buffer
    /// ## `dts`
    /// The decoding timestamp of the next output buffer
    /// ## `duration`
    /// The duration of the next output buffer
    /// ## `info`
    /// a [`gst::Structure`][crate::gst::Structure] containing additional information
    #[cfg(feature = "v1_18")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_18")))]
    #[doc(alias = "gst_aggregator_selected_samples")]
    fn selected_samples(
        &self,
        pts: impl Into<Option<gst::ClockTime>>,
        dts: impl Into<Option<gst::ClockTime>>,
        duration: impl Into<Option<gst::ClockTime>>,
        info: Option<&gst::StructureRef>,
    ) {
        unsafe {
            ffi::gst_aggregator_selected_samples(
                self.as_ref().to_glib_none().0,
                pts.into().into_glib(),
                dts.into().into_glib(),
                duration.into().into_glib(),
                info.as_ref()
                    .map(|s| s.as_ptr() as *mut _)
                    .unwrap_or(ptr::null_mut()),
            );
        }
    }

    #[cfg(feature = "v1_18")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_18")))]
    fn connect_samples_selected<
        F: Fn(
                &Self,
                &gst::Segment,
                Option<gst::ClockTime>,
                Option<gst::ClockTime>,
                Option<gst::ClockTime>,
                Option<&gst::StructureRef>,
            ) + Send
            + 'static,
    >(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn samples_selected_trampoline<
            P,
            F: Fn(
                    &P,
                    &gst::Segment,
                    Option<gst::ClockTime>,
                    Option<gst::ClockTime>,
                    Option<gst::ClockTime>,
                    Option<&gst::StructureRef>,
                ) + Send
                + 'static,
        >(
            this: *mut ffi::GstAggregator,
            segment: *mut gst::ffi::GstSegment,
            pts: gst::ffi::GstClockTime,
            dts: gst::ffi::GstClockTime,
            duration: gst::ffi::GstClockTime,
            info: *mut gst::ffi::GstStructure,
            f: glib::ffi::gpointer,
        ) where
            P: IsA<Aggregator>,
        {
            let f: &F = &*(f as *const F);
            f(
                Aggregator::from_glib_borrow(this).unsafe_cast_ref(),
                gst::Segment::from_glib_ptr_borrow(segment),
                from_glib(pts),
                from_glib(dts),
                from_glib(duration),
                if info.is_null() {
                    None
                } else {
                    Some(gst::StructureRef::from_glib_borrow(info))
                },
            )
        }

        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"samples-selected\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    samples_selected_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    fn src_pad(&self) -> &AggregatorPad {
        unsafe {
            let elt = &*(self.as_ptr() as *const ffi::GstAggregator);
            &*(&elt.srcpad as *const *mut gst::ffi::GstPad as *const AggregatorPad)
        }
    }
}

impl<O: IsA<Aggregator>> AggregatorExtManual for O {}

#[cfg(feature = "v1_16")]
#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
unsafe extern "C" fn notify_min_upstream_latency_trampoline<P, F: Fn(&P) + Send + Sync + 'static>(
    this: *mut ffi::GstAggregator,
    _param_spec: glib::ffi::gpointer,
    f: glib::ffi::gpointer,
) where
    P: IsA<Aggregator>,
{
    let f: &F = &*(f as *const F);
    f(Aggregator::from_glib_borrow(this).unsafe_cast_ref())
}