diff --git a/c_engine/portal_engine.c b/c_engine/portal_engine.c index 0126386..0c4cb6d 100644 --- a/c_engine/portal_engine.c +++ b/c_engine/portal_engine.c @@ -558,7 +558,7 @@ static int wait_for_first_frame(struct uu_portal *p) { while (!p->sequence && !p->error && !open_cancelled(p) && !(p->dma_requested && p->dma_bad)) { gint64 remaining = deadline - g_get_monotonic_time(); if (remaining <= 0) break; - clock_gettime(CLOCK_REALTIME, &until); + clock_gettime(CLOCK_MONOTONIC, &until); gint64 wait_us = MIN(100000, remaining); until.tv_nsec += wait_us * 1000; if (until.tv_nsec >= 1000000000) { until.tv_sec++; until.tv_nsec -= 1000000000; } @@ -616,7 +616,12 @@ static struct uu_portal *open_persist(const char *restore, void (*save_token)(co for (gchar **desktop = desktops; *desktop; desktop++) if (!g_ascii_strcasecmp(*desktop, "GNOME")) p->absolute_stream_pixels = 1; g_strfreev(desktops); - pthread_mutex_init(&p->lock, NULL); pthread_cond_init(&p->changed, NULL); + pthread_mutex_init(&p->lock, NULL); + pthread_condattr_t cond_attr; + pthread_condattr_init(&cond_attr); + pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC); + pthread_cond_init(&p->changed, &cond_attr); + pthread_condattr_destroy(&cond_attr); p->context = g_main_context_new(); g_main_context_push_thread_default(p->context); p->bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); if (!p->bus) { *error = 1; goto done; } @@ -832,6 +837,36 @@ int uu_portal_capture_alive(struct uu_portal *p) { pthread_mutex_unlock(&p->lock); return alive; } +int uu_portal_wait_frame(struct uu_portal *p, int64_t timeout_us) { + if (!p || atomic_load(&p->closed)) return -1; + pthread_mutex_lock(&p->lock); + if (p->error || atomic_load(&p->closed) || stream_stalled(p)) { + pthread_mutex_unlock(&p->lock); + return -1; + } + uint64_t prev_seq = p->sequence; + if (timeout_us <= 0) { + int ready = (p->sequence != prev_seq); + pthread_mutex_unlock(&p->lock); + return ready; + } + struct timespec until; + clock_gettime(CLOCK_MONOTONIC, &until); + until.tv_sec += timeout_us / 1000000LL; + until.tv_nsec += (long)(timeout_us % 1000000LL) * 1000L; + if (until.tv_nsec >= 1000000000L) { + until.tv_sec += 1; + until.tv_nsec -= 1000000000L; + } + while (p->sequence == prev_seq && !p->error && !atomic_load(&p->closed) && !stream_stalled(p)) { + int rc = pthread_cond_timedwait(&p->changed, &p->lock, &until); + if (rc != 0) break; // timeout or error + } + int res = (p->error || atomic_load(&p->closed) || stream_stalled(p)) ? -1 : + (p->sequence != prev_seq) ? 1 : 0; + pthread_mutex_unlock(&p->lock); + return res; +} void uu_portal_input_dispatch(struct uu_portal *p) { if (p->ei) portal_eis_dispatch(p); } diff --git a/c_engine/portal_engine.h b/c_engine/portal_engine.h index 3943e8c..186e760 100644 --- a/c_engine/portal_engine.h +++ b/c_engine/portal_engine.h @@ -25,6 +25,9 @@ int uu_portal_clipboard_set(struct uu_portal *portal, const uint8_t *text, size_ int uu_portal_clipboard_poll(struct uu_portal *portal, uint8_t *text, size_t capacity); int uu_portal_alive(struct uu_portal *portal); int uu_portal_capture_alive(struct uu_portal *portal); +/* Wait for a new frame or status change with a timeout in microseconds. + * Returns 1 if a new frame or status change occurred, 0 on timeout, <0 on closed/error. */ +int uu_portal_wait_frame(struct uu_portal *portal, int64_t timeout_us); void uu_portal_input_dispatch(struct uu_portal *portal); void uu_portal_logical_size(struct uu_portal *portal, uint32_t *width, uint32_t *height); void uu_portal_reset_frame(struct uu_portal *portal); diff --git a/src/inproc_encoder.rs b/src/inproc_encoder.rs index a2b5370..ad4c0ad 100644 --- a/src/inproc_encoder.rs +++ b/src/inproc_encoder.rs @@ -450,7 +450,18 @@ fn run_portal_vaapi( if dma_disabled { log::info!("Portal VAAPI DMA-BUF disabled by setting; pipeline=host-upload"); } loop { if stop.load(Ordering::Relaxed) || units.is_closed() { return Ok(()); } - std::thread::sleep(next_poll.saturating_duration_since(Instant::now()).min(Duration::from_millis(20))); + let wait_dur = next_poll.saturating_duration_since(Instant::now()); + if wait_dur > Duration::ZERO { + match portal.wait_frame(wait_dur) { + Ok(true) | Ok(false) => (), + Err(_) => { + // Frame wait failed or stream closed/stalled: back off to next_poll + // (preventing 100% core busy-spin) and allow existing recovery in with_dmabuf + // and capture_changed to handle lock/scaling without prematurely aborting the encoder. + std::thread::sleep(wait_dur); + } + } + } let now = Instant::now(); if now < next_poll { continue; } next_poll = (next_poll + interval).max(now); diff --git a/src/portal.rs b/src/portal.rs index 9dbc421..1852c61 100644 --- a/src/portal.rs +++ b/src/portal.rs @@ -35,7 +35,7 @@ mod permissions; #[cfg(all(target_os = "linux", feature = "portal"))] mod native { - use std::{ffi::c_void, ptr::NonNull, sync::{Mutex, MutexGuard, TryLockError}}; + use std::{ffi::c_void, ptr::NonNull, sync::{Arc, Mutex, MutexGuard, TryLockError}}; crate::engine_ffi! { crate::engine_plugin::Engine::Portal; fn uu_portal_open_persist(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void; fn uu_portal_open_virtual(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void; @@ -49,6 +49,7 @@ mod native { fn uu_portal_close(portal: *mut c_void); fn uu_portal_alive(portal: *mut c_void) -> i32; fn uu_portal_capture_alive(portal: *mut c_void) -> i32; + fn uu_portal_wait_frame(portal: *mut c_void, timeout_us: i64) -> i32; fn uu_portal_input_dispatch(portal: *mut c_void); fn uu_portal_reset_frame(portal: *mut c_void); fn uu_portal_capture_since(portal: *mut c_void, bgra: *mut u8, length: usize, revision: *mut u64) -> i32; @@ -68,9 +69,14 @@ mod native { } struct Handle(NonNull); fn pack(width: u32, height: u32) -> u64 { (u64::from(width) << 32) | u64::from(height) } - // The engine owns callback threads; public calls are serialized by Mutex. + // Calls are serialized by Session's mutex except wait_frame, whose C-side + // condition wait synchronizes with callbacks and input through the engine lock. unsafe impl Send for Handle {} + unsafe impl Sync for Handle {} impl Drop for Handle { fn drop(&mut self) { unsafe { uu_portal_close(self.0.as_ptr()) } } } + fn lease_handle(current: &Mutex>) -> Result, String> { + current.lock().map(|handle| Arc::clone(&handle)).map_err(|_| "Portal session lock poisoned".into()) + } fn blank_changed(frame: &mut [u8], version: &mut Option) -> bool { if *version == Some(super::FrameVersion(0, 0)) { return false; } super::blank(frame); *version = Some(super::FrameVersion(0, 0)); true @@ -112,7 +118,7 @@ mod native { was_locked.store(false, std::sync::atomic::Ordering::Release); } } - pub struct Session { handle: Mutex, locked: tokio::sync::watch::Receiver>, was_locked: std::sync::atomic::AtomicBool, recovery: Mutex, size: std::sync::atomic::AtomicU64, monitor: Mutex>, virtual_output: std::sync::atomic::AtomicBool } + pub struct Session { handle: Mutex>, locked: tokio::sync::watch::Receiver>, was_locked: std::sync::atomic::AtomicBool, recovery: Mutex, size: std::sync::atomic::AtomicU64, monitor: Mutex>, virtual_output: std::sync::atomic::AtomicBool } impl Session { fn take_lock_observation(&self) -> Result { // A recovery in progress must see the lock even if another capture @@ -260,7 +266,7 @@ mod native { if wanted.is_some() && granted != wanted { log::warn!("Portal granted a different monitor than requested"); } // Keep a freshly granted compositor frame regardless of lock state. Discarding it // before new damage can leave a static desktop permanently blank (#2). - Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), size: pack(width, height).into(), monitor: Mutex::new(granted), virtual_output: virtual_output.into() }) + Ok(Self { handle: Mutex::new(Arc::new(Handle(handle))), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), size: pack(width, height).into(), monitor: Mutex::new(granted), virtual_output: virtual_output.into() }) } /// Frame pixels of the monitor the stream currently follows. pub fn size(&self) -> (u32, u32) { @@ -524,6 +530,17 @@ mod native { pub fn clipboard_supported(&self) -> bool { self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_supported(handle.0.as_ptr()) != 0 }) } + pub fn wait_frame(&self, timeout: std::time::Duration) -> Result { + let handle = lease_handle(&self.handle)?; + // Retain sub-millisecond precision across the FFI boundary and clamp to 5s. + let us = (timeout.as_micros().min(5_000_000) as i64).max(1); + let ret = unsafe { uu_portal_wait_frame(handle.0.as_ptr(), us) }; + if ret < 0 { + Err("Portal stream closed or failed during frame wait".into()) + } else { + Ok(ret > 0) + } + } pub fn clipboard_ready(&self) -> bool { self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_ready(handle.0.as_ptr()) != 0 }) } @@ -601,7 +618,7 @@ mod native { fn new(physical: (u32, u32)) -> Self { let (_, locked) = tokio::sync::watch::channel(None); Self(ManuallyDrop::new(Session { - handle: Mutex::new(Handle(NonNull::dangling())), + handle: Mutex::new(Arc::new(Handle(NonNull::dangling()))), locked, was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), @@ -640,6 +657,35 @@ mod native { button_held: bool, retirement: Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>, } + #[test] + fn frame_wait_lease_keeps_replaced_handle_alive_without_blocking_input() { + use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::channel}; + struct Tracked(Arc); + impl Drop for Tracked { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } + let dropped = Arc::new(AtomicBool::new(false)); + let current = Arc::new(Mutex::new(Arc::new(Tracked(dropped.clone())))); + let (waiting, ready) = channel(); + let (resume, resumed) = channel(); + let worker = { + let current = current.clone(); + std::thread::spawn(move || { + let lease = lease_handle(¤t).unwrap(); + waiting.send(()).unwrap(); + resumed.recv_timeout(std::time::Duration::from_secs(3)).unwrap(); + assert!(!lease.0.load(Ordering::SeqCst)); + }) + }; + ready.recv_timeout(std::time::Duration::from_secs(3)).unwrap(); + let old = { + let mut guard = current.try_lock().expect("frame wait must not block input"); + std::mem::replace(&mut *guard, Arc::new(Tracked(Arc::new(AtomicBool::new(false))))) + }; + drop(old); + assert!(!dropped.load(Ordering::SeqCst)); + resume.send(()).unwrap(); + worker.join().unwrap(); + assert!(dropped.load(Ordering::SeqCst)); + } impl Drop for TestHandle { fn drop(&mut self) { if let Some((entered, resume)) = self.retirement.take() { @@ -896,6 +942,7 @@ impl PortalSession { pub fn capture(&self, _: &mut [u8]) -> Result<(), String> { Err(error(15)) } pub fn capture_changed(&self, _: &mut [u8], _: &mut Option) -> Result { Err(error(15)) } pub fn disable_dmabuf(&self) {} + pub fn wait_frame(&self, _: std::time::Duration) -> Result { Err(error(15)) } pub fn with_dmabuf(&self, _: &mut Option, _: impl FnOnce(&DmaFrame, bool) -> Result) -> Result, String> { Ok(DmaCapture::Unavailable(-1)) }