Skip to main content

gstreamer/subclass/
element.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{borrow::Cow, future::Future, sync::atomic};
4
5use glib::{subclass::prelude::*, translate::*};
6
7use super::prelude::*;
8use crate::{
9    Element, Event, PadTemplate, QueryRef, StateChange, StateChangeError, StateChangeReturn,
10    StateChangeSuccess, ffi, prelude::*,
11};
12
13#[derive(Debug, Clone)]
14pub struct ElementMetadata {
15    long_name: Cow<'static, str>,
16    classification: Cow<'static, str>,
17    description: Cow<'static, str>,
18    author: Cow<'static, str>,
19    additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
20}
21
22impl ElementMetadata {
23    pub fn new(long_name: &str, classification: &str, description: &str, author: &str) -> Self {
24        Self {
25            long_name: Cow::Owned(long_name.into()),
26            classification: Cow::Owned(classification.into()),
27            description: Cow::Owned(description.into()),
28            author: Cow::Owned(author.into()),
29            additional: Cow::Borrowed(&[]),
30        }
31    }
32
33    pub fn with_additional(
34        long_name: &str,
35        classification: &str,
36        description: &str,
37        author: &str,
38        additional: &[(&str, &str)],
39    ) -> Self {
40        Self {
41            long_name: Cow::Owned(long_name.into()),
42            classification: Cow::Owned(classification.into()),
43            description: Cow::Owned(description.into()),
44            author: Cow::Owned(author.into()),
45            additional: additional
46                .iter()
47                .copied()
48                .map(|(key, value)| (Cow::Owned(key.into()), Cow::Owned(value.into())))
49                .collect(),
50        }
51    }
52
53    pub const fn with_cow(
54        long_name: Cow<'static, str>,
55        classification: Cow<'static, str>,
56        description: Cow<'static, str>,
57        author: Cow<'static, str>,
58        additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
59    ) -> Self {
60        Self {
61            long_name,
62            classification,
63            description,
64            author,
65            additional,
66        }
67    }
68}
69
70pub trait ElementImpl: GstObjectImpl + ObjectSubclass<Type: IsA<Element>> {
71    fn metadata() -> Option<&'static ElementMetadata> {
72        None
73    }
74
75    fn pad_templates() -> &'static [PadTemplate] {
76        &[]
77    }
78
79    /// Perform `transition` on `element`.
80    ///
81    /// This function must be called with STATE_LOCK held and is mainly used
82    /// internally.
83    /// ## `transition`
84    /// the requested transition
85    ///
86    /// # Returns
87    ///
88    /// the [`StateChangeReturn`][crate::StateChangeReturn] of the state transition.
89    fn change_state(
90        &self,
91        transition: StateChange,
92    ) -> Result<StateChangeSuccess, StateChangeError> {
93        self.parent_change_state(transition)
94    }
95
96    /// Retrieves a request pad from the element according to the provided template.
97    /// Pad templates can be looked up using
98    /// [`ElementFactory::static_pad_templates()`][crate::ElementFactory::static_pad_templates()].
99    ///
100    /// The pad should be released with [`ElementExt::release_request_pad()`][crate::prelude::ElementExt::release_request_pad()].
101    /// ## `templ`
102    /// a [`PadTemplate`][crate::PadTemplate] of which we want a pad of.
103    /// ## `name`
104    /// the name of the request [`Pad`][crate::Pad]
105    /// to retrieve. Can be [`None`].
106    /// ## `caps`
107    /// the caps of the pad we want to
108    /// request. Can be [`None`].
109    ///
110    /// # Returns
111    ///
112    /// requested [`Pad`][crate::Pad] if found,
113    ///  otherwise [`None`]. Release after usage.
114    fn request_new_pad(
115        &self,
116        templ: &crate::PadTemplate,
117        name: Option<&str>,
118        caps: Option<&crate::Caps>,
119    ) -> Option<crate::Pad> {
120        self.parent_request_new_pad(templ, name, caps)
121    }
122
123    /// called when a request pad is to be released
124    fn release_pad(&self, pad: &crate::Pad) {
125        self.parent_release_pad(pad)
126    }
127
128    /// Sends an event to an element. If the element doesn't implement an
129    /// event handler, the event will be pushed on a random linked sink pad for
130    /// downstream events or a random linked source pad for upstream events.
131    ///
132    /// This function takes ownership of the provided event so you should
133    /// `gst_event_ref()` it if you want to reuse the event after this call.
134    ///
135    /// MT safe.
136    /// ## `event`
137    /// the [`Event`][crate::Event] to send to the element.
138    ///
139    /// # Returns
140    ///
141    /// [`true`] if the event was handled. Events that trigger a preroll (such
142    /// as flushing seeks and steps) will emit `GST_MESSAGE_ASYNC_DONE`.
143    fn send_event(&self, event: Event) -> bool {
144        self.parent_send_event(event)
145    }
146
147    /// Performs a query on the given element.
148    ///
149    /// For elements that don't implement a query handler, this function
150    /// forwards the query to a random srcpad or to the peer of a
151    /// random linked sinkpad of this element.
152    ///
153    /// Please note that some queries might need a running pipeline to work.
154    /// ## `query`
155    /// the [`Query`][crate::Query].
156    ///
157    /// # Returns
158    ///
159    /// [`true`] if the query could be performed.
160    ///
161    /// MT safe.
162    fn query(&self, query: &mut QueryRef) -> bool {
163        self.parent_query(query)
164    }
165
166    /// Sets the context of the element. Increases the refcount of the context.
167    ///
168    /// MT safe.
169    /// ## `context`
170    /// the [`Context`][crate::Context] to set.
171    fn set_context(&self, context: &crate::Context) {
172        self.parent_set_context(context)
173    }
174
175    /// Sets the clock for the element. This function increases the
176    /// refcount on the clock. Any previously set clock on the object
177    /// is unreffed.
178    /// ## `clock`
179    /// the [`Clock`][crate::Clock] to set for the element.
180    ///
181    /// # Returns
182    ///
183    /// [`true`] if the element accepted the clock. An element can refuse a
184    /// clock when it, for example, is not able to slave its internal clock to the
185    /// `clock` or when it requires a specific clock to operate.
186    ///
187    /// MT safe.
188    fn set_clock(&self, clock: Option<&crate::Clock>) -> bool {
189        self.parent_set_clock(clock)
190    }
191
192    /// Get the clock provided by the given element.
193    /// > An element is only required to provide a clock in the PAUSED
194    /// > state. Some elements can provide a clock in other states.
195    ///
196    /// # Returns
197    ///
198    /// the GstClock provided by the
199    /// element or [`None`] if no clock could be provided. Unref after usage.
200    ///
201    /// MT safe.
202    fn provide_clock(&self) -> Option<crate::Clock> {
203        self.parent_provide_clock()
204    }
205
206    /// Post a message on the element's [`Bus`][crate::Bus]. This function takes ownership of the
207    /// message; if you want to access the message after this call, you should add an
208    /// additional reference before calling.
209    /// ## `message`
210    /// a [`Message`][crate::Message] to post
211    ///
212    /// # Returns
213    ///
214    /// [`true`] if the message was successfully posted. The function returns
215    /// [`false`] if the element did not have a bus.
216    ///
217    /// MT safe.
218    fn post_message(&self, msg: crate::Message) -> bool {
219        self.parent_post_message(msg)
220    }
221}
222
223pub trait ElementImplExt: ElementImpl {
224    fn parent_change_state(
225        &self,
226        transition: StateChange,
227    ) -> Result<StateChangeSuccess, StateChangeError> {
228        unsafe {
229            let data = Self::type_data();
230            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
231
232            let f = (*parent_class)
233                .change_state
234                .expect("Missing parent function `change_state`");
235            try_from_glib(f(
236                self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
237                transition.into_glib(),
238            ))
239        }
240    }
241
242    fn parent_request_new_pad(
243        &self,
244        templ: &crate::PadTemplate,
245        name: Option<&str>,
246        caps: Option<&crate::Caps>,
247    ) -> Option<crate::Pad> {
248        unsafe {
249            let data = Self::type_data();
250            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
251
252            (*parent_class)
253                .request_new_pad
254                .map(|f| {
255                    from_glib_none(f(
256                        self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
257                        templ.to_glib_none().0,
258                        name.to_glib_none().0,
259                        caps.to_glib_none().0,
260                    ))
261                })
262                .unwrap_or(None)
263        }
264    }
265
266    fn parent_release_pad(&self, pad: &crate::Pad) {
267        unsafe {
268            let data = Self::type_data();
269            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
270
271            if let Some(f) = (*parent_class).release_pad {
272                f(
273                    self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
274                    pad.to_glib_none().0,
275                )
276            } else if self.obj().remove_pad(pad).is_err() {
277                crate::warning!(
278                    crate::CAT_RUST,
279                    imp = self,
280                    "Failed to remove pad {}",
281                    pad.name()
282                );
283            }
284        }
285    }
286
287    fn parent_send_event(&self, event: Event) -> bool {
288        unsafe {
289            let data = Self::type_data();
290            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
291
292            (*parent_class)
293                .send_event
294                .map(|f| {
295                    from_glib(f(
296                        self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
297                        event.into_glib_ptr(),
298                    ))
299                })
300                .unwrap_or(false)
301        }
302    }
303
304    fn parent_query(&self, query: &mut QueryRef) -> bool {
305        unsafe {
306            let data = Self::type_data();
307            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
308
309            (*parent_class)
310                .query
311                .map(|f| {
312                    from_glib(f(
313                        self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
314                        query.as_mut_ptr(),
315                    ))
316                })
317                .unwrap_or(false)
318        }
319    }
320
321    fn parent_set_context(&self, context: &crate::Context) {
322        unsafe {
323            let data = Self::type_data();
324            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
325
326            (*parent_class)
327                .set_context
328                .map(|f| {
329                    f(
330                        self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
331                        context.to_glib_none().0,
332                    )
333                })
334                .unwrap_or(())
335        }
336    }
337
338    fn parent_set_clock(&self, clock: Option<&crate::Clock>) -> bool {
339        unsafe {
340            let data = Self::type_data();
341            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
342
343            (*parent_class)
344                .set_clock
345                .map(|f| {
346                    from_glib(f(
347                        self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
348                        clock.to_glib_none().0,
349                    ))
350                })
351                .unwrap_or(false)
352        }
353    }
354
355    fn parent_provide_clock(&self) -> Option<crate::Clock> {
356        unsafe {
357            let data = Self::type_data();
358            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
359
360            (*parent_class)
361                .provide_clock
362                .map(|f| {
363                    from_glib_none(f(self.obj().unsafe_cast_ref::<Element>().to_glib_none().0))
364                })
365                .unwrap_or(None)
366        }
367    }
368
369    fn parent_post_message(&self, msg: crate::Message) -> bool {
370        unsafe {
371            let data = Self::type_data();
372            let parent_class = data.as_ref().parent_class() as *mut ffi::GstElementClass;
373
374            if let Some(f) = (*parent_class).post_message {
375                from_glib(f(
376                    self.obj().unsafe_cast_ref::<Element>().to_glib_none().0,
377                    msg.into_glib_ptr(),
378                ))
379            } else {
380                false
381            }
382        }
383    }
384
385    #[inline(never)]
386    fn panicked(&self) -> &atomic::AtomicBool {
387        #[cfg(panic = "abort")]
388        {
389            static DUMMY: atomic::AtomicBool = atomic::AtomicBool::new(false);
390            &DUMMY
391        }
392        #[cfg(not(panic = "abort"))]
393        {
394            self.instance_data::<atomic::AtomicBool>(crate::Element::static_type())
395                .expect("instance not initialized correctly")
396        }
397    }
398
399    fn catch_panic<R, F: FnOnce(&Self) -> R, G: FnOnce() -> R>(&self, fallback: G, f: F) -> R {
400        element_panic_to_error!(self, fallback(), { f(self) })
401    }
402
403    fn catch_panic_future<R, F: FnOnce() -> R, G: Future<Output = R>>(
404        &self,
405        fallback: F,
406        fut: G,
407    ) -> CatchPanic<Self, F, G> {
408        CatchPanic {
409            self_: self.ref_counted().downgrade(),
410            fallback: Some(fallback),
411            fut,
412        }
413    }
414
415    fn catch_panic_pad_function<R, F: FnOnce(&Self) -> R, G: FnOnce() -> R>(
416        parent: Option<&crate::Object>,
417        fallback: G,
418        f: F,
419    ) -> R {
420        let element = parent.unwrap().dynamic_cast_ref::<Self::Type>().unwrap();
421        let imp = element.imp();
422
423        element_panic_to_error!(imp, fallback(), { f(imp) })
424    }
425
426    fn post_error_message(&self, msg: crate::ErrorMessage) {
427        unsafe {
428            self.obj()
429                .unsafe_cast_ref::<Element>()
430                .post_error_message(msg)
431        }
432    }
433}
434
435impl<T: ElementImpl> ElementImplExt for T {}
436
437pin_project_lite::pin_project! {
438    #[must_use = "futures do nothing unless you `.await` or poll them"]
439    pub struct CatchPanic<T: glib::subclass::types::ObjectSubclass, F, G> {
440        self_: glib::subclass::ObjectImplWeakRef<T>,
441        fallback: Option<F>,
442        #[pin]
443        fut: G,
444    }
445}
446
447impl<R, T: ElementImpl, F: FnOnce() -> R, G: Future<Output = R>> Future for CatchPanic<T, F, G> {
448    type Output = R;
449
450    fn poll(
451        self: std::pin::Pin<&mut Self>,
452        cx: &mut std::task::Context<'_>,
453    ) -> std::task::Poll<Self::Output> {
454        let this = self.project();
455
456        let Some(self_) = this.self_.upgrade() else {
457            return std::task::Poll::Ready((this
458                .fallback
459                .take()
460                .expect("Future polled after resolving"))(
461            ));
462        };
463
464        element_panic_to_error!(
465            &*self_,
466            std::task::Poll::Ready(this.fallback.take().expect("Future polled after resolving")()),
467            {
468                let fut = this.fut;
469                fut.poll(cx)
470            }
471        )
472    }
473}
474
475unsafe impl<T: ElementImpl> IsSubclassable<T> for Element {
476    fn class_init(klass: &mut glib::Class<Self>) {
477        Self::parent_class_init::<T>(klass);
478        let klass = klass.as_mut();
479        klass.change_state = Some(element_change_state::<T>);
480        klass.request_new_pad = Some(element_request_new_pad::<T>);
481        klass.release_pad = Some(element_release_pad::<T>);
482        klass.send_event = Some(element_send_event::<T>);
483        klass.query = Some(element_query::<T>);
484        klass.set_context = Some(element_set_context::<T>);
485        klass.set_clock = Some(element_set_clock::<T>);
486        klass.provide_clock = Some(element_provide_clock::<T>);
487        klass.post_message = Some(element_post_message::<T>);
488
489        unsafe {
490            for pad_template in T::pad_templates() {
491                ffi::gst_element_class_add_pad_template(klass, pad_template.to_glib_none().0);
492            }
493
494            if let Some(metadata) = T::metadata() {
495                ffi::gst_element_class_set_metadata(
496                    klass,
497                    metadata.long_name.to_glib_none().0,
498                    metadata.classification.to_glib_none().0,
499                    metadata.description.to_glib_none().0,
500                    metadata.author.to_glib_none().0,
501                );
502
503                for (key, value) in &metadata.additional[..] {
504                    ffi::gst_element_class_add_metadata(
505                        klass,
506                        key.to_glib_none().0,
507                        value.to_glib_none().0,
508                    );
509                }
510            }
511        }
512    }
513
514    fn instance_init(instance: &mut glib::subclass::InitializingObject<T>) {
515        Self::parent_instance_init::<T>(instance);
516
517        #[cfg(not(panic = "abort"))]
518        instance.set_instance_data(Self::static_type(), atomic::AtomicBool::new(false));
519    }
520}
521
522unsafe extern "C" fn element_change_state<T: ElementImpl>(
523    ptr: *mut ffi::GstElement,
524    transition: ffi::GstStateChange,
525) -> ffi::GstStateChangeReturn {
526    unsafe {
527        let instance = &*(ptr as *mut T::Instance);
528        let imp = instance.imp();
529
530        // *Never* fail downwards state changes, this causes bugs in GStreamer
531        // and leads to crashes and deadlocks.
532        let transition = from_glib(transition);
533        let fallback = match transition {
534            StateChange::PlayingToPaused
535            | StateChange::PausedToReady
536            | StateChange::ReadyToNull => StateChangeReturn::Success,
537            _ => StateChangeReturn::Failure,
538        };
539
540        element_panic_to_error!(imp, fallback, {
541            StateChangeReturn::from(imp.change_state(transition))
542        })
543        .into_glib()
544    }
545}
546
547unsafe extern "C" fn element_request_new_pad<T: ElementImpl>(
548    ptr: *mut ffi::GstElement,
549    templ: *mut ffi::GstPadTemplate,
550    name: *const libc::c_char,
551    caps: *const ffi::GstCaps,
552) -> *mut ffi::GstPad {
553    unsafe {
554        let instance = &*(ptr as *mut T::Instance);
555        let imp = instance.imp();
556
557        let caps = Option::<crate::Caps>::from_glib_borrow(caps);
558        let name = Option::<String>::from_glib_none(name);
559
560        // XXX: This is effectively unsafe but the best we can do
561        // See https://bugzilla.gnome.org/show_bug.cgi?id=791193
562        let pad = element_panic_to_error!(imp, None, {
563            imp.request_new_pad(
564                &from_glib_borrow(templ),
565                name.as_deref(),
566                caps.as_ref().as_ref(),
567            )
568        });
569
570        // Ensure that the pad is owned by the element now, if a pad was returned
571        if let Some(ref pad) = pad {
572            assert_eq!(
573                pad.parent().as_ref(),
574                Some(&*crate::Object::from_glib_borrow(
575                    ptr as *mut ffi::GstObject
576                ))
577            );
578        }
579
580        pad.to_glib_none().0
581    }
582}
583
584unsafe extern "C" fn element_release_pad<T: ElementImpl>(
585    ptr: *mut ffi::GstElement,
586    pad: *mut ffi::GstPad,
587) {
588    unsafe {
589        let instance = &*(ptr as *mut T::Instance);
590        let imp = instance.imp();
591
592        // If we get a floating reference passed simply return here. It can't be stored inside this
593        // element, and if we continued to use it we would take ownership of this floating reference.
594        if glib::gobject_ffi::g_object_is_floating(pad as *mut glib::gobject_ffi::GObject)
595            != glib::ffi::GFALSE
596        {
597            return;
598        }
599
600        element_panic_to_error!(imp, (), { imp.release_pad(&from_glib_none(pad)) })
601    }
602}
603
604unsafe extern "C" fn element_send_event<T: ElementImpl>(
605    ptr: *mut ffi::GstElement,
606    event: *mut ffi::GstEvent,
607) -> glib::ffi::gboolean {
608    unsafe {
609        let instance = &*(ptr as *mut T::Instance);
610        let imp = instance.imp();
611
612        element_panic_to_error!(imp, false, { imp.send_event(from_glib_full(event)) }).into_glib()
613    }
614}
615
616unsafe extern "C" fn element_query<T: ElementImpl>(
617    ptr: *mut ffi::GstElement,
618    query: *mut ffi::GstQuery,
619) -> glib::ffi::gboolean {
620    unsafe {
621        let instance = &*(ptr as *mut T::Instance);
622        let imp = instance.imp();
623        let query = QueryRef::from_mut_ptr(query);
624
625        element_panic_to_error!(imp, false, { imp.query(query) }).into_glib()
626    }
627}
628
629unsafe extern "C" fn element_set_context<T: ElementImpl>(
630    ptr: *mut ffi::GstElement,
631    context: *mut ffi::GstContext,
632) {
633    unsafe {
634        let instance = &*(ptr as *mut T::Instance);
635        let imp = instance.imp();
636
637        element_panic_to_error!(imp, (), { imp.set_context(&from_glib_borrow(context)) })
638    }
639}
640
641unsafe extern "C" fn element_set_clock<T: ElementImpl>(
642    ptr: *mut ffi::GstElement,
643    clock: *mut ffi::GstClock,
644) -> glib::ffi::gboolean {
645    unsafe {
646        let instance = &*(ptr as *mut T::Instance);
647        let imp = instance.imp();
648
649        let clock = Option::<crate::Clock>::from_glib_borrow(clock);
650
651        element_panic_to_error!(imp, false, { imp.set_clock(clock.as_ref().as_ref()) }).into_glib()
652    }
653}
654
655unsafe extern "C" fn element_provide_clock<T: ElementImpl>(
656    ptr: *mut ffi::GstElement,
657) -> *mut ffi::GstClock {
658    unsafe {
659        let instance = &*(ptr as *mut T::Instance);
660        let imp = instance.imp();
661
662        element_panic_to_error!(imp, None, { imp.provide_clock() }).into_glib_ptr()
663    }
664}
665
666unsafe extern "C" fn element_post_message<T: ElementImpl>(
667    ptr: *mut ffi::GstElement,
668    msg: *mut ffi::GstMessage,
669) -> glib::ffi::gboolean {
670    unsafe {
671        let instance = &*(ptr as *mut T::Instance);
672        let imp = instance.imp();
673
674        // Can't catch panics here as posting the error message would cause
675        // this code to be called again recursively forever.
676        imp.post_message(from_glib_full(msg)).into_glib()
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use std::sync::{Arc, Mutex, OnceLock, atomic};
683
684    use super::*;
685    use crate::ElementFactory;
686
687    pub mod imp {
688        use super::*;
689
690        pub struct TestElement {
691            pub(super) srcpad: crate::Pad,
692            pub(super) sinkpad: crate::Pad,
693            pub(super) n_buffers: atomic::AtomicU32,
694            pub(super) reached_playing: atomic::AtomicBool,
695            pub(super) array: Arc<Mutex<Vec<String>>>,
696        }
697
698        impl TestElement {
699            fn sink_chain(
700                &self,
701                _pad: &crate::Pad,
702                buffer: crate::Buffer,
703            ) -> Result<crate::FlowSuccess, crate::FlowError> {
704                self.n_buffers.fetch_add(1, atomic::Ordering::SeqCst);
705                self.srcpad.push(buffer)
706            }
707
708            fn sink_event(&self, _pad: &crate::Pad, event: crate::Event) -> bool {
709                self.srcpad.push_event(event)
710            }
711
712            fn sink_query(&self, _pad: &crate::Pad, query: &mut crate::QueryRef) -> bool {
713                self.srcpad.peer_query(query)
714            }
715
716            fn src_event(&self, _pad: &crate::Pad, event: crate::Event) -> bool {
717                self.sinkpad.push_event(event)
718            }
719
720            fn src_query(&self, _pad: &crate::Pad, query: &mut crate::QueryRef) -> bool {
721                self.sinkpad.peer_query(query)
722            }
723        }
724
725        #[glib::object_subclass]
726        impl ObjectSubclass for TestElement {
727            const NAME: &'static str = "TestElement";
728            type Type = super::TestElement;
729            type ParentType = Element;
730
731            fn with_class(klass: &Self::Class) -> Self {
732                let templ = klass.pad_template("sink").unwrap();
733                let sinkpad = crate::Pad::builder_from_template(&templ)
734                    .chain_function(|pad, parent, buffer| {
735                        TestElement::catch_panic_pad_function(
736                            parent,
737                            || Err(crate::FlowError::Error),
738                            |identity| identity.sink_chain(pad, buffer),
739                        )
740                    })
741                    .event_function(|pad, parent, event| {
742                        TestElement::catch_panic_pad_function(
743                            parent,
744                            || false,
745                            |identity| identity.sink_event(pad, event),
746                        )
747                    })
748                    .query_function(|pad, parent, query| {
749                        TestElement::catch_panic_pad_function(
750                            parent,
751                            || false,
752                            |identity| identity.sink_query(pad, query),
753                        )
754                    })
755                    .build();
756
757                let templ = klass.pad_template("src").unwrap();
758                let srcpad = crate::Pad::builder_from_template(&templ)
759                    .event_function(|pad, parent, event| {
760                        TestElement::catch_panic_pad_function(
761                            parent,
762                            || false,
763                            |identity| identity.src_event(pad, event),
764                        )
765                    })
766                    .query_function(|pad, parent, query| {
767                        TestElement::catch_panic_pad_function(
768                            parent,
769                            || false,
770                            |identity| identity.src_query(pad, query),
771                        )
772                    })
773                    .build();
774
775                Self {
776                    n_buffers: atomic::AtomicU32::new(0),
777                    reached_playing: atomic::AtomicBool::new(false),
778                    array: Arc::new(Mutex::new(vec![
779                        "default0".to_string(),
780                        "default1".to_string(),
781                    ])),
782                    srcpad,
783                    sinkpad,
784                }
785            }
786        }
787
788        impl ObjectImpl for TestElement {
789            fn constructed(&self) {
790                self.parent_constructed();
791
792                let element = self.obj();
793                element.add_pad(&self.sinkpad).unwrap();
794                element.add_pad(&self.srcpad).unwrap();
795            }
796
797            fn properties() -> &'static [glib::ParamSpec] {
798                static PROPERTIES: OnceLock<Vec<glib::ParamSpec>> = OnceLock::new();
799                PROPERTIES.get_or_init(|| vec![crate::ParamSpecArray::builder("array").build()])
800            }
801
802            fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
803                match pspec.name() {
804                    "array" => {
805                        let value = value.get::<crate::Array>().unwrap();
806                        let mut array = self.array.lock().unwrap();
807                        array.clear();
808                        array.extend(value.iter().map(|v| v.get().unwrap()));
809                    }
810                    _ => unimplemented!(),
811                }
812            }
813
814            fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
815                match pspec.name() {
816                    "array" => crate::Array::new(&*self.array.lock().unwrap()).to_value(),
817                    _ => unimplemented!(),
818                }
819            }
820        }
821
822        impl GstObjectImpl for TestElement {}
823
824        impl ElementImpl for TestElement {
825            fn metadata() -> Option<&'static ElementMetadata> {
826                static ELEMENT_METADATA: std::sync::OnceLock<ElementMetadata> =
827                    std::sync::OnceLock::new();
828
829                Some(ELEMENT_METADATA.get_or_init(|| {
830                    ElementMetadata::new(
831                        "Test Element",
832                        "Generic",
833                        "Does nothing",
834                        "Sebastian Dröge <sebastian@centricular.com>",
835                    )
836                }))
837            }
838
839            fn pad_templates() -> &'static [PadTemplate] {
840                static PAD_TEMPLATES: std::sync::OnceLock<Vec<PadTemplate>> =
841                    std::sync::OnceLock::new();
842
843                PAD_TEMPLATES.get_or_init(|| {
844                    let caps = crate::Caps::new_any();
845                    vec![
846                        PadTemplate::new(
847                            "src",
848                            crate::PadDirection::Src,
849                            crate::PadPresence::Always,
850                            &caps,
851                        )
852                        .unwrap(),
853                        PadTemplate::new(
854                            "sink",
855                            crate::PadDirection::Sink,
856                            crate::PadPresence::Always,
857                            &caps,
858                        )
859                        .unwrap(),
860                    ]
861                })
862            }
863
864            fn change_state(
865                &self,
866                transition: crate::StateChange,
867            ) -> Result<crate::StateChangeSuccess, crate::StateChangeError> {
868                let res = self.parent_change_state(transition)?;
869
870                if transition == crate::StateChange::PausedToPlaying {
871                    self.reached_playing.store(true, atomic::Ordering::SeqCst);
872                }
873
874                Ok(res)
875            }
876        }
877    }
878
879    glib::wrapper! {
880        pub struct TestElement(ObjectSubclass<imp::TestElement>) @extends Element, crate::Object;
881    }
882
883    impl TestElement {
884        pub fn new(name: Option<&str>) -> Self {
885            glib::Object::builder().property("name", name).build()
886        }
887    }
888
889    fn plugin_init(plugin: &crate::Plugin) -> Result<(), glib::BoolError> {
890        crate::Element::register(
891            Some(plugin),
892            "testelement",
893            crate::Rank::MARGINAL,
894            TestElement::static_type(),
895        )
896    }
897
898    crate::plugin_define!(
899        rssubclasstestelem,
900        env!("CARGO_PKG_DESCRIPTION"),
901        plugin_init,
902        env!("CARGO_PKG_VERSION"),
903        "MPL-2.0",
904        env!("CARGO_PKG_NAME"),
905        env!("CARGO_PKG_NAME"),
906        env!("CARGO_PKG_REPOSITORY"),
907        "1970-01-01"
908    );
909
910    fn init() {
911        use std::sync::Once;
912        static INIT: Once = Once::new();
913
914        INIT.call_once(|| {
915            crate::init().unwrap();
916            plugin_register_static().expect("gstreamer subclass element test");
917        });
918    }
919
920    #[test]
921    fn test_element_subclass() {
922        init();
923
924        let element = TestElement::new(Some("test"));
925
926        assert_eq!(element.name(), "test");
927
928        assert_eq!(
929            element.metadata(crate::ELEMENT_METADATA_LONGNAME),
930            Some("Test Element")
931        );
932
933        let pipeline = crate::Pipeline::new();
934        let src = ElementFactory::make("fakesrc")
935            .property("num-buffers", 100i32)
936            .build()
937            .unwrap();
938        let sink = ElementFactory::make("fakesink").build().unwrap();
939
940        pipeline
941            .add_many([&src, element.upcast_ref(), &sink])
942            .unwrap();
943        Element::link_many([&src, element.upcast_ref(), &sink]).unwrap();
944
945        pipeline.set_state(crate::State::Playing).unwrap();
946        let bus = pipeline.bus().unwrap();
947
948        let eos = bus.timed_pop_filtered(crate::ClockTime::NONE, &[crate::MessageType::Eos]);
949        assert!(eos.is_some());
950
951        pipeline.set_state(crate::State::Null).unwrap();
952
953        let imp = element.imp();
954        assert_eq!(imp.n_buffers.load(atomic::Ordering::SeqCst), 100);
955        assert!(imp.reached_playing.load(atomic::Ordering::SeqCst));
956    }
957
958    #[test]
959    fn property_from_iter_if_not_empty() {
960        init();
961
962        let elem = crate::ElementFactory::make("testelement").build().unwrap();
963        assert!(
964            elem.property::<crate::Array>("array")
965                .iter()
966                .map(|val| val.get::<&str>().unwrap())
967                .eq(["default0", "default1"])
968        );
969
970        let elem = crate::ElementFactory::make("testelement")
971            .property_from_iter::<crate::Array, _>("array", ["value0", "value1"])
972            .build()
973            .unwrap();
974        assert!(
975            elem.property::<crate::Array>("array")
976                .iter()
977                .map(|val| val.get::<&str>().unwrap())
978                .eq(["value0", "value1"])
979        );
980
981        let array = Vec::<String>::new();
982        let elem = crate::ElementFactory::make("testelement")
983            .property_if_not_empty::<crate::Array, _>("array", &array)
984            .build()
985            .unwrap();
986        assert!(
987            elem.property::<crate::Array>("array")
988                .iter()
989                .map(|val| val.get::<&str>().unwrap())
990                .eq(["default0", "default1"])
991        );
992
993        let elem = crate::ElementFactory::make("testelement")
994            .property_if_not_empty::<crate::Array, _>("array", ["value0", "value1"])
995            .build()
996            .unwrap();
997        assert!(
998            elem.property::<crate::Array>("array")
999                .iter()
1000                .map(|val| val.get::<&str>().unwrap())
1001                .eq(["value0", "value1"])
1002        );
1003    }
1004}