Skip to main content

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::{PromiseResult, Structure, StructureRef, ffi};
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            unsafe {
127                let user_data: &mut Option<F> = &mut *(user_data as *mut _);
128                let callback = user_data.take().unwrap();
129
130                let promise: Borrowed<Promise> = from_glib_borrow(promise);
131
132                let res = match promise.wait() {
133                    PromiseResult::Replied => Ok(promise.get_reply()),
134                    PromiseResult::Interrupted => Err(PromiseError::Interrupted),
135                    PromiseResult::Expired => Err(PromiseError::Expired),
136                    PromiseResult::Pending => {
137                        panic!("Promise resolved but returned Pending");
138                    }
139                    err => Err(PromiseError::Other(err)),
140                };
141
142                callback(res);
143            }
144        }
145
146        unsafe extern "C" fn free_user_data<
147            F: FnOnce(Result<Option<&StructureRef>, PromiseError>) + Send + 'static,
148        >(
149            user_data: glib::ffi::gpointer,
150        ) {
151            unsafe {
152                let _: Box<Option<F>> = Box::from_raw(user_data as *mut _);
153            }
154        }
155
156        unsafe {
157            from_glib_full(ffi::gst_promise_new_with_change_func(
158                Some(trampoline::<F>),
159                Box::into_raw(user_data) as *mut _,
160                Some(free_user_data::<F>),
161            ))
162        }
163    }
164
165    pub fn new_future() -> (Self, PromiseFuture) {
166        use futures_channel::oneshot;
167
168        // We only use the channel as a convenient waker
169        let (sender, receiver) = oneshot::channel();
170        let promise = Self::with_change_func(move |_res| {
171            let _ = sender.send(());
172        });
173
174        (promise.clone(), PromiseFuture(promise, receiver))
175    }
176
177    /// Expire a `self`. This will wake up any waiters with
178    /// [`PromiseResult::Expired`][crate::PromiseResult::Expired]. Called by a message loop when the parent
179    /// message is handled and/or destroyed (possibly unanswered).
180    #[doc(alias = "gst_promise_expire")]
181    pub fn expire(&self) {
182        unsafe {
183            ffi::gst_promise_expire(self.to_glib_none().0);
184        }
185    }
186
187    #[doc(alias = "gst_promise_get_reply")]
188    pub fn get_reply(&self) -> Option<&StructureRef> {
189        unsafe {
190            let s = ffi::gst_promise_get_reply(self.to_glib_none().0);
191            if s.is_null() {
192                None
193            } else {
194                Some(StructureRef::from_glib_borrow(s))
195            }
196        }
197    }
198
199    /// Interrupt waiting for a `self`. This will wake up any waiters with
200    /// [`PromiseResult::Interrupted`][crate::PromiseResult::Interrupted]. Called when the consumer does not want
201    /// the value produced anymore.
202    #[doc(alias = "gst_promise_interrupt")]
203    pub fn interrupt(&self) {
204        unsafe {
205            ffi::gst_promise_interrupt(self.to_glib_none().0);
206        }
207    }
208
209    /// Retrieve the reply set on `self`. `self` must be in
210    /// [`PromiseResult::Replied`][crate::PromiseResult::Replied] and the returned structure is owned by `self`
211    ///
212    /// # Returns
213    ///
214    /// The reply set on `self`
215    #[doc(alias = "gst_promise_reply")]
216    pub fn reply(&self, s: Option<Structure>) {
217        unsafe {
218            ffi::gst_promise_reply(
219                self.to_glib_none().0,
220                s.map(|s| s.into_glib_ptr()).unwrap_or(ptr::null_mut()),
221            );
222        }
223    }
224
225    /// Wait for `self` to move out of the [`PromiseResult::Pending`][crate::PromiseResult::Pending] state.
226    /// If `self` is not in [`PromiseResult::Pending`][crate::PromiseResult::Pending] then it will return
227    /// immediately with the current result.
228    ///
229    /// # Returns
230    ///
231    /// the result of the promise
232    #[doc(alias = "gst_promise_wait")]
233    pub fn wait(&self) -> PromiseResult {
234        unsafe { from_glib(ffi::gst_promise_wait(self.to_glib_none().0)) }
235    }
236}
237
238impl Default for Promise {
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244unsafe impl Send for Promise {}
245unsafe impl Sync for Promise {}
246
247#[derive(Debug)]
248pub struct PromiseFuture(Promise, futures_channel::oneshot::Receiver<()>);
249
250pub struct PromiseReply(Promise);
251
252impl std::future::Future for PromiseFuture {
253    type Output = Result<Option<PromiseReply>, PromiseError>;
254
255    fn poll(mut self: Pin<&mut Self>, context: &mut Context) -> Poll<Self::Output> {
256        match Pin::new(&mut self.1).poll(context) {
257            Poll::Ready(Err(_)) => panic!("Sender dropped before callback was called"),
258            Poll::Ready(Ok(())) => {
259                let res = match self.0.wait() {
260                    PromiseResult::Replied => {
261                        if self.0.get_reply().is_none() {
262                            Ok(None)
263                        } else {
264                            Ok(Some(PromiseReply(self.0.clone())))
265                        }
266                    }
267                    PromiseResult::Interrupted => Err(PromiseError::Interrupted),
268                    PromiseResult::Expired => Err(PromiseError::Expired),
269                    PromiseResult::Pending => {
270                        panic!("Promise resolved but returned Pending");
271                    }
272                    err => Err(PromiseError::Other(err)),
273                };
274                Poll::Ready(res)
275            }
276            Poll::Pending => Poll::Pending,
277        }
278    }
279}
280
281impl futures_core::future::FusedFuture for PromiseFuture {
282    fn is_terminated(&self) -> bool {
283        self.1.is_terminated()
284    }
285}
286
287impl Deref for PromiseReply {
288    type Target = StructureRef;
289
290    #[inline]
291    fn deref(&self) -> &StructureRef {
292        self.0.get_reply().expect("Promise without reply")
293    }
294}
295
296impl std::fmt::Debug for PromiseReply {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        let mut debug = f.debug_tuple("PromiseReply");
299
300        match self.0.get_reply() {
301            Some(reply) => debug.field(reply),
302            None => debug.field(&"<no reply>"),
303        }
304        .finish()
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use std::{sync::mpsc::channel, thread};
311
312    use super::*;
313
314    #[test]
315    fn test_change_func() {
316        crate::init().unwrap();
317
318        let (sender, receiver) = channel();
319        let promise = Promise::with_change_func(move |res| {
320            sender.send(res.map(|s| s.map(ToOwned::to_owned))).unwrap();
321        });
322
323        thread::spawn(move || {
324            promise.reply(Some(crate::Structure::new_empty("foo/bar")));
325        });
326
327        let res = receiver.recv().unwrap();
328        let res = res.expect("promise failed").expect("promise returned None");
329        assert_eq!(res.name(), "foo/bar");
330    }
331}