gstreamer/
promise.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{
4    ops::Deref,
5    pin::Pin,
6    ptr,
7    task::{Context, Poll},
8};
9
10use glib::translate::*;
11
12use crate::{ffi, PromiseResult, Structure, StructureRef};
13
14glib::wrapper! {
15    /// The [`Promise`][crate::Promise] object implements the container for values that may
16    /// be available later. i.e. a Future or a Promise in
17    /// <https://en.wikipedia.org/wiki/Futures_and_promises>.
18    /// As with all Future/Promise-like functionality, there is the concept of the
19    /// producer of the value and the consumer of the value.
20    ///
21    /// A [`Promise`][crate::Promise] is created with [`new()`][Self::new()] by the consumer and passed
22    /// to the producer to avoid thread safety issues with the change callback.
23    /// A [`Promise`][crate::Promise] can be replied to with a value (or an error) by the producer
24    /// with [`reply()`][Self::reply()]. The exact value returned is defined by the API
25    /// contract of the producer and [`None`] may be a valid reply.
26    /// [`interrupt()`][Self::interrupt()] is for the consumer to
27    /// indicate to the producer that the value is not needed anymore and producing
28    /// that value can stop. The [`PromiseResult::Expired`][crate::PromiseResult::Expired] state set by a call
29    /// to [`expire()`][Self::expire()] indicates to the consumer that a value will never
30    /// be produced and is intended to be called by a third party that implements
31    /// some notion of message handling such as [`Bus`][crate::Bus].
32    /// A callback can also be installed at [`Promise`][crate::Promise] creation for
33    /// result changes with [`with_change_func()`][Self::with_change_func()].
34    /// The change callback can be used to chain `GstPromises`'s together as in the
35    /// following example.
36    ///
37    ///
38    /// **⚠️ The following code is in C ⚠️**
39    ///
40    /// ```C
41    /// const GstStructure *reply;
42    /// GstPromise *p;
43    /// if (gst_promise_wait (promise) != GST_PROMISE_RESULT_REPLIED)
44    ///   return; // interrupted or expired value
45    /// reply = gst_promise_get_reply (promise);
46    /// if (error in reply)
47    ///   return; // propagate error
48    /// p = gst_promise_new_with_change_func (another_promise_change_func, user_data, notify);
49    /// pass p to promise-using API
50    /// ```
51    ///
52    /// Each [`Promise`][crate::Promise] starts out with a [`PromiseResult`][crate::PromiseResult] of
53    /// [`PromiseResult::Pending`][crate::PromiseResult::Pending] and only ever transitions once
54    /// into one of the other [`PromiseResult`][crate::PromiseResult]'s.
55    ///
56    /// In order to support multi-threaded code, [`reply()`][Self::reply()],
57    /// [`interrupt()`][Self::interrupt()] and [`expire()`][Self::expire()] may all be from
58    /// different threads with some restrictions and the final result of the promise
59    /// is whichever call is made first. There are two restrictions on ordering:
60    ///
61    /// 1. That [`reply()`][Self::reply()] and [`interrupt()`][Self::interrupt()] cannot be called
62    /// after [`expire()`][Self::expire()]
63    /// 2. That [`reply()`][Self::reply()] and [`interrupt()`][Self::interrupt()]
64    /// cannot be called twice.
65    ///
66    /// The change function set with [`with_change_func()`][Self::with_change_func()] is
67    /// called directly from either the [`reply()`][Self::reply()],
68    /// [`interrupt()`][Self::interrupt()] or [`expire()`][Self::expire()] and can be called
69    /// from an arbitrary thread. [`Promise`][crate::Promise] using APIs can restrict this to
70    /// a single thread or a subset of threads but that is entirely up to the API
71    /// that uses [`Promise`][crate::Promise].
72    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
73    #[doc(alias = "GstPromise")]
74    pub struct Promise(Shared<ffi::GstPromise>);
75
76    match fn {
77        ref => |ptr| ffi::gst_mini_object_ref(ptr as *mut _),
78        unref => |ptr| ffi::gst_mini_object_unref(ptr as *mut _),
79        type_ => || ffi::gst_promise_get_type(),
80    }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
84pub enum PromiseError {
85    Interrupted,
86    Expired,
87    Other(PromiseResult),
88}
89
90impl Promise {
91    ///
92    /// # Returns
93    ///
94    /// a new [`Promise`][crate::Promise]
95    #[doc(alias = "gst_promise_new")]
96    pub fn new() -> Promise {
97        assert_initialized_main_thread!();
98        unsafe { from_glib_full(ffi::gst_promise_new()) }
99    }
100
101    /// `func` will be called exactly once when transitioning out of
102    /// [`PromiseResult::Pending`][crate::PromiseResult::Pending] into any of the other [`PromiseResult`][crate::PromiseResult]
103    /// states.
104    /// ## `func`
105    /// a `GstPromiseChangeFunc` to call
106    /// ## `notify`
107    /// notification function that `user_data` is no longer needed
108    ///
109    /// # Returns
110    ///
111    /// a new [`Promise`][crate::Promise]
112    #[doc(alias = "gst_promise_new_with_change_func")]
113    pub fn with_change_func<F>(func: F) -> Promise
114    where
115        F: FnOnce(Result<Option<&StructureRef>, PromiseError>) + Send + 'static,
116    {
117        assert_initialized_main_thread!();
118        let user_data: Box<Option<F>> = Box::new(Some(func));
119
120        unsafe extern "C" fn trampoline<
121            F: FnOnce(Result<Option<&StructureRef>, PromiseError>) + Send + 'static,
122        >(
123            promise: *mut ffi::GstPromise,
124            user_data: glib::ffi::gpointer,
125        ) {
126            let user_data: &mut Option<F> = &mut *(user_data as *mut _);
127            let callback = user_data.take().unwrap();
128
129            let promise: Borrowed<Promise> = from_glib_borrow(promise);
130
131            let res = match promise.wait() {
132                PromiseResult::Replied => Ok(promise.get_reply()),
133                PromiseResult::Interrupted => Err(PromiseError::Interrupted),
134                PromiseResult::Expired => Err(PromiseError::Expired),
135                PromiseResult::Pending => {
136                    panic!("Promise resolved but returned Pending");
137                }
138                err => Err(PromiseError::Other(err)),
139            };
140
141            callback(res);
142        }
143
144        unsafe extern "C" fn free_user_data<
145            F: FnOnce(Result<Option<&StructureRef>, PromiseError>) + Send + 'static,
146        >(
147            user_data: glib::ffi::gpointer,
148        ) {
149            let _: Box<Option<F>> = Box::from_raw(user_data as *mut _);
150        }
151
152        unsafe {
153            from_glib_full(ffi::gst_promise_new_with_change_func(
154                Some(trampoline::<F>),
155                Box::into_raw(user_data) as *mut _,
156                Some(free_user_data::<F>),
157            ))
158        }
159    }
160
161    pub fn new_future() -> (Self, PromiseFuture) {
162        use futures_channel::oneshot;
163
164        // We only use the channel as a convenient waker
165        let (sender, receiver) = oneshot::channel();
166        let promise = Self::with_change_func(move |_res| {
167            let _ = sender.send(());
168        });
169
170        (promise.clone(), PromiseFuture(promise, receiver))
171    }
172
173    /// Expire a `self`. This will wake up any waiters with
174    /// [`PromiseResult::Expired`][crate::PromiseResult::Expired]. Called by a message loop when the parent
175    /// message is handled and/or destroyed (possibly unanswered).
176    #[doc(alias = "gst_promise_expire")]
177    pub fn expire(&self) {
178        unsafe {
179            ffi::gst_promise_expire(self.to_glib_none().0);
180        }
181    }
182
183    #[doc(alias = "gst_promise_get_reply")]
184    pub fn get_reply(&self) -> Option<&StructureRef> {
185        unsafe {
186            let s = ffi::gst_promise_get_reply(self.to_glib_none().0);
187            if s.is_null() {
188                None
189            } else {
190                Some(StructureRef::from_glib_borrow(s))
191            }
192        }
193    }
194
195    /// Interrupt waiting for a `self`. This will wake up any waiters with
196    /// [`PromiseResult::Interrupted`][crate::PromiseResult::Interrupted]. Called when the consumer does not want
197    /// the value produced anymore.
198    #[doc(alias = "gst_promise_interrupt")]
199    pub fn interrupt(&self) {
200        unsafe {
201            ffi::gst_promise_interrupt(self.to_glib_none().0);
202        }
203    }
204
205    /// Retrieve the reply set on `self`. `self` must be in
206    /// [`PromiseResult::Replied`][crate::PromiseResult::Replied] and the returned structure is owned by `self`
207    ///
208    /// # Returns
209    ///
210    /// The reply set on `self`
211    #[doc(alias = "gst_promise_reply")]
212    pub fn reply(&self, s: Option<Structure>) {
213        unsafe {
214            ffi::gst_promise_reply(
215                self.to_glib_none().0,
216                s.map(|s| s.into_glib_ptr()).unwrap_or(ptr::null_mut()),
217            );
218        }
219    }
220
221    /// Wait for `self` to move out of the [`PromiseResult::Pending`][crate::PromiseResult::Pending] state.
222    /// If `self` is not in [`PromiseResult::Pending`][crate::PromiseResult::Pending] then it will return
223    /// immediately with the current result.
224    ///
225    /// # Returns
226    ///
227    /// the result of the promise
228    #[doc(alias = "gst_promise_wait")]
229    pub fn wait(&self) -> PromiseResult {
230        unsafe { from_glib(ffi::gst_promise_wait(self.to_glib_none().0)) }
231    }
232}
233
234impl Default for Promise {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240unsafe impl Send for Promise {}
241unsafe impl Sync for Promise {}
242
243#[derive(Debug)]
244pub struct PromiseFuture(Promise, futures_channel::oneshot::Receiver<()>);
245
246pub struct PromiseReply(Promise);
247
248impl std::future::Future for PromiseFuture {
249    type Output = Result<Option<PromiseReply>, PromiseError>;
250
251    fn poll(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Self::Output> {
252        match Pin::new(&mut self.1).poll(context) {
253            Poll::Ready(Err(_)) => panic!("Sender dropped before callback was called"),
254            Poll::Ready(Ok(())) => {
255                let res = match self.0.wait() {
256                    PromiseResult::Replied => {
257                        if self.0.get_reply().is_none() {
258                            Ok(None)
259                        } else {
260                            Ok(Some(PromiseReply(self.0.clone())))
261                        }
262                    }
263                    PromiseResult::Interrupted => Err(PromiseError::Interrupted),
264                    PromiseResult::Expired => Err(PromiseError::Expired),
265                    PromiseResult::Pending => {
266                        panic!("Promise resolved but returned Pending");
267                    }
268                    err => Err(PromiseError::Other(err)),
269                };
270                Poll::Ready(res)
271            }
272            Poll::Pending => Poll::Pending,
273        }
274    }
275}
276
277impl futures_core::future::FusedFuture for PromiseFuture {
278    fn is_terminated(&self) -> bool {
279        self.1.is_terminated()
280    }
281}
282
283impl Deref for PromiseReply {
284    type Target = StructureRef;
285
286    #[inline]
287    fn deref(&self) -> &StructureRef {
288        self.0.get_reply().expect("Promise without reply")
289    }
290}
291
292impl std::fmt::Debug for PromiseReply {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        let mut debug = f.debug_tuple("PromiseReply");
295
296        match self.0.get_reply() {
297            Some(reply) => debug.field(reply),
298            None => debug.field(&"<no reply>"),
299        }
300        .finish()
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use std::{sync::mpsc::channel, thread};
307
308    use super::*;
309
310    #[test]
311    fn test_change_func() {
312        crate::init().unwrap();
313
314        let (sender, receiver) = channel();
315        let promise = Promise::with_change_func(move |res| {
316            sender.send(res.map(|s| s.map(ToOwned::to_owned))).unwrap();
317        });
318
319        thread::spawn(move || {
320            promise.reply(Some(crate::Structure::new_empty("foo/bar")));
321        });
322
323        let res = receiver.recv().unwrap();
324        let res = res.expect("promise failed").expect("promise returned None");
325        assert_eq!(res.name(), "foo/bar");
326    }
327}