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