now safer

This commit is contained in:
Erica Z 2024-11-03 15:06:11 +01:00
parent 225292d08a
commit e4083288e6
2 changed files with 18 additions and 3 deletions

View file

@ -13,6 +13,8 @@ pub struct Handle {
inner: NonNull<ffi::mpv_handle>, inner: NonNull<ffi::mpv_handle>,
wakeup: Pin<Box<Event>>, // the wakeup callback holds a pointer to this wakeup: Pin<Box<Event>>, // the wakeup callback holds a pointer to this
wait_event_cell: RefCell<()>, wait_event_cell: RefCell<()>,
pending_hooks: RefCell<Vec<u64>>,
} }
// The client API is generally fully thread-safe, unless otherwise noted. // The client API is generally fully thread-safe, unless otherwise noted.
@ -67,6 +69,8 @@ impl Handle {
inner, inner,
wakeup, wakeup,
wait_event_cell: RefCell::new(()), wait_event_cell: RefCell::new(()),
pending_hooks: RefCell::new(vec![]),
} }
} }
@ -141,6 +145,18 @@ impl Handle {
Error::from_return_code(unsafe { ffi::mpv_hook_continue(self.inner.as_ptr(), id) }) Error::from_return_code(unsafe { ffi::mpv_hook_continue(self.inner.as_ptr(), id) })
} }
pub fn continue_hook(&self, id: u64) -> Result<(), Error> {
let mut pending_hooks = self.pending_hooks.borrow_mut();
for (i, pending_id) in pending_hooks.iter().enumerate() {
if *pending_id == id {
pending_hooks.swap_remove(i);
return unsafe { self.continue_hook_unchecked(id) };
}
}
panic!("invalid hook id")
}
// should take listener before we drain the event queue, so we don't miss any notifications // should take listener before we drain the event queue, so we don't miss any notifications
pub fn wakeup_listener(&self) -> EventListener { pub fn wakeup_listener(&self) -> EventListener {
self.wakeup.listen() self.wakeup.listen()
@ -219,6 +235,7 @@ impl Handle {
ffi::mpv_event_id_MPV_EVENT_HOOK => { ffi::mpv_event_id_MPV_EVENT_HOOK => {
let data = unsafe { &*(event.data as *mut ffi::mpv_event_hook) }; let data = unsafe { &*(event.data as *mut ffi::mpv_event_hook) };
self.pending_hooks.borrow_mut().push(data.id);
Some(MpvEvent::Hook(HookEvent { Some(MpvEvent::Hook(HookEvent {
reply_userdata: event.reply_userdata, reply_userdata: event.reply_userdata,
name: unsafe { CStr::from_ptr(data.name) } name: unsafe { CStr::from_ptr(data.name) }

View file

@ -179,9 +179,7 @@ where
assert_eq!(&event.name, "on_before_start_file"); assert_eq!(&event.name, "on_before_start_file");
// just use this as a barrier // just use this as a barrier
println!("on_before_start_file triggered"); println!("on_before_start_file triggered");
unsafe { self.mpv.continue_hook(event.id).unwrap();
self.mpv.continue_hook_unchecked(event.id).unwrap();
}
} }
_ => unreachable!(), _ => unreachable!(),