gstreamer_app/
app_src.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{
4    mem, panic,
5    pin::Pin,
6    ptr,
7    sync::{Arc, Mutex},
8    task::{Context, Poll, Waker},
9};
10
11#[cfg(not(panic = "abort"))]
12use std::sync::atomic::{AtomicBool, Ordering};
13
14use futures_sink::Sink;
15use glib::{
16    ffi::{gboolean, gpointer},
17    prelude::*,
18    translate::*,
19};
20
21use crate::{ffi, AppSrc};
22
23#[allow(clippy::type_complexity)]
24pub struct AppSrcCallbacks {
25    need_data: Option<Box<dyn FnMut(&AppSrc, u32) + Send + 'static>>,
26    enough_data: Option<Box<dyn Fn(&AppSrc) + Send + Sync + 'static>>,
27    seek_data: Option<Box<dyn Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>>,
28    #[cfg(not(panic = "abort"))]
29    panicked: AtomicBool,
30    callbacks: ffi::GstAppSrcCallbacks,
31}
32
33unsafe impl Send for AppSrcCallbacks {}
34unsafe impl Sync for AppSrcCallbacks {}
35
36impl AppSrcCallbacks {
37    pub fn builder() -> AppSrcCallbacksBuilder {
38        skip_assert_initialized!();
39
40        AppSrcCallbacksBuilder {
41            need_data: None,
42            enough_data: None,
43            seek_data: None,
44        }
45    }
46}
47
48#[allow(clippy::type_complexity)]
49#[must_use = "The builder must be built to be used"]
50pub struct AppSrcCallbacksBuilder {
51    need_data: Option<Box<dyn FnMut(&AppSrc, u32) + Send + 'static>>,
52    enough_data: Option<Box<dyn Fn(&AppSrc) + Send + Sync + 'static>>,
53    seek_data: Option<Box<dyn Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>>,
54}
55
56impl AppSrcCallbacksBuilder {
57    pub fn need_data<F: FnMut(&AppSrc, u32) + Send + 'static>(self, need_data: F) -> Self {
58        Self {
59            need_data: Some(Box::new(need_data)),
60            ..self
61        }
62    }
63
64    pub fn need_data_if<F: FnMut(&AppSrc, u32) + Send + 'static>(
65        self,
66        need_data: F,
67        predicate: bool,
68    ) -> Self {
69        if predicate {
70            self.need_data(need_data)
71        } else {
72            self
73        }
74    }
75
76    pub fn need_data_if_some<F: FnMut(&AppSrc, u32) + Send + 'static>(
77        self,
78        need_data: Option<F>,
79    ) -> Self {
80        if let Some(need_data) = need_data {
81            self.need_data(need_data)
82        } else {
83            self
84        }
85    }
86
87    pub fn enough_data<F: Fn(&AppSrc) + Send + Sync + 'static>(self, enough_data: F) -> Self {
88        Self {
89            enough_data: Some(Box::new(enough_data)),
90            ..self
91        }
92    }
93
94    pub fn enough_data_if<F: Fn(&AppSrc) + Send + Sync + 'static>(
95        self,
96        enough_data: F,
97        predicate: bool,
98    ) -> Self {
99        if predicate {
100            self.enough_data(enough_data)
101        } else {
102            self
103        }
104    }
105
106    pub fn enough_data_if_some<F: Fn(&AppSrc) + Send + Sync + 'static>(
107        self,
108        enough_data: Option<F>,
109    ) -> Self {
110        if let Some(enough_data) = enough_data {
111            self.enough_data(enough_data)
112        } else {
113            self
114        }
115    }
116
117    pub fn seek_data<F: Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>(
118        self,
119        seek_data: F,
120    ) -> Self {
121        Self {
122            seek_data: Some(Box::new(seek_data)),
123            ..self
124        }
125    }
126
127    pub fn seek_data_if<F: Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>(
128        self,
129        seek_data: F,
130        predicate: bool,
131    ) -> Self {
132        if predicate {
133            self.seek_data(seek_data)
134        } else {
135            self
136        }
137    }
138
139    pub fn seek_data_if_some<F: Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>(
140        self,
141        seek_data: Option<F>,
142    ) -> Self {
143        if let Some(seek_data) = seek_data {
144            self.seek_data(seek_data)
145        } else {
146            self
147        }
148    }
149
150    #[must_use = "Building the callbacks without using them has no effect"]
151    pub fn build(self) -> AppSrcCallbacks {
152        let have_need_data = self.need_data.is_some();
153        let have_enough_data = self.enough_data.is_some();
154        let have_seek_data = self.seek_data.is_some();
155
156        AppSrcCallbacks {
157            need_data: self.need_data,
158            enough_data: self.enough_data,
159            seek_data: self.seek_data,
160            #[cfg(not(panic = "abort"))]
161            panicked: AtomicBool::new(false),
162            callbacks: ffi::GstAppSrcCallbacks {
163                need_data: if have_need_data {
164                    Some(trampoline_need_data)
165                } else {
166                    None
167                },
168                enough_data: if have_enough_data {
169                    Some(trampoline_enough_data)
170                } else {
171                    None
172                },
173                seek_data: if have_seek_data {
174                    Some(trampoline_seek_data)
175                } else {
176                    None
177                },
178                _gst_reserved: [
179                    ptr::null_mut(),
180                    ptr::null_mut(),
181                    ptr::null_mut(),
182                    ptr::null_mut(),
183                ],
184            },
185        }
186    }
187}
188
189unsafe extern "C" fn trampoline_need_data(
190    appsrc: *mut ffi::GstAppSrc,
191    length: u32,
192    callbacks: gpointer,
193) {
194    let callbacks = callbacks as *mut AppSrcCallbacks;
195    let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
196
197    #[cfg(not(panic = "abort"))]
198    if (*callbacks).panicked.load(Ordering::Relaxed) {
199        let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
200        gst::subclass::post_panic_error_message(element.upcast_ref(), element.upcast_ref(), None);
201        return;
202    }
203
204    if let Some(ref mut need_data) = (*callbacks).need_data {
205        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| need_data(&element, length)));
206        match result {
207            Ok(result) => result,
208            Err(err) => {
209                #[cfg(panic = "abort")]
210                {
211                    unreachable!("{err:?}");
212                }
213                #[cfg(not(panic = "abort"))]
214                {
215                    (*callbacks).panicked.store(true, Ordering::Relaxed);
216                    gst::subclass::post_panic_error_message(
217                        element.upcast_ref(),
218                        element.upcast_ref(),
219                        Some(err),
220                    );
221                }
222            }
223        }
224    }
225}
226
227unsafe extern "C" fn trampoline_enough_data(appsrc: *mut ffi::GstAppSrc, callbacks: gpointer) {
228    let callbacks = callbacks as *const AppSrcCallbacks;
229    let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
230
231    #[cfg(not(panic = "abort"))]
232    if (*callbacks).panicked.load(Ordering::Relaxed) {
233        let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
234        gst::subclass::post_panic_error_message(element.upcast_ref(), element.upcast_ref(), None);
235        return;
236    }
237
238    if let Some(ref enough_data) = (*callbacks).enough_data {
239        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| enough_data(&element)));
240        match result {
241            Ok(result) => result,
242            Err(err) => {
243                #[cfg(panic = "abort")]
244                {
245                    unreachable!("{err:?}");
246                }
247                #[cfg(not(panic = "abort"))]
248                {
249                    (*callbacks).panicked.store(true, Ordering::Relaxed);
250                    gst::subclass::post_panic_error_message(
251                        element.upcast_ref(),
252                        element.upcast_ref(),
253                        Some(err),
254                    );
255                }
256            }
257        }
258    }
259}
260
261unsafe extern "C" fn trampoline_seek_data(
262    appsrc: *mut ffi::GstAppSrc,
263    offset: u64,
264    callbacks: gpointer,
265) -> gboolean {
266    let callbacks = callbacks as *const AppSrcCallbacks;
267    let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
268
269    #[cfg(not(panic = "abort"))]
270    if (*callbacks).panicked.load(Ordering::Relaxed) {
271        let element: Borrowed<AppSrc> = from_glib_borrow(appsrc);
272        gst::subclass::post_panic_error_message(element.upcast_ref(), element.upcast_ref(), None);
273        return false.into_glib();
274    }
275
276    let ret = if let Some(ref seek_data) = (*callbacks).seek_data {
277        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| seek_data(&element, offset)));
278        match result {
279            Ok(result) => result,
280            Err(err) => {
281                #[cfg(panic = "abort")]
282                {
283                    unreachable!("{err:?}");
284                }
285                #[cfg(not(panic = "abort"))]
286                {
287                    (*callbacks).panicked.store(true, Ordering::Relaxed);
288                    gst::subclass::post_panic_error_message(
289                        element.upcast_ref(),
290                        element.upcast_ref(),
291                        Some(err),
292                    );
293
294                    false
295                }
296            }
297        }
298    } else {
299        false
300    };
301
302    ret.into_glib()
303}
304
305unsafe extern "C" fn destroy_callbacks(ptr: gpointer) {
306    let _ = Box::<AppSrcCallbacks>::from_raw(ptr as *mut _);
307}
308
309impl AppSrc {
310    // rustdoc-stripper-ignore-next
311    /// Creates a new builder-pattern struct instance to construct [`AppSrc`] objects.
312    ///
313    /// This method returns an instance of [`AppSrcBuilder`](crate::builders::AppSrcBuilder) which can be used to create [`AppSrc`] objects.
314    pub fn builder<'a>() -> AppSrcBuilder<'a> {
315        assert_initialized_main_thread!();
316        AppSrcBuilder {
317            builder: gst::Object::builder(),
318            callbacks: None,
319            automatic_eos: None,
320        }
321    }
322
323    /// Set callbacks which will be executed when data is needed, enough data has
324    /// been collected or when a seek should be performed.
325    /// This is an alternative to using the signals, it has lower overhead and is thus
326    /// less expensive, but also less flexible.
327    ///
328    /// If callbacks are installed, no signals will be emitted for performance
329    /// reasons.
330    ///
331    /// Before 1.16.3 it was not possible to change the callbacks in a thread-safe
332    /// way.
333    /// ## `callbacks`
334    /// the callbacks
335    /// ## `notify`
336    /// a destroy notify function
337    #[doc(alias = "gst_app_src_set_callbacks")]
338    pub fn set_callbacks(&self, callbacks: AppSrcCallbacks) {
339        unsafe {
340            let src = self.to_glib_none().0;
341            #[cfg(not(feature = "v1_18"))]
342            {
343                static SET_ONCE_QUARK: std::sync::OnceLock<glib::Quark> =
344                    std::sync::OnceLock::new();
345
346                let set_once_quark = SET_ONCE_QUARK
347                    .get_or_init(|| glib::Quark::from_str("gstreamer-rs-app-src-callbacks"));
348
349                // This is not thread-safe before 1.16.3, see
350                // https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/merge_requests/570
351                if gst::version() < (1, 16, 3, 0) {
352                    if !glib::gobject_ffi::g_object_get_qdata(
353                        src as *mut _,
354                        set_once_quark.into_glib(),
355                    )
356                    .is_null()
357                    {
358                        panic!("AppSrc callbacks can only be set once");
359                    }
360
361                    glib::gobject_ffi::g_object_set_qdata(
362                        src as *mut _,
363                        set_once_quark.into_glib(),
364                        1 as *mut _,
365                    );
366                }
367            }
368
369            ffi::gst_app_src_set_callbacks(
370                src,
371                mut_override(&callbacks.callbacks),
372                Box::into_raw(Box::new(callbacks)) as *mut _,
373                Some(destroy_callbacks),
374            );
375        }
376    }
377
378    /// Configure the `min` and `max` latency in `src`. If `min` is set to -1, the
379    /// default latency calculations for pseudo-live sources will be used.
380    /// ## `min`
381    /// the min latency
382    /// ## `max`
383    /// the max latency
384    #[doc(alias = "gst_app_src_set_latency")]
385    pub fn set_latency(
386        &self,
387        min: impl Into<Option<gst::ClockTime>>,
388        max: impl Into<Option<gst::ClockTime>>,
389    ) {
390        unsafe {
391            ffi::gst_app_src_set_latency(
392                self.to_glib_none().0,
393                min.into().into_glib(),
394                max.into().into_glib(),
395            );
396        }
397    }
398
399    /// Retrieve the min and max latencies in `min` and `max` respectively.
400    ///
401    /// # Returns
402    ///
403    ///
404    /// ## `min`
405    /// the min latency
406    ///
407    /// ## `max`
408    /// the max latency
409    #[doc(alias = "get_latency")]
410    #[doc(alias = "gst_app_src_get_latency")]
411    pub fn latency(&self) -> (Option<gst::ClockTime>, Option<gst::ClockTime>) {
412        unsafe {
413            let mut min = mem::MaybeUninit::uninit();
414            let mut max = mem::MaybeUninit::uninit();
415            ffi::gst_app_src_get_latency(self.to_glib_none().0, min.as_mut_ptr(), max.as_mut_ptr());
416            (from_glib(min.assume_init()), from_glib(max.assume_init()))
417        }
418    }
419
420    #[doc(alias = "do-timestamp")]
421    #[doc(alias = "gst_base_src_set_do_timestamp")]
422    pub fn set_do_timestamp(&self, timestamp: bool) {
423        unsafe {
424            gst_base::ffi::gst_base_src_set_do_timestamp(
425                self.as_ptr() as *mut gst_base::ffi::GstBaseSrc,
426                timestamp.into_glib(),
427            );
428        }
429    }
430
431    #[doc(alias = "do-timestamp")]
432    #[doc(alias = "gst_base_src_get_do_timestamp")]
433    pub fn do_timestamp(&self) -> bool {
434        unsafe {
435            from_glib(gst_base::ffi::gst_base_src_get_do_timestamp(
436                self.as_ptr() as *mut gst_base::ffi::GstBaseSrc
437            ))
438        }
439    }
440
441    #[doc(alias = "do-timestamp")]
442    pub fn connect_do_timestamp_notify<F: Fn(&Self) + Send + Sync + 'static>(
443        &self,
444        f: F,
445    ) -> glib::SignalHandlerId {
446        unsafe extern "C" fn notify_do_timestamp_trampoline<
447            F: Fn(&AppSrc) + Send + Sync + 'static,
448        >(
449            this: *mut ffi::GstAppSrc,
450            _param_spec: glib::ffi::gpointer,
451            f: glib::ffi::gpointer,
452        ) {
453            let f: &F = &*(f as *const F);
454            f(&AppSrc::from_glib_borrow(this))
455        }
456        unsafe {
457            let f: Box<F> = Box::new(f);
458            glib::signal::connect_raw(
459                self.as_ptr() as *mut _,
460                b"notify::do-timestamp\0".as_ptr() as *const _,
461                Some(mem::transmute::<*const (), unsafe extern "C" fn()>(
462                    notify_do_timestamp_trampoline::<F> as *const (),
463                )),
464                Box::into_raw(f),
465            )
466        }
467    }
468
469    #[doc(alias = "set-automatic-eos")]
470    #[doc(alias = "gst_base_src_set_automatic_eos")]
471    pub fn set_automatic_eos(&self, automatic_eos: bool) {
472        unsafe {
473            gst_base::ffi::gst_base_src_set_automatic_eos(
474                self.as_ptr() as *mut gst_base::ffi::GstBaseSrc,
475                automatic_eos.into_glib(),
476            );
477        }
478    }
479
480    pub fn sink(&self) -> AppSrcSink {
481        AppSrcSink::new(self)
482    }
483}
484
485// rustdoc-stripper-ignore-next
486/// A [builder-pattern] type to construct [`AppSrc`] objects.
487///
488/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
489#[must_use = "The builder must be built to be used"]
490pub struct AppSrcBuilder<'a> {
491    builder: gst::gobject::GObjectBuilder<'a, AppSrc>,
492    callbacks: Option<AppSrcCallbacks>,
493    automatic_eos: Option<bool>,
494}
495
496impl<'a> AppSrcBuilder<'a> {
497    // rustdoc-stripper-ignore-next
498    /// Build the [`AppSrc`].
499    ///
500    /// # Panics
501    ///
502    /// This panics if the [`AppSrc`] doesn't have all the given properties or
503    /// property values of the wrong type are provided.
504    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
505    pub fn build(self) -> AppSrc {
506        let appsrc = self.builder.build().unwrap();
507
508        if let Some(callbacks) = self.callbacks {
509            appsrc.set_callbacks(callbacks);
510        }
511
512        if let Some(automatic_eos) = self.automatic_eos {
513            appsrc.set_automatic_eos(automatic_eos);
514        }
515
516        appsrc
517    }
518
519    pub fn automatic_eos(self, automatic_eos: bool) -> Self {
520        Self {
521            automatic_eos: Some(automatic_eos),
522            ..self
523        }
524    }
525
526    pub fn block(self, block: bool) -> Self {
527        Self {
528            builder: self.builder.property("block", block),
529            ..self
530        }
531    }
532
533    pub fn callbacks(self, callbacks: AppSrcCallbacks) -> Self {
534        Self {
535            callbacks: Some(callbacks),
536            ..self
537        }
538    }
539
540    pub fn caps(self, caps: &'a gst::Caps) -> Self {
541        Self {
542            builder: self.builder.property("caps", caps),
543            ..self
544        }
545    }
546
547    pub fn do_timestamp(self, do_timestamp: bool) -> Self {
548        Self {
549            builder: self.builder.property("do-timestamp", do_timestamp),
550            ..self
551        }
552    }
553
554    pub fn duration(self, duration: u64) -> Self {
555        Self {
556            builder: self.builder.property("duration", duration),
557            ..self
558        }
559    }
560
561    pub fn format(self, format: gst::Format) -> Self {
562        Self {
563            builder: self.builder.property("format", format),
564            ..self
565        }
566    }
567
568    #[cfg(feature = "v1_18")]
569    #[cfg_attr(docsrs, doc(cfg(feature = "v1_18")))]
570    pub fn handle_segment_change(self, handle_segment_change: bool) -> Self {
571        Self {
572            builder: self
573                .builder
574                .property("handle-segment-change", handle_segment_change),
575            ..self
576        }
577    }
578
579    pub fn is_live(self, is_live: bool) -> Self {
580        Self {
581            builder: self.builder.property("is-live", is_live),
582            ..self
583        }
584    }
585
586    #[cfg(feature = "v1_20")]
587    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
588    pub fn leaky_type(self, leaky_type: crate::AppLeakyType) -> Self {
589        Self {
590            builder: self.builder.property("leaky-type", leaky_type),
591            ..self
592        }
593    }
594
595    #[cfg(feature = "v1_20")]
596    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
597    pub fn max_buffers(self, max_buffers: u64) -> Self {
598        Self {
599            builder: self.builder.property("max-buffers", max_buffers),
600            ..self
601        }
602    }
603
604    pub fn max_bytes(self, max_bytes: u64) -> Self {
605        Self {
606            builder: self.builder.property("max-bytes", max_bytes),
607            ..self
608        }
609    }
610
611    pub fn max_latency(self, max_latency: i64) -> Self {
612        Self {
613            builder: self.builder.property("max-latency", max_latency),
614            ..self
615        }
616    }
617
618    #[cfg(feature = "v1_20")]
619    #[cfg_attr(docsrs, doc(cfg(feature = "v1_20")))]
620    pub fn max_time(self, max_time: Option<gst::ClockTime>) -> Self {
621        Self {
622            builder: self.builder.property("max-time", max_time),
623            ..self
624        }
625    }
626
627    pub fn min_latency(self, min_latency: i64) -> Self {
628        Self {
629            builder: self.builder.property("min-latency", min_latency),
630            ..self
631        }
632    }
633
634    pub fn min_percent(self, min_percent: u32) -> Self {
635        Self {
636            builder: self.builder.property("min-percent", min_percent),
637            ..self
638        }
639    }
640
641    pub fn size(self, size: i64) -> Self {
642        Self {
643            builder: self.builder.property("size", size),
644            ..self
645        }
646    }
647
648    pub fn stream_type(self, stream_type: crate::AppStreamType) -> Self {
649        Self {
650            builder: self.builder.property("stream-type", stream_type),
651            ..self
652        }
653    }
654
655    // rustdoc-stripper-ignore-next
656    /// Sets property `name` to the given value `value`.
657    ///
658    /// Overrides any default or previously defined value for `name`.
659    #[inline]
660    pub fn property(self, name: &'a str, value: impl Into<glib::Value> + 'a) -> Self {
661        Self {
662            builder: self.builder.property(name, value),
663            ..self
664        }
665    }
666
667    // rustdoc-stripper-ignore-next
668    /// Sets property `name` to the given string value `value`.
669    #[inline]
670    pub fn property_from_str(self, name: &'a str, value: &'a str) -> Self {
671        Self {
672            builder: self.builder.property_from_str(name, value),
673            ..self
674        }
675    }
676
677    gst::impl_builder_gvalue_extra_setters!(property_and_name);
678}
679
680#[derive(Debug)]
681pub struct AppSrcSink {
682    app_src: glib::WeakRef<AppSrc>,
683    waker_reference: Arc<Mutex<Option<Waker>>>,
684}
685
686impl AppSrcSink {
687    fn new(app_src: &AppSrc) -> Self {
688        skip_assert_initialized!();
689
690        let waker_reference = Arc::new(Mutex::new(None as Option<Waker>));
691
692        app_src.set_callbacks(
693            AppSrcCallbacks::builder()
694                .need_data({
695                    let waker_reference = Arc::clone(&waker_reference);
696
697                    move |_, _| {
698                        if let Some(waker) = waker_reference.lock().unwrap().take() {
699                            waker.wake();
700                        }
701                    }
702                })
703                .build(),
704        );
705
706        Self {
707            app_src: app_src.downgrade(),
708            waker_reference,
709        }
710    }
711}
712
713impl Drop for AppSrcSink {
714    fn drop(&mut self) {
715        #[cfg(not(feature = "v1_18"))]
716        {
717            // This is not thread-safe before 1.16.3, see
718            // https://gitlab.freedesktop.org/gstreamer/gst-plugins-base/merge_requests/570
719            if gst::version() >= (1, 16, 3, 0) {
720                if let Some(app_src) = self.app_src.upgrade() {
721                    app_src.set_callbacks(AppSrcCallbacks::builder().build());
722                }
723            }
724        }
725    }
726}
727
728impl Sink<gst::Sample> for AppSrcSink {
729    type Error = gst::FlowError;
730
731    fn poll_ready(self: Pin<&mut Self>, context: &mut Context) -> Poll<Result<(), Self::Error>> {
732        let mut waker = self.waker_reference.lock().unwrap();
733
734        let Some(app_src) = self.app_src.upgrade() else {
735            return Poll::Ready(Err(gst::FlowError::Eos));
736        };
737
738        let current_level_bytes = app_src.current_level_bytes();
739        let max_bytes = app_src.max_bytes();
740
741        if current_level_bytes >= max_bytes && max_bytes != 0 {
742            waker.replace(context.waker().to_owned());
743
744            Poll::Pending
745        } else {
746            Poll::Ready(Ok(()))
747        }
748    }
749
750    fn start_send(self: Pin<&mut Self>, sample: gst::Sample) -> Result<(), Self::Error> {
751        let Some(app_src) = self.app_src.upgrade() else {
752            return Err(gst::FlowError::Eos);
753        };
754
755        app_src.push_sample(&sample)?;
756
757        Ok(())
758    }
759
760    fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), Self::Error>> {
761        Poll::Ready(Ok(()))
762    }
763
764    fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), Self::Error>> {
765        let Some(app_src) = self.app_src.upgrade() else {
766            return Poll::Ready(Ok(()));
767        };
768
769        app_src.end_of_stream()?;
770
771        Poll::Ready(Ok(()))
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use std::sync::atomic::{AtomicUsize, Ordering};
778
779    use futures_util::{sink::SinkExt, stream::StreamExt};
780    use gst::prelude::*;
781
782    use super::*;
783
784    #[test]
785    fn test_app_src_sink() {
786        gst::init().unwrap();
787
788        let appsrc = gst::ElementFactory::make("appsrc").build().unwrap();
789        let fakesink = gst::ElementFactory::make("fakesink")
790            .property("signal-handoffs", true)
791            .build()
792            .unwrap();
793
794        let pipeline = gst::Pipeline::new();
795        pipeline.add(&appsrc).unwrap();
796        pipeline.add(&fakesink).unwrap();
797
798        appsrc.link(&fakesink).unwrap();
799
800        let mut bus_stream = pipeline.bus().unwrap().stream();
801        let mut app_src_sink = appsrc.dynamic_cast::<AppSrc>().unwrap().sink();
802
803        let sample_quantity = 5;
804
805        let samples = (0..sample_quantity)
806            .map(|_| gst::Sample::builder().buffer(&gst::Buffer::new()).build())
807            .collect::<Vec<gst::Sample>>();
808
809        let mut sample_stream = futures_util::stream::iter(samples).map(Ok);
810
811        let handoff_count_reference = Arc::new(AtomicUsize::new(0));
812
813        fakesink.connect("handoff", false, {
814            let handoff_count_reference = Arc::clone(&handoff_count_reference);
815
816            move |_| {
817                handoff_count_reference.fetch_add(1, Ordering::AcqRel);
818
819                None
820            }
821        });
822
823        pipeline.set_state(gst::State::Playing).unwrap();
824
825        futures_executor::block_on(app_src_sink.send_all(&mut sample_stream)).unwrap();
826        futures_executor::block_on(app_src_sink.close()).unwrap();
827
828        while let Some(message) = futures_executor::block_on(bus_stream.next()) {
829            match message.view() {
830                gst::MessageView::Eos(_) => break,
831                gst::MessageView::Error(_) => unreachable!(),
832                _ => continue,
833            }
834        }
835
836        pipeline.set_state(gst::State::Null).unwrap();
837
838        assert_eq!(
839            handoff_count_reference.load(Ordering::Acquire),
840            sample_quantity
841        );
842    }
843
844    #[test]
845    fn builder_caps_lt() {
846        gst::init().unwrap();
847
848        let caps = &gst::Caps::new_any();
849        {
850            let stream_type = "random-access".to_owned();
851            let appsrc = AppSrc::builder()
852                .property_from_str("stream-type", &stream_type)
853                .caps(caps)
854                .build();
855            assert_eq!(
856                appsrc.property::<crate::AppStreamType>("stream-type"),
857                crate::AppStreamType::RandomAccess
858            );
859            assert!(appsrc.property::<gst::Caps>("caps").is_any());
860        }
861
862        let stream_type = &"random-access".to_owned();
863        {
864            let caps = &gst::Caps::new_any();
865            let appsrc = AppSrc::builder()
866                .property_from_str("stream-type", stream_type)
867                .caps(caps)
868                .build();
869            assert_eq!(
870                appsrc.property::<crate::AppStreamType>("stream-type"),
871                crate::AppStreamType::RandomAccess
872            );
873            assert!(appsrc.property::<gst::Caps>("caps").is_any());
874        }
875    }
876}