Implement initial window screencasting
Browse files at this commitdc92d80b9f8de761df2aa0bfc90b61d53b9c0831Parent: 0757ad06 changed files +685 -139
- src/dbus/mod.rs +1 -4
- src/dbus/mutter_screen_cast.rs +96 -16
- src/handlers/compositor.rs +9 -0
- src/handlers/xdg_shell.rs +6 -0
- src/niri.rs +351 -79
- src/pw_utils.rs +222 -40
src/dbus/mod.rsmodified+1 -4
| @@ -87,11 +87,8 @@ impl DBusServers { | |||
| 87 | let (to_niri, from_screen_cast) = calloop::channel::channel(); | 87 | let (to_niri, from_screen_cast) = calloop::channel::channel(); |
| 88 | niri.event_loop | 88 | niri.event_loop |
| 89 | .insert_source(from_screen_cast, { | 89 | .insert_source(from_screen_cast, { |
| 90 | - let to_niri = to_niri.clone(); | ||
| 91 | move |event, _, state| match event { | 90 | move |event, _, state| match event { |
| 92 | - calloop::channel::Event::Msg(msg) => { | 91 | + calloop::channel::Event::Msg(msg) => state.on_screen_cast_msg(msg), |
| 93 | - state.on_screen_cast_msg(&to_niri, msg) | ||
| 94 | - } | ||
| 95 | calloop::channel::Event::Closed => (), | 92 | calloop::channel::Event::Closed => (), |
| 96 | } | 93 | } |
| 97 | }) | 94 | }) |
src/dbus/mutter_screen_cast.rsmodified+96 -16
| @@ -4,7 +4,6 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; | |||
| 4 | use std::sync::{Arc, Mutex}; | 4 | use std::sync::{Arc, Mutex}; |
| 5 | 5 | ||
| 6 | use serde::Deserialize; | 6 | use serde::Deserialize; |
| 7 | -use smithay::output::Output; | ||
| 8 | use zbus::fdo::RequestNameFlags; | 7 | use zbus::fdo::RequestNameFlags; |
| 9 | use zbus::zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type, Value}; | 8 | use zbus::zvariant::{DeserializeDict, OwnedObjectPath, SerializeDict, Type, Value}; |
| 10 | use zbus::{dbus_interface, fdo, InterfaceRef, ObjectServer, SignalContext}; | 9 | use zbus::{dbus_interface, fdo, InterfaceRef, ObjectServer, SignalContext}; |
| @@ -47,15 +46,40 @@ struct RecordMonitorProperties { | |||
| 47 | _is_recording: Option<bool>, | 46 | _is_recording: Option<bool>, |
| 48 | } | 47 | } |
| 49 | 48 | ||
| 49 | +#[derive(Debug, DeserializeDict, Type)] | ||
| 50 | +#[zvariant(signature = "dict")] | ||
| 51 | +struct RecordWindowProperties { | ||
| 52 | + #[zvariant(rename = "window-id")] | ||
| 53 | + window_id: u64, | ||
| 54 | + #[zvariant(rename = "cursor-mode")] | ||
| 55 | + cursor_mode: Option<CursorMode>, | ||
| 56 | + #[zvariant(rename = "is-recording")] | ||
| 57 | + _is_recording: Option<bool>, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +static STREAM_ID: AtomicUsize = AtomicUsize::new(0); | ||
| 61 | + | ||
| 50 | #[derive(Clone)] | 62 | #[derive(Clone)] |
| 51 | pub struct Stream { | 63 | pub struct Stream { |
| 52 | - // FIXME: update on scale changes and whatnot. | 64 | + target: StreamTarget, |
| 53 | - output: niri_ipc::Output, | ||
| 54 | cursor_mode: CursorMode, | 65 | cursor_mode: CursorMode, |
| 55 | was_started: Arc<AtomicBool>, | 66 | was_started: Arc<AtomicBool>, |
| 56 | to_niri: calloop::channel::Sender<ScreenCastToNiri>, | 67 | to_niri: calloop::channel::Sender<ScreenCastToNiri>, |
| 57 | } | 68 | } |
| 58 | 69 | ||
| 70 | +#[derive(Clone)] | ||
| 71 | +enum StreamTarget { | ||
| 72 | + // FIXME: update on scale changes and whatnot. | ||
| 73 | + Output(niri_ipc::Output), | ||
| 74 | + Window { id: u64 }, | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +#[derive(Debug, Clone)] | ||
| 78 | +pub enum StreamTargetId { | ||
| 79 | + Output { name: String }, | ||
| 80 | + Window { id: u64 }, | ||
| 81 | +} | ||
| 82 | + | ||
| 59 | #[derive(Debug, SerializeDict, Type, Value)] | 83 | #[derive(Debug, SerializeDict, Type, Value)] |
| 60 | #[zvariant(signature = "dict")] | 84 | #[zvariant(signature = "dict")] |
| 61 | struct StreamParameters { | 85 | struct StreamParameters { |
| @@ -68,14 +92,13 @@ struct StreamParameters { | |||
| 68 | pub enum ScreenCastToNiri { | 92 | pub enum ScreenCastToNiri { |
| 69 | StartCast { | 93 | StartCast { |
| 70 | session_id: usize, | 94 | session_id: usize, |
| 71 | - output: String, | 95 | + target: StreamTargetId, |
| 72 | cursor_mode: CursorMode, | 96 | cursor_mode: CursorMode, |
| 73 | signal_ctx: SignalContext<'static>, | 97 | signal_ctx: SignalContext<'static>, |
| 74 | }, | 98 | }, |
| 75 | StopCast { | 99 | StopCast { |
| 76 | session_id: usize, | 100 | session_id: usize, |
| 77 | }, | 101 | }, |
| 78 | - Redraw(Output), | ||
| 79 | } | 102 | } |
| 80 | 103 | ||
| 81 | #[dbus_interface(name = "org.gnome.Mutter.ScreenCast")] | 104 | #[dbus_interface(name = "org.gnome.Mutter.ScreenCast")] |
| @@ -176,16 +199,51 @@ impl Session { | |||
| 176 | return Err(fdo::Error::Failed("monitor is disabled".to_owned())); | 199 | return Err(fdo::Error::Failed("monitor is disabled".to_owned())); |
| 177 | } | 200 | } |
| 178 | 201 | ||
| 179 | - static NUMBER: AtomicUsize = AtomicUsize::new(0); | ||
| 180 | let path = format!( | 202 | let path = format!( |
| 181 | "/org/gnome/Mutter/ScreenCast/Stream/u{}", | 203 | "/org/gnome/Mutter/ScreenCast/Stream/u{}", |
| 182 | - NUMBER.fetch_add(1, Ordering::SeqCst) | 204 | + STREAM_ID.fetch_add(1, Ordering::SeqCst) |
| 205 | + ); | ||
| 206 | + let path = OwnedObjectPath::try_from(path).unwrap(); | ||
| 207 | + | ||
| 208 | + let cursor_mode = properties.cursor_mode.unwrap_or_default(); | ||
| 209 | + | ||
| 210 | + let target = StreamTarget::Output(output); | ||
| 211 | + let stream = Stream::new(target, cursor_mode, self.to_niri.clone()); | ||
| 212 | + match server.at(&path, stream.clone()).await { | ||
| 213 | + Ok(true) => { | ||
| 214 | + let iface = server.interface(&path).await.unwrap(); | ||
| 215 | + self.streams.lock().unwrap().push((stream, iface)); | ||
| 216 | + } | ||
| 217 | + Ok(false) => return Err(fdo::Error::Failed("stream path already exists".to_owned())), | ||
| 218 | + Err(err) => { | ||
| 219 | + return Err(fdo::Error::Failed(format!( | ||
| 220 | + "error creating stream object: {err:?}" | ||
| 221 | + ))) | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + Ok(path) | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + async fn record_window( | ||
| 229 | + &mut self, | ||
| 230 | + #[zbus(object_server)] server: &ObjectServer, | ||
| 231 | + properties: RecordWindowProperties, | ||
| 232 | + ) -> fdo::Result<OwnedObjectPath> { | ||
| 233 | + debug!(?properties, "record_window"); | ||
| 234 | + | ||
| 235 | + let path = format!( | ||
| 236 | + "/org/gnome/Mutter/ScreenCast/Stream/u{}", | ||
| 237 | + STREAM_ID.fetch_add(1, Ordering::SeqCst) | ||
| 183 | ); | 238 | ); |
| 184 | let path = OwnedObjectPath::try_from(path).unwrap(); | 239 | let path = OwnedObjectPath::try_from(path).unwrap(); |
| 185 | 240 | ||
| 186 | let cursor_mode = properties.cursor_mode.unwrap_or_default(); | 241 | let cursor_mode = properties.cursor_mode.unwrap_or_default(); |
| 187 | 242 | ||
| 188 | - let stream = Stream::new(output.clone(), cursor_mode, self.to_niri.clone()); | 243 | + let target = StreamTarget::Window { |
| 244 | + id: properties.window_id, | ||
| 245 | + }; | ||
| 246 | + let stream = Stream::new(target, cursor_mode, self.to_niri.clone()); | ||
| 189 | match server.at(&path, stream.clone()).await { | 247 | match server.at(&path, stream.clone()).await { |
| 190 | Ok(true) => { | 248 | Ok(true) => { |
| 191 | let iface = server.interface(&path).await.unwrap(); | 249 | let iface = server.interface(&path).await.unwrap(); |
| @@ -214,10 +272,21 @@ impl Stream { | |||
| 214 | 272 | ||
| 215 | #[dbus_interface(property)] | 273 | #[dbus_interface(property)] |
| 216 | async fn parameters(&self) -> StreamParameters { | 274 | async fn parameters(&self) -> StreamParameters { |
| 217 | - let logical = self.output.logical.as_ref().unwrap(); | 275 | + match &self.target { |
| 218 | - StreamParameters { | 276 | + StreamTarget::Output(output) => { |
| 219 | - position: (logical.x, logical.y), | 277 | + let logical = output.logical.as_ref().unwrap(); |
| 220 | - size: (logical.width as i32, logical.height as i32), | 278 | + StreamParameters { |
| 279 | + position: (logical.x, logical.y), | ||
| 280 | + size: (logical.width as i32, logical.height as i32), | ||
| 281 | + } | ||
| 282 | + } | ||
| 283 | + StreamTarget::Window { .. } => { | ||
| 284 | + // Does any consumer need this? | ||
| 285 | + StreamParameters { | ||
| 286 | + position: (0, 0), | ||
| 287 | + size: (1, 1), | ||
| 288 | + } | ||
| 289 | + } | ||
| 221 | } | 290 | } |
| 222 | } | 291 | } |
| 223 | } | 292 | } |
| @@ -275,13 +344,13 @@ impl Drop for Session { | |||
| 275 | } | 344 | } |
| 276 | 345 | ||
| 277 | impl Stream { | 346 | impl Stream { |
| 278 | - pub fn new( | 347 | + fn new( |
| 279 | - output: niri_ipc::Output, | 348 | + target: StreamTarget, |
| 280 | cursor_mode: CursorMode, | 349 | cursor_mode: CursorMode, |
| 281 | to_niri: calloop::channel::Sender<ScreenCastToNiri>, | 350 | to_niri: calloop::channel::Sender<ScreenCastToNiri>, |
| 282 | ) -> Self { | 351 | ) -> Self { |
| 283 | Self { | 352 | Self { |
| 284 | - output, | 353 | + target, |
| 285 | cursor_mode, | 354 | cursor_mode, |
| 286 | was_started: Arc::new(AtomicBool::new(false)), | 355 | was_started: Arc::new(AtomicBool::new(false)), |
| 287 | to_niri, | 356 | to_niri, |
| @@ -295,7 +364,7 @@ impl Stream { | |||
| 295 | 364 | ||
| 296 | let msg = ScreenCastToNiri::StartCast { | 365 | let msg = ScreenCastToNiri::StartCast { |
| 297 | session_id, | 366 | session_id, |
| 298 | - output: self.output.name.clone(), | 367 | + target: self.target.make_id(), |
| 299 | cursor_mode: self.cursor_mode, | 368 | cursor_mode: self.cursor_mode, |
| 300 | signal_ctx: ctxt, | 369 | signal_ctx: ctxt, |
| 301 | }; | 370 | }; |
| @@ -305,3 +374,14 @@ impl Stream { | |||
| 305 | } | 374 | } |
| 306 | } | 375 | } |
| 307 | } | 376 | } |
| 377 | + | ||
| 378 | +impl StreamTarget { | ||
| 379 | + fn make_id(&self) -> StreamTargetId { | ||
| 380 | + match self { | ||
| 381 | + StreamTarget::Output(output) => StreamTargetId::Output { | ||
| 382 | + name: output.name.clone(), | ||
| 383 | + }, | ||
| 384 | + StreamTarget::Window { id } => StreamTargetId::Window { id: *id }, | ||
| 385 | + } | ||
| 386 | + } | ||
| 387 | +} | ||
src/handlers/compositor.rsmodified+9 -0
| @@ -209,6 +209,9 @@ impl CompositorHandler for State { | |||
| 209 | let window = mapped.window.clone(); | 209 | let window = mapped.window.clone(); |
| 210 | let output = output.clone(); | 210 | let output = output.clone(); |
| 211 | 211 | ||
| 212 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 213 | + let id = mapped.id(); | ||
| 214 | + | ||
| 212 | // This is a commit of a previously-mapped toplevel. | 215 | // This is a commit of a previously-mapped toplevel. |
| 213 | let is_mapped = | 216 | let is_mapped = |
| 214 | with_renderer_surface_state(surface, |state| state.buffer().is_some()) | 217 | with_renderer_surface_state(surface, |state| state.buffer().is_some()) |
| @@ -235,6 +238,12 @@ impl CompositorHandler for State { | |||
| 235 | let active_window = self.niri.layout.active_window().map(|(m, _)| &m.window); | 238 | let active_window = self.niri.layout.active_window().map(|(m, _)| &m.window); |
| 236 | let was_active = active_window == Some(&window); | 239 | let was_active = active_window == Some(&window); |
| 237 | 240 | ||
| 241 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 242 | + self.niri | ||
| 243 | + .stop_casts_for_target(crate::pw_utils::CastTarget::Window { | ||
| 244 | + id: u64::from(id.get()), | ||
| 245 | + }); | ||
| 246 | + | ||
| 238 | self.niri.layout.remove_window(&window); | 247 | self.niri.layout.remove_window(&window); |
| 239 | 248 | ||
| 240 | if was_active { | 249 | if was_active { |
src/handlers/xdg_shell.rsmodified+6 -0
| @@ -466,6 +466,12 @@ impl XdgShellHandler for State { | |||
| 466 | let window = mapped.window.clone(); | 466 | let window = mapped.window.clone(); |
| 467 | let output = output.clone(); | 467 | let output = output.clone(); |
| 468 | 468 | ||
| 469 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 470 | + self.niri | ||
| 471 | + .stop_casts_for_target(crate::pw_utils::CastTarget::Window { | ||
| 472 | + id: u64::from(mapped.id().get()), | ||
| 473 | + }); | ||
| 474 | + | ||
| 469 | self.backend.with_primary_renderer(|renderer| { | 475 | self.backend.with_primary_renderer(|renderer| { |
| 470 | self.niri.layout.store_unmap_snapshot(renderer, &window); | 476 | self.niri.layout.store_unmap_snapshot(renderer, &window); |
| 471 | }); | 477 | }); |
src/niri.rsmodified+351 -79
| @@ -116,6 +116,8 @@ use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState}; | |||
| 116 | use crate::protocols::gamma_control::GammaControlManagerState; | 116 | use crate::protocols::gamma_control::GammaControlManagerState; |
| 117 | use crate::protocols::screencopy::{Screencopy, ScreencopyManagerState}; | 117 | use crate::protocols::screencopy::{Screencopy, ScreencopyManagerState}; |
| 118 | use crate::pw_utils::{Cast, PipeWire}; | 118 | use crate::pw_utils::{Cast, PipeWire}; |
| 119 | +#[cfg(feature = "xdp-gnome-screencast")] | ||
| 120 | +use crate::pw_utils::{CastSizeChange, CastTarget, PwToNiri}; | ||
| 119 | use crate::render_helpers::debug::draw_opaque_regions; | 121 | use crate::render_helpers::debug::draw_opaque_regions; |
| 120 | use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement; | 122 | use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement; |
| 121 | use crate::render_helpers::renderer::NiriRenderer; | 123 | use crate::render_helpers::renderer::NiriRenderer; |
| @@ -277,6 +279,10 @@ pub struct Niri { | |||
| 277 | // Casts are dropped before PipeWire to prevent a double-free (yay). | 279 | // Casts are dropped before PipeWire to prevent a double-free (yay). |
| 278 | pub casts: Vec<Cast>, | 280 | pub casts: Vec<Cast>, |
| 279 | pub pipewire: Option<PipeWire>, | 281 | pub pipewire: Option<PipeWire>, |
| 282 | + | ||
| 283 | + // Screencast output for each mapped window. | ||
| 284 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 285 | + pub mapped_cast_output: HashMap<Window, Output>, | ||
| 280 | } | 286 | } |
| 281 | 287 | ||
| 282 | pub struct OutputState { | 288 | pub struct OutputState { |
| @@ -508,6 +514,9 @@ impl State { | |||
| 508 | foreign_toplevel::refresh(self); | 514 | foreign_toplevel::refresh(self); |
| 509 | self.niri.refresh_window_rules(); | 515 | self.niri.refresh_window_rules(); |
| 510 | self.refresh_ipc_outputs(); | 516 | self.refresh_ipc_outputs(); |
| 517 | + | ||
| 518 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 519 | + self.niri.refresh_mapped_cast_outputs(); | ||
| 511 | } | 520 | } |
| 512 | 521 | ||
| 513 | pub fn move_cursor(&mut self, location: Point<f64, Logical>) { | 522 | pub fn move_cursor(&mut self, location: Point<f64, Logical>) { |
| @@ -1172,15 +1181,34 @@ impl State { | |||
| 1172 | } | 1181 | } |
| 1173 | 1182 | ||
| 1174 | #[cfg(feature = "xdp-gnome-screencast")] | 1183 | #[cfg(feature = "xdp-gnome-screencast")] |
| 1175 | - pub fn on_screen_cast_msg( | 1184 | + pub fn on_pw_msg(&mut self, msg: PwToNiri) { |
| 1176 | - &mut self, | 1185 | + match msg { |
| 1177 | - to_niri: &calloop::channel::Sender<ScreenCastToNiri>, | 1186 | + PwToNiri::StopCast { session_id } => self.niri.stop_cast(session_id), |
| 1178 | - msg: ScreenCastToNiri, | 1187 | + PwToNiri::Redraw(target) => match target { |
| 1179 | - ) { | 1188 | + CastTarget::Output(weak) => { |
| 1189 | + if let Some(output) = weak.upgrade() { | ||
| 1190 | + self.niri.queue_redraw(&output); | ||
| 1191 | + } | ||
| 1192 | + } | ||
| 1193 | + CastTarget::Window { id } => { | ||
| 1194 | + self.backend.with_primary_renderer(|renderer| { | ||
| 1195 | + // FIXME: target presentation time at the time of window commit? | ||
| 1196 | + self.niri | ||
| 1197 | + .render_window_for_screen_cast(renderer, id, get_monotonic_time()); | ||
| 1198 | + }); | ||
| 1199 | + } | ||
| 1200 | + }, | ||
| 1201 | + } | ||
| 1202 | + } | ||
| 1203 | + | ||
| 1204 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 1205 | + pub fn on_screen_cast_msg(&mut self, msg: ScreenCastToNiri) { | ||
| 1206 | + use crate::dbus::mutter_screen_cast::StreamTargetId; | ||
| 1207 | + | ||
| 1180 | match msg { | 1208 | match msg { |
| 1181 | ScreenCastToNiri::StartCast { | 1209 | ScreenCastToNiri::StartCast { |
| 1182 | session_id, | 1210 | session_id, |
| 1183 | - output, | 1211 | + target, |
| 1184 | cursor_mode, | 1212 | cursor_mode, |
| 1185 | signal_ctx, | 1213 | signal_ctx, |
| 1186 | } => { | 1214 | } => { |
| @@ -1201,25 +1229,65 @@ impl State { | |||
| 1201 | return; | 1229 | return; |
| 1202 | }; | 1230 | }; |
| 1203 | 1231 | ||
| 1204 | - let Some(output) = self | 1232 | + let (target, size, refresh) = match target { |
| 1205 | - .niri | 1233 | + StreamTargetId::Output { name } => { |
| 1206 | - .global_space | 1234 | + let global_space = &self.niri.global_space; |
| 1207 | - .outputs() | 1235 | + let output = global_space.outputs().find(|out| out.name() == name); |
| 1208 | - .find(|out| out.name() == output) | 1236 | + let Some(output) = output else { |
| 1209 | - .cloned() | 1237 | + warn!("error starting screencast: requested output is missing"); |
| 1210 | - else { | 1238 | + self.niri.stop_cast(session_id); |
| 1211 | - warn!("tried to start a screencast on missing output: {output}"); | 1239 | + return; |
| 1212 | - return; | 1240 | + }; |
| 1241 | + | ||
| 1242 | + let mode = output.current_mode().unwrap(); | ||
| 1243 | + let transform = output.current_transform(); | ||
| 1244 | + let size = transform.transform_size(mode.size); | ||
| 1245 | + let refresh = mode.refresh as u32; | ||
| 1246 | + (CastTarget::Output(output.downgrade()), size, refresh) | ||
| 1247 | + } | ||
| 1248 | + StreamTargetId::Window { id } => { | ||
| 1249 | + let mut window = None; | ||
| 1250 | + self.niri.layout.with_windows(|mapped, _| { | ||
| 1251 | + if u64::from(mapped.id().get()) != id { | ||
| 1252 | + return; | ||
| 1253 | + } | ||
| 1254 | + | ||
| 1255 | + window = Some(mapped.window.clone()); | ||
| 1256 | + }); | ||
| 1257 | + | ||
| 1258 | + let Some(window) = window else { | ||
| 1259 | + warn!("error starting screencast: requested window is missing"); | ||
| 1260 | + self.niri.stop_cast(session_id); | ||
| 1261 | + return; | ||
| 1262 | + }; | ||
| 1263 | + | ||
| 1264 | + // Use the cached output since it will be present even if the output was | ||
| 1265 | + // currently disconnected. | ||
| 1266 | + let Some(output) = self.niri.mapped_cast_output.get(&window) else { | ||
| 1267 | + warn!("error starting screencast: requested window is missing"); | ||
| 1268 | + self.niri.stop_cast(session_id); | ||
| 1269 | + return; | ||
| 1270 | + }; | ||
| 1271 | + | ||
| 1272 | + let scale = Scale::from(output.current_scale().fractional_scale()); | ||
| 1273 | + let bbox = window.bbox_with_popups(); | ||
| 1274 | + let size = bbox.size.to_physical_precise_ceil(scale); | ||
| 1275 | + let refresh = output.current_mode().unwrap().refresh as u32; | ||
| 1276 | + | ||
| 1277 | + (CastTarget::Window { id }, size, refresh) | ||
| 1278 | + } | ||
| 1213 | }; | 1279 | }; |
| 1214 | 1280 | ||
| 1215 | - match pw.start_cast( | 1281 | + let res = pw.start_cast( |
| 1216 | - to_niri.clone(), | ||
| 1217 | gbm, | 1282 | gbm, |
| 1218 | session_id, | 1283 | session_id, |
| 1219 | - output, | 1284 | + target, |
| 1285 | + size, | ||
| 1286 | + refresh, | ||
| 1220 | cursor_mode, | 1287 | cursor_mode, |
| 1221 | signal_ctx, | 1288 | signal_ctx, |
| 1222 | - ) { | 1289 | + ); |
| 1290 | + match res { | ||
| 1223 | Ok(cast) => { | 1291 | Ok(cast) => { |
| 1224 | self.niri.casts.push(cast); | 1292 | self.niri.casts.push(cast); |
| 1225 | } | 1293 | } |
| @@ -1230,7 +1298,6 @@ impl State { | |||
| 1230 | } | 1298 | } |
| 1231 | } | 1299 | } |
| 1232 | ScreenCastToNiri::StopCast { session_id } => self.niri.stop_cast(session_id), | 1300 | ScreenCastToNiri::StopCast { session_id } => self.niri.stop_cast(session_id), |
| 1233 | - ScreenCastToNiri::Redraw(output) => self.niri.queue_redraw(&output), | ||
| 1234 | } | 1301 | } |
| 1235 | } | 1302 | } |
| 1236 | 1303 | ||
| @@ -1631,6 +1698,9 @@ impl Niri { | |||
| 1631 | 1698 | ||
| 1632 | pipewire, | 1699 | pipewire, |
| 1633 | casts: vec![], | 1700 | casts: vec![], |
| 1701 | + | ||
| 1702 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 1703 | + mapped_cast_output: HashMap::new(), | ||
| 1634 | } | 1704 | } |
| 1635 | } | 1705 | } |
| 1636 | 1706 | ||
| @@ -1860,6 +1930,9 @@ impl Niri { | |||
| 1860 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => self.event_loop.remove(token), | 1930 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => self.event_loop.remove(token), |
| 1861 | } | 1931 | } |
| 1862 | 1932 | ||
| 1933 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 1934 | + self.stop_casts_for_target(CastTarget::Output(output.downgrade())); | ||
| 1935 | + | ||
| 1863 | // Disable the output global and remove some time later to give the clients some time to | 1936 | // Disable the output global and remove some time later to give the clients some time to |
| 1864 | // process it. | 1937 | // process it. |
| 1865 | let global = state.global; | 1938 | let global = state.global; |
| @@ -2574,6 +2647,54 @@ impl Niri { | |||
| 2574 | } | 2647 | } |
| 2575 | } | 2648 | } |
| 2576 | 2649 | ||
| 2650 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 2651 | + pub fn refresh_mapped_cast_outputs(&mut self) { | ||
| 2652 | + use std::collections::hash_map::Entry; | ||
| 2653 | + | ||
| 2654 | + let mut seen = HashSet::new(); | ||
| 2655 | + let mut output_changed = vec![]; | ||
| 2656 | + | ||
| 2657 | + self.layout.with_windows(|mapped, output| { | ||
| 2658 | + seen.insert(mapped.window.clone()); | ||
| 2659 | + | ||
| 2660 | + let Some(output) = output else { | ||
| 2661 | + return; | ||
| 2662 | + }; | ||
| 2663 | + | ||
| 2664 | + match self.mapped_cast_output.entry(mapped.window.clone()) { | ||
| 2665 | + Entry::Occupied(mut entry) => { | ||
| 2666 | + if entry.get() != output { | ||
| 2667 | + entry.insert(output.clone()); | ||
| 2668 | + output_changed.push((mapped.id(), output.clone())); | ||
| 2669 | + } | ||
| 2670 | + } | ||
| 2671 | + Entry::Vacant(entry) => { | ||
| 2672 | + entry.insert(output.clone()); | ||
| 2673 | + } | ||
| 2674 | + } | ||
| 2675 | + }); | ||
| 2676 | + | ||
| 2677 | + self.mapped_cast_output.retain(|win, _| seen.contains(win)); | ||
| 2678 | + | ||
| 2679 | + let mut to_stop = vec![]; | ||
| 2680 | + for (id, out) in output_changed { | ||
| 2681 | + let refresh = out.current_mode().unwrap().refresh as u32; | ||
| 2682 | + let target = CastTarget::Window { | ||
| 2683 | + id: u64::from(id.get()), | ||
| 2684 | + }; | ||
| 2685 | + for cast in self.casts.iter_mut().filter(|cast| cast.target == target) { | ||
| 2686 | + if let Err(err) = cast.set_refresh(refresh) { | ||
| 2687 | + warn!("error changing cast FPS: {err:?}"); | ||
| 2688 | + to_stop.push(cast.session_id); | ||
| 2689 | + }; | ||
| 2690 | + } | ||
| 2691 | + } | ||
| 2692 | + | ||
| 2693 | + for session_id in to_stop { | ||
| 2694 | + self.stop_cast(session_id); | ||
| 2695 | + } | ||
| 2696 | + } | ||
| 2697 | + | ||
| 2577 | pub fn render<R: NiriRenderer>( | 2698 | pub fn render<R: NiriRenderer>( |
| 2578 | &self, | 2699 | &self, |
| 2579 | renderer: &mut R, | 2700 | renderer: &mut R, |
| @@ -2859,6 +2980,11 @@ impl Niri { | |||
| 2859 | backend.with_primary_renderer(|renderer| { | 2980 | backend.with_primary_renderer(|renderer| { |
| 2860 | // Render and send to PipeWire screencast streams. | 2981 | // Render and send to PipeWire screencast streams. |
| 2861 | self.render_for_screen_cast(renderer, output, target_presentation_time); | 2982 | self.render_for_screen_cast(renderer, output, target_presentation_time); |
| 2983 | + | ||
| 2984 | + // FIXME: when a window is hidden, it should probably still receive frame callbacks and | ||
| 2985 | + // get rendered for screen cast. This is currently unimplemented, but happens to work | ||
| 2986 | + // by chance, since output redrawing is more eager than it should be. | ||
| 2987 | + self.render_windows_for_screen_cast(renderer, output, target_presentation_time); | ||
| 2862 | }); | 2988 | }); |
| 2863 | } | 2989 | } |
| 2864 | 2990 | ||
| @@ -3294,10 +3420,10 @@ impl Niri { | |||
| 3294 | output: &Output, | 3420 | output: &Output, |
| 3295 | target_presentation_time: Duration, | 3421 | target_presentation_time: Duration, |
| 3296 | ) { | 3422 | ) { |
| 3297 | - use crate::render_helpers::render_to_dmabuf; | ||
| 3298 | - | ||
| 3299 | let _span = tracy_client::span!("Niri::render_for_screen_cast"); | 3423 | let _span = tracy_client::span!("Niri::render_for_screen_cast"); |
| 3300 | 3424 | ||
| 3425 | + let target = CastTarget::Output(output.downgrade()); | ||
| 3426 | + | ||
| 3301 | let size = output.current_mode().unwrap().size; | 3427 | let size = output.current_mode().unwrap().size; |
| 3302 | let transform = output.current_transform(); | 3428 | let transform = output.current_transform(); |
| 3303 | let size = transform.transform_size(size); | 3429 | let size = transform.transform_size(size); |
| @@ -3313,84 +3439,213 @@ impl Niri { | |||
| 3313 | continue; | 3439 | continue; |
| 3314 | } | 3440 | } |
| 3315 | 3441 | ||
| 3316 | - if &cast.output != output { | 3442 | + if cast.target != target { |
| 3317 | continue; | 3443 | continue; |
| 3318 | } | 3444 | } |
| 3319 | 3445 | ||
| 3320 | - if cast.size.get() != size { | 3446 | + match cast.ensure_size(size) { |
| 3321 | - if cast.pending_size.get() != size { | 3447 | + Ok(CastSizeChange::Ready) => (), |
| 3322 | - debug!("output size changed, updating stream size"); | 3448 | + Ok(CastSizeChange::Pending) => continue, |
| 3323 | - if let Err(err) = cast.set_size(size) { | 3449 | + Err(err) => { |
| 3324 | - warn!("error updating stream size, stopping screencast: {err:?}"); | 3450 | + warn!("error updating stream size, stopping screencast: {err:?}"); |
| 3325 | - casts_to_stop.push(cast.session_id); | 3451 | + casts_to_stop.push(cast.session_id); |
| 3326 | - } | ||
| 3327 | - } else { | ||
| 3328 | - debug!("stream size still hasn't changed, skipping frame"); | ||
| 3329 | } | 3452 | } |
| 3453 | + } | ||
| 3330 | 3454 | ||
| 3331 | - // Even in the successful case, we'll need to wait till the size actually changes. | 3455 | + if cast.should_skip_frame(target_presentation_time) { |
| 3332 | continue; | 3456 | continue; |
| 3333 | } | 3457 | } |
| 3334 | 3458 | ||
| 3335 | - let last = cast.last_frame_time; | 3459 | + // FIXME: Hidden / embedded / metadata cursor |
| 3336 | - let min = cast.min_time_between_frames.get(); | 3460 | + let elements = elements.get_or_insert_with(|| { |
| 3337 | - if last.is_zero() { | 3461 | + self.render(renderer, output, true, RenderTarget::Screencast) |
| 3338 | - trace!(?target_presentation_time, ?last, "last is zero, recording"); | 3462 | + }); |
| 3339 | - } else if target_presentation_time < last { | 3463 | + let elements = elements.iter().rev(); |
| 3340 | - // Record frame with a warning; in case it was an overflow this will fix it. | 3464 | + |
| 3341 | - warn!( | 3465 | + if cast.dequeue_buffer_and_render(renderer, elements, size, scale) { |
| 3342 | - ?target_presentation_time, | 3466 | + cast.last_frame_time = target_presentation_time; |
| 3343 | - ?last, | 3467 | + } |
| 3344 | - "target presentation time is below last, did it overflow or did we mispredict?" | 3468 | + } |
| 3345 | - ); | 3469 | + self.casts = casts; |
| 3346 | - } else { | 3470 | + |
| 3347 | - let diff = target_presentation_time - last; | 3471 | + for id in casts_to_stop { |
| 3348 | - if diff < min { | 3472 | + self.stop_cast(id); |
| 3349 | - trace!( | 3473 | + } |
| 3350 | - ?target_presentation_time, | 3474 | + } |
| 3351 | - ?last, | 3475 | + |
| 3352 | - "skipping frame because it is too soon: diff={diff:?} < min={min:?}", | 3476 | + #[cfg(feature = "xdp-gnome-screencast")] |
| 3353 | - ); | 3477 | + fn render_windows_for_screen_cast( |
| 3354 | - continue; | 3478 | + &mut self, |
| 3479 | + renderer: &mut GlesRenderer, | ||
| 3480 | + output: &Output, | ||
| 3481 | + target_presentation_time: Duration, | ||
| 3482 | + ) { | ||
| 3483 | + let _span = tracy_client::span!("Niri::render_windows_for_screen_cast"); | ||
| 3484 | + | ||
| 3485 | + let scale = Scale::from(output.current_scale().fractional_scale()); | ||
| 3486 | + | ||
| 3487 | + let mut casts_to_stop = vec![]; | ||
| 3488 | + | ||
| 3489 | + let mut casts = mem::take(&mut self.casts); | ||
| 3490 | + for cast in &mut casts { | ||
| 3491 | + if !cast.is_active.get() { | ||
| 3492 | + continue; | ||
| 3493 | + } | ||
| 3494 | + | ||
| 3495 | + let CastTarget::Window { id } = cast.target else { | ||
| 3496 | + continue; | ||
| 3497 | + }; | ||
| 3498 | + | ||
| 3499 | + let mut windows = self.layout.windows_for_output(output); | ||
| 3500 | + let Some(mapped) = windows.find(|win| u64::from(win.id().get()) == id) else { | ||
| 3501 | + continue; | ||
| 3502 | + }; | ||
| 3503 | + | ||
| 3504 | + let bbox = mapped.window.bbox_with_popups(); | ||
| 3505 | + let size = bbox.size.to_physical_precise_ceil(scale); | ||
| 3506 | + | ||
| 3507 | + match cast.ensure_size(size) { | ||
| 3508 | + Ok(CastSizeChange::Ready) => (), | ||
| 3509 | + Ok(CastSizeChange::Pending) => continue, | ||
| 3510 | + Err(err) => { | ||
| 3511 | + warn!("error updating stream size, stopping screencast: {err:?}"); | ||
| 3512 | + casts_to_stop.push(cast.session_id); | ||
| 3355 | } | 3513 | } |
| 3356 | } | 3514 | } |
| 3357 | 3515 | ||
| 3358 | - { | 3516 | + if cast.should_skip_frame(target_presentation_time) { |
| 3359 | - let mut buffer = match cast.stream.dequeue_buffer() { | 3517 | + continue; |
| 3360 | - Some(buffer) => buffer, | 3518 | + } |
| 3361 | - None => { | ||
| 3362 | - warn!("no available buffer in pw stream, skipping frame"); | ||
| 3363 | - continue; | ||
| 3364 | - } | ||
| 3365 | - }; | ||
| 3366 | 3519 | ||
| 3367 | - let data = &mut buffer.datas_mut()[0]; | 3520 | + let alpha = if mapped.is_fullscreen() { |
| 3368 | - let fd = data.as_raw().fd as i32; | 3521 | + 1. |
| 3369 | - let dmabuf = cast.dmabufs.borrow()[&fd].clone(); | 3522 | + } else { |
| 3523 | + mapped.rules().opacity.unwrap_or(1.).clamp(0., 1.) | ||
| 3524 | + }; | ||
| 3525 | + // FIXME: pointer. | ||
| 3526 | + let elements = mapped.render( | ||
| 3527 | + renderer, | ||
| 3528 | + mapped.window.geometry().loc.to_f64(), | ||
| 3529 | + scale, | ||
| 3530 | + alpha, | ||
| 3531 | + RenderTarget::Screencast, | ||
| 3532 | + ); | ||
| 3533 | + let geo = elements | ||
| 3534 | + .iter() | ||
| 3535 | + .map(|ele| ele.geometry(scale)) | ||
| 3536 | + .reduce(|a, b| a.merge(b)) | ||
| 3537 | + .unwrap_or_default(); | ||
| 3538 | + let elements = elements.iter().rev().map(|elem| { | ||
| 3539 | + RelocateRenderElement::from_element(elem, geo.loc.upscale(-1), Relocate::Relative) | ||
| 3540 | + }); | ||
| 3370 | 3541 | ||
| 3371 | - // FIXME: Hidden / embedded / metadata cursor | 3542 | + if cast.dequeue_buffer_and_render(renderer, elements, size, scale) { |
| 3372 | - let elements = elements.get_or_insert_with(|| { | 3543 | + cast.last_frame_time = target_presentation_time; |
| 3373 | - self.render::<GlesRenderer>(renderer, output, true, RenderTarget::Screencast) | 3544 | + } |
| 3374 | - }); | 3545 | + } |
| 3375 | - let elements = elements.iter().rev(); | 3546 | + self.casts = casts; |
| 3376 | 3547 | ||
| 3377 | - if let Err(err) = | 3548 | + for id in casts_to_stop { |
| 3378 | - render_to_dmabuf(renderer, dmabuf, size, scale, Transform::Normal, elements) | 3549 | + self.stop_cast(id); |
| 3379 | - { | 3550 | + } |
| 3380 | - warn!("error rendering to dmabuf: {err:?}"); | 3551 | + } |
| 3381 | - continue; | 3552 | + |
| 3553 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 3554 | + fn render_window_for_screen_cast( | ||
| 3555 | + &mut self, | ||
| 3556 | + renderer: &mut GlesRenderer, | ||
| 3557 | + window_id: u64, | ||
| 3558 | + target_presentation_time: Duration, | ||
| 3559 | + ) { | ||
| 3560 | + let _span = tracy_client::span!("Niri::render_window_for_screen_cast"); | ||
| 3561 | + | ||
| 3562 | + let mut window = None; | ||
| 3563 | + self.layout.with_windows(|mapped, _| { | ||
| 3564 | + if u64::from(mapped.id().get()) != window_id { | ||
| 3565 | + return; | ||
| 3566 | + } | ||
| 3567 | + | ||
| 3568 | + window = Some(mapped.window.clone()); | ||
| 3569 | + }); | ||
| 3570 | + | ||
| 3571 | + let Some(window) = window else { | ||
| 3572 | + return; | ||
| 3573 | + }; | ||
| 3574 | + | ||
| 3575 | + // Use the cached output since it will be present even if the output was | ||
| 3576 | + // currently disconnected. | ||
| 3577 | + let Some(output) = self.mapped_cast_output.get(&window) else { | ||
| 3578 | + return; | ||
| 3579 | + }; | ||
| 3580 | + | ||
| 3581 | + let mut windows = self.layout.windows_for_output(output); | ||
| 3582 | + let mapped = windows | ||
| 3583 | + .find(|mapped| u64::from(mapped.id().get()) == window_id) | ||
| 3584 | + .unwrap(); | ||
| 3585 | + | ||
| 3586 | + let scale = Scale::from(output.current_scale().fractional_scale()); | ||
| 3587 | + let bbox = mapped.window.bbox_with_popups(); | ||
| 3588 | + let size = bbox.size.to_physical_precise_ceil(scale); | ||
| 3589 | + | ||
| 3590 | + let mut elements = None; | ||
| 3591 | + let mut casts_to_stop = vec![]; | ||
| 3592 | + | ||
| 3593 | + let mut casts = mem::take(&mut self.casts); | ||
| 3594 | + for cast in &mut casts { | ||
| 3595 | + if !cast.is_active.get() { | ||
| 3596 | + continue; | ||
| 3597 | + } | ||
| 3598 | + | ||
| 3599 | + if cast.target != (CastTarget::Window { id: window_id }) { | ||
| 3600 | + continue; | ||
| 3601 | + } | ||
| 3602 | + | ||
| 3603 | + match cast.ensure_size(size) { | ||
| 3604 | + Ok(CastSizeChange::Ready) => (), | ||
| 3605 | + Ok(CastSizeChange::Pending) => continue, | ||
| 3606 | + Err(err) => { | ||
| 3607 | + warn!("error updating stream size, stopping screencast: {err:?}"); | ||
| 3608 | + casts_to_stop.push(cast.session_id); | ||
| 3382 | } | 3609 | } |
| 3610 | + } | ||
| 3383 | 3611 | ||
| 3384 | - let maxsize = data.as_raw().maxsize; | 3612 | + if cast.should_skip_frame(target_presentation_time) { |
| 3385 | - let chunk = data.chunk_mut(); | 3613 | + continue; |
| 3386 | - *chunk.size_mut() = maxsize; | ||
| 3387 | - *chunk.stride_mut() = maxsize as i32 / size.h; | ||
| 3388 | } | 3614 | } |
| 3389 | 3615 | ||
| 3390 | - cast.last_frame_time = target_presentation_time; | 3616 | + let (elements, geo) = elements.get_or_insert_with(|| { |
| 3617 | + let alpha = if mapped.is_fullscreen() { | ||
| 3618 | + 1. | ||
| 3619 | + } else { | ||
| 3620 | + mapped.rules().opacity.unwrap_or(1.).clamp(0., 1.) | ||
| 3621 | + }; | ||
| 3622 | + // FIXME: pointer. | ||
| 3623 | + let elements = mapped.render( | ||
| 3624 | + renderer, | ||
| 3625 | + mapped.window.geometry().loc.to_f64(), | ||
| 3626 | + scale, | ||
| 3627 | + alpha, | ||
| 3628 | + RenderTarget::Screencast, | ||
| 3629 | + ); | ||
| 3630 | + let geo = elements | ||
| 3631 | + .iter() | ||
| 3632 | + .map(|ele| ele.geometry(scale)) | ||
| 3633 | + .reduce(|a, b| a.merge(b)) | ||
| 3634 | + .unwrap_or_default(); | ||
| 3635 | + (elements, geo) | ||
| 3636 | + }); | ||
| 3637 | + let elements = elements.iter().rev().map(|elem| { | ||
| 3638 | + RelocateRenderElement::from_element(elem, geo.loc.upscale(-1), Relocate::Relative) | ||
| 3639 | + }); | ||
| 3640 | + | ||
| 3641 | + if cast.dequeue_buffer_and_render(renderer, elements, size, scale) { | ||
| 3642 | + cast.last_frame_time = target_presentation_time; | ||
| 3643 | + } | ||
| 3391 | } | 3644 | } |
| 3392 | self.casts = casts; | 3645 | self.casts = casts; |
| 3393 | 3646 | ||
| 3647 | + drop(windows); | ||
| 3648 | + | ||
| 3394 | for id in casts_to_stop { | 3649 | for id in casts_to_stop { |
| 3395 | self.stop_cast(id); | 3650 | self.stop_cast(id); |
| 3396 | } | 3651 | } |
| @@ -3472,6 +3727,23 @@ impl Niri { | |||
| 3472 | } | 3727 | } |
| 3473 | } | 3728 | } |
| 3474 | 3729 | ||
| 3730 | + #[cfg(feature = "xdp-gnome-screencast")] | ||
| 3731 | + pub fn stop_casts_for_target(&mut self, target: CastTarget) { | ||
| 3732 | + let _span = tracy_client::span!("Niri::stop_casts_for_target"); | ||
| 3733 | + | ||
| 3734 | + // This is O(N^2) but it shouldn't be a problem I think. | ||
| 3735 | + let ids: Vec<_> = self | ||
| 3736 | + .casts | ||
| 3737 | + .iter() | ||
| 3738 | + .filter(|cast| cast.target == target) | ||
| 3739 | + .map(|cast| cast.session_id) | ||
| 3740 | + .collect(); | ||
| 3741 | + | ||
| 3742 | + for id in ids { | ||
| 3743 | + self.stop_cast(id); | ||
| 3744 | + } | ||
| 3745 | + } | ||
| 3746 | + | ||
| 3475 | pub fn debug_toggle_damage(&mut self) { | 3747 | pub fn debug_toggle_damage(&mut self) { |
| 3476 | self.debug_draw_damage = !self.debug_draw_damage; | 3748 | self.debug_draw_damage = !self.debug_draw_damage; |
| 3477 | 3749 | ||
src/pw_utils.rsmodified+222 -40
| @@ -27,19 +27,28 @@ use smithay::backend::allocator::dmabuf::{AsDmabuf, Dmabuf}; | |||
| 27 | use smithay::backend::allocator::gbm::{GbmBuffer, GbmBufferFlags, GbmDevice}; | 27 | use smithay::backend::allocator::gbm::{GbmBuffer, GbmBufferFlags, GbmDevice}; |
| 28 | use smithay::backend::allocator::Fourcc; | 28 | use smithay::backend::allocator::Fourcc; |
| 29 | use smithay::backend::drm::DrmDeviceFd; | 29 | use smithay::backend::drm::DrmDeviceFd; |
| 30 | -use smithay::output::Output; | 30 | +use smithay::backend::renderer::element::RenderElement; |
| 31 | +use smithay::backend::renderer::gles::GlesRenderer; | ||
| 32 | +use smithay::output::WeakOutput; | ||
| 31 | use smithay::reexports::calloop::generic::Generic; | 33 | use smithay::reexports::calloop::generic::Generic; |
| 32 | use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; | 34 | use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; |
| 33 | use smithay::reexports::gbm::Modifier; | 35 | use smithay::reexports::gbm::Modifier; |
| 34 | -use smithay::utils::{Physical, Size}; | 36 | +use smithay::utils::{Physical, Scale, Size, Transform}; |
| 35 | use zbus::SignalContext; | 37 | use zbus::SignalContext; |
| 36 | 38 | ||
| 37 | -use crate::dbus::mutter_screen_cast::{self, CursorMode, ScreenCastToNiri}; | 39 | +use crate::dbus::mutter_screen_cast::{self, CursorMode}; |
| 38 | use crate::niri::State; | 40 | use crate::niri::State; |
| 41 | +use crate::render_helpers::render_to_dmabuf; | ||
| 39 | 42 | ||
| 40 | pub struct PipeWire { | 43 | pub struct PipeWire { |
| 41 | _context: Context, | 44 | _context: Context, |
| 42 | pub core: Core, | 45 | pub core: Core, |
| 46 | + to_niri: calloop::channel::Sender<PwToNiri>, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +pub enum PwToNiri { | ||
| 50 | + StopCast { session_id: usize }, | ||
| 51 | + Redraw(CastTarget), | ||
| 43 | } | 52 | } |
| 44 | 53 | ||
| 45 | pub struct Cast { | 54 | pub struct Cast { |
| @@ -47,9 +56,8 @@ pub struct Cast { | |||
| 47 | pub stream: Stream, | 56 | pub stream: Stream, |
| 48 | _listener: StreamListener<()>, | 57 | _listener: StreamListener<()>, |
| 49 | pub is_active: Rc<Cell<bool>>, | 58 | pub is_active: Rc<Cell<bool>>, |
| 50 | - pub output: Output, | 59 | + pub target: CastTarget, |
| 51 | - pub size: Rc<Cell<Size<i32, Physical>>>, | 60 | + pub size: Rc<Cell<CastSize>>, |
| 52 | - pub pending_size: Rc<Cell<Size<i32, Physical>>>, | ||
| 53 | pub refresh: u32, | 61 | pub refresh: u32, |
| 54 | pub cursor_mode: CursorMode, | 62 | pub cursor_mode: CursorMode, |
| 55 | pub last_frame_time: Duration, | 63 | pub last_frame_time: Duration, |
| @@ -57,6 +65,28 @@ pub struct Cast { | |||
| 57 | pub dmabufs: Rc<RefCell<HashMap<i32, Dmabuf>>>, | 65 | pub dmabufs: Rc<RefCell<HashMap<i32, Dmabuf>>>, |
| 58 | } | 66 | } |
| 59 | 67 | ||
| 68 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 69 | +pub enum CastSize { | ||
| 70 | + InitialPending(Size<i32, Physical>), | ||
| 71 | + Ready(Size<i32, Physical>), | ||
| 72 | + ChangePending { | ||
| 73 | + last_negotiated: Size<i32, Physical>, | ||
| 74 | + pending: Size<i32, Physical>, | ||
| 75 | + }, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +#[derive(PartialEq, Eq)] | ||
| 79 | +pub enum CastSizeChange { | ||
| 80 | + Ready, | ||
| 81 | + Pending, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +#[derive(Clone, PartialEq, Eq)] | ||
| 85 | +pub enum CastTarget { | ||
| 86 | + Output(WeakOutput), | ||
| 87 | + Window { id: u64 }, | ||
| 88 | +} | ||
| 89 | + | ||
| 60 | impl PipeWire { | 90 | impl PipeWire { |
| 61 | pub fn new(event_loop: &LoopHandle<'static, State>) -> anyhow::Result<Self> { | 91 | pub fn new(event_loop: &LoopHandle<'static, State>) -> anyhow::Result<Self> { |
| 62 | let main_loop = MainLoop::new(None).context("error creating MainLoop")?; | 92 | let main_loop = MainLoop::new(None).context("error creating MainLoop")?; |
| @@ -86,45 +116,49 @@ impl PipeWire { | |||
| 86 | }) | 116 | }) |
| 87 | .unwrap(); | 117 | .unwrap(); |
| 88 | 118 | ||
| 119 | + let (to_niri, from_pipewire) = calloop::channel::channel(); | ||
| 120 | + event_loop | ||
| 121 | + .insert_source(from_pipewire, move |event, _, state| match event { | ||
| 122 | + calloop::channel::Event::Msg(msg) => state.on_pw_msg(msg), | ||
| 123 | + calloop::channel::Event::Closed => (), | ||
| 124 | + }) | ||
| 125 | + .unwrap(); | ||
| 126 | + | ||
| 89 | Ok(Self { | 127 | Ok(Self { |
| 90 | _context: context, | 128 | _context: context, |
| 91 | core, | 129 | core, |
| 130 | + to_niri, | ||
| 92 | }) | 131 | }) |
| 93 | } | 132 | } |
| 94 | 133 | ||
| 134 | + #[allow(clippy::too_many_arguments)] | ||
| 95 | pub fn start_cast( | 135 | pub fn start_cast( |
| 96 | &self, | 136 | &self, |
| 97 | - to_niri: calloop::channel::Sender<ScreenCastToNiri>, | ||
| 98 | gbm: GbmDevice<DrmDeviceFd>, | 137 | gbm: GbmDevice<DrmDeviceFd>, |
| 99 | session_id: usize, | 138 | session_id: usize, |
| 100 | - output: Output, | 139 | + target: CastTarget, |
| 140 | + size: Size<i32, Physical>, | ||
| 141 | + refresh: u32, | ||
| 101 | cursor_mode: CursorMode, | 142 | cursor_mode: CursorMode, |
| 102 | signal_ctx: SignalContext<'static>, | 143 | signal_ctx: SignalContext<'static>, |
| 103 | ) -> anyhow::Result<Cast> { | 144 | ) -> anyhow::Result<Cast> { |
| 104 | let _span = tracy_client::span!("PipeWire::start_cast"); | 145 | let _span = tracy_client::span!("PipeWire::start_cast"); |
| 105 | 146 | ||
| 106 | - let to_niri_ = to_niri.clone(); | 147 | + let to_niri_ = self.to_niri.clone(); |
| 107 | let stop_cast = move || { | 148 | let stop_cast = move || { |
| 108 | - if let Err(err) = to_niri_.send(ScreenCastToNiri::StopCast { session_id }) { | 149 | + if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) { |
| 109 | warn!("error sending StopCast to niri: {err:?}"); | 150 | warn!("error sending StopCast to niri: {err:?}"); |
| 110 | } | 151 | } |
| 111 | }; | 152 | }; |
| 112 | - let weak = output.downgrade(); | 153 | + let target_ = target.clone(); |
| 154 | + let to_niri_ = self.to_niri.clone(); | ||
| 113 | let redraw = move || { | 155 | let redraw = move || { |
| 114 | - if let Some(output) = weak.upgrade() { | 156 | + if let Err(err) = to_niri_.send(PwToNiri::Redraw(target_.clone())) { |
| 115 | - if let Err(err) = to_niri.send(ScreenCastToNiri::Redraw(output)) { | 157 | + warn!("error sending Redraw to niri: {err:?}"); |
| 116 | - warn!("error sending Redraw to niri: {err:?}"); | ||
| 117 | - } | ||
| 118 | } | 158 | } |
| 119 | }; | 159 | }; |
| 120 | let redraw_ = redraw.clone(); | 160 | let redraw_ = redraw.clone(); |
| 121 | 161 | ||
| 122 | - let mode = output.current_mode().unwrap(); | ||
| 123 | - let size = mode.size; | ||
| 124 | - let transform = output.current_transform(); | ||
| 125 | - let size = transform.transform_size(size); | ||
| 126 | - let refresh = mode.refresh as u32; | ||
| 127 | - | ||
| 128 | let stream = Stream::new(&self.core, "niri-screen-cast-src", Properties::new()) | 162 | let stream = Stream::new(&self.core, "niri-screen-cast-src", Properties::new()) |
| 129 | .context("error creating Stream")?; | 163 | .context("error creating Stream")?; |
| 130 | 164 | ||
| @@ -133,8 +167,9 @@ impl PipeWire { | |||
| 133 | let is_active = Rc::new(Cell::new(false)); | 167 | let is_active = Rc::new(Cell::new(false)); |
| 134 | let min_time_between_frames = Rc::new(Cell::new(Duration::ZERO)); | 168 | let min_time_between_frames = Rc::new(Cell::new(Duration::ZERO)); |
| 135 | let dmabufs = Rc::new(RefCell::new(HashMap::new())); | 169 | let dmabufs = Rc::new(RefCell::new(HashMap::new())); |
| 136 | - let pending_size = Rc::new(Cell::new(size)); | 170 | + |
| 137 | - let size = Rc::new(Cell::new(Size::from((0, 0)))); | 171 | + let pending_size = size; |
| 172 | + let size = Rc::new(Cell::new(CastSize::InitialPending(size))); | ||
| 138 | 173 | ||
| 139 | let listener = stream | 174 | let listener = stream |
| 140 | .add_local_listener_with_user_data(()) | 175 | .add_local_listener_with_user_data(()) |
| @@ -186,7 +221,6 @@ impl PipeWire { | |||
| 186 | .param_changed({ | 221 | .param_changed({ |
| 187 | let min_time_between_frames = min_time_between_frames.clone(); | 222 | let min_time_between_frames = min_time_between_frames.clone(); |
| 188 | let size = size.clone(); | 223 | let size = size.clone(); |
| 189 | - let pending_size = pending_size.clone(); | ||
| 190 | move |stream, (), id, pod| { | 224 | move |stream, (), id, pod| { |
| 191 | let id = ParamType::from_raw(id); | 225 | let id = ParamType::from_raw(id); |
| 192 | trace!(?id, "pw stream: param_changed"); | 226 | trace!(?id, "pw stream: param_changed"); |
| @@ -213,9 +247,18 @@ impl PipeWire { | |||
| 213 | format.parse(pod).unwrap(); | 247 | format.parse(pod).unwrap(); |
| 214 | trace!("pw stream: got format = {format:?}"); | 248 | trace!("pw stream: got format = {format:?}"); |
| 215 | 249 | ||
| 216 | - assert_eq!(pending_size.get().w as u32, format.size().width); | 250 | + let expected_size = size.get().expected_format_size(); |
| 217 | - assert_eq!(pending_size.get().h as u32, format.size().height); | 251 | + let format_size = |
| 218 | - size.set(pending_size.get()); | 252 | + Size::from((format.size().width as i32, format.size().height as i32)); |
| 253 | + | ||
| 254 | + if format_size == expected_size { | ||
| 255 | + size.set(CastSize::Ready(expected_size)); | ||
| 256 | + } else { | ||
| 257 | + size.set(CastSize::ChangePending { | ||
| 258 | + last_negotiated: format_size, | ||
| 259 | + pending: expected_size, | ||
| 260 | + }); | ||
| 261 | + } | ||
| 219 | 262 | ||
| 220 | let max_frame_rate = format.max_framerate(); | 263 | let max_frame_rate = format.max_framerate(); |
| 221 | // Subtract 0.5 ms to improve edge cases when equal to refresh rate. | 264 | // Subtract 0.5 ms to improve edge cases when equal to refresh rate. |
| @@ -283,7 +326,9 @@ impl PipeWire { | |||
| 283 | let stop_cast = stop_cast.clone(); | 326 | let stop_cast = stop_cast.clone(); |
| 284 | let size = size.clone(); | 327 | let size = size.clone(); |
| 285 | move |stream, (), buffer| { | 328 | move |stream, (), buffer| { |
| 286 | - trace!("pw stream: add_buffer"); | 329 | + let size = size.get().negotiated_size(); |
| 330 | + trace!("pw stream: add_buffer, size={:?}", size); | ||
| 331 | + let size = size.expect("size must be negotiated to allocate buffers"); | ||
| 287 | 332 | ||
| 288 | unsafe { | 333 | unsafe { |
| 289 | let spa_buffer = (*buffer).buffer; | 334 | let spa_buffer = (*buffer).buffer; |
| @@ -291,8 +336,6 @@ impl PipeWire { | |||
| 291 | assert!((*spa_buffer).n_datas > 0); | 336 | assert!((*spa_buffer).n_datas > 0); |
| 292 | assert!((*spa_data).type_ & (1 << DataType::DmaBuf.as_raw()) > 0); | 337 | assert!((*spa_data).type_ & (1 << DataType::DmaBuf.as_raw()) > 0); |
| 293 | 338 | ||
| 294 | - let size = size.get(); | ||
| 295 | - | ||
| 296 | let bo = match gbm.create_buffer_object::<()>( | 339 | let bo = match gbm.create_buffer_object::<()>( |
| 297 | size.w as u32, | 340 | size.w as u32, |
| 298 | size.h as u32, | 341 | size.h as u32, |
| @@ -351,7 +394,9 @@ impl PipeWire { | |||
| 351 | .register() | 394 | .register() |
| 352 | .unwrap(); | 395 | .unwrap(); |
| 353 | 396 | ||
| 354 | - let object = make_video_params(pending_size.get(), refresh); | 397 | + trace!("starting pw stream with size={pending_size:?}, refresh={refresh}"); |
| 398 | + | ||
| 399 | + let object = make_video_params(pending_size, refresh); | ||
| 355 | let mut buffer = vec![]; | 400 | let mut buffer = vec![]; |
| 356 | let mut params = [make_pod(&mut buffer, object)]; | 401 | let mut params = [make_pod(&mut buffer, object)]; |
| 357 | stream | 402 | stream |
| @@ -368,9 +413,8 @@ impl PipeWire { | |||
| 368 | stream, | 413 | stream, |
| 369 | _listener: listener, | 414 | _listener: listener, |
| 370 | is_active, | 415 | is_active, |
| 371 | - output, | 416 | + target, |
| 372 | size, | 417 | size, |
| 373 | - pending_size, | ||
| 374 | refresh, | 418 | refresh, |
| 375 | cursor_mode, | 419 | cursor_mode, |
| 376 | last_frame_time: Duration::ZERO, | 420 | last_frame_time: Duration::ZERO, |
| @@ -382,22 +426,160 @@ impl PipeWire { | |||
| 382 | } | 426 | } |
| 383 | 427 | ||
| 384 | impl Cast { | 428 | impl Cast { |
| 385 | - pub fn set_size(&self, size: Size<i32, Physical>) -> anyhow::Result<()> { | 429 | + pub fn ensure_size(&self, size: Size<i32, Physical>) -> anyhow::Result<CastSizeChange> { |
| 386 | - if self.pending_size.get() == size { | 430 | + let current_size = self.size.get(); |
| 387 | - return Ok(()); | 431 | + if current_size == CastSize::Ready(size) { |
| 432 | + return Ok(CastSizeChange::Ready); | ||
| 388 | } | 433 | } |
| 389 | 434 | ||
| 390 | - let _span = tracy_client::span!("Cast::set_size"); | 435 | + if current_size.pending_size() == Some(size) { |
| 436 | + debug!("stream size still hasn't changed, skipping frame"); | ||
| 437 | + return Ok(CastSizeChange::Pending); | ||
| 438 | + } | ||
| 391 | 439 | ||
| 392 | - self.size.set(Size::from((0, 0))); | 440 | + let _span = tracy_client::span!("Cast::ensure_size"); |
| 393 | - self.pending_size.set(size); | 441 | + debug!("cast size changed, updating stream size"); |
| 442 | + | ||
| 443 | + self.size.set(current_size.with_pending(size)); | ||
| 394 | 444 | ||
| 395 | let object = make_video_params(size, self.refresh); | 445 | let object = make_video_params(size, self.refresh); |
| 396 | let mut buffer = vec![]; | 446 | let mut buffer = vec![]; |
| 397 | let mut params = [make_pod(&mut buffer, object)]; | 447 | let mut params = [make_pod(&mut buffer, object)]; |
| 398 | self.stream | 448 | self.stream |
| 399 | .update_params(&mut params) | 449 | .update_params(&mut params) |
| 400 | - .context("error updating stream params") | 450 | + .context("error updating stream params")?; |
| 451 | + | ||
| 452 | + Ok(CastSizeChange::Pending) | ||
| 453 | + } | ||
| 454 | + | ||
| 455 | + pub fn set_refresh(&mut self, refresh: u32) -> anyhow::Result<()> { | ||
| 456 | + if self.refresh == refresh { | ||
| 457 | + return Ok(()); | ||
| 458 | + } | ||
| 459 | + | ||
| 460 | + let _span = tracy_client::span!("Cast::set_refresh"); | ||
| 461 | + debug!("cast FPS changed, updating stream FPS"); | ||
| 462 | + self.refresh = refresh; | ||
| 463 | + | ||
| 464 | + let size = self.size.get().expected_format_size(); | ||
| 465 | + let object = make_video_params(size, self.refresh); | ||
| 466 | + let mut buffer = vec![]; | ||
| 467 | + let mut params = [make_pod(&mut buffer, object)]; | ||
| 468 | + self.stream | ||
| 469 | + .update_params(&mut params) | ||
| 470 | + .context("error updating stream params")?; | ||
| 471 | + | ||
| 472 | + Ok(()) | ||
| 473 | + } | ||
| 474 | + | ||
| 475 | + pub fn should_skip_frame(&self, target_frame_time: Duration) -> bool { | ||
| 476 | + let last = self.last_frame_time; | ||
| 477 | + let min = self.min_time_between_frames.get(); | ||
| 478 | + | ||
| 479 | + if last.is_zero() { | ||
| 480 | + trace!(?target_frame_time, ?last, "last is zero, recording"); | ||
| 481 | + return false; | ||
| 482 | + } | ||
| 483 | + | ||
| 484 | + if target_frame_time < last { | ||
| 485 | + // Record frame with a warning; in case it was an overflow this will fix it. | ||
| 486 | + warn!( | ||
| 487 | + ?target_frame_time, | ||
| 488 | + ?last, | ||
| 489 | + "target frame time is below last, did it overflow or did we mispredict?" | ||
| 490 | + ); | ||
| 491 | + return false; | ||
| 492 | + } | ||
| 493 | + | ||
| 494 | + let diff = target_frame_time - last; | ||
| 495 | + if diff < min { | ||
| 496 | + trace!( | ||
| 497 | + ?target_frame_time, | ||
| 498 | + ?last, | ||
| 499 | + "skipping frame because it is too soon: diff={diff:?} < min={min:?}", | ||
| 500 | + ); | ||
| 501 | + return true; | ||
| 502 | + } | ||
| 503 | + | ||
| 504 | + false | ||
| 505 | + } | ||
| 506 | + | ||
| 507 | + pub fn dequeue_buffer_and_render( | ||
| 508 | + &mut self, | ||
| 509 | + renderer: &mut GlesRenderer, | ||
| 510 | + elements: impl Iterator<Item = impl RenderElement<GlesRenderer>>, | ||
| 511 | + size: Size<i32, Physical>, | ||
| 512 | + scale: Scale<f64>, | ||
| 513 | + ) -> bool { | ||
| 514 | + let mut buffer = match self.stream.dequeue_buffer() { | ||
| 515 | + Some(buffer) => buffer, | ||
| 516 | + None => { | ||
| 517 | + warn!("no available buffer in pw stream, skipping frame"); | ||
| 518 | + return false; | ||
| 519 | + } | ||
| 520 | + }; | ||
| 521 | + | ||
| 522 | + let data = &mut buffer.datas_mut()[0]; | ||
| 523 | + let fd = data.as_raw().fd as i32; | ||
| 524 | + let dmabuf = self.dmabufs.borrow()[&fd].clone(); | ||
| 525 | + | ||
| 526 | + if let Err(err) = | ||
| 527 | + render_to_dmabuf(renderer, dmabuf, size, scale, Transform::Normal, elements) | ||
| 528 | + { | ||
| 529 | + warn!("error rendering to dmabuf: {err:?}"); | ||
| 530 | + return false; | ||
| 531 | + } | ||
| 532 | + | ||
| 533 | + let maxsize = data.as_raw().maxsize; | ||
| 534 | + let chunk = data.chunk_mut(); | ||
| 535 | + *chunk.size_mut() = maxsize; | ||
| 536 | + *chunk.stride_mut() = maxsize as i32 / size.h; | ||
| 537 | + | ||
| 538 | + true | ||
| 539 | + } | ||
| 540 | +} | ||
| 541 | + | ||
| 542 | +impl CastSize { | ||
| 543 | + fn pending_size(self) -> Option<Size<i32, Physical>> { | ||
| 544 | + match self { | ||
| 545 | + CastSize::InitialPending(pending) => Some(pending), | ||
| 546 | + CastSize::Ready(_) => None, | ||
| 547 | + CastSize::ChangePending { pending, .. } => Some(pending), | ||
| 548 | + } | ||
| 549 | + } | ||
| 550 | + | ||
| 551 | + fn negotiated_size(self) -> Option<Size<i32, Physical>> { | ||
| 552 | + match self { | ||
| 553 | + CastSize::InitialPending(_) => None, | ||
| 554 | + CastSize::Ready(size) => Some(size), | ||
| 555 | + CastSize::ChangePending { | ||
| 556 | + last_negotiated, .. | ||
| 557 | + } => Some(last_negotiated), | ||
| 558 | + } | ||
| 559 | + } | ||
| 560 | + | ||
| 561 | + fn expected_format_size(self) -> Size<i32, Physical> { | ||
| 562 | + match self { | ||
| 563 | + CastSize::InitialPending(pending) => pending, | ||
| 564 | + CastSize::Ready(size) => size, | ||
| 565 | + CastSize::ChangePending { pending, .. } => pending, | ||
| 566 | + } | ||
| 567 | + } | ||
| 568 | + | ||
| 569 | + fn with_pending(self, pending: Size<i32, Physical>) -> Self { | ||
| 570 | + match self { | ||
| 571 | + CastSize::InitialPending(_) => CastSize::InitialPending(pending), | ||
| 572 | + CastSize::Ready(size) => CastSize::ChangePending { | ||
| 573 | + last_negotiated: size, | ||
| 574 | + pending, | ||
| 575 | + }, | ||
| 576 | + CastSize::ChangePending { | ||
| 577 | + last_negotiated, .. | ||
| 578 | + } => CastSize::ChangePending { | ||
| 579 | + last_negotiated, | ||
| 580 | + pending, | ||
| 581 | + }, | ||
| 582 | + } | ||
| 401 | } | 583 | } |
| 402 | } | 584 | } |
| 403 | 585 | ||