Skip to content

Commit 93979f6

Browse files
committed
loop: Add idle source.
1 parent 3226b84 commit 93979f6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

pipewire/src/loop_.rs

+47
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,49 @@ impl LoopRef {
161161
}
162162
}
163163

164+
/// Register a callback to be called whenever the loop is idle.
165+
///
166+
/// This can be enabled and disabled as needed with the `enabled` parameter,
167+
/// and also with the `enable` method on the returned source.
168+
#[must_use]
169+
pub fn add_idle<F>(&self, enabled: bool, callback: F) -> IdleSource
170+
where
171+
F: Fn() + 'static,
172+
{
173+
unsafe extern "C" fn call_closure<F>(data: *mut c_void)
174+
where
175+
F: Fn(),
176+
{
177+
let callback = (data as *mut F).as_ref().unwrap();
178+
callback();
179+
}
180+
181+
let data = Box::into_raw(Box::new(callback));
182+
183+
let (source, data) = unsafe {
184+
let mut iface = self.as_raw().utils.as_ref().unwrap().iface;
185+
186+
let source = spa_interface_call_method!(
187+
&mut iface as *mut spa_sys::spa_interface,
188+
spa_sys::spa_loop_utils_methods,
189+
add_idle,
190+
enabled,
191+
Some(call_closure::<F>),
192+
data as *mut _
193+
);
194+
195+
(source, Box::from_raw(data))
196+
};
197+
198+
let ptr = ptr::NonNull::new(source).expect("source is NULL");
199+
200+
IdleSource {
201+
ptr,
202+
loop_: self,
203+
_data: data,
204+
}
205+
}
206+
164207
/// Register a signal with a callback that is called when the signal is sent.
165208
///
166209
/// For example, this can be used to quit the loop when the process receives the `SIGTERM` signal.
@@ -415,6 +458,9 @@ where
415458
}
416459
}
417460

461+
/// A source that can be used to have a callback called when the loop is idle.
462+
///
463+
/// This source can be obtained by calling [`add_idle`](`LoopRef::add_idle`) on a loop, registering a callback to it.
418464
pub struct IdleSource<'l> {
419465
ptr: ptr::NonNull<spa_sys::spa_source>,
420466
loop_: &'l LoopRef,
@@ -423,6 +469,7 @@ pub struct IdleSource<'l> {
423469
}
424470

425471
impl<'l> IdleSource<'l> {
472+
/// Set the source as enabled or disabled, allowing or preventing the callback from being called.
426473
pub fn enable(&self, enable: bool) {
427474
unsafe {
428475
let mut iface = self.loop_.as_raw().utils.as_ref().unwrap().iface;

0 commit comments

Comments
 (0)