From 570ea119bae8e8cd3fa9677b634c173b8f3db8cf Mon Sep 17 00:00:00 2001 From: Ivan Molodetskikh Date: Mon, 12 Jan 2026 21:33:09 +0300 Subject: [PATCH] Extract cast session/stream ID counters to global scope Add CastSessionId and CastStreamId newtypes. This lifts the atomic counters from the D-Bus mutter_screen_cast module to a shared location, preparing for adding screencopy cast tracking which will need the same ID types. --- src/dbus/mutter_screen_cast.rs | 36 ++++++++++++-------------- src/screencasting/mod.rs | 16 ++++++------ src/screencasting/pw_utils.rs | 30 +++++++++++----------- src/utils/mod.rs | 47 +++++++++++++++++++++++++++++++++- 4 files changed, 86 insertions(+), 43 deletions(-) diff --git a/src/dbus/mutter_screen_cast.rs b/src/dbus/mutter_screen_cast.rs index 1d07e05b..82591bd3 100644 --- a/src/dbus/mutter_screen_cast.rs +++ b/src/dbus/mutter_screen_cast.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; use std::mem; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use serde::Deserialize; @@ -11,6 +11,7 @@ use zbus::{fdo, interface, ObjectServer}; use super::Start; use crate::backend::IpcOutputMap; +use crate::utils::{CastSessionId, CastStreamId}; #[derive(Clone)] pub struct ScreenCast { @@ -22,7 +23,7 @@ pub struct ScreenCast { #[derive(Clone)] pub struct Session { - id: usize, + id: CastSessionId, ipc_outputs: Arc>, to_niri: calloop::channel::Sender, #[allow(clippy::type_complexity)] @@ -58,12 +59,10 @@ struct RecordWindowProperties { _is_recording: Option, } -static STREAM_ID: AtomicUsize = AtomicUsize::new(0); - #[derive(Clone)] pub struct Stream { - id: usize, - session_id: usize, + id: CastStreamId, + session_id: CastSessionId, target: StreamTarget, cursor_mode: CursorMode, was_started: Arc, @@ -94,14 +93,14 @@ struct StreamParameters { pub enum ScreenCastToNiri { StartCast { - session_id: usize, - stream_id: usize, + session_id: CastSessionId, + stream_id: CastStreamId, target: StreamTargetId, cursor_mode: CursorMode, signal_ctx: SignalEmitter<'static>, }, StopCast { - session_id: usize, + session_id: CastSessionId, }, } @@ -118,9 +117,8 @@ impl ScreenCast { )); } - static NUMBER: AtomicUsize = AtomicUsize::new(0); - let session_id = NUMBER.fetch_add(1, Ordering::SeqCst); - let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{session_id}"); + let session_id = CastSessionId::next(); + let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get()); let path = OwnedObjectPath::try_from(path).unwrap(); let session = Session::new(session_id, self.ipc_outputs.clone(), self.to_niri.clone()); @@ -207,8 +205,8 @@ impl Session { return Err(fdo::Error::Failed("monitor is disabled".to_owned())); } - let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst); - let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}"); + let stream_id = CastStreamId::next(); + let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get()); let path = OwnedObjectPath::try_from(path).unwrap(); let cursor_mode = properties.cursor_mode.unwrap_or_default(); @@ -244,8 +242,8 @@ impl Session { ) -> fdo::Result { debug!(?properties, "record_window"); - let stream_id = STREAM_ID.fetch_add(1, Ordering::SeqCst); - let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{stream_id}"); + let stream_id = CastStreamId::next(); + let path = format!("/org/gnome/Mutter/ScreenCast/Stream/u{}", stream_id.get()); let path = OwnedObjectPath::try_from(path).unwrap(); let cursor_mode = properties.cursor_mode.unwrap_or_default(); @@ -337,7 +335,7 @@ impl Start for ScreenCast { impl Session { pub fn new( - id: usize, + id: CastSessionId, ipc_outputs: Arc>, to_niri: calloop::channel::Sender, ) -> Self { @@ -361,8 +359,8 @@ impl Drop for Session { impl Stream { fn new( - id: usize, - session_id: usize, + id: CastStreamId, + session_id: CastSessionId, target: StreamTarget, cursor_mode: CursorMode, to_niri: calloop::channel::Sender, diff --git a/src/screencasting/mod.rs b/src/screencasting/mod.rs index 405c75e2..adadbc72 100644 --- a/src/screencasting/mod.rs +++ b/src/screencasting/mod.rs @@ -20,7 +20,7 @@ use crate::dbus::mutter_screen_cast::{self, CursorMode, ScreenCastToNiri, Stream use crate::niri::{CastTarget, Niri, OutputRenderElements, PointerRenderElements, State}; use crate::niri_render_elements; use crate::render_helpers::RenderTarget; -use crate::utils::get_monotonic_time; +use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId}; use crate::window::mapped::{MappedId, WindowCastRenderElements}; mod pw_utils; @@ -46,8 +46,8 @@ pub struct Screencasting { /// A screencast request that hasn't been started yet. pub struct PendingCast { - pub session_id: usize, - pub stream_id: usize, + pub session_id: CastSessionId, + pub stream_id: CastStreamId, pub cursor_mode: CursorMode, pub signal_ctx: SignalEmitter<'static>, } @@ -137,7 +137,7 @@ impl State { } } - fn redraw_cast(&mut self, stream_id: usize) { + fn redraw_cast(&mut self, stream_id: CastStreamId) { let _span = tracy_client::span!("State::redraw_cast"); let casts = &mut self.niri.casting.casts; @@ -391,7 +391,7 @@ impl State { signal_ctx, } => { let _span = tracy_client::span!("StartCast"); - let _span = debug_span!("StartCast", session_id, stream_id).entered(); + let _span = debug_span!("StartCast", %session_id, %stream_id).entered(); let (target, size, refresh, alpha) = match target { StreamTargetId::Output { name } => { @@ -694,9 +694,9 @@ impl Niri { } } - fn stop_cast(&mut self, session_id: usize) { + fn stop_cast(&mut self, session_id: CastSessionId) { let _span = tracy_client::span!("Niri::stop_cast"); - let _span = debug_span!("stop_cast", session_id).entered(); + let _span = debug_span!("stop_cast", %session_id).entered(); self.casting .pending_dynamic_casts @@ -716,7 +716,7 @@ impl Niri { let dbus = &self.dbus.as_ref().unwrap(); let server = dbus.conn_screen_cast.as_ref().unwrap().object_server(); - let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{session_id}"); + let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get()); if let Ok(iface) = server.interface::<_, mutter_screen_cast::Session>(path) { let _span = tracy_client::span!("invoking Session::stop"); diff --git a/src/screencasting/pw_utils.rs b/src/screencasting/pw_utils.rs index fd5f1a38..0dcaf014 100644 --- a/src/screencasting/pw_utils.rs +++ b/src/screencasting/pw_utils.rs @@ -55,7 +55,7 @@ use crate::render_helpers::{ clear_dmabuf, encompassing_geo, render_and_download, render_to_dmabuf, }; use crate::screencasting::CastRenderElement; -use crate::utils::get_monotonic_time; +use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId}; // Give a 0.1 ms allowance for presentation time errors. const CAST_DELAY_ALLOWANCE: Duration = Duration::from_micros(100); @@ -79,15 +79,15 @@ pub struct PipeWire { } pub enum PwToNiri { - StopCast { session_id: usize }, - Redraw { stream_id: usize }, + StopCast { session_id: CastSessionId }, + Redraw { stream_id: CastStreamId }, FatalError, } pub struct Cast { event_loop: LoopHandle<'static, State>, - pub session_id: usize, - pub stream_id: usize, + pub session_id: CastSessionId, + pub stream_id: CastStreamId, // Listener is dropped before Stream to prevent a use-after-free. _listener: StreamListener<()>, pub stream: StreamRc, @@ -269,8 +269,8 @@ impl PipeWire { &self, gbm: GbmDevice, formats: FormatSet, - session_id: usize, - stream_id: usize, + session_id: CastSessionId, + stream_id: CastStreamId, target: CastTarget, size: Size, refresh: u32, @@ -283,13 +283,13 @@ impl PipeWire { let to_niri_ = self.to_niri.clone(); let stop_cast = move || { if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) { - warn!(session_id, "error sending StopCast to niri: {err:?}"); + warn!(%session_id, "error sending StopCast to niri: {err:?}"); } }; let to_niri_ = self.to_niri.clone(); let redraw = move || { if let Err(err) = to_niri_.send(PwToNiri::Redraw { stream_id }) { - warn!(stream_id, "error sending Redraw to niri: {err:?}"); + warn!(%stream_id, "error sending Redraw to niri: {err:?}"); } }; let redraw_ = redraw.clone(); @@ -328,7 +328,7 @@ impl PipeWire { let inner = inner.clone(); let stop_cast = stop_cast.clone(); move |stream, (), old, new| { - let _span = debug_span!("state_changed", stream_id).entered(); + let _span = debug_span!("state_changed", %stream_id).entered(); debug!("{old:?} -> {new:?}"); let mut inner = inner.borrow_mut(); @@ -378,7 +378,7 @@ impl PipeWire { let formats = formats.clone(); move |stream, (), id, pod| { let id = ParamType::from_raw(id); - trace!(stream_id, ?id, "param_changed"); + trace!(%stream_id, ?id, "param_changed"); let mut inner = inner.borrow_mut(); let inner = &mut *inner; @@ -386,7 +386,7 @@ impl PipeWire { return; } - let _span = debug_span!("param_changed", stream_id).entered(); + let _span = debug_span!("param_changed", %stream_id).entered(); let Some(pod) = pod else { return }; @@ -678,7 +678,7 @@ impl PipeWire { let inner = inner.clone(); let stop_cast = stop_cast.clone(); move |stream, (), buffer| { - let _span = debug_span!("add_buffer", stream_id).entered(); + let _span = debug_span!("add_buffer", %stream_id).entered(); let mut inner = inner.borrow_mut(); let (size, alpha, modifier) = if let CastState::Ready { @@ -758,7 +758,7 @@ impl PipeWire { .remove_buffer({ let inner = inner.clone(); move |_stream, (), buffer| { - trace!(stream_id, "remove_buffer"); + trace!(%stream_id, "remove_buffer"); let mut inner = inner.borrow_mut(); inner @@ -779,7 +779,7 @@ impl PipeWire { .unwrap(); trace!( - stream_id, + %stream_id, "starting pw stream with size={pending_size:?}, refresh={refresh:?}" ); diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 4e15b644..d15628ce 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,12 +1,13 @@ use std::cmp::{max, min}; -use std::f64; use std::ffi::{CString, OsStr}; +use std::fmt::Display; use std::io::Write; use std::os::unix::prelude::OsStrExt; use std::path::{Path, PathBuf}; use std::ptr::null_mut; use std::sync::atomic::AtomicBool; use std::time::Duration; +use std::{f64, fmt}; use anyhow::{ensure, Context}; use bitflags::bitflags; @@ -44,6 +45,50 @@ pub mod xwayland; pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false); +use id::IdCounter; + +/// Unique ID for a screencast session. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CastSessionId(u64); + +impl CastSessionId { + pub fn next() -> Self { + static COUNTER: IdCounter = IdCounter::new(); + Self(COUNTER.next()) + } + + pub fn get(self) -> u64 { + self.0 + } +} + +impl Display for CastSessionId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Unique ID for a screencast stream. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CastStreamId(u64); + +impl CastStreamId { + pub fn next() -> Self { + static COUNTER: IdCounter = IdCounter::new(); + Self(COUNTER.next()) + } + + pub fn get(self) -> u64 { + self.0 + } +} + +impl Display for CastStreamId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ResizeEdge: u32 {