niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·9d8f4f8·Ivan Molodetskikh·1 month ago·2997 commits
| 1 | use std::collections::hash_map::Entry; |
| 2 | use std::collections::{HashMap, HashSet}; |
| 3 | use std::mem; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use anyhow::Context as _; |
| 7 | use calloop::LoopHandle; |
| 8 | use smithay::backend::allocator::format::FormatSet; |
| 9 | use smithay::backend::allocator::gbm::GbmDevice; |
| 10 | use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement}; |
| 11 | use smithay::backend::renderer::gles::GlesRenderer; |
| 12 | use smithay::desktop::Window; |
| 13 | use smithay::output::Output; |
| 14 | use smithay::reexports::gbm::Modifier; |
| 15 | use smithay::utils::{DeviceFd, Physical, Point, Scale, Size}; |
| 16 | use zbus::object_server::SignalEmitter; |
| 17 | |
| 18 | use crate::dbus::mutter_screen_cast::{self, CursorMode, ScreenCastToNiri, StreamTargetId}; |
| 19 | use crate::niri::{CastTarget, Niri, OutputRenderElements, PointerRenderElements, State}; |
| 20 | use crate::niri_render_elements; |
| 21 | use crate::render_helpers::{RenderCtx, RenderTarget}; |
| 22 | use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId}; |
| 23 | use crate::window::mapped::{MappedId, WindowCastRenderElements}; |
| 24 | |
| 25 | mod pw_utils; |
| 26 | use pw_utils::{Cast, CastSizeChange, CursorData, PipeWire, PwToNiri}; |
| 27 | |
| 28 | pub struct Screencasting { |
| 29 | pub casts: Vec<Cast>, |
| 30 | |
| 31 | /// Dynamic-target casts waiting for their first target to start. |
| 32 | pub pending_dynamic_casts: Vec<PendingCast>, |
| 33 | |
| 34 | pub pw_to_niri: calloop::channel::Sender<PwToNiri>, |
| 35 | |
| 36 | /// Screencast output for each mapped window. |
| 37 | pub mapped_cast_output: HashMap<Window, Output>, |
| 38 | |
| 39 | /// Window ID for the "dynamic cast" special window for the xdp-gnome picker. |
| 40 | pub dynamic_cast_id_for_portal: MappedId, |
| 41 | |
| 42 | // Drop PipeWire last, and specifically after casts, to prevent a double-free (yay). |
| 43 | pub pipewire: Option<PipeWire>, |
| 44 | } |
| 45 | |
| 46 | /// A screencast request that hasn't been started yet. |
| 47 | pub struct PendingCast { |
| 48 | pub session_id: CastSessionId, |
| 49 | pub stream_id: CastStreamId, |
| 50 | pub cursor_mode: CursorMode, |
| 51 | pub signal_ctx: SignalEmitter<'static>, |
| 52 | } |
| 53 | |
| 54 | impl Screencasting { |
| 55 | pub fn new(event_loop: &LoopHandle<'static, State>) -> Self { |
| 56 | let pw_to_niri = { |
| 57 | let (pw_to_niri, from_pipewire) = calloop::channel::channel(); |
| 58 | event_loop |
| 59 | .insert_source(from_pipewire, move |event, _, state| match event { |
| 60 | calloop::channel::Event::Msg(msg) => state.on_pw_msg(msg), |
| 61 | calloop::channel::Event::Closed => (), |
| 62 | }) |
| 63 | .unwrap(); |
| 64 | pw_to_niri |
| 65 | }; |
| 66 | |
| 67 | Self { |
| 68 | casts: vec![], |
| 69 | pending_dynamic_casts: vec![], |
| 70 | pw_to_niri, |
| 71 | mapped_cast_output: HashMap::new(), |
| 72 | dynamic_cast_id_for_portal: MappedId::next(), |
| 73 | pipewire: None, |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl State { |
| 79 | fn prepare_pw_cast(&mut self) -> anyhow::Result<Option<(GbmDevice<DeviceFd>, FormatSet)>> { |
| 80 | // Ensure PipeWire is initialized. |
| 81 | if self.niri.casting.pipewire.is_none() { |
| 82 | let pw = PipeWire::new( |
| 83 | self.niri.event_loop.clone(), |
| 84 | self.niri.casting.pw_to_niri.clone(), |
| 85 | ) |
| 86 | .context("error initializing PipeWire")?; |
| 87 | self.niri.casting.pipewire = Some(pw); |
| 88 | } |
| 89 | |
| 90 | if self.niri.config.borrow().debug.disable_pipewire_dmabuf { |
| 91 | return Ok(None); |
| 92 | } |
| 93 | |
| 94 | let Some(gbm) = self.backend.gbm_device() else { |
| 95 | // We will offer shm only. |
| 96 | return Ok(None); |
| 97 | }; |
| 98 | |
| 99 | let mut render_formats = self |
| 100 | .backend |
| 101 | .with_primary_renderer(|renderer| { |
| 102 | renderer.egl_context().dmabuf_render_formats().clone() |
| 103 | }) |
| 104 | .unwrap_or_default(); |
| 105 | |
| 106 | { |
| 107 | let config = self.niri.config.borrow(); |
| 108 | if config.debug.force_pipewire_invalid_modifier { |
| 109 | render_formats = render_formats |
| 110 | .into_iter() |
| 111 | .filter(|f| f.modifier == Modifier::Invalid) |
| 112 | .collect(); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | Ok(Some((gbm, render_formats))) |
| 117 | } |
| 118 | |
| 119 | pub fn on_pw_msg(&mut self, msg: PwToNiri) { |
| 120 | match msg { |
| 121 | PwToNiri::StopCast { session_id } => self.niri.stop_cast(session_id), |
| 122 | PwToNiri::Redraw { stream_id } => self.redraw_cast(stream_id), |
| 123 | PwToNiri::FatalError => { |
| 124 | warn!("stopping PipeWire due to fatal error"); |
| 125 | let casting = &mut self.niri.casting; |
| 126 | if let Some(pw) = casting.pipewire.take() { |
| 127 | let mut ids = HashSet::new(); |
| 128 | for cast in &casting.pending_dynamic_casts { |
| 129 | ids.insert(cast.session_id); |
| 130 | } |
| 131 | for cast in &casting.casts { |
| 132 | ids.insert(cast.session_id); |
| 133 | } |
| 134 | for id in ids { |
| 135 | self.niri.stop_cast(id); |
| 136 | } |
| 137 | self.niri.event_loop.remove(pw.token); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | fn redraw_cast(&mut self, stream_id: CastStreamId) { |
| 144 | let _span = tracy_client::span!("State::redraw_cast"); |
| 145 | |
| 146 | let casts = &mut self.niri.casting.casts; |
| 147 | let Some(idx) = casts.iter().position(|cast| cast.stream_id == stream_id) else { |
| 148 | warn!("cast to redraw is missing"); |
| 149 | return; |
| 150 | }; |
| 151 | let cast = &mut casts[idx]; |
| 152 | |
| 153 | let id = match &cast.target { |
| 154 | CastTarget::Nothing => { |
| 155 | self.backend.with_primary_renderer(|renderer| { |
| 156 | if cast.dequeue_buffer_and_clear(renderer) { |
| 157 | cast.record_frame_time(get_monotonic_time()); |
| 158 | } |
| 159 | }); |
| 160 | return; |
| 161 | } |
| 162 | CastTarget::Output { output, .. } => { |
| 163 | if let Some(output) = output.upgrade() { |
| 164 | self.niri.queue_redraw(&output); |
| 165 | } |
| 166 | return; |
| 167 | } |
| 168 | CastTarget::Window { id } => *id, |
| 169 | }; |
| 170 | |
| 171 | // Lack of partial borrowing strikes again... |
| 172 | let mut casts = mem::take(&mut self.niri.casting.casts); |
| 173 | let cast = &mut casts[idx]; |
| 174 | let mut stop = false; |
| 175 | // Use a loop {} so we can break instead of early-return. |
| 176 | #[allow(clippy::never_loop)] |
| 177 | loop { |
| 178 | let mut windows = self.niri.layout.windows(); |
| 179 | let Some((_, mapped)) = windows.find(|(_, mapped)| mapped.id().get() == id) else { |
| 180 | break; |
| 181 | }; |
| 182 | |
| 183 | // Use the cached output since it will be present even if the output was |
| 184 | // currently disconnected. |
| 185 | let Some(output) = self.niri.casting.mapped_cast_output.get(&mapped.window) else { |
| 186 | break; |
| 187 | }; |
| 188 | |
| 189 | let scale = Scale::from(output.current_scale().fractional_scale()); |
| 190 | let bbox = mapped |
| 191 | .window |
| 192 | .bbox_with_popups() |
| 193 | .to_physical_precise_up(scale); |
| 194 | |
| 195 | match cast.ensure_size(bbox.size) { |
| 196 | Ok(CastSizeChange::Ready) => (), |
| 197 | Ok(CastSizeChange::Pending) => break, |
| 198 | Err(err) => { |
| 199 | warn!("error updating stream size, stopping screencast: {err:?}"); |
| 200 | stop = true; |
| 201 | break; |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | self.backend.with_primary_renderer(|renderer| { |
| 206 | let mut elements = Vec::new(); |
| 207 | let mut pointer_location = Point::default(); |
| 208 | |
| 209 | if self.niri.pointer_visibility.is_visible() { |
| 210 | if let Some((pointer_pos, win_pos)) = |
| 211 | self.niri.pointer_pos_for_window_cast(mapped) |
| 212 | { |
| 213 | // Pointer location must be relative to the screencast buffer. |
| 214 | // - win_pos is the position of the main window surface in output-local |
| 215 | // coordinates |
| 216 | // - bbox.loc moves us relative to the screencast buffer |
| 217 | let buf_pos = win_pos + bbox.loc.to_f64().to_logical(scale); |
| 218 | let output_pos = |
| 219 | self.niri.global_space.output_geometry(output).unwrap().loc; |
| 220 | pointer_location = pointer_pos - output_pos.to_f64() - buf_pos; |
| 221 | |
| 222 | let pos = buf_pos.to_physical_precise_round(scale).upscale(-1); |
| 223 | self.niri.render_pointer(renderer, output, &mut |elem| { |
| 224 | let elem = |
| 225 | RelocateRenderElement::from_element(elem, pos, Relocate::Relative); |
| 226 | elements.push(CastRenderElement::from(elem)); |
| 227 | }); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | let main_start = elements.len(); |
| 232 | mapped.render_for_screen_cast(renderer, scale, &mut |elem| { |
| 233 | elements.push(CastRenderElement::from(elem)) |
| 234 | }); |
| 235 | |
| 236 | let cursor_data = |
| 237 | CursorData::compute(&elements, main_start, pointer_location, scale); |
| 238 | |
| 239 | if cast.dequeue_buffer_and_render( |
| 240 | renderer, |
| 241 | &elements, |
| 242 | &cursor_data, |
| 243 | bbox.size, |
| 244 | scale, |
| 245 | ) { |
| 246 | cast.record_frame_time(get_monotonic_time()); |
| 247 | } |
| 248 | }); |
| 249 | |
| 250 | break; |
| 251 | } |
| 252 | let session_id = cast.session_id; |
| 253 | self.niri.casting.casts = casts; |
| 254 | |
| 255 | if stop { |
| 256 | self.niri.stop_cast(session_id); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | pub fn set_dynamic_cast_target(&mut self, target: CastTarget) { |
| 261 | let _span = tracy_client::span!("State::set_dynamic_cast_target"); |
| 262 | |
| 263 | let mut refresh = None; |
| 264 | match &target { |
| 265 | // Leave refresh as is when clearing. Chances are, the next refresh will match it, |
| 266 | // then we'll avoid reconfiguring. |
| 267 | CastTarget::Nothing => (), |
| 268 | CastTarget::Output { output, .. } => { |
| 269 | if let Some(output) = output.upgrade() { |
| 270 | refresh = Some(output.current_mode().unwrap().refresh as u32); |
| 271 | } |
| 272 | } |
| 273 | CastTarget::Window { id } => { |
| 274 | let mut windows = self.niri.layout.windows(); |
| 275 | if let Some((_, mapped)) = windows.find(|(_, mapped)| mapped.id().get() == *id) { |
| 276 | if let Some(output) = self.niri.casting.mapped_cast_output.get(&mapped.window) { |
| 277 | refresh = Some(output.current_mode().unwrap().refresh as u32); |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | let mut to_redraw = Vec::new(); |
| 284 | let mut to_stop = Vec::new(); |
| 285 | for cast in &mut self.niri.casting.casts { |
| 286 | if !cast.dynamic_target { |
| 287 | continue; |
| 288 | } |
| 289 | |
| 290 | if let Some(refresh) = refresh { |
| 291 | if let Err(err) = cast.set_refresh(refresh) { |
| 292 | warn!("error changing cast FPS: {err:?}"); |
| 293 | to_stop.push(cast.session_id); |
| 294 | continue; |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | cast.target = target.clone(); |
| 299 | to_redraw.push(cast.stream_id); |
| 300 | } |
| 301 | |
| 302 | for id in to_redraw { |
| 303 | self.redraw_cast(id); |
| 304 | } |
| 305 | |
| 306 | // Start any pending dynamic casts if we have a real target. |
| 307 | if !matches!(target, CastTarget::Nothing) { |
| 308 | self.start_pending_dynamic_casts(&target); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn start_pending_dynamic_casts(&mut self, target: &CastTarget) { |
| 313 | let pending = &self.niri.casting.pending_dynamic_casts; |
| 314 | if pending.is_empty() { |
| 315 | return; |
| 316 | } |
| 317 | debug!("starting {} pending dynamic cast(s)", pending.len()); |
| 318 | |
| 319 | let _span = tracy_client::span!("State::start_pending_dynamic_casts"); |
| 320 | |
| 321 | // We don't stop dynamic casts on missing output/window. |
| 322 | let (size, refresh) = match target { |
| 323 | CastTarget::Nothing => panic!("dynamic cast starting target must not be Nothing"), |
| 324 | CastTarget::Output { output, .. } => { |
| 325 | let Some(output) = output.upgrade() else { |
| 326 | return; |
| 327 | }; |
| 328 | cast_params_for_output(&output) |
| 329 | } |
| 330 | CastTarget::Window { id } => { |
| 331 | let Some((size, refresh)) = self.niri.cast_params_for_window(*id) else { |
| 332 | return; |
| 333 | }; |
| 334 | (size, refresh) |
| 335 | } |
| 336 | }; |
| 337 | |
| 338 | let gbm = match self.prepare_pw_cast() { |
| 339 | Ok(x) => x, |
| 340 | Err(err) => { |
| 341 | warn!("error starting pending screencasts: {err:?}"); |
| 342 | let mut ids = HashSet::new(); |
| 343 | for pending in self.niri.casting.pending_dynamic_casts.drain(..) { |
| 344 | ids.insert(pending.session_id); |
| 345 | } |
| 346 | for id in ids { |
| 347 | self.niri.stop_cast(id); |
| 348 | } |
| 349 | return; |
| 350 | } |
| 351 | }; |
| 352 | let pw = self.niri.casting.pipewire.as_ref().unwrap(); |
| 353 | |
| 354 | // Alpha is always true since the dynamic target can change between window & output. |
| 355 | let alpha = true; |
| 356 | |
| 357 | // Start each pending cast. |
| 358 | let mut to_stop = HashSet::new(); |
| 359 | for pending in self.niri.casting.pending_dynamic_casts.drain(..) { |
| 360 | let res = pw.start_cast( |
| 361 | gbm.clone(), |
| 362 | pending.session_id, |
| 363 | pending.stream_id, |
| 364 | target.clone(), |
| 365 | size, |
| 366 | refresh, |
| 367 | alpha, |
| 368 | pending.cursor_mode, |
| 369 | pending.signal_ctx, |
| 370 | ); |
| 371 | match res { |
| 372 | Ok(mut cast) => { |
| 373 | cast.dynamic_target = true; |
| 374 | self.niri.casting.casts.push(cast); |
| 375 | } |
| 376 | Err(err) => { |
| 377 | warn!("error starting pending screencast: {err:?}"); |
| 378 | to_stop.insert(pending.session_id); |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | for session_id in to_stop { |
| 384 | self.niri.stop_cast(session_id); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | pub fn on_screen_cast_msg(&mut self, msg: ScreenCastToNiri) { |
| 389 | match msg { |
| 390 | ScreenCastToNiri::StartCast { |
| 391 | session_id, |
| 392 | stream_id, |
| 393 | target, |
| 394 | cursor_mode, |
| 395 | signal_ctx, |
| 396 | } => { |
| 397 | let _span = tracy_client::span!("StartCast"); |
| 398 | let _span = debug_span!("StartCast", %session_id, %stream_id).entered(); |
| 399 | |
| 400 | let (target, size, refresh, alpha) = match target { |
| 401 | StreamTargetId::Output { name } => { |
| 402 | let global_space = &self.niri.global_space; |
| 403 | let output = global_space.outputs().find(|out| out.name() == name); |
| 404 | let Some(output) = output else { |
| 405 | warn!("error starting screencast: requested output is missing"); |
| 406 | self.niri.stop_cast(session_id); |
| 407 | return; |
| 408 | }; |
| 409 | |
| 410 | let (size, refresh) = cast_params_for_output(output); |
| 411 | (CastTarget::output(output), size, refresh, false) |
| 412 | } |
| 413 | StreamTargetId::Window { id } |
| 414 | if id == self.niri.casting.dynamic_cast_id_for_portal.get() => |
| 415 | { |
| 416 | debug!("delaying dynamic cast until target is set"); |
| 417 | self.niri.casting.pending_dynamic_casts.push(PendingCast { |
| 418 | session_id, |
| 419 | stream_id, |
| 420 | cursor_mode, |
| 421 | signal_ctx, |
| 422 | }); |
| 423 | return; |
| 424 | } |
| 425 | StreamTargetId::Window { id } => { |
| 426 | let Some((size, refresh)) = self.niri.cast_params_for_window(id) else { |
| 427 | warn!("error starting screencast: requested window is missing"); |
| 428 | self.niri.stop_cast(session_id); |
| 429 | return; |
| 430 | }; |
| 431 | (CastTarget::Window { id }, size, refresh, true) |
| 432 | } |
| 433 | }; |
| 434 | |
| 435 | let gbm = match self.prepare_pw_cast() { |
| 436 | Ok(x) => x, |
| 437 | Err(err) => { |
| 438 | warn!("error starting screencast: {err:?}"); |
| 439 | self.niri.stop_cast(session_id); |
| 440 | return; |
| 441 | } |
| 442 | }; |
| 443 | let pw = self.niri.casting.pipewire.as_ref().unwrap(); |
| 444 | |
| 445 | let res = pw.start_cast( |
| 446 | gbm, |
| 447 | session_id, |
| 448 | stream_id, |
| 449 | target, |
| 450 | size, |
| 451 | refresh, |
| 452 | alpha, |
| 453 | cursor_mode, |
| 454 | signal_ctx, |
| 455 | ); |
| 456 | match res { |
| 457 | Ok(cast) => { |
| 458 | self.niri.casting.casts.push(cast); |
| 459 | } |
| 460 | Err(err) => { |
| 461 | warn!("error starting screencast: {err:?}"); |
| 462 | self.niri.stop_cast(session_id); |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | ScreenCastToNiri::StopCast { session_id } => self.niri.stop_cast(session_id), |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | impl Niri { |
| 472 | pub fn refresh_mapped_cast_window_rules(&mut self) { |
| 473 | // O(N^2) but should be fine since there aren't many casts usually. |
| 474 | self.layout.with_windows_mut(|mapped, _| { |
| 475 | let id = mapped.id().get(); |
| 476 | // Find regardless of cast.is_active. |
| 477 | let value = self |
| 478 | .casting |
| 479 | .casts |
| 480 | .iter() |
| 481 | .any(|cast| cast.target == (CastTarget::Window { id })); |
| 482 | mapped.set_is_window_cast_target(value); |
| 483 | }); |
| 484 | } |
| 485 | |
| 486 | pub fn refresh_mapped_cast_outputs(&mut self) { |
| 487 | let mut seen = HashSet::new(); |
| 488 | let mut output_changed = vec![]; |
| 489 | |
| 490 | self.layout.with_windows(|mapped, output, _, _| { |
| 491 | seen.insert(mapped.window.clone()); |
| 492 | |
| 493 | let Some(output) = output else { |
| 494 | return; |
| 495 | }; |
| 496 | |
| 497 | match self.casting.mapped_cast_output.entry(mapped.window.clone()) { |
| 498 | Entry::Occupied(mut entry) => { |
| 499 | if entry.get() != output { |
| 500 | entry.insert(output.clone()); |
| 501 | output_changed.push((mapped.id(), output.clone())); |
| 502 | } |
| 503 | } |
| 504 | Entry::Vacant(entry) => { |
| 505 | entry.insert(output.clone()); |
| 506 | } |
| 507 | } |
| 508 | }); |
| 509 | |
| 510 | self.casting |
| 511 | .mapped_cast_output |
| 512 | .retain(|win, _| seen.contains(win)); |
| 513 | |
| 514 | let mut to_stop = vec![]; |
| 515 | for (id, out) in output_changed { |
| 516 | let refresh = out.current_mode().unwrap().refresh as u32; |
| 517 | let target = CastTarget::Window { id: id.get() }; |
| 518 | for cast in self |
| 519 | .casting |
| 520 | .casts |
| 521 | .iter_mut() |
| 522 | .filter(|cast| cast.target == target) |
| 523 | { |
| 524 | if let Err(err) = cast.set_refresh(refresh) { |
| 525 | warn!("error changing cast FPS: {err:?}"); |
| 526 | to_stop.push(cast.session_id); |
| 527 | }; |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | for session_id in to_stop { |
| 532 | self.stop_cast(session_id); |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | pub fn render_for_screen_cast( |
| 537 | &mut self, |
| 538 | renderer: &mut GlesRenderer, |
| 539 | output: &Output, |
| 540 | target_presentation_time: Duration, |
| 541 | ) { |
| 542 | let _span = tracy_client::span!("Niri::render_for_screen_cast"); |
| 543 | |
| 544 | let weak = output.downgrade(); |
| 545 | let size = output.current_mode().unwrap().size; |
| 546 | let transform = output.current_transform(); |
| 547 | let size = transform.transform_size(size); |
| 548 | |
| 549 | let scale = Scale::from(output.current_scale().fractional_scale()); |
| 550 | |
| 551 | let mut elements = Vec::new(); |
| 552 | let mut cursor_data = None; |
| 553 | |
| 554 | let mut casts_to_stop = vec![]; |
| 555 | |
| 556 | let mut casts = mem::take(&mut self.casting.casts); |
| 557 | for cast in &mut casts { |
| 558 | if !cast.is_active() { |
| 559 | continue; |
| 560 | } |
| 561 | |
| 562 | if !cast.target.matches_output(&weak) { |
| 563 | continue; |
| 564 | } |
| 565 | |
| 566 | match cast.ensure_size(size) { |
| 567 | Ok(CastSizeChange::Ready) => (), |
| 568 | Ok(CastSizeChange::Pending) => continue, |
| 569 | Err(err) => { |
| 570 | warn!("error updating stream size, stopping screencast: {err:?}"); |
| 571 | casts_to_stop.push(cast.session_id); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | if cast.check_time_and_schedule(output, target_presentation_time) { |
| 576 | continue; |
| 577 | } |
| 578 | |
| 579 | if cursor_data.is_none() { |
| 580 | let mut pointer_pos = Point::default(); |
| 581 | if self.pointer_visibility.is_visible() { |
| 582 | let output_geo = self.global_space.output_geometry(output).unwrap().to_f64(); |
| 583 | let pointer_loc = self |
| 584 | .tablet_cursor_location |
| 585 | .unwrap_or_else(|| self.seat.get_pointer().unwrap().current_location()); |
| 586 | // Only render when the pointer is within the output. Otherwise, it will |
| 587 | // happily appear anywhere outside the output video source in OBS. |
| 588 | if output_geo.contains(pointer_loc) { |
| 589 | pointer_pos = pointer_loc - output_geo.loc; |
| 590 | self.render_pointer(renderer, output, &mut |elem| { |
| 591 | elements.push(elem.into()) |
| 592 | }); |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | let main_start = elements.len(); |
| 597 | let ctx = RenderCtx { |
| 598 | renderer, |
| 599 | target: RenderTarget::Screencast, |
| 600 | xray: None, |
| 601 | }; |
| 602 | self.render(ctx, output, false, &mut |elem| elements.push(elem.into())); |
| 603 | |
| 604 | cursor_data = Some(CursorData::compute( |
| 605 | &elements, |
| 606 | main_start, |
| 607 | pointer_pos, |
| 608 | scale, |
| 609 | )); |
| 610 | } |
| 611 | let cursor_data = cursor_data.as_ref().unwrap(); |
| 612 | |
| 613 | if cast.dequeue_buffer_and_render(renderer, &elements, cursor_data, size, scale) { |
| 614 | cast.record_frame_time(target_presentation_time); |
| 615 | } |
| 616 | } |
| 617 | self.casting.casts = casts; |
| 618 | |
| 619 | for id in casts_to_stop { |
| 620 | self.stop_cast(id); |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | pub fn render_windows_for_screen_cast( |
| 625 | &mut self, |
| 626 | renderer: &mut GlesRenderer, |
| 627 | output: &Output, |
| 628 | target_presentation_time: Duration, |
| 629 | ) { |
| 630 | let _span = tracy_client::span!("Niri::render_windows_for_screen_cast"); |
| 631 | |
| 632 | let scale = Scale::from(output.current_scale().fractional_scale()); |
| 633 | |
| 634 | let mut casts_to_stop = vec![]; |
| 635 | |
| 636 | let mut casts = mem::take(&mut self.casting.casts); |
| 637 | for cast in &mut casts { |
| 638 | if !cast.is_active() { |
| 639 | continue; |
| 640 | } |
| 641 | |
| 642 | let CastTarget::Window { id } = cast.target else { |
| 643 | continue; |
| 644 | }; |
| 645 | |
| 646 | let mut windows = self.layout.windows_for_output(output); |
| 647 | let Some(mapped) = windows.find(|win| win.id().get() == id) else { |
| 648 | continue; |
| 649 | }; |
| 650 | |
| 651 | let bbox = mapped |
| 652 | .window |
| 653 | .bbox_with_popups() |
| 654 | .to_physical_precise_up(scale); |
| 655 | |
| 656 | match cast.ensure_size(bbox.size) { |
| 657 | Ok(CastSizeChange::Ready) => (), |
| 658 | Ok(CastSizeChange::Pending) => continue, |
| 659 | Err(err) => { |
| 660 | warn!("error updating stream size, stopping screencast: {err:?}"); |
| 661 | casts_to_stop.push(cast.session_id); |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | if cast.check_time_and_schedule(output, target_presentation_time) { |
| 666 | continue; |
| 667 | } |
| 668 | |
| 669 | let mut elements = Vec::new(); |
| 670 | let mut pointer_location = Point::default(); |
| 671 | |
| 672 | if self.pointer_visibility.is_visible() { |
| 673 | if let Some((pointer_pos, win_pos)) = self.pointer_pos_for_window_cast(mapped) { |
| 674 | // Pointer location must be relative to the screencast buffer. |
| 675 | // - win_pos is the position of the main window surface in output-local |
| 676 | // coordinates |
| 677 | // - bbox.loc moves us relative to the screencast buffer |
| 678 | let buf_pos = win_pos + bbox.loc.to_f64().to_logical(scale); |
| 679 | let output_pos = self.global_space.output_geometry(output).unwrap().loc; |
| 680 | pointer_location = pointer_pos - output_pos.to_f64() - buf_pos; |
| 681 | |
| 682 | let pos = buf_pos.to_physical_precise_round(scale).upscale(-1); |
| 683 | self.render_pointer(renderer, output, &mut |elem| { |
| 684 | let elem = |
| 685 | RelocateRenderElement::from_element(elem, pos, Relocate::Relative); |
| 686 | elements.push(CastRenderElement::from(elem)); |
| 687 | }); |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | let main_start = elements.len(); |
| 692 | mapped.render_for_screen_cast(renderer, scale, &mut |elem| { |
| 693 | elements.push(CastRenderElement::from(elem)) |
| 694 | }); |
| 695 | |
| 696 | let cursor_data = CursorData::compute(&elements, main_start, pointer_location, scale); |
| 697 | |
| 698 | if cast.dequeue_buffer_and_render(renderer, &elements, &cursor_data, bbox.size, scale) { |
| 699 | cast.record_frame_time(target_presentation_time); |
| 700 | } |
| 701 | } |
| 702 | self.casting.casts = casts; |
| 703 | |
| 704 | for id in casts_to_stop { |
| 705 | self.stop_cast(id); |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | pub fn stop_cast(&mut self, session_id: CastSessionId) { |
| 710 | let _span = tracy_client::span!("Niri::stop_cast"); |
| 711 | let _span = debug_span!("stop_cast", %session_id).entered(); |
| 712 | |
| 713 | self.casting |
| 714 | .pending_dynamic_casts |
| 715 | .retain(|p| p.session_id != session_id); |
| 716 | |
| 717 | for i in (0..self.casting.casts.len()).rev() { |
| 718 | let cast = &self.casting.casts[i]; |
| 719 | if cast.session_id != session_id { |
| 720 | continue; |
| 721 | } |
| 722 | |
| 723 | let cast = self.casting.casts.swap_remove(i); |
| 724 | if let Err(err) = cast.stream.disconnect() { |
| 725 | warn!("error disconnecting stream: {err:?}"); |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | let dbus = &self.dbus.as_ref().unwrap(); |
| 730 | let server = dbus.conn_screen_cast.as_ref().unwrap().object_server(); |
| 731 | let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id.get()); |
| 732 | if let Ok(iface) = server.interface::<_, mutter_screen_cast::Session>(path) { |
| 733 | let _span = tracy_client::span!("invoking Session::stop"); |
| 734 | |
| 735 | async_io::block_on(async move { |
| 736 | iface |
| 737 | .get() |
| 738 | .stop(server.inner(), iface.signal_emitter().clone()) |
| 739 | .await |
| 740 | }); |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | pub fn stop_casts_for_target(&mut self, target: CastTarget) { |
| 745 | let _span = tracy_client::span!("Niri::stop_casts_for_target"); |
| 746 | |
| 747 | // This is O(N^2) but it shouldn't be a problem I think. |
| 748 | let mut saw_dynamic = false; |
| 749 | let mut ids = Vec::new(); |
| 750 | for cast in &self.casting.casts { |
| 751 | if cast.target != target { |
| 752 | continue; |
| 753 | } |
| 754 | |
| 755 | if cast.dynamic_target { |
| 756 | saw_dynamic = true; |
| 757 | continue; |
| 758 | } |
| 759 | |
| 760 | ids.push(cast.session_id); |
| 761 | } |
| 762 | |
| 763 | for id in ids { |
| 764 | self.stop_cast(id); |
| 765 | } |
| 766 | |
| 767 | // We don't stop dynamic casts, instead we switch them to Nothing. |
| 768 | if saw_dynamic { |
| 769 | self.event_loop |
| 770 | .insert_idle(|state| state.set_dynamic_cast_target(CastTarget::Nothing)); |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | fn cast_params_for_window(&self, window_id: u64) -> Option<(Size<i32, Physical>, u32)> { |
| 775 | let (_, mapped) = self |
| 776 | .layout |
| 777 | .windows() |
| 778 | .find(|(_, m)| m.id().get() == window_id)?; |
| 779 | let output = self.casting.mapped_cast_output.get(&mapped.window)?; |
| 780 | let scale = Scale::from(output.current_scale().fractional_scale()); |
| 781 | let bbox = mapped |
| 782 | .window |
| 783 | .bbox_with_popups() |
| 784 | .to_physical_precise_up(scale); |
| 785 | let refresh = output.current_mode().unwrap().refresh as u32; |
| 786 | Some((bbox.size, refresh)) |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | fn cast_params_for_output(output: &Output) -> (Size<i32, Physical>, u32) { |
| 791 | let mode = output.current_mode().unwrap(); |
| 792 | let transform = output.current_transform(); |
| 793 | let size = transform.transform_size(mode.size); |
| 794 | let refresh = mode.refresh as u32; |
| 795 | (size, refresh) |
| 796 | } |
| 797 | |
| 798 | niri_render_elements! { |
| 799 | CastRenderElement<R> => { |
| 800 | Output = OutputRenderElements<R>, |
| 801 | Window = WindowCastRenderElements<R>, |
| 802 | Pointer = PointerRenderElements<R>, |
| 803 | RelocatedPointer = RelocateRenderElement<PointerRenderElements<R>>, |
| 804 | } |
| 805 | } |